blob: 0b5a6d35a6e576f7ecf7fa4b1b037dde965604e8 [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//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000017
Daniel Dunbar0498cfc2009-11-10 19:51:53 +000018#include "Options.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000019#include "clang/AST/ASTConsumer.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclGroup.h"
23#include "clang/Analysis/PathDiagnostic.h"
24#include "clang/Basic/FileManager.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Basic/Version.h"
28#include "clang/CodeGen/ModuleBuilder.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000029#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +000030#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000031#include "clang/Frontend/AnalysisConsumer.h"
Daniel Dunbardbf75fe2009-11-11 08:13:24 +000032#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000033#include "clang/Frontend/CommandLineSourceLoc.h"
Daniel Dunbare29709f2009-11-09 20:55:08 +000034#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbar0e0bae82009-11-11 21:43:12 +000035#include "clang/Frontend/DependencyOutputOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000036#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000037#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000038#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000039#include "clang/Frontend/PathDiagnosticClients.h"
40#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000041#include "clang/Frontend/PreprocessorOutputOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000042#include "clang/Frontend/TextDiagnosticBuffer.h"
43#include "clang/Frontend/TextDiagnosticPrinter.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000044#include "clang/Frontend/Utils.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000045#include "clang/Lex/HeaderSearch.h"
46#include "clang/Lex/LexDiagnostic.h"
47#include "clang/Parse/Parser.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000048#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000049#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000050#include "clang/Sema/SemaDiagnostic.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000051#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000053#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000055#include "llvm/ADT/StringMap.h"
Daniel Dunbar227b2382009-11-09 22:45:57 +000056#include "llvm/ADT/StringSwitch.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000057#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000058#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000059#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000060#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000061#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000062#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000063#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000064#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000065#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000066#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000067#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000068#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000069#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000070#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000071#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000072#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000073# include <sys/types.h>
74#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000075
Reid Spencer5f016e22007-07-11 17:01:13 +000076using namespace clang;
77
78//===----------------------------------------------------------------------===//
79// Global options.
80//===----------------------------------------------------------------------===//
81
Chris Lattner47099742009-02-18 01:51:21 +000082/// ClangFrontendTimer - The front-end activities should charge time to it with
83/// TimeRegion. The -ftime-report option controls whether this will do
84/// anything.
85llvm::Timer *ClangFrontendTimer = 0;
86
Reid Spencer5f016e22007-07-11 17:01:13 +000087static llvm::cl::opt<bool>
88Verbose("v", llvm::cl::desc("Enable verbose output"));
89static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +000090Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +000091 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000092static llvm::cl::opt<bool>
93DisableFree("disable-free",
94 llvm::cl::desc("Disable freeing of memory on exit"),
95 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +000096static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +000097EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +000098 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +000099
100enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000101 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000102 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000103 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000104 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000105 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000106 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000107 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000109 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000110 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000111 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000112 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000113 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000114 ASTDump, // Parse ASTs and dump them.
115 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000116 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000117 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 ParsePrintCallbacks, // Parse and print each callback.
119 ParseSyntaxOnly, // Parse and perform semantic analysis.
120 ParseNoop, // Parse with noop callbacks.
121 RunPreprocessorOnly, // Just lex, no output.
122 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000123 DumpTokens, // Dump out preprocessed tokens.
124 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000125 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000126 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000127 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000128 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000129};
130
Mike Stump1eb44332009-09-09 15:08:12 +0000131static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000132ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
133 llvm::cl::init(ParseSyntaxOnly),
134 llvm::cl::values(
135 clEnumValN(RunPreprocessorOnly, "Eonly",
136 "Just run preprocessor, no output (for timings)"),
137 clEnumValN(PrintPreprocessedInput, "E",
138 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000139 clEnumValN(DumpRawTokens, "dump-raw-tokens",
140 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000141 clEnumValN(RunAnalysis, "analyze",
142 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000143 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 "Run preprocessor, dump internal rep of tokens"),
145 clEnumValN(ParseNoop, "parse-noop",
146 "Run parser with noop callbacks (for timings)"),
147 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
148 "Run parser and perform semantic analysis"),
149 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
150 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000151 clEnumValN(EmitHTML, "emit-html",
152 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000153 clEnumValN(ASTPrint, "ast-print",
154 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000155 clEnumValN(ASTPrintXML, "ast-print-xml",
156 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000157 clEnumValN(ASTDump, "ast-dump",
158 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000159 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000160 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000161 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000162 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000163 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
164 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000165 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000166 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000167 clEnumValN(GeneratePCH, "emit-pch",
168 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000169 clEnumValN(EmitAssembly, "S",
170 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000172 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000173 clEnumValN(EmitBC, "emit-llvm-bc",
174 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000175 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
176 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000177 clEnumValN(RewriteTest, "rewrite-test",
178 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000179 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000180 "Rewrite ObjC into C (code rewriter example)"),
181 clEnumValN(RewriteMacros, "rewrite-macros",
182 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000183 clEnumValN(RewriteBlocks, "rewrite-blocks",
184 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000185 clEnumValN(FixIt, "fixit",
186 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 clEnumValEnd));
188
Ted Kremenekccc76472007-12-19 19:47:59 +0000189
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000190enum CodeCompletionPrinter {
191 CCP_Debug,
192 CCP_CIndex
193};
194
Douglas Gregorb657f112009-09-22 21:11:38 +0000195static llvm::cl::opt<ParsedSourceLocation>
196CodeCompletionAt("code-completion-at",
197 llvm::cl::value_desc("file:line:column"),
198 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000199
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000200static llvm::cl::opt<CodeCompletionPrinter>
201CodeCompletionPrinter("code-completion-printer",
202 llvm::cl::desc("Choose output type:"),
203 llvm::cl::init(CCP_Debug),
204 llvm::cl::values(
205 clEnumValN(CCP_Debug, "debug",
206 "Debug code-completion results"),
207 clEnumValN(CCP_CIndex, "cindex",
208 "Code-completion results for the CIndex library"),
209 clEnumValEnd));
210
211static llvm::cl::opt<bool>
212CodeCompletionWantsMacros("code-completion-macros",
213 llvm::cl::desc("Include macros in code-completion results"));
214
Douglas Gregor81b747b2009-09-17 21:32:03 +0000215/// \brief Buld a new code-completion consumer that prints the results of
216/// code completion to standard output.
217static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000218 switch (CodeCompletionPrinter.getValue()) {
219 case CCP_Debug:
220 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
221 llvm::outs());
222
223 case CCP_CIndex:
224 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
225 llvm::outs());
226 };
227
228 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000229}
230
Ted Kremenekc2e72992008-12-02 19:57:31 +0000231//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000232// C++ Visualization.
233//===----------------------------------------------------------------------===//
234
235static llvm::cl::opt<std::string>
236InheritanceViewCls("cxx-inheritance-view",
237 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000238 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000239
240//===----------------------------------------------------------------------===//
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000241// Frontend Options
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000242//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000243
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000244static llvm::cl::list<std::string>
245InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
246
247static llvm::cl::opt<std::string>
248OutputFile("o",
249 llvm::cl::value_desc("path"),
250 llvm::cl::desc("Specify output file"));
251
Chris Lattnerb2509e12009-02-18 01:12:43 +0000252static llvm::cl::opt<bool>
253TimeReport("ftime-report",
254 llvm::cl::desc("Print the amount of time each "
255 "phase of compilation takes"));
256
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000257static llvm::cl::opt<std::string>
258TokenCache("token-cache", llvm::cl::value_desc("path"),
259 llvm::cl::desc("Use specified token cache file"));
260
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000261static llvm::cl::opt<bool>
262VerifyDiagnostics("verify",
263 llvm::cl::desc("Verify emitted diagnostics and warnings"));
264
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000265//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000266// Language Options
267//===----------------------------------------------------------------------===//
268
Reid Spencer5f016e22007-07-11 17:01:13 +0000269static llvm::cl::opt<LangKind>
270BaseLang("x", llvm::cl::desc("Base language to compile"),
271 llvm::cl::init(langkind_unspecified),
272 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000273 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 clEnumValN(langkind_cxx, "c++", "C++"),
275 clEnumValN(langkind_objc, "objective-c", "Objective C"),
276 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000277 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000279 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
280 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000282 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
284 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000285 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000287 clEnumValN(langkind_c, "c-header",
288 "C header"),
289 clEnumValN(langkind_objc, "objective-c-header",
290 "Objective-C header"),
291 clEnumValN(langkind_cxx, "c++-header",
292 "C++ header"),
293 clEnumValN(langkind_objcxx, "objective-c++-header",
294 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000295 clEnumValN(langkind_ast, "ast",
296 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 clEnumValEnd));
298
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000299static llvm::cl::opt<std::string>
300TargetTriple("triple",
301 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
302
Daniel Dunbar56749082009-11-11 07:26:12 +0000303static llvm::cl::opt<std::string>
304TargetABI("target-abi",
305 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000306
307//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000308// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000309//===----------------------------------------------------------------------===//
310
Douglas Gregore1d918e2009-04-10 23:10:45 +0000311static bool InitializeSourceManager(Preprocessor &PP,
312 const std::string &InFile) {
313 // Figure out where to get and map in the main file.
314 SourceManager &SourceMgr = PP.getSourceManager();
315 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000316
317 if (EmptyInputOnly) {
318 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000319 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000320 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
321 SourceMgr.createMainFileIDForMemBuffer(SB);
322 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000323 const FileEntry *File = FileMgr.getFile(InFile);
324 if (File) SourceMgr.createMainFileID(File, SourceLocation());
325 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000326 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000327 return true;
328 }
329 } else {
330 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000331 SourceMgr.createMainFileIDForMemBuffer(SB);
332 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000333 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000334 return true;
335 }
336 }
337
338 return false;
339}
340
Chris Lattneraa391972008-04-19 23:09:31 +0000341
Chris Lattnere116ccf2009-04-21 05:40:52 +0000342//===----------------------------------------------------------------------===//
343// Preprocessor Initialization
344//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000345
Chris Lattnere6113de2009-11-03 19:50:27 +0000346static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000347RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000348 llvm::cl::desc("Whether to build a relocatable precompiled "
349 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000350
Reid Spencer5f016e22007-07-11 17:01:13 +0000351// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +0000352
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000353// Add the clang headers, which are relative to the clang binary.
Daniel Dunbar750156a2009-11-07 04:19:57 +0000354std::string GetBuiltinIncludePath(const char *Argv0) {
355 llvm::sys::Path P =
356 llvm::sys::Path::GetMainExecutable(Argv0,
357 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000358
Daniel Dunbar750156a2009-11-07 04:19:57 +0000359 if (!P.isEmpty()) {
360 P.eraseComponent(); // Remove /clang from foo/bin/clang
361 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000362
Daniel Dunbar750156a2009-11-07 04:19:57 +0000363 // Get foo/lib/clang/<version>/include
364 P.appendComponent("lib");
365 P.appendComponent("clang");
366 P.appendComponent(CLANG_VERSION_STRING);
367 P.appendComponent("include");
368 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000369
Daniel Dunbar750156a2009-11-07 04:19:57 +0000370 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000371}
372
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000373//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +0000374// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000375//===----------------------------------------------------------------------===//
376
Daniel Dunbar90b18272009-11-04 23:56:25 +0000377static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000378CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000379 const PreprocessorOptions &PPOpts,
380 const DependencyOutputOptions &DepOpts,
381 TargetInfo &Target, SourceManager &SourceMgr,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000382 FileManager &FileMgr) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000383 PTHManager *PTHMgr = 0;
Daniel Dunbare0a95812009-11-10 22:09:38 +0000384 if (!TokenCache.empty() && !PPOpts.getImplicitPTHInclude().empty()) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000385 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
386 "options\n");
387 exit(1);
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000388 }
Daniel Dunbar90b18272009-11-04 23:56:25 +0000389
390 // Use PTH?
Daniel Dunbare0a95812009-11-10 22:09:38 +0000391 if (!TokenCache.empty() || !PPOpts.getImplicitPTHInclude().empty()) {
392 const std::string& x = TokenCache.empty() ?
393 PPOpts.getImplicitPTHInclude() : TokenCache;
Daniel Dunbar90b18272009-11-04 23:56:25 +0000394 PTHMgr = PTHManager::Create(x, &Diags,
395 TokenCache.empty() ? Diagnostic::Error
396 : Diagnostic::Warning);
397 }
398
399 if (Diags.hasErrorOccurred())
400 exit(1);
401
402 // Create the Preprocessor.
Daniel Dunbar5814e652009-11-11 21:44:21 +0000403 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000404 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000405 SourceMgr, *HeaderInfo, PTHMgr,
406 /*OwnsHeaderSearch=*/true);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000407
408 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
409 // That argument is used as the IdentifierInfoLookup argument to
410 // IdentifierTable's ctor.
411 if (PTHMgr) {
412 PTHMgr->setPreprocessor(PP);
413 PP->setPTHManager(PTHMgr);
414 }
415
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000416 InitializePreprocessor(*PP, PPOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000417
Daniel Dunbarca11f612009-11-11 21:44:00 +0000418 // Handle generating dependencies, if requested.
419 if (!DepOpts.OutputFile.empty())
420 AttachDependencyFileGen(*PP, DepOpts);
421
Daniel Dunbar90b18272009-11-04 23:56:25 +0000422 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000423}
Reid Spencer5f016e22007-07-11 17:01:13 +0000424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425//===----------------------------------------------------------------------===//
426// Basic Parser driver
427//===----------------------------------------------------------------------===//
428
Chris Lattner51574ea2008-04-19 23:25:44 +0000429static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000431 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 // Parsing the specified input file.
434 P.ParseTranslationUnit();
435 delete PA;
436}
437
438//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +0000439// Fix-It Options
440//===----------------------------------------------------------------------===//
441static llvm::cl::list<ParsedSourceLocation>
442FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
443 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
444
445//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000446// ObjC Rewriter Options
447//===----------------------------------------------------------------------===//
448static llvm::cl::opt<bool>
449SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
450 llvm::cl::desc("Silence ObjC rewriting warnings"));
451
452//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +0000453// Warning Options
454//===----------------------------------------------------------------------===//
455
456// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
457// driver has stripped off -Wa,foo etc. The driver has also translated -W to
458// -Wextra, so we don't need to worry about it.
459static llvm::cl::list<std::string>
460OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
461
462static llvm::cl::opt<bool> OptPedantic("pedantic");
463static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
464static llvm::cl::opt<bool> OptNoWarnings("w");
465
466//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +0000467// -dump-build-information Stuff
468//===----------------------------------------------------------------------===//
469
470static llvm::cl::opt<std::string>
471DumpBuildInformation("dump-build-information",
472 llvm::cl::value_desc("filename"),
473 llvm::cl::desc("output a dump of some build information to a file"));
474
Daniel Dunbar227b2382009-11-09 22:45:57 +0000475static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000476 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000477 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000478 std::string ErrorInfo;
Daniel Dunbaraea36412009-11-11 09:38:24 +0000479 llvm::raw_ostream *OS = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
480 ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000481 if (!ErrorInfo.empty()) {
482 llvm::errs() << "error opening -dump-build-information file '"
483 << DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000484 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000485 return;
486 }
487
Daniel Dunbaraea36412009-11-11 09:38:24 +0000488 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000489 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000490 (*OS) << argv[i] << ' ';
491 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000493 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000494 DiagnosticClient *Logger =
495 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000496 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000497}
498
Chris Lattner75a97cb2009-04-17 21:05:01 +0000499//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000500// Main driver
501//===----------------------------------------------------------------------===//
502
Daniel Dunbare29709f2009-11-09 20:55:08 +0000503static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
504 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000505 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000506 bool Binary,
507 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000508 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000509 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000510 if (!CompOpts.getOutputFile().empty())
511 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +0000512 else if (InFile == "-") {
513 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000514 } else if (Extension) {
515 llvm::sys::Path Path(InFile);
516 Path.eraseSuffix();
517 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000518 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000519 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000520 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000521 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000522
Chris Lattner92bcc272009-08-23 02:59:41 +0000523 std::string Error;
524 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000525 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000526 if (!Error.empty()) {
527 // FIXME: Don't fail this way.
528 llvm::errs() << "ERROR: " << Error << "\n";
529 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000530 }
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Chris Lattner92bcc272009-08-23 02:59:41 +0000532 if (OutFile != "-")
533 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000534
535 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000536}
537
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000538/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000539/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000540static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000541 FileManager &FileMgr) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000542 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000543
544 for (unsigned i = 0, e = FixItAtLocations.size(); i != e; ++i) {
545 if (const FileEntry *File = FileMgr.getFile(FixItAtLocations[i].FileName)) {
546 RequestedSourceLocation Requested;
547 Requested.File = File;
548 Requested.Line = FixItAtLocations[i].Line;
549 Requested.Column = FixItAtLocations[i].Column;
550 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000551 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000552 } else {
553 llvm::errs() << "FIX-IT could not find file \""
554 << FixItAtLocations[i].FileName << "\"\n";
555 }
556 }
557
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000558 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000559}
560
Daniel Dunbare29709f2009-11-09 20:55:08 +0000561static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
562 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000563 const std::string &InFile,
564 ProgActions PA,
565 llvm::OwningPtr<llvm::raw_ostream> &OS,
566 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000567 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +0000568 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000570 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000571
572 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000573 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000574 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregoree75c052009-05-21 20:55:50 +0000576 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000577 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000578 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000579
Eli Friedman66d6f042009-05-18 22:20:00 +0000580 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000581 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000582
Eli Friedman66d6f042009-05-18 22:20:00 +0000583 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000584 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000585
Anders Carlsson78762eb2009-09-24 18:54:49 +0000586 case DumpRecordLayouts:
587 return CreateRecordLayoutDumper();
588
Eli Friedman66d6f042009-05-18 22:20:00 +0000589 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000590 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +0000591
592 case EmitAssembly:
593 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000594 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000595 case EmitLLVMOnly: {
596 BackendAction Act;
597 if (ProgAction == EmitAssembly) {
598 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000599 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000600 } else if (ProgAction == EmitLLVM) {
601 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000602 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000603 } else if (ProgAction == EmitLLVMOnly) {
604 Act = Backend_EmitNothing;
605 } else {
606 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000607 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000608 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000609
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000610 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000611 CompOpts.getCompileOpts(), InFile, OS.get(),
612 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000613 }
614
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000615 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000616 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000617 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
618 PP.getLangOptions(), SilenceRewriteMacroWarning);
619
620 case RewriteBlocks:
621 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
622 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000623
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000624 case FixIt: // We add the rewriter later.
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000625 case ParseSyntaxOnly:
626 return new ASTConsumer();
627
628 case PrintDeclContext:
629 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000630 }
631}
632
633/// ProcessInputFile - Process a single input file with the specified state.
634///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000635static void ProcessInputFile(const CompilerInvocation &CompOpts,
636 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000637 ProgActions PA, llvm::LLVMContext& Context) {
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000638 llvm::OwningPtr<llvm::raw_ostream> OS;
639 llvm::OwningPtr<ASTConsumer> Consumer;
640 bool ClearSourceMgr = false;
641 FixItRewriter *FixItRewrite = 0;
642 bool CompleteTranslationUnit = true;
643 llvm::sys::Path OutPath;
644
645 switch (PA) {
646 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000647 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000648 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000649 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000650 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000651 return;
652 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000653 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000654
655 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000656 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000657 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000658 break;
659
Daniel Dunbar339c1342009-11-11 08:13:55 +0000660 case RunAnalysis: {
661 AnalyzerOptions AnalyzerOpts;
662 // FIXME: Move into CompilerInvocation.
663 InitializeAnalyzerOptions(AnalyzerOpts);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000664 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar339c1342009-11-11 08:13:55 +0000665 AnalyzerOpts));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000666 break;
Daniel Dunbar339c1342009-11-11 08:13:55 +0000667 }
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000668
Daniel Dunbarf7973292009-11-11 08:13:32 +0000669 case GeneratePCH: {
670 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
671 if (RelocatablePCH.getValue() && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000672 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
673 RelocatablePCH.setValue(false);
674 }
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Daniel Dunbare29709f2009-11-09 20:55:08 +0000676 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000677 if (RelocatablePCH.getValue())
Daniel Dunbarf7973292009-11-11 08:13:32 +0000678 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000679 else
680 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000681 CompleteTranslationUnit = false;
682 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000683 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000684 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +0000685 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +0000686 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +0000687 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +0000688 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +0000689 RawLex.SetKeepWhitespaceMode(true);
690
691 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +0000692 RawLex.LexFromRawLexer(RawTok);
693 while (RawTok.isNot(tok::eof)) {
694 PP.DumpToken(RawTok, true);
695 fprintf(stderr, "\n");
696 RawLex.LexFromRawLexer(RawTok);
697 }
698 ClearSourceMgr = true;
699 break;
700 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +0000702 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +0000703 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +0000704 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000705 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 do {
707 PP.Lex(Tok);
708 PP.DumpToken(Tok, true);
709 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000710 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000711 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 break;
713 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000714 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000717 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +0000718 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000719 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000720 // FIXME: Don't fail this way.
721 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000722 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000723 ::exit(1);
724 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000725 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000726 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +0000727 ClearSourceMgr = true;
728 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000729 }
Douglas Gregor6ab35242009-04-09 21:40:53 +0000730
Chris Lattnercc7dea82009-04-27 22:02:30 +0000731 case PrintPreprocessedInput:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000732 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000735 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattner47099742009-02-18 01:51:21 +0000738 case ParsePrintCallbacks: {
739 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000740 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000741 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +0000742 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000743 break;
Chris Lattner47099742009-02-18 01:51:21 +0000744 }
745
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000746 case RewriteMacros:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000747 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000748 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000749 ClearSourceMgr = true;
750 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Eli Friedmanf54fce82009-05-19 01:02:07 +0000752 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000753 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000754 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000755 ClearSourceMgr = true;
756 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000757 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000758
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000759 // Check if we want a fix-it rewriter.
760 if (PA == FixIt || !FixItAtLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000761 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000762 PP.getSourceManager(),
763 PP.getLangOptions());
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000764 if (!FixItAtLocations.empty() &&
765 !AddFixItLocations(FixItRewrite, PP.getFileManager())) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000766 // All of the fix-it locations were bad. Don't fix anything.
767 delete FixItRewrite;
768 FixItRewrite = 0;
769 }
770 }
771
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000772
Chris Lattner1aee61a2009-04-27 21:25:27 +0000773 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000774 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000775 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
776 PP.getSourceManager(),
777 PP.getTargetInfo(),
778 PP.getIdentifierTable(),
779 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000780 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +0000781 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000782 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattnercc7dea82009-04-27 22:02:30 +0000784 llvm::OwningPtr<PCHReader> Reader;
785 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Daniel Dunbare0a95812009-11-10 22:09:38 +0000787 const std::string &ImplicitPCHInclude =
788 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
789 if (!ImplicitPCHInclude.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000790 // If the user specified -isysroot, it will be used for relocatable PCH
791 // files.
Daniel Dunbarf7973292009-11-11 08:13:32 +0000792 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
793 if (isysrootPCH[0] == '\0')
794 isysrootPCH = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Douglas Gregore650c8c2009-07-07 00:12:59 +0000796 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000798 // The user has asked us to include a precompiled header. Load
799 // the precompiled header into the AST context.
Daniel Dunbare0a95812009-11-10 22:09:38 +0000800 switch (Reader->ReadPCH(ImplicitPCHInclude)) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000801 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +0000802 // Set the predefines buffer as suggested by the PCH
803 // reader. Typically, the predefines buffer will be empty.
804 PP.setPredefines(Reader->getSuggestedPredefines());
805
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000806 // Attach the PCH reader to the AST context as an external AST
807 // source, so that declarations will be deserialized from the
808 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +0000809 if (ContextOwner) {
810 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +0000811 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +0000812 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000813 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000814 }
815
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000816 case PCHReader::Failure:
817 // Unrecoverable failure: don't even try to process the input
818 // file.
819 return;
820
821 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +0000822 // No suitable PCH file could be found. Return an error.
823 return;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000824 }
825
826 // Finish preprocessor initialization. We do this now (rather
827 // than earlier) because this initialization creates new source
828 // location entries in the source manager, which must come after
829 // the source location entries for the PCH file.
830 if (InitializeSourceManager(PP, InFile))
831 return;
Ted Kremenek46157b52009-01-28 04:29:29 +0000832 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000833
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000834 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +0000835 if (Consumer) {
836 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
837 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000838
Douglas Gregorb657f112009-09-22 21:11:38 +0000839 if (!CodeCompletionAt.FileName.empty()) {
840 // Tell the source manager to chop off the given file at a specific
841 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000842 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +0000843 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
844 // Truncate the named file at the given line/column.
845 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
846 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000847
Douglas Gregorb657f112009-09-22 21:11:38 +0000848 // Set up the creation routine for code-completion.
849 CreateCodeCompleter = BuildPrintingCodeCompleter;
850 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000851 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +0000852 << CodeCompletionAt.FileName;
853 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000854 }
855
Mike Stump1eb44332009-09-09 15:08:12 +0000856 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000857 CompleteTranslationUnit,
858 CreateCodeCompleter, CreateCodeCompleterData);
859 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000860
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000861 // Perform post processing actions and actions which don't use a consumer.
862 switch (PA) {
863 default: break;
864
865 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000866 llvm::TimeRegion Timer(ClangFrontendTimer);
867 Token Tok;
868 // Start parsing the specified input file.
869 PP.EnterMainSourceFile();
870 do {
871 PP.Lex(Tok);
872 } while (Tok.isNot(tok::eof));
873 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000874 break;
875 }
876
877 case ParseNoop: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000878 llvm::TimeRegion Timer(ClangFrontendTimer);
879 ParseFile(PP, new MinimalAction(PP));
880 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000881 break;
882 }
883
884 case PrintPreprocessedInput: {
Chris Lattnercc7dea82009-04-27 22:02:30 +0000885 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000886 DoPrintPreprocessedInput(PP, OS.get(),
887 CompOpts.getPreprocessorOutputOpts());
Chris Lattnercc7dea82009-04-27 22:02:30 +0000888 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000889 }
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000891 }
892
Chris Lattner1aee61a2009-04-27 21:25:27 +0000893 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +0000894 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000895
896 // Disable the consumer prior to the context, the consumer may perform actions
897 // in its destructor which require the context.
898 if (DisableFree)
899 Consumer.take();
900 else
901 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Chris Lattner1aee61a2009-04-27 21:25:27 +0000903 // If in -disable-free mode, don't deallocate ASTContext.
904 if (DisableFree)
905 ContextOwner.take();
906 else
907 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +0000908
Daniel Dunbar879c3ea2008-10-27 22:03:52 +0000909 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000910 if (CheckDiagnostics(PP))
911 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000912
Reid Spencer5f016e22007-07-11 17:01:13 +0000913 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000914 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000915 PP.PrintStats();
916 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000917 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000918 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 fprintf(stderr, "\n");
920 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000921
Mike Stump1eb44332009-09-09 15:08:12 +0000922 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +0000923 // manager tables, other require stable fileid/macroid's across multiple
924 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +0000925 if (ClearSourceMgr)
926 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000927
Eli Friedman66d6f042009-05-18 22:20:00 +0000928 // Always delete the output stream because we don't want to leak file
929 // handles. Also, we don't want to try to erase an open file.
930 OS.reset();
931
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000932 // If we had errors, try to erase the output file.
933 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000934 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000935}
936
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000937/// ProcessInputFile - Process a single AST input file with the specified state.
938///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000939static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
940 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000941 Diagnostic &Diags, FileManager &FileMgr,
942 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000943 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000944 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000945 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000946 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000947 return;
948 }
949
950 Preprocessor &PP = AST->getPreprocessor();
951
952 llvm::OwningPtr<llvm::raw_ostream> OS;
953 llvm::sys::Path OutPath;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000954 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
955 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000956 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000957
958 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000959 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000960 return;
961 }
962
Daniel Dunbara674bf42009-09-21 03:03:56 +0000963 // Set the main file ID to an empty file.
964 //
965 // FIXME: We probably shouldn't need this, but for now this is the simplest
966 // way to reuse the logic in ParseAST.
967 const char *EmptyStr = "";
968 llvm::MemoryBuffer *SB =
969 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
970 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000971
Daniel Dunbara674bf42009-09-21 03:03:56 +0000972 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000973 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +0000974 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000975 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000976
977 // Release the consumer and the AST, in that order since the consumer may
978 // perform actions in its destructor which require the context.
979 if (DisableFree) {
980 Consumer.take();
981 AST.take();
982 } else {
983 Consumer.reset();
984 AST.reset();
985 }
986
987 // Always delete the output stream because we don't want to leak file
988 // handles. Also, we don't want to try to erase an open file.
989 OS.reset();
990
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000991 // If we had errors, try to erase the output file.
992 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000993 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000994}
995
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000996static void LLVMErrorHandler(void *UserData, const std::string &Message) {
997 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
998
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000999 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001000
1001 // We cannot recover from llvm errors.
1002 exit(1);
1003}
1004
Daniel Dunbar227b2382009-11-09 22:45:57 +00001005static LangKind GetLanguage() {
1006 // If -x was given, that's the language.
1007 if (BaseLang != langkind_unspecified)
1008 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001009
Daniel Dunbar227b2382009-11-09 22:45:57 +00001010 // Otherwise guess it from the input filenames;
1011 LangKind LK = langkind_unspecified;
1012 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
1013 llvm::StringRef Name(InputFilenames[i]);
1014 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
1015 .Case("ast", langkind_ast)
1016 .Case("c", langkind_c)
1017 .Cases("S", "s", langkind_asm_cpp)
1018 .Case("i", langkind_c_cpp)
1019 .Case("ii", langkind_cxx_cpp)
1020 .Case("m", langkind_objc)
1021 .Case("mi", langkind_objc_cpp)
1022 .Cases("mm", "M", langkind_objcxx)
1023 .Case("mii", langkind_objcxx_cpp)
1024 .Case("C", langkind_cxx)
1025 .Cases("C", "cc", "cp", langkind_cxx)
1026 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
1027 .Case("cl", langkind_ocl)
1028 .Default(langkind_c);
1029
1030 if (LK != langkind_unspecified && ThisKind != LK) {
1031 llvm::errs() << "error: cannot have multiple input files of distinct "
1032 << "language kinds without -x\n";
1033 exit(1);
1034 }
1035
1036 LK = ThisKind;
1037 }
1038
1039 return LK;
1040}
1041
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001042static void FinalizeCompileOptions(CompileOptions &Opts,
1043 const LangOptions &Lang) {
1044 if (Lang.NoBuiltin)
1045 Opts.SimplifyLibCalls = 0;
1046 if (Lang.CPlusPlus)
1047 Opts.NoCommon = 1;
1048
1049 // Handle -ftime-report.
1050 Opts.TimePasses = TimeReport;
1051}
1052
Daniel Dunbar227b2382009-11-09 22:45:57 +00001053static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001054 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +00001055 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001056 TargetInfo &Target,
1057 LangKind LK) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001058 Opts.getDiagnosticOpts() = DiagOpts;
1059
1060 Opts.getOutputFile() = OutputFile;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001061
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001062 // Initialize backend options, which may also be used to key some language
1063 // options.
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001064 InitializeCompileOptions(Opts.getCompileOpts(), Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001065
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001066 // Initialize language options.
1067 LangOptions LangInfo;
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001068
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001069 // FIXME: These aren't used during operations on ASTs. Split onto a separate
1070 // code path to make this obvious.
Daniel Dunbar56749082009-11-11 07:26:12 +00001071 if (LK != langkind_ast)
1072 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001073 Opts.getCompileOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001074
Daniel Dunbar0e0bae82009-11-11 21:43:12 +00001075 // Initialize the dependency output options (-M...).
1076 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
1077
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001078 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +00001079 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
1080 GetBuiltinIncludePath(Argv0),
1081 Verbose,
1082 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001083
1084 // Initialize the other preprocessor options.
1085 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001086
Daniel Dunbar29cf7462009-11-11 10:07:44 +00001087 // Initialize the preprocessed output options.
1088 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
1089
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001090 // Finalize some code generation options.
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001091 FinalizeCompileOptions(Opts.getCompileOpts(), Opts.getLangOpts());
Daniel Dunbare29709f2009-11-09 20:55:08 +00001092}
1093
Reid Spencer5f016e22007-07-11 17:01:13 +00001094int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001096 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001097 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001098
Daniel Dunbar4d861512009-09-03 04:54:12 +00001099 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001100 llvm::InitializeAllTargets();
1101 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001102
1103 llvm::cl::ParseCommandLineOptions(argc, argv,
1104 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Chris Lattner47099742009-02-18 01:51:21 +00001106 if (TimeReport)
1107 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00001109 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00001110 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
1111 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00001112 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 // If no input was specified, read from stdin.
1115 if (InputFilenames.empty())
1116 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00001117
Daniel Dunbar227b2382009-11-09 22:45:57 +00001118 // Construct the diagnostic options first, which cannot fail, so that we can
1119 // build a diagnostic client to use for any errors during option handling.
1120 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +00001121 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbareace8742009-11-04 06:24:30 +00001122
Ted Kremenek31e703b2007-12-11 23:28:38 +00001123 // Create the diagnostic client for reporting errors or for
1124 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001125 llvm::OwningPtr<DiagnosticClient> DiagClient;
1126 if (VerifyDiagnostics) {
1127 // When checking diagnostics, just buffer them up.
1128 DiagClient.reset(new TextDiagnosticBuffer());
1129 if (InputFilenames.size() != 1) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001130 fprintf(stderr, "-verify only works on single input files.\n");
Chris Lattner409d4e72009-04-17 20:40:01 +00001131 return 1;
1132 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001133 } else {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001134 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 }
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Daniel Dunbarad451cc2009-11-05 02:11:37 +00001137 if (!DumpBuildInformation.empty())
Daniel Dunbar227b2382009-11-09 22:45:57 +00001138 SetUpBuildDumpLog(DiagOpts, argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001139
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001141 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001142 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
1143 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001144 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001145
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001146 // Set an error handler, so that any LLVM backend diagnostics go through our
1147 // error handler.
1148 llvm::llvm_install_error_handler(LLVMErrorHandler,
1149 static_cast<void*>(&Diags));
1150
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001151 // Initialize base triple. If a -triple option has been specified, use
1152 // that triple. Otherwise, default to the host triple.
1153 llvm::Triple Triple(TargetTriple);
1154 if (Triple.getTriple().empty())
1155 Triple = llvm::Triple(llvm::sys::getHostTriple());
1156
Chris Lattner11215192008-03-14 06:12:05 +00001157 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001158 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001159 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Chris Lattner11215192008-03-14 06:12:05 +00001161 if (Target == 0) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001162 Diags.Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001163 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001164 }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Daniel Dunbar73b79592009-09-14 00:02:12 +00001166 // Set the target ABI if specified.
1167 if (!TargetABI.empty()) {
1168 if (!Target->setABI(TargetABI)) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001169 Diags.Report(diag::err_fe_unknown_target_abi) << TargetABI;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001170 return 1;
1171 }
1172 }
1173
Daniel Dunbard4270232009-01-20 23:17:32 +00001174 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001175 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Daniel Dunbar227b2382009-11-09 22:45:57 +00001177 // Infer the input language.
1178 //
1179 // FIXME: We should move .ast inputs to taking a separate path, they are
1180 // really quite different.
1181 LangKind LK = GetLanguage();
1182
1183 // Now that we have initialized the diagnostics engine and the target, finish
1184 // setting up the compiler invocation.
1185 CompilerInvocation CompOpts;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001186 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, LK);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001187
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001188 // Create the source manager.
1189 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Chris Lattner2c78b872009-04-14 23:22:57 +00001191 // Create a file manager object to provide access to and cache the filesystem.
1192 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001193
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001195 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001197 // AST inputs are handled specially.
1198 if (LK == langkind_ast) {
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001199 ProcessASTInputFile(CompOpts, InFile, ProgAction, Diags, FileMgr,
1200 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001201 continue;
1202 }
1203
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001204 // Reset the ID tables if we are reusing the SourceManager.
1205 if (i)
1206 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Chris Lattnerf63aea32009-03-04 21:40:56 +00001208 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001209 llvm::OwningPtr<Preprocessor>
1210 PP(CreatePreprocessor(Diags, CompOpts.getLangOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001211 CompOpts.getPreprocessorOpts(),
1212 CompOpts.getDependencyOutputOpts(),
Daniel Dunbar5814e652009-11-11 21:44:21 +00001213 *Target, SourceMgr, FileMgr));
1214
1215 // Apply all the options to the header search object.
1216 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(),
1217 CompOpts.getHeaderSearchOpts(),
1218 CompOpts.getLangOpts(), Triple);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001219
Daniel Dunbare0a95812009-11-10 22:09:38 +00001220 if (CompOpts.getPreprocessorOpts().getImplicitPCHInclude().empty()) {
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001221 if (InitializeSourceManager(*PP.get(), InFile))
1222 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001224 // Initialize builtin info.
1225 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001226 PP->getLangOptions().NoBuiltin);
1227 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001228
Chris Lattnerf63aea32009-03-04 21:40:56 +00001229 // Process the source file.
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001230 Diags.getClient()->BeginSourceFile(CompOpts.getLangOpts());
1231 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001232 Diags.getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 }
Chris Lattner11215192008-03-14 06:12:05 +00001234
Daniel Dunbar9253e492009-11-10 00:46:12 +00001235 if (CompOpts.getDiagnosticOpts().ShowCarets)
Mike Stumpfc0fed32009-04-28 01:19:10 +00001236 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
1237 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1238 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 FileMgr.PrintStats();
1242 fprintf(stderr, "\n");
1243 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001244
1245 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Daniel Dunbar276373d2008-10-27 22:10:13 +00001247 // If verifying diagnostics and we reached here, all is well.
1248 if (VerifyDiagnostics)
1249 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001251 // Managed static deconstruction. Useful for making things like
1252 // -time-passes usable.
1253 llvm::llvm_shutdown();
1254
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001255 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001256}