blob: 6f159e061535a65a9fe0466b085259429f000a4b [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"
Chris Lattnere116ccf2009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000036#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000037#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000038#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000039#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000040#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000041#include "clang/AST/ASTContext.h"
42#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000043#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044#include "clang/Parse/Parser.h"
45#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000046#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include "clang/Basic/FileManager.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000050#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000051#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/ADT/StringExtras.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000055#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000056#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000057#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000058#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000059#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000060#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000061#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000062#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000063#include "llvm/System/Signals.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000064#include <cstdlib>
65
Reid Spencer5f016e22007-07-11 17:01:13 +000066using namespace clang;
67
68//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000069// Source Location Parser
70//===----------------------------------------------------------------------===//
71
72/// \brief A source location that has been parsed on the command line.
73struct ParsedSourceLocation {
74 std::string FileName;
75 unsigned Line;
76 unsigned Column;
77
78 /// \brief Try to resolve the file name of a parsed source location.
79 ///
80 /// \returns true if there was an error, false otherwise.
81 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
82};
83
84bool
85ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
86 RequestedSourceLocation &Result) {
87 const FileEntry *File = FileMgr.getFile(FileName);
88 if (!File)
89 return true;
90
91 Result.File = File;
92 Result.Line = Line;
93 Result.Column = Column;
94 return false;
95}
96
97namespace llvm {
98 namespace cl {
99 /// \brief Command-line option parser that parses source locations.
100 ///
101 /// Source locations are of the form filename:line:column.
102 template<>
103 class parser<ParsedSourceLocation>
104 : public basic_parser<ParsedSourceLocation> {
105 public:
106 bool parse(Option &O, const char *ArgName,
107 const std::string &ArgValue,
108 ParsedSourceLocation &Val);
109 };
110
111 bool
112 parser<ParsedSourceLocation>::
113 parse(Option &O, const char *ArgName, const std::string &ArgValue,
114 ParsedSourceLocation &Val) {
115 using namespace clang;
116
117 const char *ExpectedFormat
118 = "source location must be of the form filename:line:column";
119 std::string::size_type SecondColon = ArgValue.rfind(':');
120 if (SecondColon == std::string::npos) {
121 std::fprintf(stderr, "%s\n", ExpectedFormat);
122 return true;
123 }
124 char *EndPtr;
125 long Column
126 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
127 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
128 std::fprintf(stderr, "%s\n", ExpectedFormat);
129 return true;
130 }
131
132 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
133 if (SecondColon == std::string::npos) {
134 std::fprintf(stderr, "%s\n", ExpectedFormat);
135 return true;
136 }
137 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
138 if (EndPtr != ArgValue.c_str() + SecondColon) {
139 std::fprintf(stderr, "%s\n", ExpectedFormat);
140 return true;
141 }
142
143 Val.FileName = ArgValue.substr(0, FirstColon);
144 Val.Line = Line;
145 Val.Column = Column;
146 return false;
147 }
148 }
149}
150
151//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000152// Global options.
153//===----------------------------------------------------------------------===//
154
Chris Lattner47099742009-02-18 01:51:21 +0000155/// ClangFrontendTimer - The front-end activities should charge time to it with
156/// TimeRegion. The -ftime-report option controls whether this will do
157/// anything.
158llvm::Timer *ClangFrontendTimer = 0;
159
Daniel Dunbard3db4012008-10-16 16:54:18 +0000160static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000161
Reid Spencer5f016e22007-07-11 17:01:13 +0000162static llvm::cl::opt<bool>
163Verbose("v", llvm::cl::desc("Enable verbose output"));
164static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000165Stats("print-stats",
166 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000167static llvm::cl::opt<bool>
168DisableFree("disable-free",
169 llvm::cl::desc("Disable freeing of memory on exit"),
170 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000171static llvm::cl::opt<bool>
172EmptyInputOnly("empty-input-only",
173 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000174
175enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000176 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000177 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000178 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000179 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000180 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000181 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000182 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000184 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000185 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000186 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000187 ASTPrint, // Parse ASTs and print them.
188 ASTDump, // Parse ASTs and dump them.
Douglas Gregor609e72f2009-04-26 02:02:08 +0000189 ASTDumpFull, // Parse ASTs and dump them, including the
190 // contents of a PCH file.
Chris Lattner3b427b32007-10-11 00:18:28 +0000191 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000192 PrintDeclContext, // Print DeclContext and their Decls.
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 ParsePrintCallbacks, // Parse and print each callback.
194 ParseSyntaxOnly, // Parse and perform semantic analysis.
195 ParseNoop, // Parse with noop callbacks.
196 RunPreprocessorOnly, // Just lex, no output.
197 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000198 DumpTokens, // Dump out preprocessed tokens.
199 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000200 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000201 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000202 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000203 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000204};
205
206static llvm::cl::opt<ProgActions>
207ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
208 llvm::cl::init(ParseSyntaxOnly),
209 llvm::cl::values(
210 clEnumValN(RunPreprocessorOnly, "Eonly",
211 "Just run preprocessor, no output (for timings)"),
212 clEnumValN(PrintPreprocessedInput, "E",
213 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000214 clEnumValN(DumpRawTokens, "dump-raw-tokens",
215 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000216 clEnumValN(RunAnalysis, "analyze",
217 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000218 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000219 "Run preprocessor, dump internal rep of tokens"),
220 clEnumValN(ParseNoop, "parse-noop",
221 "Run parser with noop callbacks (for timings)"),
222 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
223 "Run parser and perform semantic analysis"),
224 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
225 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000226 clEnumValN(EmitHTML, "emit-html",
227 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000228 clEnumValN(ASTPrint, "ast-print",
229 "Build ASTs and then pretty-print them"),
230 clEnumValN(ASTDump, "ast-dump",
231 "Build ASTs and then debug dump them"),
Douglas Gregor609e72f2009-04-26 02:02:08 +0000232 clEnumValN(ASTDumpFull, "ast-dump-full",
233 "Build ASTs and then debug dump them, including PCH"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000234 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000235 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000236 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000237 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000238 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000239 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000240 clEnumValN(GeneratePCH, "emit-pch",
241 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000242 clEnumValN(EmitAssembly, "S",
243 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000245 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000246 clEnumValN(EmitBC, "emit-llvm-bc",
247 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000248 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
249 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000250 clEnumValN(RewriteTest, "rewrite-test",
251 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000252 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000253 "Rewrite ObjC into C (code rewriter example)"),
254 clEnumValN(RewriteMacros, "rewrite-macros",
255 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000256 clEnumValN(RewriteBlocks, "rewrite-blocks",
257 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000258 clEnumValN(FixIt, "fixit",
259 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 clEnumValEnd));
261
Ted Kremenekccc76472007-12-19 19:47:59 +0000262
263static llvm::cl::opt<std::string>
264OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000265 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000266 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000267
Ted Kremenekc2e72992008-12-02 19:57:31 +0000268
269//===----------------------------------------------------------------------===//
270// PTH.
271//===----------------------------------------------------------------------===//
272
273static llvm::cl::opt<std::string>
274TokenCache("token-cache", llvm::cl::value_desc("path"),
275 llvm::cl::desc("Use specified token cache file"));
276
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000277//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000278// Diagnostic Options
279//===----------------------------------------------------------------------===//
280
Ted Kremenek41193e42007-09-26 19:42:19 +0000281static llvm::cl::opt<bool>
282VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000283 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000284
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000285static llvm::cl::opt<std::string>
286HTMLDiag("html-diags",
287 llvm::cl::desc("Generate HTML to report diagnostics"),
288 llvm::cl::value_desc("HTML directory"));
289
Nico Weberfd54ebc2008-08-05 23:33:20 +0000290static llvm::cl::opt<bool>
291NoShowColumn("fno-show-column",
292 llvm::cl::desc("Do not include column number on diagnostics"));
293
294static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000295NoShowLocation("fno-show-source-location",
296 llvm::cl::desc("Do not include source location information with"
297 " diagnostics"));
298
299static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000300NoCaretDiagnostics("fno-caret-diagnostics",
301 llvm::cl::desc("Do not include source line and caret with"
302 " diagnostics"));
303
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000304static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000305NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
306 llvm::cl::desc("Do not include fixit information in"
307 " diagnostics"));
308
309static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000310PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
311 llvm::cl::desc("Print source range spans in numeric form"));
312
313static llvm::cl::alias
314PrintSourceRangeInfo2("fprint-source-range-info",
315 llvm::cl::desc("Print source range spans in numeric form [deprecated]"),
316 llvm::cl::aliasopt(PrintSourceRangeInfo));
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000317
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000318static llvm::cl::opt<bool>
319PrintDiagnosticOption("fdiagnostics-show-option",
320 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000321
Reid Spencer5f016e22007-07-11 17:01:13 +0000322//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000323// C++ Visualization.
324//===----------------------------------------------------------------------===//
325
326static llvm::cl::opt<std::string>
327InheritanceViewCls("cxx-inheritance-view",
328 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000329 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000330
331//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000332// Builtin Options
333//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000334
335static llvm::cl::opt<bool>
336TimeReport("ftime-report",
337 llvm::cl::desc("Print the amount of time each "
338 "phase of compilation takes"));
339
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000340static llvm::cl::opt<bool>
341Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000342 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000343 "freestanding environment"));
344
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000345static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000346AllowBuiltins("fbuiltin", llvm::cl::init(true),
347 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000348
349
350static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000351MathErrno("fmath-errno", llvm::cl::init(true),
352 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000353
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000354//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000355// Language Options
356//===----------------------------------------------------------------------===//
357
358enum LangKind {
359 langkind_unspecified,
360 langkind_c,
361 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000362 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 langkind_cxx,
364 langkind_cxx_cpp,
365 langkind_objc,
366 langkind_objc_cpp,
367 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000368 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000369};
370
Reid Spencer5f016e22007-07-11 17:01:13 +0000371static llvm::cl::opt<LangKind>
372BaseLang("x", llvm::cl::desc("Base language to compile"),
373 llvm::cl::init(langkind_unspecified),
374 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
375 clEnumValN(langkind_cxx, "c++", "C++"),
376 clEnumValN(langkind_objc, "objective-c", "Objective C"),
377 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000378 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000380 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
381 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000383 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
385 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000386 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000388 clEnumValN(langkind_c, "c-header",
389 "C header"),
390 clEnumValN(langkind_objc, "objective-c-header",
391 "Objective-C header"),
392 clEnumValN(langkind_cxx, "c++-header",
393 "C++ header"),
394 clEnumValN(langkind_objcxx, "objective-c++-header",
395 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 clEnumValEnd));
397
398static llvm::cl::opt<bool>
399LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
400 llvm::cl::Hidden);
401static llvm::cl::opt<bool>
402LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
403 llvm::cl::Hidden);
404
Chris Lattner2c78b872009-04-14 23:22:57 +0000405static llvm::cl::opt<bool>
406ObjCExclusiveGC("fobjc-gc-only",
407 llvm::cl::desc("Use GC exclusively for Objective-C related "
408 "memory management"));
409
410static llvm::cl::opt<bool>
411ObjCEnableGC("fobjc-gc",
412 llvm::cl::desc("Enable Objective-C garbage collection"));
413
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000414static llvm::cl::opt<bool>
415ObjCEnableGCBitmapPrint("print-ivar-layout",
416 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
417
Chris Lattner2c78b872009-04-14 23:22:57 +0000418static llvm::cl::opt<LangOptions::VisibilityMode>
419SymbolVisibility("fvisibility",
420 llvm::cl::desc("Set the default symbol visibility:"),
421 llvm::cl::init(LangOptions::Default),
422 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
423 "Use default symbol visibility"),
424 clEnumValN(LangOptions::Hidden, "hidden",
425 "Use hidden symbol visibility"),
426 clEnumValN(LangOptions::Protected,"protected",
427 "Use protected symbol visibility"),
428 clEnumValEnd));
429
430static llvm::cl::opt<bool>
431OverflowChecking("ftrapv",
432 llvm::cl::desc("Trap on integer overflow"),
433 llvm::cl::init(false));
434
435
Ted Kremenek8904f152007-12-05 23:49:08 +0000436/// InitializeBaseLanguage - Handle the -x foo options.
437static void InitializeBaseLanguage() {
438 if (LangObjC)
439 BaseLang = langkind_objc;
440 else if (LangObjCXX)
441 BaseLang = langkind_objcxx;
442}
443
444static LangKind GetLanguage(const std::string &Filename) {
445 if (BaseLang != langkind_unspecified)
446 return BaseLang;
447
448 std::string::size_type DotPos = Filename.rfind('.');
449
450 if (DotPos == std::string::npos) {
451 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000452 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 }
454
Ted Kremenek8904f152007-12-05 23:49:08 +0000455 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
456 // C header: .h
457 // C++ header: .hh or .H;
458 // assembler no preprocessing: .s
459 // assembler: .S
460 if (Ext == "c")
461 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000462 else if (Ext == "S" ||
463 // If the compiler is run on a .s file, preprocess it as .S
464 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000465 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000466 else if (Ext == "i")
467 return langkind_c_cpp;
468 else if (Ext == "ii")
469 return langkind_cxx_cpp;
470 else if (Ext == "m")
471 return langkind_objc;
472 else if (Ext == "mi")
473 return langkind_objc_cpp;
474 else if (Ext == "mm" || Ext == "M")
475 return langkind_objcxx;
476 else if (Ext == "mii")
477 return langkind_objcxx_cpp;
478 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
479 Ext == "c++" || Ext == "cp" || Ext == "cxx")
480 return langkind_cxx;
481 else
482 return langkind_c;
483}
484
485
Ted Kremenek85888962008-10-21 00:54:44 +0000486static void InitializeCOptions(LangOptions &Options) {
487 // Do nothing.
488}
489
490static void InitializeObjCOptions(LangOptions &Options) {
491 Options.ObjC1 = Options.ObjC2 = 1;
492}
493
494
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000495static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 // FIXME: implement -fpreprocessed mode.
497 bool NoPreprocess = false;
498
Ted Kremenek8904f152007-12-05 23:49:08 +0000499 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000501 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000502 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000503 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 case langkind_c_cpp:
505 NoPreprocess = true;
506 // FALLTHROUGH
507 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000508 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 break;
510 case langkind_cxx_cpp:
511 NoPreprocess = true;
512 // FALLTHROUGH
513 case langkind_cxx:
514 Options.CPlusPlus = 1;
515 break;
516 case langkind_objc_cpp:
517 NoPreprocess = true;
518 // FALLTHROUGH
519 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000520 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 break;
522 case langkind_objcxx_cpp:
523 NoPreprocess = true;
524 // FALLTHROUGH
525 case langkind_objcxx:
526 Options.ObjC1 = Options.ObjC2 = 1;
527 Options.CPlusPlus = 1;
528 break;
529 }
Chris Lattner2c78b872009-04-14 23:22:57 +0000530
531 if (ObjCExclusiveGC)
532 Options.setGCMode(LangOptions::GCOnly);
533 else if (ObjCEnableGC)
534 Options.setGCMode(LangOptions::HybridGC);
535
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000536 if (ObjCEnableGCBitmapPrint)
537 Options.ObjCGCBitmapPrint = 1;
538
Chris Lattner2c78b872009-04-14 23:22:57 +0000539 Options.setVisibilityMode(SymbolVisibility);
540 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000541}
542
543/// LangStds - Language standards we support.
544enum LangStds {
545 lang_unspecified,
546 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000547 lang_gnu_START,
548 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000549 lang_cxx98, lang_gnucxx98,
550 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000551};
552
553static llvm::cl::opt<LangStds>
554LangStd("std", llvm::cl::desc("Language standard to compile for"),
555 llvm::cl::init(lang_unspecified),
556 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
557 clEnumValN(lang_c89, "c90", "ISO C 1990"),
558 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
559 clEnumValN(lang_c94, "iso9899:199409",
560 "ISO C 1990 with amendment 1"),
561 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000562 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000564 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000566 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000568 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 clEnumValN(lang_gnu99, "gnu9x",
570 "ISO C 1999 with GNU extensions"),
571 clEnumValN(lang_cxx98, "c++98",
572 "ISO C++ 1998 with amendments"),
573 clEnumValN(lang_gnucxx98, "gnu++98",
574 "ISO C++ 1998 with amendments and GNU "
575 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000576 clEnumValN(lang_cxx0x, "c++0x",
577 "Upcoming ISO C++ 200x with amendments"),
578 clEnumValN(lang_gnucxx0x, "gnu++0x",
579 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000580 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 clEnumValEnd));
582
583static llvm::cl::opt<bool>
584NoOperatorNames("fno-operator-names",
585 llvm::cl::desc("Do not treat C++ operator name keywords as "
586 "synonyms for operators"));
587
Anders Carlssonee98ac52007-10-15 02:50:23 +0000588static llvm::cl::opt<bool>
589PascalStrings("fpascal-strings",
590 llvm::cl::desc("Recognize and construct Pascal-style "
591 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000592
593static llvm::cl::opt<bool>
594MSExtensions("fms-extensions",
595 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000596 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000597
598static llvm::cl::opt<bool>
599WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000600 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000601
602static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000603NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000604 llvm::cl::desc("Disallow implicit conversions between "
605 "vectors with a different number of "
606 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000607
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000608static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000609EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000610
611static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000612EnableHeinousExtensions("fheinous-gnu-extensions",
613 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
614 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
615
616static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000617ObjCNonFragileABI("fobjc-nonfragile-abi",
618 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000619
Daniel Dunbard604c402009-02-04 21:19:06 +0000620static llvm::cl::opt<bool>
621EmitAllDecls("femit-all-decls",
622 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000623
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000624// FIXME: This (and all GCC -f options) really come in -f... and
625// -fno-... forms, and additionally support automagic behavior when
626// they are not defined. For example, -fexceptions defaults to on or
627// off depending on the language. We should support this behavior in
628// some form (perhaps just add a facility for distinguishing when an
629// has its default value from when it has been set to its default
630// value).
631static llvm::cl::opt<bool>
632Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000633 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000634
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000635static llvm::cl::opt<bool>
636GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000637 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000638 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000639
640static llvm::cl::opt<bool>
641NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000642 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000643 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000644
Ted Kremenekea644d82008-09-03 21:22:16 +0000645
646
647static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000648Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000649
Chris Lattner16167a62009-03-02 22:11:07 +0000650static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000651TargetFeatures("mattr", llvm::cl::CommaSeparated,
652 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
653
Douglas Gregor26dce442009-03-10 00:06:19 +0000654static llvm::cl::opt<unsigned>
655TemplateDepth("ftemplate-depth", llvm::cl::init(99),
656 llvm::cl::desc("Maximum depth of recursive template "
657 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000658static llvm::cl::opt<bool>
659DollarsInIdents("fdollars-in-identifiers",
660 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000661
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000662
663static llvm::cl::opt<bool>
664OptSize("Os", llvm::cl::desc("Optimize for size"));
665
666static llvm::cl::opt<bool>
667NoCommon("fno-common",
668 llvm::cl::desc("Compile common globals like normal definitions"),
669 llvm::cl::ValueDisallowed);
670
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000671static llvm::cl::opt<std::string>
672MainFileName("main-file-name",
673 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000674
675// It might be nice to add bounds to the CommandLine library directly.
676struct OptLevelParser : public llvm::cl::parser<unsigned> {
677 bool parse(llvm::cl::Option &O, const char *ArgName,
678 const std::string &Arg, unsigned &Val) {
679 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
680 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000681 if (Val > 3)
682 return O.error(": '" + Arg + "' invalid optimization level!");
683 return false;
684 }
685};
686static llvm::cl::opt<unsigned, false, OptLevelParser>
687OptLevel("O", llvm::cl::Prefix,
688 llvm::cl::desc("Optimization level"),
689 llvm::cl::init(0));
690
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000691static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000692PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
693
694static llvm::cl::opt<bool>
695StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000696
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000697static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
698 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000699 // Allow the target to set the default the langauge options as it sees fit.
700 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000701
Chris Lattner6328cc32009-03-03 19:56:18 +0000702 // If there are any -mattr options, pass them to the target for validation and
703 // processing. The driver should have already consolidated all the
704 // target-feature settings and passed them to us in the -mattr list. The
705 // -mattr list is treated by the code generator as a diff against the -mcpu
706 // setting, but the driver should pass all enabled options as "+" settings.
707 // This means that the target should only look at + settings.
Chris Lattner4d417652009-04-13 06:33:49 +0000708 if (!TargetFeatures.empty()) {
Chris Lattner16167a62009-03-02 22:11:07 +0000709 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000710 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
711 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000712 if (Opt != -1) {
713 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000714 fprintf(stderr, "invalid feature '%s'\n",
715 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000716 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000717 fprintf(stderr, "feature '%s': %s\n",
718 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000719 exit(1);
720 }
721 }
722
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 if (LangStd == lang_unspecified) {
724 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000725 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000726 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000728 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 case langkind_c_cpp:
730 case langkind_objc:
731 case langkind_objc_cpp:
732 LangStd = lang_gnu99;
733 break;
734 case langkind_cxx:
735 case langkind_cxx_cpp:
736 case langkind_objcxx:
737 case langkind_objcxx_cpp:
738 LangStd = lang_gnucxx98;
739 break;
740 }
741 }
742
743 switch (LangStd) {
744 default: assert(0 && "Unknown language standard!");
745
746 // Fall through from newer standards to older ones. This isn't really right.
747 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000748 case lang_gnucxx0x:
749 case lang_cxx0x:
750 Options.CPlusPlus0x = 1;
751 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 case lang_gnucxx98:
753 case lang_cxx98:
754 Options.CPlusPlus = 1;
755 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000756 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 // FALL THROUGH.
758 case lang_gnu99:
759 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 Options.C99 = 1;
761 Options.HexFloats = 1;
762 // FALL THROUGH.
763 case lang_gnu89:
764 Options.BCPLComment = 1; // Only for C99/C++.
765 // FALL THROUGH.
766 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000767 Options.Digraphs = 1; // C94, C99, C++.
768 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 case lang_c89:
770 break;
771 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000772
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000773 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
774 Options.GNUMode = LangStd >= lang_gnu_START;
775
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000776 if (Options.CPlusPlus) {
777 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000778 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000779 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000780
Chris Lattnerd658b562008-04-05 06:32:51 +0000781 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
782 Options.ImplicitInt = 1;
783 else
784 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000785
Daniel Dunbard573d262009-04-07 22:13:21 +0000786 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
787 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000788 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000789 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000790 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000791
Chris Lattner802db9b2008-12-05 00:10:44 +0000792 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
793 // even if they are normally on for the target. In GNU modes (e.g.
794 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000795 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000796 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000797 Options.Blocks = 0;
798
Chris Lattner01638a62009-04-19 07:06:52 +0000799 // Default to not accepting '$' in identifiers when preprocessing assembler,
800 // but do accept when preprocessing C. FIXME: these defaults are right for
801 // darwin, are they right everywhere?
802 Options.DollarIdents = LK != langkind_asm_cpp;
803 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000804 Options.DollarIdents = DollarsInIdents;
805
Chris Lattnerae0ee032008-12-04 23:20:07 +0000806 if (PascalStrings.getPosition())
807 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000808 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000809 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000810 if (NoLaxVectorConversions.getPosition())
811 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000812 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000813 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000814 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000815
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000816 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000817 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000818 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000819 Options.Freestanding = Options.NoBuiltin = 1;
820
Chris Lattner810f6d52009-03-13 17:38:01 +0000821 if (EnableHeinousExtensions)
822 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000823
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000824 Options.MathErrno = MathErrno;
825
Douglas Gregor26dce442009-03-10 00:06:19 +0000826 Options.InstantiationDepth = TemplateDepth;
827
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000828 // Override the default runtime if the user requested it.
829 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000830 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000831 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000832 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000833
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000834 if (ObjCNonFragileABI)
835 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000836
837 if (EmitAllDecls)
838 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000839
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000840 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
841 // support.
842 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000843
844 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000845 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000846 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000847
848 assert(PICLevel <= 2 && "Invalid value for -pic-level");
849 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000850
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000851 Options.GNUInline = !Options.C99;
852 // FIXME: This is affected by other options (-fno-inline).
853 Options.NoInline = !OptSize && !OptLevel;
854
855 Options.Static = StaticDefine;
856
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000857 if (MainFileName.getPosition())
858 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000859}
860
861//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000862// Target Triple Processing.
863//===----------------------------------------------------------------------===//
864
865static llvm::cl::opt<std::string>
866TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000867 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000868
Chris Lattner42e67372008-03-05 01:18:20 +0000869static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000870Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000871
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000872static llvm::cl::opt<std::string>
873MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000874 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000875
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000876// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
877// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000878
879// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000880static void HandleMacOSVersionMin(std::string &Triple) {
881 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
882 if (DarwinDashIdx == std::string::npos) {
883 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000884 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000885 exit(1);
886 }
887 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
888
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000889 // Remove the number.
890 Triple.resize(DarwinNumIdx);
891
892 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
893 bool MacOSVersionMinIsInvalid = false;
894 int VersionNum = 0;
895 if (MacOSVersionMin.size() < 4 ||
896 MacOSVersionMin.substr(0, 3) != "10." ||
897 !isdigit(MacOSVersionMin[3])) {
898 MacOSVersionMinIsInvalid = true;
899 } else {
900 const char *Start = MacOSVersionMin.c_str()+3;
901 char *End = 0;
902 VersionNum = (int)strtol(Start, &End, 10);
903
Chris Lattner079f2c462008-09-30 20:30:12 +0000904 // The version number must be in the range 0-9.
905 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
906
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000907 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
908 Triple += llvm::itostr(VersionNum+4);
909
Chris Lattner079f2c462008-09-30 20:30:12 +0000910 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
911 // Add the period piece (.7) to the end of the triple. This gives us
912 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000913 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000914 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
915 MacOSVersionMinIsInvalid = true;
916 }
917 }
918
919 if (MacOSVersionMinIsInvalid) {
920 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000921 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000922 MacOSVersionMin.c_str());
923 exit(1);
924 }
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000925 else if (VersionNum <= 4 &&
926 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
927 fprintf(stderr,
928 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
929 MacOSVersionMin.c_str());
930 exit(1);
931 }
932
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000933}
934
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000935static llvm::cl::opt<std::string>
936IPhoneOSVersionMin("miphoneos-version-min",
937 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
938
939// If -miphoneos-version-min=2.2 is specified, change the triple from being
940// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
941// 9 as the default major Darwin number, and encode the iPhone OS version
942// number in the minor version and revision.
943
944// FIXME: We should have the driver do this instead.
945static void HandleIPhoneOSVersionMin(std::string &Triple) {
946 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
947 if (DarwinDashIdx == std::string::npos) {
948 fprintf(stderr,
949 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
950 exit(1);
951 }
952 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
953
954 // Remove the number.
955 Triple.resize(DarwinNumIdx);
956
957 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
958 bool IPhoneOSVersionMinIsInvalid = false;
959 int VersionNum = 0;
960 if (IPhoneOSVersionMin.size() < 3 ||
961 !isdigit(IPhoneOSVersionMin[0])) {
962 IPhoneOSVersionMinIsInvalid = true;
963 } else {
964 const char *Start = IPhoneOSVersionMin.c_str();
965 char *End = 0;
966 VersionNum = (int)strtol(Start, &End, 10);
967
968 // The version number must be in the range 0-9.
969 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
970
971 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
972 Triple += "9." + llvm::itostr(VersionNum);
973
974 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
975 // Add the period piece (.2) to the end of the triple. This gives us
976 // something like ...-darwin9.2.2
977 Triple += End;
978 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
979 IPhoneOSVersionMinIsInvalid = true;
980 }
981 }
982
983 if (IPhoneOSVersionMinIsInvalid) {
984 fprintf(stderr,
985 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
986 IPhoneOSVersionMin.c_str());
987 exit(1);
988 }
989}
990
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000991/// CreateTargetTriple - Process the various options that affect the target
992/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000993static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000994 // Initialize base triple. If a -triple option has been specified, use
995 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000996 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000997 if (Triple.empty())
998 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000999
Chris Lattner6fd9fa12008-03-09 01:35:13 +00001000 // If -arch foo was specified, remove the architecture from the triple we have
1001 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +00001002
1003 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001004 if (!Arch.empty()) {
1005 // Decompose the base triple into "arch" and suffix.
1006 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +00001007
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001008 if (FirstDashIdx == std::string::npos) {
1009 fprintf(stderr,
1010 "Malformed target triple: \"%s\" ('-' could not be found).\n",
1011 Triple.c_str());
1012 exit(1);
1013 }
Chris Lattner37e217c2009-03-24 16:18:41 +00001014
1015 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1016 if (Arch == "ppc")
1017 Arch = "powerpc";
1018 else if (Arch == "ppc64")
1019 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +00001020
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001021 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1022 }
1023
1024 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1025 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +00001026 if (!MacOSVersionMin.empty())
1027 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +00001028 else if (!IPhoneOSVersionMin.empty())
1029 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenekae360762007-12-03 22:06:55 +00001030
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001031 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +00001032}
1033
1034//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +00001035// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +00001036//===----------------------------------------------------------------------===//
1037
Douglas Gregore1d918e2009-04-10 23:10:45 +00001038static bool InitializeSourceManager(Preprocessor &PP,
1039 const std::string &InFile) {
1040 // Figure out where to get and map in the main file.
1041 SourceManager &SourceMgr = PP.getSourceManager();
1042 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001043
1044 if (EmptyInputOnly) {
1045 const char *EmptyStr = "";
1046 llvm::MemoryBuffer *SB =
1047 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1048 SourceMgr.createMainFileIDForMemBuffer(SB);
1049 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001050 const FileEntry *File = FileMgr.getFile(InFile);
1051 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1052 if (SourceMgr.getMainFileID().isInvalid()) {
1053 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1054 << InFile.c_str();
1055 return true;
1056 }
1057 } else {
1058 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1059
1060 // If stdin was empty, SB is null. Cons up an empty memory
1061 // buffer now.
1062 if (!SB) {
1063 const char *EmptyStr = "";
1064 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1065 }
1066
1067 SourceMgr.createMainFileIDForMemBuffer(SB);
1068 if (SourceMgr.getMainFileID().isInvalid()) {
1069 PP.getDiagnostics().Report(FullSourceLoc(),
1070 diag::err_fe_error_reading_stdin);
1071 return true;
1072 }
1073 }
1074
1075 return false;
1076}
1077
Chris Lattneraa391972008-04-19 23:09:31 +00001078
Chris Lattnere116ccf2009-04-21 05:40:52 +00001079//===----------------------------------------------------------------------===//
1080// Preprocessor Initialization
1081//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001082
Chris Lattnere116ccf2009-04-21 05:40:52 +00001083// FIXME: Preprocessor builtins to support.
1084// -A... - Play with #assertions
1085// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001086
Chris Lattnere116ccf2009-04-21 05:40:52 +00001087static llvm::cl::list<std::string>
1088D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1089 llvm::cl::desc("Predefine the specified macro"));
1090static llvm::cl::list<std::string>
1091U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1092 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001093
Chris Lattnere116ccf2009-04-21 05:40:52 +00001094static llvm::cl::list<std::string>
1095ImplicitIncludes("include", llvm::cl::value_desc("file"),
1096 llvm::cl::desc("Include file before parsing"));
1097static llvm::cl::list<std::string>
1098ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1099 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001100
Chris Lattnere116ccf2009-04-21 05:40:52 +00001101static llvm::cl::opt<std::string>
1102ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1103 llvm::cl::desc("Include precompiled header file"));
1104
1105static llvm::cl::opt<std::string>
1106ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1107 llvm::cl::desc("Include file before parsing"));
1108
Reid Spencer5f016e22007-07-11 17:01:13 +00001109
1110//===----------------------------------------------------------------------===//
1111// Preprocessor include path information.
1112//===----------------------------------------------------------------------===//
1113
1114// This tool exports a large number of command line options to control how the
1115// preprocessor searches for header files. At root, however, the Preprocessor
1116// object takes a very simple interface: a list of directories to search for
1117//
1118// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001119// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001120//
Reid Spencer5f016e22007-07-11 17:01:13 +00001121
1122static llvm::cl::opt<bool>
1123nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1124
1125// Various command line options. These four add directories to each chain.
1126static llvm::cl::list<std::string>
1127F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1128 llvm::cl::desc("Add directory to framework include search path"));
1129static llvm::cl::list<std::string>
1130I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1131 llvm::cl::desc("Add directory to include search path"));
1132static llvm::cl::list<std::string>
1133idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1134 llvm::cl::desc("Add directory to AFTER include search path"));
1135static llvm::cl::list<std::string>
1136iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1137 llvm::cl::desc("Add directory to QUOTE include search path"));
1138static llvm::cl::list<std::string>
1139isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1140 llvm::cl::desc("Add directory to SYSTEM include search path"));
1141
1142// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1143static llvm::cl::list<std::string>
1144iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1145 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1146static llvm::cl::list<std::string>
1147iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1148 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1149static llvm::cl::list<std::string>
1150iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1151 llvm::cl::Prefix,
1152 llvm::cl::desc("Set directory to include search path with prefix"));
1153
Chris Lattner0c946412007-08-26 17:47:35 +00001154static llvm::cl::opt<std::string>
1155isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1156 llvm::cl::desc("Set the system root directory (usually /)"));
1157
Reid Spencer5f016e22007-07-11 17:01:13 +00001158// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001159
Reid Spencer5f016e22007-07-11 17:01:13 +00001160/// InitializeIncludePaths - Process the -I options and set them in the
1161/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001162void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1163 FileManager &FM, const LangOptions &Lang) {
1164 InitHeaderSearch Init(Headers, Verbose, isysroot);
1165
Ted Kremenekf3721112008-05-31 00:27:00 +00001166 // Handle -I... and -F... options, walking the lists in parallel.
1167 unsigned Iidx = 0, Fidx = 0;
1168 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1169 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001170 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001171 ++Iidx;
1172 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001173 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001174 ++Fidx;
1175 }
1176 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001177
Ted Kremenekf3721112008-05-31 00:27:00 +00001178 // Consume what's left from whatever list was longer.
1179 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001180 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001181 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001182 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001183
1184 // Handle -idirafter... options.
1185 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001186 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1187 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001188
1189 // Handle -iquote... options.
1190 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001191 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001192
1193 // Handle -isystem... options.
1194 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001195 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001196
1197 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1198 // parallel, processing the values in order of occurance to get the right
1199 // prefixes.
1200 {
1201 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1202 unsigned iprefix_idx = 0;
1203 unsigned iwithprefix_idx = 0;
1204 unsigned iwithprefixbefore_idx = 0;
1205 bool iprefix_done = iprefix_vals.empty();
1206 bool iwithprefix_done = iwithprefix_vals.empty();
1207 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1208 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1209 if (!iprefix_done &&
1210 (iwithprefix_done ||
1211 iprefix_vals.getPosition(iprefix_idx) <
1212 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1213 (iwithprefixbefore_done ||
1214 iprefix_vals.getPosition(iprefix_idx) <
1215 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1216 Prefix = iprefix_vals[iprefix_idx];
1217 ++iprefix_idx;
1218 iprefix_done = iprefix_idx == iprefix_vals.size();
1219 } else if (!iwithprefix_done &&
1220 (iwithprefixbefore_done ||
1221 iwithprefix_vals.getPosition(iwithprefix_idx) <
1222 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001223 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1224 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 ++iwithprefix_idx;
1226 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1227 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001228 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1229 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 ++iwithprefixbefore_idx;
1231 iwithprefixbefore_done =
1232 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1233 }
1234 }
1235 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001236
Nico Weber0fca0222008-08-22 09:25:22 +00001237 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001238
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001239 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001240 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001241 llvm::sys::Path::GetMainExecutable(Argv0,
1242 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001243 if (!MainExecutablePath.isEmpty()) {
1244 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1245 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001246
1247 // Get foo/lib/clang/1.0/include
1248 //
1249 // FIXME: Don't embed version here.
1250 MainExecutablePath.appendComponent("lib");
1251 MainExecutablePath.appendComponent("clang");
1252 MainExecutablePath.appendComponent("1.0");
1253 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001254
1255 // We pass true to ignore sysroot so that we *always* look for clang headers
1256 // relative to our executable, never relative to -isysroot.
1257 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1258 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001259 }
1260
Nico Weber0fca0222008-08-22 09:25:22 +00001261 if (!nostdinc)
1262 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263
1264 // Now that we have collected all of the include paths, merge them all
1265 // together and tell the preprocessor about them.
1266
Nico Weber0fca0222008-08-22 09:25:22 +00001267 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001268}
1269
Chris Lattnere116ccf2009-04-21 05:40:52 +00001270void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1271{
1272 // Add macros from the command line.
1273 unsigned d = 0, D = D_macros.size();
1274 unsigned u = 0, U = U_macros.size();
1275 while (d < D || u < U) {
1276 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1277 InitOpts.addMacroDef(D_macros[d++]);
1278 else
1279 InitOpts.addMacroUndef(U_macros[u++]);
1280 }
1281
1282 // If -imacros are specified, include them now. These are processed before
1283 // any -include directives.
1284 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1285 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1286
1287 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1288 // We want to add these paths to the predefines buffer in order, make a
1289 // temporary vector to sort by their occurrence.
1290 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1291
1292 if (!ImplicitIncludePTH.empty())
1293 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1294 &ImplicitIncludePTH));
1295 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1296 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1297 &ImplicitIncludes[i]));
1298 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1299
1300
1301 // Now that they are ordered by position, add to the predefines buffer.
1302 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1303 std::string *Ptr = OrderedPaths[i].second;
1304 if (!ImplicitIncludes.empty() &&
1305 Ptr >= &ImplicitIncludes[0] &&
1306 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1307 InitOpts.addInclude(*Ptr, false);
1308 } else {
1309 assert(Ptr == &ImplicitIncludePTH);
1310 InitOpts.addInclude(*Ptr, true);
1311 }
1312 }
1313 }
1314}
1315
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001316//===----------------------------------------------------------------------===//
1317// Driver PreprocessorFactory - For lazily generating preprocessors ...
1318//===----------------------------------------------------------------------===//
1319
1320namespace {
1321class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001322 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001323 Diagnostic &Diags;
1324 const LangOptions &LangInfo;
1325 TargetInfo &Target;
1326 SourceManager &SourceMgr;
1327 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001328
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001329public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001330 DriverPreprocessorFactory(const std::string &infile,
1331 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001332 TargetInfo &target, SourceManager &SM,
1333 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001334 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001335 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek339b9c22008-04-17 22:31:54 +00001336
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001337
1338 virtual ~DriverPreprocessorFactory() {}
1339
1340 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001341 llvm::OwningPtr<PTHManager> PTHMgr;
1342
Ted Kremenek748d5d62009-03-20 00:26:38 +00001343 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1344 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1345 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001346 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001347 }
1348
Ted Kremenek72b1b152009-01-15 18:47:46 +00001349 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001350 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1351 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001352 PTHMgr.reset(PTHManager::Create(x, &Diags,
1353 TokenCache.empty() ? Diagnostic::Error
1354 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001355 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001356
Ted Kremenek22f0d092009-03-22 06:42:39 +00001357 if (Diags.hasErrorOccurred())
1358 exit(1);
1359
Ted Kremenek72b1b152009-01-15 18:47:46 +00001360 // Create the Preprocessor.
1361 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1362 SourceMgr, HeaderInfo,
1363 PTHMgr.get()));
1364
1365 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1366 // That argument is used as the IdentifierInfoLookup argument to
1367 // IdentifierTable's ctor.
1368 if (PTHMgr) {
1369 PTHMgr->setPreprocessor(PP.get());
1370 PP->setPTHManager(PTHMgr.take());
1371 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001372
Chris Lattnere116ccf2009-04-21 05:40:52 +00001373 PreprocessorInitOptions InitOpts;
1374 InitializePreprocessorInitOptions(InitOpts);
1375 if (InitializePreprocessor(*PP, InFile, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001376 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001377
Daniel Dunbar750c3582008-10-24 22:12:41 +00001378 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001379 if (ProgAction != PrintPreprocessedInput) {
1380 std::string ErrStr;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001381 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001382 if (!DFG && !ErrStr.empty()) {
1383 fprintf(stderr, "%s", ErrStr.c_str());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001384 return 0;
Daniel Dunbar750c3582008-10-24 22:12:41 +00001385 }
1386 }
1387
Douglas Gregore1d918e2009-04-10 23:10:45 +00001388 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001389 }
1390};
1391}
Reid Spencer5f016e22007-07-11 17:01:13 +00001392
Reid Spencer5f016e22007-07-11 17:01:13 +00001393//===----------------------------------------------------------------------===//
1394// Basic Parser driver
1395//===----------------------------------------------------------------------===//
1396
Chris Lattner51574ea2008-04-19 23:25:44 +00001397static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001399 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001400
1401 // Parsing the specified input file.
1402 P.ParseTranslationUnit();
1403 delete PA;
1404}
1405
1406//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001407// Code generation options
1408//===----------------------------------------------------------------------===//
1409
1410static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001411GenerateDebugInfo("g",
1412 llvm::cl::desc("Generate source level debug information"));
1413
Daniel Dunbara034ba82009-02-17 19:47:34 +00001414static llvm::cl::opt<std::string>
1415TargetCPU("mcpu",
1416 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1417
Chris Lattner7afae712009-03-16 18:41:18 +00001418static void InitializeCompileOptions(CompileOptions &Opts,
1419 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001420 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001421 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001422 if (OptSize) {
1423 // -Os implies -O2
1424 // FIXME: Diagnose conflicting options.
1425 Opts.OptimizationLevel = 2;
1426 } else {
1427 Opts.OptimizationLevel = OptLevel;
1428 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001429
1430 // FIXME: There are llvm-gcc options to control these selectively.
1431 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1432 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001433 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001434
1435#ifdef NDEBUG
1436 Opts.VerifyModule = 0;
1437#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001438
1439 Opts.CPU = TargetCPU;
1440 Opts.Features.insert(Opts.Features.end(),
1441 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001442
Chris Lattnerbd360642009-03-26 05:00:52 +00001443 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1444
Chris Lattner44502662009-02-18 01:23:44 +00001445 // Handle -ftime-report.
1446 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001447}
1448
1449//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001450// Fix-It Options
1451//===----------------------------------------------------------------------===//
1452static llvm::cl::list<ParsedSourceLocation>
1453FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1454 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1455
1456//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001457// -dump-build-information Stuff
1458//===----------------------------------------------------------------------===//
1459
1460static llvm::cl::opt<std::string>
1461DumpBuildInformation("dump-build-information",
1462 llvm::cl::value_desc("filename"),
1463 llvm::cl::desc("output a dump of some build information to a file"));
1464
1465static llvm::raw_ostream *BuildLogFile = 0;
1466
1467/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1468/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1469namespace {
1470class LoggingDiagnosticClient : public DiagnosticClient {
1471 llvm::OwningPtr<DiagnosticClient> Chain1;
1472 llvm::OwningPtr<DiagnosticClient> Chain2;
1473public:
1474
1475 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1476 // Output diags both where requested...
1477 Chain1.reset(Normal);
1478 // .. and to our log file.
1479 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1480 !NoShowColumn,
1481 !NoCaretDiagnostics,
1482 !NoShowLocation,
1483 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001484 PrintDiagnosticOption,
1485 !NoDiagnosticsFixIt));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001486 }
1487
1488 virtual void setLangOptions(const LangOptions *LO) {
1489 Chain1->setLangOptions(LO);
1490 Chain2->setLangOptions(LO);
1491 }
1492
1493 virtual bool IncludeInDiagnosticCounts() const {
1494 return Chain1->IncludeInDiagnosticCounts();
1495 }
1496
1497 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1498 const DiagnosticInfo &Info) {
1499 Chain1->HandleDiagnostic(DiagLevel, Info);
1500 Chain2->HandleDiagnostic(DiagLevel, Info);
1501 }
1502};
1503} // end anonymous namespace.
1504
1505static void SetUpBuildDumpLog(unsigned argc, char **argv,
1506 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1507
1508 std::string ErrorInfo;
1509 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1510 ErrorInfo);
1511
1512 if (!ErrorInfo.empty()) {
1513 llvm::errs() << "error opening -dump-build-information file '"
1514 << DumpBuildInformation << "', option ignored!\n";
1515 delete BuildLogFile;
1516 BuildLogFile = 0;
1517 DumpBuildInformation = "";
1518 return;
1519 }
1520
1521 (*BuildLogFile) << "clang-cc command line arguments: ";
1522 for (unsigned i = 0; i != argc; ++i)
1523 (*BuildLogFile) << argv[i] << ' ';
1524 (*BuildLogFile) << '\n';
1525
1526 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1527 // the diagnostic producers and the normal receiver.
1528 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1529}
1530
1531
1532
1533//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001534// Main driver
1535//===----------------------------------------------------------------------===//
1536
Ted Kremenekdb094a22007-12-05 18:27:04 +00001537/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001538/// action. These consumers can operate on both ASTs that are freshly
1539/// parsed from source files as well as those deserialized from Bitcode.
1540/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001541static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001542 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001543 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001544 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001545 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001546 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001547 default:
1548 return NULL;
1549
1550 case ASTPrint:
1551 return CreateASTPrinter();
1552
1553 case ASTDump:
Douglas Gregor609e72f2009-04-26 02:02:08 +00001554 return CreateASTDumper(false);
1555
1556 case ASTDumpFull:
1557 return CreateASTDumper(true);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001558
1559 case ASTView:
1560 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001561
Chris Lattner8a5c8092009-02-18 01:20:05 +00001562 case PrintDeclContext:
1563 return CreateDeclContextPrinter();
1564
1565 case EmitHTML:
1566 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001567
Chris Lattner8a5c8092009-02-18 01:20:05 +00001568 case InheritanceView:
1569 return CreateInheritanceViewer(InheritanceViewCls);
1570
Chris Lattner8a5c8092009-02-18 01:20:05 +00001571 case EmitAssembly:
1572 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001573 case EmitBC:
1574 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001575 BackendAction Act;
1576 if (ProgAction == EmitAssembly)
1577 Act = Backend_EmitAssembly;
1578 else if (ProgAction == EmitLLVM)
1579 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001580 else if (ProgAction == EmitLLVMOnly)
1581 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001582 else
1583 Act = Backend_EmitBC;
1584
1585 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001586 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001587 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001588 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001589 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001590
Douglas Gregor2cf26342009-04-09 22:27:44 +00001591 case GeneratePCH:
Chris Lattner0b1fb982009-04-10 17:15:23 +00001592 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001593
Chris Lattner8a5c8092009-02-18 01:20:05 +00001594 case RewriteObjC:
1595 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001596
Chris Lattner8a5c8092009-02-18 01:20:05 +00001597 case RewriteBlocks:
1598 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1599
1600 case RunAnalysis:
1601 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001602 }
1603}
1604
Reid Spencer5f016e22007-07-11 17:01:13 +00001605/// ProcessInputFile - Process a single input file with the specified state.
1606///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001607static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001608 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001609 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001610 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001611 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001612 bool CompleteTranslationUnit = true;
Douglas Gregor558cb562009-04-02 01:08:08 +00001613
Ted Kremenek85888962008-10-21 00:54:44 +00001614 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001616 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1617 PP.getFileManager(), PP.getLangOptions(),
1618 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001619
1620 if (!Consumer) {
1621 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001622 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001623 return;
1624 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001625
Douglas Gregorf807fe02009-04-14 16:27:31 +00001626 if (ProgAction == GeneratePCH)
1627 CompleteTranslationUnit = false;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001628 break;
1629
Chris Lattnerc106c102008-10-12 05:03:36 +00001630 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001631 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001632 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001633 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001634 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001635 RawLex.SetKeepWhitespaceMode(true);
1636
1637 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001638 RawLex.LexFromRawLexer(RawTok);
1639 while (RawTok.isNot(tok::eof)) {
1640 PP.DumpToken(RawTok, true);
1641 fprintf(stderr, "\n");
1642 RawLex.LexFromRawLexer(RawTok);
1643 }
1644 ClearSourceMgr = true;
1645 break;
1646 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001648 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001649 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001650 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001651 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 do {
1653 PP.Lex(Tok);
1654 PP.DumpToken(Tok, true);
1655 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001656 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001657 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 break;
1659 }
1660 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001661 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001662 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001664 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 do {
1666 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001667 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001668 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 break;
1670 }
Ted Kremenek85888962008-10-21 00:54:44 +00001671
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001672 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001673 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001674 CacheTokens(PP, OutputFile);
1675 ClearSourceMgr = true;
1676 break;
1677 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001678
Chris Lattner47099742009-02-18 01:51:21 +00001679 case PrintPreprocessedInput: { // -E mode.
1680 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001681 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001682 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 break;
Chris Lattner47099742009-02-18 01:51:21 +00001684 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001685
Chris Lattner47099742009-02-18 01:51:21 +00001686 case ParseNoop: { // -parse-noop
1687 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001688 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001689 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 break;
Chris Lattner47099742009-02-18 01:51:21 +00001691 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001692
Chris Lattner47099742009-02-18 01:51:21 +00001693 case ParsePrintCallbacks: {
1694 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001695 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001696 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 break;
Chris Lattner47099742009-02-18 01:51:21 +00001698 }
1699
1700 case ParseSyntaxOnly: { // -fsyntax-only
1701 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001702 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001703 break;
Chris Lattner47099742009-02-18 01:51:21 +00001704 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001705
1706 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001707 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001708 ClearSourceMgr = true;
1709 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001710
Chris Lattner47099742009-02-18 01:51:21 +00001711 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001712 DoRewriteTest(PP, InFile, OutputFile);
1713 ClearSourceMgr = true;
1714 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001715 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001716
1717 case FixIt:
1718 llvm::TimeRegion Timer(ClangFrontendTimer);
1719 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001720 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001721 PP.getSourceManager(),
1722 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001723 break;
Chris Lattner47099742009-02-18 01:51:21 +00001724 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001725
1726 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001727 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001728
Douglas Gregor26df2f02009-04-02 19:05:20 +00001729 if (FixItAtLocations.size() > 0) {
1730 // Even without the "-fixit" flag, with may have some specific
1731 // locations where the user has requested fixes. Process those
1732 // locations now.
1733 if (!FixItRewrite)
1734 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001735 PP.getSourceManager(),
1736 PP.getLangOptions());
Douglas Gregor26df2f02009-04-02 19:05:20 +00001737
1738 bool AddedFixitLocation = false;
1739 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1740 Idx != Last; ++Idx) {
1741 RequestedSourceLocation Requested;
1742 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1743 Requested)) {
1744 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1745 FixItAtLocations[Idx].FileName.c_str());
1746 } else {
1747 FixItRewrite->addFixItLocation(Requested);
1748 AddedFixitLocation = true;
1749 }
1750 }
1751
1752 if (!AddedFixitLocation) {
1753 // All of the fix-it locations were bad. Don't fix anything.
1754 delete FixItRewrite;
1755 FixItRewrite = 0;
1756 }
1757 }
1758
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001759 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1760 PP.getSourceManager(),
1761 PP.getTargetInfo(),
1762 PP.getIdentifierTable(),
1763 PP.getSelectorTable(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001764 /* FreeMemory = */ !DisableFree,
1765 /* size_reserve = */0,
1766 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001767
Douglas Gregor2cf26342009-04-09 22:27:44 +00001768 if (!ImplicitIncludePCH.empty()) {
1769 // The user has asked us to include a precompiled header. Load
1770 // the precompiled header into the AST context.
Douglas Gregore1d918e2009-04-10 23:10:45 +00001771 llvm::OwningPtr<PCHReader> Reader(new PCHReader(PP, *ContextOwner.get()));
1772 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1773 case PCHReader::Success: {
1774 // Attach the PCH reader to the AST context as an external AST
1775 // source, so that declarations will be deserialized from the
1776 // PCH file as needed.
1777 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
1778 ContextOwner->setExternalSource(Source);
1779
1780 // Clear out the predefines buffer, because all of the
1781 // predefines are already in the PCH file.
1782 PP.setPredefines("");
1783 break;
1784 }
1785
1786 case PCHReader::Failure:
1787 // Unrecoverable failure: don't even try to process the input
1788 // file.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001789 return;
1790
Douglas Gregore1d918e2009-04-10 23:10:45 +00001791 case PCHReader::IgnorePCH:
1792 // No suitable PCH file could be found. Just ignore the
1793 // -include-pch option entirely.
Douglas Gregor2deaea32009-04-22 18:49:13 +00001794
1795 // We delayed the initialization of builtins in the hope of
1796 // loading the PCH file. Since the PCH file could not be
1797 // loaded, initialize builtins now.
1798 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001799 break;
1800 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001801
1802 // Finish preprocessor initialization. We do this now (rather
1803 // than earlier) because this initialization creates new source
1804 // location entries in the source manager, which must come after
1805 // the source location entries for the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +00001806 if (InitializeSourceManager(PP, InFile))
Douglas Gregor14f79002009-04-10 03:52:48 +00001807 return;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001808 }
1809
Douglas Gregorf807fe02009-04-14 16:27:31 +00001810 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
1811 CompleteTranslationUnit);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001812
Douglas Gregor558cb562009-04-02 01:08:08 +00001813 if (FixItRewrite)
1814 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1815
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001816 // If in -disable-free mode, don't deallocate these when they go out of
1817 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001818 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001819 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001820 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001821
1822 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001823 if (CheckDiagnostics(PP))
1824 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001825
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001827 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 PP.PrintStats();
1829 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001830 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001831 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 fprintf(stderr, "\n");
1833 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001834
1835 // For a multi-file compilation, some things are ok with nuking the source
1836 // manager tables, other require stable fileid/macroid's across multiple
1837 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001838 if (ClearSourceMgr)
1839 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001840
1841 if (DisableFree)
1842 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001843}
1844
1845static llvm::cl::list<std::string>
1846InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1847
Reid Spencer5f016e22007-07-11 17:01:13 +00001848int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001850 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001851 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001852 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001853
Chris Lattner47099742009-02-18 01:51:21 +00001854 if (TimeReport)
1855 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1856
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 // If no input was specified, read from stdin.
1858 if (InputFilenames.empty())
1859 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001860
Ted Kremenek31e703b2007-12-11 23:28:38 +00001861 // Create the diagnostic client for reporting errors or for
1862 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001863 llvm::OwningPtr<DiagnosticClient> DiagClient;
1864 if (VerifyDiagnostics) {
1865 // When checking diagnostics, just buffer them up.
1866 DiagClient.reset(new TextDiagnosticBuffer());
1867 if (InputFilenames.size() != 1) {
1868 fprintf(stderr, "-verify only works on single input files for now.\n");
1869 return 1;
1870 }
1871 if (!HTMLDiag.empty()) {
1872 fprintf(stderr, "-verify and -html-diags don't work together\n");
1873 return 1;
1874 }
1875 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001876 // Print diagnostics to stderr by default.
Chris Lattner409d4e72009-04-17 20:40:01 +00001877 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00001878 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001879 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001880 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00001881 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001882 PrintDiagnosticOption,
1883 !NoDiagnosticsFixIt));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001884 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00001885 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001887
1888 if (!DumpBuildInformation.empty()) {
1889 if (!HTMLDiag.empty()) {
1890 fprintf(stderr,
1891 "-dump-build-information and -html-diags don't work together\n");
1892 return 1;
1893 }
1894
1895 SetUpBuildDumpLog(argc, argv, DiagClient);
1896 }
1897
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001898
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001900 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001901 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001902 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001903
Chris Lattner4f037832007-12-05 23:24:17 +00001904 // -I- is a deprecated GCC feature, scan for it and reject it.
1905 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1906 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001907 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001908 I_dirs.erase(I_dirs.begin()+i);
1909 --i;
1910 }
1911 }
Chris Lattner11215192008-03-14 06:12:05 +00001912
1913 // Get information about the target being compiled for.
1914 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001915 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1916
Chris Lattner11215192008-03-14 06:12:05 +00001917 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001918 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1919 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001920 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001921 }
Chris Lattner4f037832007-12-05 23:24:17 +00001922
Daniel Dunbard4270232009-01-20 23:17:32 +00001923 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001924 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001925
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001926 llvm::OwningPtr<SourceManager> SourceMgr;
1927
Chris Lattner2c78b872009-04-14 23:22:57 +00001928 // Create a file manager object to provide access to and cache the filesystem.
1929 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001930
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001932 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001933
Chris Lattnerf63aea32009-03-04 21:40:56 +00001934 /// Create a SourceManager object. This tracks and owns all the file
1935 /// buffers allocated to a translation unit.
1936 if (!SourceMgr)
1937 SourceMgr.reset(new SourceManager());
1938 else
1939 SourceMgr->clearIDTables();
1940
1941 // Initialize language options, inferring file types from input filenames.
1942 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00001943 DiagClient->setLangOptions(&LangInfo);
Chris Lattner2c78b872009-04-14 23:22:57 +00001944
Chris Lattnerf63aea32009-03-04 21:40:56 +00001945 InitializeBaseLanguage();
1946 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001947 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001948 InitializeLanguageStandard(LangInfo, LK, Target.get());
1949
1950 // Process the -I options and set them in the HeaderInfo.
1951 HeaderSearch HeaderInfo(FileMgr);
1952
Chris Lattner2c78b872009-04-14 23:22:57 +00001953
Chris Lattnerf63aea32009-03-04 21:40:56 +00001954 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1955
1956 // Set up the preprocessor with these options.
1957 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1958 *SourceMgr.get(), HeaderInfo);
1959
1960 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1961
1962 if (!PP)
1963 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001964
Douglas Gregore1d918e2009-04-10 23:10:45 +00001965 if (ImplicitIncludePCH.empty() &&
1966 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregor14f79002009-04-10 03:52:48 +00001967 continue;
1968
Chris Lattner409d4e72009-04-17 20:40:01 +00001969 if (!HTMLDiag.empty())
1970 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00001971
1972 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001973 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001974
Chris Lattner40469652009-04-17 20:16:08 +00001975 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00001976 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 }
Chris Lattner11215192008-03-14 06:12:05 +00001978
Mike Stump007f2a92009-01-28 02:43:35 +00001979 if (Verbose)
1980 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1981 " hosted on " LLVM_HOSTTRIPLE "\n");
1982
Ted Kremenek7a08e282008-08-07 18:13:12 +00001983 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1985 (NumDiagnostics == 1 ? "" : "s"));
1986
1987 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 FileMgr.PrintStats();
1989 fprintf(stderr, "\n");
1990 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001991
1992 delete ClangFrontendTimer;
1993 delete BuildLogFile;
Reid Spencer5f016e22007-07-11 17:01:13 +00001994
Daniel Dunbar276373d2008-10-27 22:10:13 +00001995 // If verifying diagnostics and we reached here, all is well.
1996 if (VerifyDiagnostics)
1997 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001998
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001999 // Managed static deconstruction. Useful for making things like
2000 // -time-passes usable.
2001 llvm::llvm_shutdown();
2002
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002003 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002004}