blob: ad5575352729a94f90e9db942a850fc5850a3e98 [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
Ted Kremenek13e479b2008-03-19 07:53:42 +0000105 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000106 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000108 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000109 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000110 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000111 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000112 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000113 ASTDump, // Parse ASTs and dump them.
114 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000115 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000116 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 ParsePrintCallbacks, // Parse and print each callback.
118 ParseSyntaxOnly, // Parse and perform semantic analysis.
119 ParseNoop, // Parse with noop callbacks.
120 RunPreprocessorOnly, // Just lex, no output.
121 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000122 DumpTokens, // Dump out preprocessed tokens.
123 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000124 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000125 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000126 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000127 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000128};
129
Mike Stump1eb44332009-09-09 15:08:12 +0000130static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000131ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
132 llvm::cl::init(ParseSyntaxOnly),
133 llvm::cl::values(
134 clEnumValN(RunPreprocessorOnly, "Eonly",
135 "Just run preprocessor, no output (for timings)"),
136 clEnumValN(PrintPreprocessedInput, "E",
137 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000138 clEnumValN(DumpRawTokens, "dump-raw-tokens",
139 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000140 clEnumValN(RunAnalysis, "analyze",
141 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000142 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 "Run preprocessor, dump internal rep of tokens"),
144 clEnumValN(ParseNoop, "parse-noop",
145 "Run parser with noop callbacks (for timings)"),
146 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
147 "Run parser and perform semantic analysis"),
148 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
149 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000150 clEnumValN(EmitHTML, "emit-html",
151 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000152 clEnumValN(ASTPrint, "ast-print",
153 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000154 clEnumValN(ASTPrintXML, "ast-print-xml",
155 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000156 clEnumValN(ASTDump, "ast-dump",
157 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000158 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000159 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000160 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000161 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000162 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
163 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000164 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000165 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000166 clEnumValN(GeneratePCH, "emit-pch",
167 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000168 clEnumValN(EmitAssembly, "S",
169 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000171 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000172 clEnumValN(EmitBC, "emit-llvm-bc",
173 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000174 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
175 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000176 clEnumValN(RewriteTest, "rewrite-test",
177 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000178 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000179 "Rewrite ObjC into C (code rewriter example)"),
180 clEnumValN(RewriteMacros, "rewrite-macros",
181 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000182 clEnumValN(RewriteBlocks, "rewrite-blocks",
183 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 clEnumValEnd));
185
Ted Kremenekccc76472007-12-19 19:47:59 +0000186
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000187enum CodeCompletionPrinter {
188 CCP_Debug,
189 CCP_CIndex
190};
191
Douglas Gregorb657f112009-09-22 21:11:38 +0000192static llvm::cl::opt<ParsedSourceLocation>
193CodeCompletionAt("code-completion-at",
194 llvm::cl::value_desc("file:line:column"),
195 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000196
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000197static llvm::cl::opt<CodeCompletionPrinter>
198CodeCompletionPrinter("code-completion-printer",
199 llvm::cl::desc("Choose output type:"),
200 llvm::cl::init(CCP_Debug),
201 llvm::cl::values(
202 clEnumValN(CCP_Debug, "debug",
203 "Debug code-completion results"),
204 clEnumValN(CCP_CIndex, "cindex",
205 "Code-completion results for the CIndex library"),
206 clEnumValEnd));
207
208static llvm::cl::opt<bool>
209CodeCompletionWantsMacros("code-completion-macros",
210 llvm::cl::desc("Include macros in code-completion results"));
211
Douglas Gregor81b747b2009-09-17 21:32:03 +0000212/// \brief Buld a new code-completion consumer that prints the results of
213/// code completion to standard output.
214static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000215 switch (CodeCompletionPrinter.getValue()) {
216 case CCP_Debug:
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000217 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000218 llvm::outs());
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000219
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000220 case CCP_CIndex:
221 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
222 llvm::outs());
223 };
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000224
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000225 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000226}
227
Ted Kremenekc2e72992008-12-02 19:57:31 +0000228//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000229// C++ Visualization.
230//===----------------------------------------------------------------------===//
231
232static llvm::cl::opt<std::string>
233InheritanceViewCls("cxx-inheritance-view",
234 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000235 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000236
237//===----------------------------------------------------------------------===//
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000238// Frontend Options
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000239//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000240
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000241static llvm::cl::list<std::string>
242InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
243
244static llvm::cl::opt<std::string>
245OutputFile("o",
246 llvm::cl::value_desc("path"),
247 llvm::cl::desc("Specify output file"));
248
Chris Lattnerb2509e12009-02-18 01:12:43 +0000249static llvm::cl::opt<bool>
250TimeReport("ftime-report",
251 llvm::cl::desc("Print the amount of time each "
252 "phase of compilation takes"));
253
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000254static llvm::cl::opt<bool>
255VerifyDiagnostics("verify",
256 llvm::cl::desc("Verify emitted diagnostics and warnings"));
257
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000258//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000259// Language Options
260//===----------------------------------------------------------------------===//
261
Reid Spencer5f016e22007-07-11 17:01:13 +0000262static llvm::cl::opt<LangKind>
263BaseLang("x", llvm::cl::desc("Base language to compile"),
264 llvm::cl::init(langkind_unspecified),
265 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000266 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000267 clEnumValN(langkind_cxx, "c++", "C++"),
268 clEnumValN(langkind_objc, "objective-c", "Objective C"),
269 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000270 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000272 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
273 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000275 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
277 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000278 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000280 clEnumValN(langkind_c, "c-header",
281 "C header"),
282 clEnumValN(langkind_objc, "objective-c-header",
283 "Objective-C header"),
284 clEnumValN(langkind_cxx, "c++-header",
285 "C++ header"),
286 clEnumValN(langkind_objcxx, "objective-c++-header",
287 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000288 clEnumValN(langkind_ast, "ast",
289 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 clEnumValEnd));
291
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000292static llvm::cl::opt<std::string>
293TargetTriple("triple",
294 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
295
Daniel Dunbar56749082009-11-11 07:26:12 +0000296static llvm::cl::opt<std::string>
297TargetABI("target-abi",
298 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000299
300//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000301// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000302//===----------------------------------------------------------------------===//
303
Douglas Gregore1d918e2009-04-10 23:10:45 +0000304static bool InitializeSourceManager(Preprocessor &PP,
305 const std::string &InFile) {
306 // Figure out where to get and map in the main file.
307 SourceManager &SourceMgr = PP.getSourceManager();
308 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000309
310 if (EmptyInputOnly) {
311 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000312 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000313 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
314 SourceMgr.createMainFileIDForMemBuffer(SB);
315 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000316 const FileEntry *File = FileMgr.getFile(InFile);
317 if (File) SourceMgr.createMainFileID(File, SourceLocation());
318 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000319 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000320 return true;
321 }
322 } else {
323 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000324 SourceMgr.createMainFileIDForMemBuffer(SB);
325 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000326 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000327 return true;
328 }
329 }
330
331 return false;
332}
333
Chris Lattneraa391972008-04-19 23:09:31 +0000334
Chris Lattnere116ccf2009-04-21 05:40:52 +0000335//===----------------------------------------------------------------------===//
336// Preprocessor Initialization
337//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000338
Chris Lattnere6113de2009-11-03 19:50:27 +0000339static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000340RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000341 llvm::cl::desc("Whether to build a relocatable precompiled "
342 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000344//===----------------------------------------------------------------------===//
345// Preprocessor construction
346//===----------------------------------------------------------------------===//
Chris Lattner5f9eae52008-03-01 08:07:28 +0000347
Daniel Dunbar750156a2009-11-07 04:19:57 +0000348std::string GetBuiltinIncludePath(const char *Argv0) {
349 llvm::sys::Path P =
350 llvm::sys::Path::GetMainExecutable(Argv0,
351 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000352
Daniel Dunbar750156a2009-11-07 04:19:57 +0000353 if (!P.isEmpty()) {
354 P.eraseComponent(); // Remove /clang from foo/bin/clang
355 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000356
Daniel Dunbar750156a2009-11-07 04:19:57 +0000357 // Get foo/lib/clang/<version>/include
358 P.appendComponent("lib");
359 P.appendComponent("clang");
360 P.appendComponent(CLANG_VERSION_STRING);
361 P.appendComponent("include");
362 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000363
Daniel Dunbar750156a2009-11-07 04:19:57 +0000364 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000365}
366
Daniel Dunbar90b18272009-11-04 23:56:25 +0000367static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000368CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000369 const PreprocessorOptions &PPOpts,
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000370 const HeaderSearchOptions &HSOpts,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000371 const DependencyOutputOptions &DepOpts,
372 TargetInfo &Target, SourceManager &SourceMgr,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000373 FileManager &FileMgr) {
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000374 // Create a PTH manager if we are using some form of a token cache.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000375 PTHManager *PTHMgr = 0;
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000376 if (!PPOpts.getTokenCache().empty())
377 PTHMgr = PTHManager::Create(PPOpts.getTokenCache(), Diags);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000378
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000379 // FIXME: Don't fail like this.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000380 if (Diags.hasErrorOccurred())
381 exit(1);
382
383 // Create the Preprocessor.
Daniel Dunbar5814e652009-11-11 21:44:21 +0000384 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000385 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000386 SourceMgr, *HeaderInfo, PTHMgr,
387 /*OwnsHeaderSearch=*/true);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000388
389 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
390 // That argument is used as the IdentifierInfoLookup argument to
391 // IdentifierTable's ctor.
392 if (PTHMgr) {
393 PTHMgr->setPreprocessor(PP);
394 PP->setPTHManager(PTHMgr);
395 }
396
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000397 InitializePreprocessor(*PP, PPOpts, HSOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000398
Daniel Dunbarca11f612009-11-11 21:44:00 +0000399 // Handle generating dependencies, if requested.
400 if (!DepOpts.OutputFile.empty())
401 AttachDependencyFileGen(*PP, DepOpts);
402
Daniel Dunbar90b18272009-11-04 23:56:25 +0000403 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000404}
Reid Spencer5f016e22007-07-11 17:01:13 +0000405
Reid Spencer5f016e22007-07-11 17:01:13 +0000406//===----------------------------------------------------------------------===//
407// Basic Parser driver
408//===----------------------------------------------------------------------===//
409
Chris Lattner51574ea2008-04-19 23:25:44 +0000410static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000412 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 // Parsing the specified input file.
415 P.ParseTranslationUnit();
416 delete PA;
417}
418
419//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +0000420// Fix-It Options
421//===----------------------------------------------------------------------===//
Daniel Dunbarbfbeadb2009-11-12 06:48:24 +0000422
423static llvm::cl::opt<bool>
424FixItAll("fixit", llvm::cl::desc("Apply fix-it advice to the input source"));
425
Douglas Gregor26df2f02009-04-02 19:05:20 +0000426static llvm::cl::list<ParsedSourceLocation>
427FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
428 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
429
430//===----------------------------------------------------------------------===//
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000431// Dump Build Information
Chris Lattner75a97cb2009-04-17 21:05:01 +0000432//===----------------------------------------------------------------------===//
433
Daniel Dunbar227b2382009-11-09 22:45:57 +0000434static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000435 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000436 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000437 std::string ErrorInfo;
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000438 llvm::raw_ostream *OS =
439 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000440 if (!ErrorInfo.empty()) {
441 llvm::errs() << "error opening -dump-build-information file '"
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000442 << DiagOpts.DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000443 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000444 return;
445 }
446
Daniel Dunbaraea36412009-11-11 09:38:24 +0000447 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000448 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000449 (*OS) << argv[i] << ' ';
450 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000452 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000453 DiagnosticClient *Logger =
454 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000455 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000456}
457
Chris Lattner75a97cb2009-04-17 21:05:01 +0000458//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000459// Main driver
460//===----------------------------------------------------------------------===//
461
Daniel Dunbare29709f2009-11-09 20:55:08 +0000462static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
463 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000464 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000465 bool Binary,
466 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000467 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000468 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000469 if (!CompOpts.getOutputFile().empty())
470 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +0000471 else if (InFile == "-") {
472 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000473 } else if (Extension) {
474 llvm::sys::Path Path(InFile);
475 Path.eraseSuffix();
476 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000477 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000478 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000479 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000480 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000481
Chris Lattner92bcc272009-08-23 02:59:41 +0000482 std::string Error;
483 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000484 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000485 if (!Error.empty()) {
486 // FIXME: Don't fail this way.
487 llvm::errs() << "ERROR: " << Error << "\n";
488 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Chris Lattner92bcc272009-08-23 02:59:41 +0000491 if (OutFile != "-")
492 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000493
494 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000495}
496
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000497/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000498/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000499static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000500 FileManager &FileMgr) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000501 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000502
503 for (unsigned i = 0, e = FixItAtLocations.size(); i != e; ++i) {
504 if (const FileEntry *File = FileMgr.getFile(FixItAtLocations[i].FileName)) {
505 RequestedSourceLocation Requested;
506 Requested.File = File;
507 Requested.Line = FixItAtLocations[i].Line;
508 Requested.Column = FixItAtLocations[i].Column;
509 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000510 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000511 } else {
512 llvm::errs() << "FIX-IT could not find file \""
513 << FixItAtLocations[i].FileName << "\"\n";
514 }
515 }
516
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000517 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000518}
519
Daniel Dunbare29709f2009-11-09 20:55:08 +0000520static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
521 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000522 const std::string &InFile,
523 ProgActions PA,
524 llvm::OwningPtr<llvm::raw_ostream> &OS,
525 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000526 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +0000527 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000529 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000530
531 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000532 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000533 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Douglas Gregoree75c052009-05-21 20:55:50 +0000535 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000536 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000537 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000538
Eli Friedman66d6f042009-05-18 22:20:00 +0000539 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000540 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000541
Eli Friedman66d6f042009-05-18 22:20:00 +0000542 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000543 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000544
Anders Carlsson78762eb2009-09-24 18:54:49 +0000545 case DumpRecordLayouts:
546 return CreateRecordLayoutDumper();
547
Eli Friedman66d6f042009-05-18 22:20:00 +0000548 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000549 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +0000550
551 case EmitAssembly:
552 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000553 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000554 case EmitLLVMOnly: {
555 BackendAction Act;
556 if (ProgAction == EmitAssembly) {
557 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000558 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000559 } else if (ProgAction == EmitLLVM) {
560 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000561 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000562 } else if (ProgAction == EmitLLVMOnly) {
563 Act = Backend_EmitNothing;
564 } else {
565 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000566 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000567 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000568
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000569 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000570 CompOpts.getCompileOpts(), InFile, OS.get(),
571 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000572 }
573
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000574 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000575 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000576 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Daniel Dunbar69079432009-11-12 07:28:44 +0000577 PP.getLangOptions(),
578 CompOpts.getDiagnosticOpts().NoRewriteMacros);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000579
580 case RewriteBlocks:
581 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
582 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000583
584 case ParseSyntaxOnly:
585 return new ASTConsumer();
586
587 case PrintDeclContext:
588 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000589 }
590}
591
Daniel Dunbar975790e2009-11-12 02:53:20 +0000592/// ReadPCHFile - Load a PCH file from disk, and initialize the preprocessor for
593/// reading from the PCH file.
594///
595/// \return The AST source, or null on failure.
596static ExternalASTSource *ReadPCHFile(llvm::StringRef Path,
597 const CompilerInvocation &CompOpts,
598 Preprocessor &PP,
599 ASTContext &Context) {
600 // If the user specified -isysroot, it will be used for relocatable PCH files.
601 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
602 if (isysrootPCH[0] == '\0')
603 isysrootPCH = 0;
604
605 llvm::OwningPtr<PCHReader> Reader;
606 Reader.reset(new PCHReader(PP, &Context, isysrootPCH));
607
608 switch (Reader->ReadPCH(Path)) {
609 case PCHReader::Success:
610 // Set the predefines buffer as suggested by the PCH reader. Typically, the
611 // predefines buffer will be empty.
612 PP.setPredefines(Reader->getSuggestedPredefines());
613 return Reader.take();
614
615 case PCHReader::Failure:
616 // Unrecoverable failure: don't even try to process the input file.
617 break;
618
619 case PCHReader::IgnorePCH:
620 // No suitable PCH file could be found. Return an error.
621 break;
622 }
623
624 return 0;
625}
626
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000627/// ProcessInputFile - Process a single input file with the specified state.
628///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000629static void ProcessInputFile(const CompilerInvocation &CompOpts,
630 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000631 ProgActions PA, llvm::LLVMContext& Context) {
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000632 llvm::OwningPtr<llvm::raw_ostream> OS;
633 llvm::OwningPtr<ASTConsumer> Consumer;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000634 FixItRewriter *FixItRewrite = 0;
635 bool CompleteTranslationUnit = true;
636 llvm::sys::Path OutPath;
637
638 switch (PA) {
639 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000640 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000641 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000642 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000643 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000644 return;
645 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000646 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000647
648 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000649 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000650 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000651 break;
652
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000653 case RunAnalysis:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000654 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000655 CompOpts.getAnalyzerOpts()));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000656 break;
657
Daniel Dunbarf7973292009-11-11 08:13:32 +0000658 case GeneratePCH: {
659 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
660 if (RelocatablePCH.getValue() && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000661 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
662 RelocatablePCH.setValue(false);
663 }
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Daniel Dunbare29709f2009-11-09 20:55:08 +0000665 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000666 if (RelocatablePCH.getValue())
Daniel Dunbarf7973292009-11-11 08:13:32 +0000667 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000668 else
669 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000670 CompleteTranslationUnit = false;
671 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000672 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000673
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000674 // Do any necessary set up for non-consumer actions.
675 case DumpRawTokens:
676 case DumpTokens:
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000677 case RunPreprocessorOnly:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000678 case ParseNoop:
679 break; // No setup.
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000681 case GeneratePTH:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000682 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000683 // FIXME: Don't fail this way.
684 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000685 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000686 ::exit(1);
687 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000688 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Ted Kremenek85888962008-10-21 00:54:44 +0000689 break;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000690
Chris Lattnercc7dea82009-04-27 22:02:30 +0000691 case PrintPreprocessedInput:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000692 case ParsePrintCallbacks:
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000693 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +0000694 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000695 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000696 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000697 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000698
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000699 // Check if we want a fix-it rewriter.
Daniel Dunbarbfbeadb2009-11-12 06:48:24 +0000700 if (FixItAll || !FixItAtLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000701 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000702 PP.getSourceManager(),
703 PP.getLangOptions());
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000704 if (!FixItAtLocations.empty() &&
705 !AddFixItLocations(FixItRewrite, PP.getFileManager())) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000706 // All of the fix-it locations were bad. Don't fix anything.
707 delete FixItRewrite;
708 FixItRewrite = 0;
709 }
710 }
711
712 llvm::OwningPtr<ASTContext> ContextOwner;
Daniel Dunbar66068642009-11-12 02:53:13 +0000713 llvm::OwningPtr<ExternalASTSource> Source;
714 const std::string &ImplicitPCHInclude =
715 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000716 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000717 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
718 PP.getSourceManager(),
719 PP.getTargetInfo(),
720 PP.getIdentifierTable(),
721 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000722 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +0000723 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000724 /* size_reserve = */0));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000725
726 if (!ImplicitPCHInclude.empty()) {
727 Source.reset(ReadPCHFile(ImplicitPCHInclude, CompOpts, PP,
728 *ContextOwner));
729 if (!Source)
730 return;
731
732 // Attach the PCH reader to the AST context as an external AST source, so
733 // that declarations will be deserialized from the PCH file as needed.
734 ContextOwner->setExternalSource(Source);
735 } else {
736 // Initialize builtin info when not using PCH.
737 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
738 PP.getLangOptions().NoBuiltin);
739 }
740
741 // Initialize the main file entry. This needs to be delayed until after PCH
742 // has loaded.
743 if (InitializeSourceManager(PP, InFile))
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000744 return;
745
Douglas Gregor81b747b2009-09-17 21:32:03 +0000746 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
747 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000748
Douglas Gregorb657f112009-09-22 21:11:38 +0000749 if (!CodeCompletionAt.FileName.empty()) {
750 // Tell the source manager to chop off the given file at a specific
751 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000752 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +0000753 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
754 // Truncate the named file at the given line/column.
755 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
756 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000757
Douglas Gregorb657f112009-09-22 21:11:38 +0000758 // Set up the creation routine for code-completion.
759 CreateCodeCompleter = BuildPrintingCodeCompleter;
760 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000761 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +0000762 << CodeCompletionAt.FileName;
763 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000764 }
765
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000766 // Run the AST consumer action.
Mike Stump1eb44332009-09-09 15:08:12 +0000767 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000768 CompleteTranslationUnit,
769 CreateCodeCompleter, CreateCodeCompleterData);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000770 } else {
771 // Initialize builtin info.
772 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
773 PP.getLangOptions().NoBuiltin);
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000774
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000775 // Initialize the main file entry. This needs to be delayed until after PCH
776 // has loaded.
777 if (InitializeSourceManager(PP, InFile))
778 return;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000779
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000780 // Run the preprocessor actions.
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000781 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000782 switch (PA) {
783 default:
784 assert(0 && "unexpected program action");
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000785
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000786 case DumpRawTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000787 SourceManager &SM = PP.getSourceManager();
788 // Start lexing the specified input file.
789 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
790 RawLex.SetKeepWhitespaceMode(true);
791
792 Token RawTok;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000793 RawLex.LexFromRawLexer(RawTok);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000794 while (RawTok.isNot(tok::eof)) {
795 PP.DumpToken(RawTok, true);
796 fprintf(stderr, "\n");
797 RawLex.LexFromRawLexer(RawTok);
798 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000799 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000800 }
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000801
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000802 case DumpTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000803 Token Tok;
804 // Start preprocessing the specified input file.
805 PP.EnterMainSourceFile();
806 do {
807 PP.Lex(Tok);
808 PP.DumpToken(Tok, true);
809 fprintf(stderr, "\n");
810 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000811 break;
812 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000813
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000814 case GeneratePTH:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000815 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000816 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000817
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000818 case ParseNoop:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000819 ParseFile(PP, new MinimalAction(PP));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000820 break;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000821
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000822 case ParsePrintCallbacks:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000823 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000824 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000825
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000826 case PrintPreprocessedInput:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000827 DoPrintPreprocessedInput(PP, OS.get(),
828 CompOpts.getPreprocessorOutputOpts());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000829 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000830
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000831 case RewriteMacros:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000832 RewriteMacrosInInput(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000833 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000834
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000835 case RewriteTest:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000836 DoRewriteTest(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000837 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000838
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000839 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000840 Token Tok;
841 // Start parsing the specified input file.
842 PP.EnterMainSourceFile();
843 do {
844 PP.Lex(Tok);
845 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000846 break;
847 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000848 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000849 }
850
Chris Lattner1aee61a2009-04-27 21:25:27 +0000851 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +0000852 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000853
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000854 // Release the consumer and the AST, in that order since the consumer may
855 // perform actions in its destructor which require the context.
856 if (DisableFree) {
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000857 Consumer.take();
Chris Lattner1aee61a2009-04-27 21:25:27 +0000858 ContextOwner.take();
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000859 } else {
860 Consumer.reset();
861 ContextOwner.reset();
862 }
Eli Friedman66d6f042009-05-18 22:20:00 +0000863
Daniel Dunbar879c3ea2008-10-27 22:03:52 +0000864 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000865 if (CheckDiagnostics(PP))
866 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000867
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000869 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 PP.PrintStats();
871 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000872 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000873 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 fprintf(stderr, "\n");
875 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000876
Eli Friedman66d6f042009-05-18 22:20:00 +0000877 // Always delete the output stream because we don't want to leak file
878 // handles. Also, we don't want to try to erase an open file.
879 OS.reset();
880
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000881 // If we had errors, try to erase the output file.
882 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000883 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000884}
885
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000886/// ProcessInputFile - Process a single AST input file with the specified state.
887///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000888static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
889 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000890 Diagnostic &Diags, FileManager &FileMgr,
891 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000892 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000893 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000894 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000895 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000896 return;
897 }
898
899 Preprocessor &PP = AST->getPreprocessor();
900
901 llvm::OwningPtr<llvm::raw_ostream> OS;
902 llvm::sys::Path OutPath;
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000903 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000904 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000905 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000906 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000907 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000908 return;
909 }
910
Daniel Dunbara674bf42009-09-21 03:03:56 +0000911 // Set the main file ID to an empty file.
912 //
913 // FIXME: We probably shouldn't need this, but for now this is the simplest
914 // way to reuse the logic in ParseAST.
915 const char *EmptyStr = "";
916 llvm::MemoryBuffer *SB =
917 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
918 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000919
Daniel Dunbara674bf42009-09-21 03:03:56 +0000920 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000921 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +0000922 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000923 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000924
925 // Release the consumer and the AST, in that order since the consumer may
926 // perform actions in its destructor which require the context.
927 if (DisableFree) {
928 Consumer.take();
929 AST.take();
930 } else {
931 Consumer.reset();
932 AST.reset();
933 }
934
935 // Always delete the output stream because we don't want to leak file
936 // handles. Also, we don't want to try to erase an open file.
937 OS.reset();
938
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000939 // If we had errors, try to erase the output file.
940 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000941 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000942}
943
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000944static void LLVMErrorHandler(void *UserData, const std::string &Message) {
945 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
946
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000947 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000948
949 // We cannot recover from llvm errors.
950 exit(1);
951}
952
Daniel Dunbar227b2382009-11-09 22:45:57 +0000953static LangKind GetLanguage() {
954 // If -x was given, that's the language.
955 if (BaseLang != langkind_unspecified)
956 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000957
Daniel Dunbar227b2382009-11-09 22:45:57 +0000958 // Otherwise guess it from the input filenames;
959 LangKind LK = langkind_unspecified;
960 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
961 llvm::StringRef Name(InputFilenames[i]);
962 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
963 .Case("ast", langkind_ast)
964 .Case("c", langkind_c)
965 .Cases("S", "s", langkind_asm_cpp)
966 .Case("i", langkind_c_cpp)
967 .Case("ii", langkind_cxx_cpp)
968 .Case("m", langkind_objc)
969 .Case("mi", langkind_objc_cpp)
970 .Cases("mm", "M", langkind_objcxx)
971 .Case("mii", langkind_objcxx_cpp)
972 .Case("C", langkind_cxx)
973 .Cases("C", "cc", "cp", langkind_cxx)
974 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
975 .Case("cl", langkind_ocl)
976 .Default(langkind_c);
977
978 if (LK != langkind_unspecified && ThisKind != LK) {
979 llvm::errs() << "error: cannot have multiple input files of distinct "
980 << "language kinds without -x\n";
981 exit(1);
982 }
983
984 LK = ThisKind;
985 }
986
987 return LK;
988}
989
Daniel Dunbar0498cfc2009-11-10 19:51:53 +0000990static void FinalizeCompileOptions(CompileOptions &Opts,
991 const LangOptions &Lang) {
992 if (Lang.NoBuiltin)
993 Opts.SimplifyLibCalls = 0;
994 if (Lang.CPlusPlus)
995 Opts.NoCommon = 1;
996
997 // Handle -ftime-report.
998 Opts.TimePasses = TimeReport;
999}
1000
Daniel Dunbar227b2382009-11-09 22:45:57 +00001001static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001002 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +00001003 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001004 TargetInfo &Target,
1005 LangKind LK) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001006 Opts.getDiagnosticOpts() = DiagOpts;
1007
1008 Opts.getOutputFile() = OutputFile;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001009
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001010 // Initialize backend options, which may also be used to key some language
1011 // options.
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001012 InitializeCompileOptions(Opts.getCompileOpts(), Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001013
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001014 // Initialize language options.
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001015 //
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001016 // FIXME: These aren't used during operations on ASTs. Split onto a separate
1017 // code path to make this obvious.
Daniel Dunbar56749082009-11-11 07:26:12 +00001018 if (LK != langkind_ast)
1019 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001020 Opts.getCompileOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001021
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001022 // Initialize the static analyzer options.
1023 InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
1024
Daniel Dunbar0e0bae82009-11-11 21:43:12 +00001025 // Initialize the dependency output options (-M...).
1026 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
1027
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001028 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +00001029 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
1030 GetBuiltinIncludePath(Argv0),
1031 Verbose,
1032 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001033
1034 // Initialize the other preprocessor options.
1035 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001036
Daniel Dunbar29cf7462009-11-11 10:07:44 +00001037 // Initialize the preprocessed output options.
1038 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
1039
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001040 // Finalize some code generation options.
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001041 FinalizeCompileOptions(Opts.getCompileOpts(), Opts.getLangOpts());
Daniel Dunbare29709f2009-11-09 20:55:08 +00001042}
1043
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001044static Diagnostic *CreateDiagnosticEngine(const DiagnosticOptions &Opts,
1045 int argc, char **argv) {
1046 // Create the diagnostic client for reporting errors or for
1047 // implementing -verify.
1048 llvm::OwningPtr<DiagnosticClient> DiagClient;
1049 if (VerifyDiagnostics) {
1050 // When checking diagnostics, just buffer them up.
1051 DiagClient.reset(new TextDiagnosticBuffer());
1052 } else {
1053 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
1054 }
1055
Daniel Dunbar11e729d2009-11-12 07:28:21 +00001056 if (!Opts.DumpBuildInformation.empty())
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001057 SetUpBuildDumpLog(Opts, argc, argv, DiagClient);
1058
1059 // Configure our handling of diagnostics.
1060 Diagnostic *Diags = new Diagnostic(DiagClient.take());
Daniel Dunbar69079432009-11-12 07:28:44 +00001061 if (ProcessWarningOptions(*Diags, Opts))
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001062 return 0;
1063
1064 // Set an error handler, so that any LLVM backend diagnostics go through our
1065 // error handler.
1066 llvm::llvm_install_error_handler(LLVMErrorHandler,
1067 static_cast<void*>(Diags));
1068
1069 return Diags;
1070}
1071
Reid Spencer5f016e22007-07-11 17:01:13 +00001072int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001074 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001075 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001076
Daniel Dunbar4d861512009-09-03 04:54:12 +00001077 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001078 llvm::InitializeAllTargets();
1079 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001080
1081 llvm::cl::ParseCommandLineOptions(argc, argv,
1082 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001084 if (VerifyDiagnostics && InputFilenames.size() > 1) {
1085 fprintf(stderr, "-verify only works on single input files.\n");
1086 return 1;
1087 }
1088
Chris Lattner47099742009-02-18 01:51:21 +00001089 if (TimeReport)
1090 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00001092 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00001093 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
1094 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00001095 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 // If no input was specified, read from stdin.
1098 if (InputFilenames.empty())
1099 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00001100
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001101 // Construct the diagnostic engine first, so that we can build a diagnostic
1102 // client to use for any errors during option handling.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001103 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +00001104 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001105 llvm::OwningPtr<Diagnostic>
1106 Diags(CreateDiagnosticEngine(DiagOpts, argc, argv));
1107 if (!Diags)
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001108 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001109
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001110 // FIXME: Hack to make sure we release the diagnostic client, the engine
1111 // should (optionally?) take ownership of it.
1112 llvm::OwningPtr<DiagnosticClient> DiagClient(Diags->getClient());
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001113
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001114 // Initialize base triple. If a -triple option has been specified, use
1115 // that triple. Otherwise, default to the host triple.
1116 llvm::Triple Triple(TargetTriple);
1117 if (Triple.getTriple().empty())
1118 Triple = llvm::Triple(llvm::sys::getHostTriple());
1119
Chris Lattner11215192008-03-14 06:12:05 +00001120 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001121 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001122 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner11215192008-03-14 06:12:05 +00001124 if (Target == 0) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001125 Diags->Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001126 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001127 }
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Daniel Dunbar73b79592009-09-14 00:02:12 +00001129 // Set the target ABI if specified.
1130 if (!TargetABI.empty()) {
1131 if (!Target->setABI(TargetABI)) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001132 Diags->Report(diag::err_fe_unknown_target_abi) << TargetABI;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001133 return 1;
1134 }
1135 }
1136
Daniel Dunbard4270232009-01-20 23:17:32 +00001137 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001138 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Daniel Dunbar227b2382009-11-09 22:45:57 +00001140 // Infer the input language.
1141 //
1142 // FIXME: We should move .ast inputs to taking a separate path, they are
1143 // really quite different.
1144 LangKind LK = GetLanguage();
1145
1146 // Now that we have initialized the diagnostics engine and the target, finish
1147 // setting up the compiler invocation.
1148 CompilerInvocation CompOpts;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001149 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, LK);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001150
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001151 // Create the source manager.
1152 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Chris Lattner2c78b872009-04-14 23:22:57 +00001154 // Create a file manager object to provide access to and cache the filesystem.
1155 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001156
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001158 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001160 // AST inputs are handled specially.
1161 if (LK == langkind_ast) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001162 ProcessASTInputFile(CompOpts, InFile, ProgAction, *Diags, FileMgr,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001163 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001164 continue;
1165 }
1166
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001167 // Reset the ID tables if we are reusing the SourceManager.
1168 if (i)
1169 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Chris Lattnerf63aea32009-03-04 21:40:56 +00001171 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001172 llvm::OwningPtr<Preprocessor>
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001173 PP(CreatePreprocessor(*Diags, CompOpts.getLangOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001174 CompOpts.getPreprocessorOpts(),
Daniel Dunbar961c76e2009-11-11 21:44:42 +00001175 CompOpts.getHeaderSearchOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001176 CompOpts.getDependencyOutputOpts(),
Daniel Dunbar5814e652009-11-11 21:44:21 +00001177 *Target, SourceMgr, FileMgr));
1178
Chris Lattnerf63aea32009-03-04 21:40:56 +00001179 // Process the source file.
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001180 Diags->getClient()->BeginSourceFile(CompOpts.getLangOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001181 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001182 Diags->getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 }
Chris Lattner11215192008-03-14 06:12:05 +00001184
Daniel Dunbar9253e492009-11-10 00:46:12 +00001185 if (CompOpts.getDiagnosticOpts().ShowCarets)
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001186 if (unsigned NumDiagnostics = Diags->getNumDiagnostics())
Mike Stumpfc0fed32009-04-28 01:19:10 +00001187 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1188 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 FileMgr.PrintStats();
1192 fprintf(stderr, "\n");
1193 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001194
1195 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Daniel Dunbar276373d2008-10-27 22:10:13 +00001197 // If verifying diagnostics and we reached here, all is well.
1198 if (VerifyDiagnostics)
1199 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001201 // Managed static deconstruction. Useful for making things like
1202 // -time-passes usable.
1203 llvm::llvm_shutdown();
1204
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001205 return (Diags->getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001206}