blob: 3f3cd6ed15603384305f64b6ae78c0c70e218b6c [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 Dunbar2a79e162009-11-13 03:51:44 +000034#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbare29709f2009-11-09 20:55:08 +000035#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbar0e0bae82009-11-11 21:43:12 +000036#include "clang/Frontend/DependencyOutputOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000037#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000038#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000039#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000040#include "clang/Frontend/PathDiagnosticClients.h"
41#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000042#include "clang/Frontend/PreprocessorOutputOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000043#include "clang/Frontend/TextDiagnosticBuffer.h"
44#include "clang/Frontend/TextDiagnosticPrinter.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000045#include "clang/Frontend/Utils.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000046#include "clang/Lex/HeaderSearch.h"
47#include "clang/Lex/LexDiagnostic.h"
48#include "clang/Parse/Parser.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000049#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000050#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000051#include "clang/Sema/SemaDiagnostic.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000052#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000053#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000054#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000055#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000056#include "llvm/ADT/StringMap.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//===----------------------------------------------------------------------===//
Daniel Dunbaraa576142009-11-12 15:23:20 +000079// Frontend Actions
80//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000081
82enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000083 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000084 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000085 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000086 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000087 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000088 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000089 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000090 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +000091 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +000092 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000093 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +000094 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +000095 ASTDump, // Parse ASTs and dump them.
96 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +000097 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +000098 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +000099 ParsePrintCallbacks, // Parse and print each callback.
100 ParseSyntaxOnly, // Parse and perform semantic analysis.
101 ParseNoop, // Parse with noop callbacks.
102 RunPreprocessorOnly, // Just lex, no output.
103 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000104 DumpTokens, // Dump out preprocessed tokens.
105 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000106 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000107 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000108 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000109 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000110};
111
Mike Stump1eb44332009-09-09 15:08:12 +0000112static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000113ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
114 llvm::cl::init(ParseSyntaxOnly),
115 llvm::cl::values(
116 clEnumValN(RunPreprocessorOnly, "Eonly",
117 "Just run preprocessor, no output (for timings)"),
118 clEnumValN(PrintPreprocessedInput, "E",
119 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000120 clEnumValN(DumpRawTokens, "dump-raw-tokens",
121 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000122 clEnumValN(RunAnalysis, "analyze",
123 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000124 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 "Run preprocessor, dump internal rep of tokens"),
126 clEnumValN(ParseNoop, "parse-noop",
127 "Run parser with noop callbacks (for timings)"),
128 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
129 "Run parser and perform semantic analysis"),
130 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
131 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000132 clEnumValN(EmitHTML, "emit-html",
133 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000134 clEnumValN(ASTPrint, "ast-print",
135 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000136 clEnumValN(ASTPrintXML, "ast-print-xml",
137 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000138 clEnumValN(ASTDump, "ast-dump",
139 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000140 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000141 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000142 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000143 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000144 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
145 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000146 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000147 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000148 clEnumValN(GeneratePCH, "emit-pch",
149 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000150 clEnumValN(EmitAssembly, "S",
151 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000153 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000154 clEnumValN(EmitBC, "emit-llvm-bc",
155 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000156 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
157 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000158 clEnumValN(RewriteTest, "rewrite-test",
159 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000160 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000161 "Rewrite ObjC into C (code rewriter example)"),
162 clEnumValN(RewriteMacros, "rewrite-macros",
163 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000164 clEnumValN(RewriteBlocks, "rewrite-blocks",
165 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 clEnumValEnd));
167
Daniel Dunbaraa576142009-11-12 15:23:20 +0000168//===----------------------------------------------------------------------===//
Daniel Dunbar914474c2009-11-13 01:02:10 +0000169// Utility Methods
Reid Spencer5f016e22007-07-11 17:01:13 +0000170//===----------------------------------------------------------------------===//
171
Douglas Gregore1d918e2009-04-10 23:10:45 +0000172static bool InitializeSourceManager(Preprocessor &PP,
Daniel Dunbar26266882009-11-12 23:52:32 +0000173 const FrontendOptions &FEOpts,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000174 const std::string &InFile) {
175 // Figure out where to get and map in the main file.
176 SourceManager &SourceMgr = PP.getSourceManager();
177 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000178
Daniel Dunbar26266882009-11-12 23:52:32 +0000179 if (FEOpts.EmptyInputOnly) {
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000180 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000181 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000182 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
183 SourceMgr.createMainFileIDForMemBuffer(SB);
184 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000185 const FileEntry *File = FileMgr.getFile(InFile);
186 if (File) SourceMgr.createMainFileID(File, SourceLocation());
187 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000188 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000189 return true;
190 }
191 } else {
192 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000193 SourceMgr.createMainFileIDForMemBuffer(SB);
194 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000195 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000196 return true;
197 }
198 }
199
200 return false;
201}
202
Daniel Dunbar750156a2009-11-07 04:19:57 +0000203std::string GetBuiltinIncludePath(const char *Argv0) {
204 llvm::sys::Path P =
205 llvm::sys::Path::GetMainExecutable(Argv0,
206 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000207
Daniel Dunbar750156a2009-11-07 04:19:57 +0000208 if (!P.isEmpty()) {
209 P.eraseComponent(); // Remove /clang from foo/bin/clang
210 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000211
Daniel Dunbar750156a2009-11-07 04:19:57 +0000212 // Get foo/lib/clang/<version>/include
213 P.appendComponent("lib");
214 P.appendComponent("clang");
215 P.appendComponent(CLANG_VERSION_STRING);
216 P.appendComponent("include");
217 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000218
Daniel Dunbar750156a2009-11-07 04:19:57 +0000219 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000220}
221
Daniel Dunbar90b18272009-11-04 23:56:25 +0000222static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000223CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000224 const PreprocessorOptions &PPOpts,
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000225 const HeaderSearchOptions &HSOpts,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000226 const DependencyOutputOptions &DepOpts,
227 TargetInfo &Target, SourceManager &SourceMgr,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000228 FileManager &FileMgr) {
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000229 // Create a PTH manager if we are using some form of a token cache.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000230 PTHManager *PTHMgr = 0;
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000231 if (!PPOpts.getTokenCache().empty())
232 PTHMgr = PTHManager::Create(PPOpts.getTokenCache(), Diags);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000233
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000234 // FIXME: Don't fail like this.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000235 if (Diags.hasErrorOccurred())
236 exit(1);
237
238 // Create the Preprocessor.
Daniel Dunbar5814e652009-11-11 21:44:21 +0000239 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000240 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000241 SourceMgr, *HeaderInfo, PTHMgr,
242 /*OwnsHeaderSearch=*/true);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000243
244 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
245 // That argument is used as the IdentifierInfoLookup argument to
246 // IdentifierTable's ctor.
247 if (PTHMgr) {
248 PTHMgr->setPreprocessor(PP);
249 PP->setPTHManager(PTHMgr);
250 }
251
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000252 InitializePreprocessor(*PP, PPOpts, HSOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000253
Daniel Dunbarca11f612009-11-11 21:44:00 +0000254 // Handle generating dependencies, if requested.
255 if (!DepOpts.OutputFile.empty())
256 AttachDependencyFileGen(*PP, DepOpts);
257
Daniel Dunbar90b18272009-11-04 23:56:25 +0000258 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000259}
Reid Spencer5f016e22007-07-11 17:01:13 +0000260
Daniel Dunbar914474c2009-11-13 01:02:10 +0000261/// \brief Buld a new code-completion consumer that prints the results of
262/// code completion to standard output.
263static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S,
264 void *UserData) {
265 const FrontendOptions &Opts = *(FrontendOptions*)UserData;
266 if (Opts.DebugCodeCompletionPrinter)
267 return new PrintingCodeCompleteConsumer(S, Opts.ShowMacrosInCodeCompletion,
268 llvm::outs());
269
270 return new CIndexCodeCompleteConsumer(S, Opts.ShowMacrosInCodeCompletion,
271 llvm::outs());
272}
273
Reid Spencer5f016e22007-07-11 17:01:13 +0000274//===----------------------------------------------------------------------===//
275// Basic Parser driver
276//===----------------------------------------------------------------------===//
277
Chris Lattner51574ea2008-04-19 23:25:44 +0000278static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000280 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 // Parsing the specified input file.
283 P.ParseTranslationUnit();
284 delete PA;
285}
286
287//===----------------------------------------------------------------------===//
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000288// Dump Build Information
Chris Lattner75a97cb2009-04-17 21:05:01 +0000289//===----------------------------------------------------------------------===//
290
Daniel Dunbar227b2382009-11-09 22:45:57 +0000291static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000292 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000293 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000294 std::string ErrorInfo;
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000295 llvm::raw_ostream *OS =
296 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000297 if (!ErrorInfo.empty()) {
298 llvm::errs() << "error opening -dump-build-information file '"
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000299 << DiagOpts.DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000300 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000301 return;
302 }
303
Daniel Dunbaraea36412009-11-11 09:38:24 +0000304 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000305 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000306 (*OS) << argv[i] << ' ';
307 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000309 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000310 DiagnosticClient *Logger =
311 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000312 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000313}
314
Chris Lattner75a97cb2009-04-17 21:05:01 +0000315//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000316// Main driver
317//===----------------------------------------------------------------------===//
318
Daniel Dunbaraa576142009-11-12 15:23:20 +0000319/// ClangFrontendTimer - The front-end activities should charge time to it with
320/// TimeRegion. The -ftime-report option controls whether this will do
321/// anything.
322llvm::Timer *ClangFrontendTimer = 0;
323
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000324static llvm::raw_ostream *ComputeOutFile(const FrontendOptions &Opts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000325 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000326 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000327 bool Binary,
328 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000329 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000330 std::string OutFile;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000331 if (!Opts.OutputFile.empty())
332 OutFile = Opts.OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +0000333 else if (InFile == "-") {
334 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000335 } else if (Extension) {
336 llvm::sys::Path Path(InFile);
337 Path.eraseSuffix();
338 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000339 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000340 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000341 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000342 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000343
Chris Lattner92bcc272009-08-23 02:59:41 +0000344 std::string Error;
345 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000346 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000347 if (!Error.empty()) {
348 // FIXME: Don't fail this way.
349 llvm::errs() << "ERROR: " << Error << "\n";
350 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000351 }
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Chris Lattner92bcc272009-08-23 02:59:41 +0000353 if (OutFile != "-")
354 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000355
356 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000357}
358
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000359/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000360/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000361static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000362 FileManager &FileMgr,
363 const std::vector<ParsedSourceLocation> &Locs) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000364 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000365
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000366 for (unsigned i = 0, e = Locs.size(); i != e; ++i) {
367 if (const FileEntry *File = FileMgr.getFile(Locs[i].FileName)) {
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000368 RequestedSourceLocation Requested;
369 Requested.File = File;
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000370 Requested.Line = Locs[i].Line;
371 Requested.Column = Locs[i].Column;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000372 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000373 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000374 } else {
375 llvm::errs() << "FIX-IT could not find file \""
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000376 << Locs[i].FileName << "\"\n";
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000377 }
378 }
379
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000380 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000381}
382
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000383static ASTConsumer *CreateConsumerAction(CompilerInstance &CI,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000384 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000385 const std::string &InFile,
386 ProgActions PA,
387 llvm::OwningPtr<llvm::raw_ostream> &OS,
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000388 llvm::sys::Path &OutPath) {
389 const FrontendOptions &FEOpts = CI.getFrontendOpts();
Daniel Dunbar26266882009-11-12 23:52:32 +0000390
Ted Kremenek85888962008-10-21 00:54:44 +0000391 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000393 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000394
395 case ASTPrint:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000396 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000397 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Douglas Gregoree75c052009-05-21 20:55:50 +0000399 case ASTPrintXML:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000400 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "xml", false,
401 OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000402 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000403
Eli Friedman66d6f042009-05-18 22:20:00 +0000404 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000405 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000406
Eli Friedman66d6f042009-05-18 22:20:00 +0000407 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000408 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000409
Anders Carlsson78762eb2009-09-24 18:54:49 +0000410 case DumpRecordLayouts:
411 return CreateRecordLayoutDumper();
412
Eli Friedman66d6f042009-05-18 22:20:00 +0000413 case InheritanceView:
Daniel Dunbar26266882009-11-12 23:52:32 +0000414 return CreateInheritanceViewer(FEOpts.ViewClassInheritance);
Eli Friedman66d6f042009-05-18 22:20:00 +0000415
416 case EmitAssembly:
417 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000418 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000419 case EmitLLVMOnly: {
420 BackendAction Act;
421 if (ProgAction == EmitAssembly) {
422 Act = Backend_EmitAssembly;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000423 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "s", true,
424 OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000425 } else if (ProgAction == EmitLLVM) {
426 Act = Backend_EmitLL;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000427 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "ll", true,
428 OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000429 } else if (ProgAction == EmitLLVMOnly) {
430 Act = Backend_EmitNothing;
431 } else {
432 Act = Backend_EmitBC;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000433 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "bc", true,
434 OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000435 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000436
Daniel Dunbare0c4ff22009-11-12 15:42:53 +0000437 // Fix-its can change semantics, disallow with any IRgen action.
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000438 if (FEOpts.FixItAll || !FEOpts.FixItLocations.empty()) {
Daniel Dunbare0c4ff22009-11-12 15:42:53 +0000439 PP.getDiagnostics().Report(diag::err_fe_no_fixit_and_codegen);
440 return 0;
441 }
442
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000443 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000444 CI.getCodeGenOpts(), InFile, OS.get(),
445 CI.getLLVMContext());
Eli Friedman66d6f042009-05-18 22:20:00 +0000446 }
447
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000448 case RewriteObjC:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000449 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000450 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Daniel Dunbar69079432009-11-12 07:28:44 +0000451 PP.getLangOptions(),
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000452 CI.getDiagnosticOpts().NoRewriteMacros);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000453
454 case RewriteBlocks:
455 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
456 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000457
458 case ParseSyntaxOnly:
459 return new ASTConsumer();
460
461 case PrintDeclContext:
462 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000463 }
464}
465
Daniel Dunbar975790e2009-11-12 02:53:20 +0000466/// ReadPCHFile - Load a PCH file from disk, and initialize the preprocessor for
467/// reading from the PCH file.
468///
469/// \return The AST source, or null on failure.
470static ExternalASTSource *ReadPCHFile(llvm::StringRef Path,
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000471 const std::string Sysroot,
Daniel Dunbar975790e2009-11-12 02:53:20 +0000472 Preprocessor &PP,
473 ASTContext &Context) {
474 // If the user specified -isysroot, it will be used for relocatable PCH files.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000475 const char *isysrootPCH = Sysroot.c_str();
Daniel Dunbar975790e2009-11-12 02:53:20 +0000476 if (isysrootPCH[0] == '\0')
477 isysrootPCH = 0;
478
479 llvm::OwningPtr<PCHReader> Reader;
480 Reader.reset(new PCHReader(PP, &Context, isysrootPCH));
481
482 switch (Reader->ReadPCH(Path)) {
483 case PCHReader::Success:
484 // Set the predefines buffer as suggested by the PCH reader. Typically, the
485 // predefines buffer will be empty.
486 PP.setPredefines(Reader->getSuggestedPredefines());
487 return Reader.take();
488
489 case PCHReader::Failure:
490 // Unrecoverable failure: don't even try to process the input file.
491 break;
492
493 case PCHReader::IgnorePCH:
494 // No suitable PCH file could be found. Return an error.
495 break;
496 }
497
498 return 0;
499}
500
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000501/// ProcessInputFile - Process a single input file with the specified state.
502///
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000503static void ProcessInputFile(CompilerInstance &CI, Preprocessor &PP,
504 const std::string &InFile, ProgActions PA) {
505 const FrontendOptions &FEOpts = CI.getFrontendOpts();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000506 llvm::OwningPtr<llvm::raw_ostream> OS;
507 llvm::OwningPtr<ASTConsumer> Consumer;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000508 FixItRewriter *FixItRewrite = 0;
509 bool CompleteTranslationUnit = true;
510 llvm::sys::Path OutPath;
511
512 switch (PA) {
513 default:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000514 Consumer.reset(CreateConsumerAction(CI, PP, InFile, PA, OS, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000515 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000516 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000517 return;
518 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000519 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000520
521 case EmitHTML:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000522 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000523 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000524 break;
525
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000526 case RunAnalysis:
Daniel Dunbar26266882009-11-12 23:52:32 +0000527 Consumer.reset(CreateAnalysisConsumer(PP, FEOpts.OutputFile,
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000528 CI.getAnalyzerOpts()));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000529 break;
530
Daniel Dunbarf7973292009-11-11 08:13:32 +0000531 case GeneratePCH: {
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000532 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Daniel Dunbar26266882009-11-12 23:52:32 +0000533 bool Relocatable = FEOpts.RelocatablePCH;
534 if (Relocatable && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000535 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
Daniel Dunbar26266882009-11-12 23:52:32 +0000536 Relocatable = false;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000539 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, true, OutPath));
Daniel Dunbar26266882009-11-12 23:52:32 +0000540 if (Relocatable)
Daniel Dunbarf7973292009-11-11 08:13:32 +0000541 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000542 else
543 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000544 CompleteTranslationUnit = false;
545 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000546 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000547
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000548 // Do any necessary set up for non-consumer actions.
549 case DumpRawTokens:
550 case DumpTokens:
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000551 case RunPreprocessorOnly:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000552 case ParseNoop:
553 break; // No setup.
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000555 case GeneratePTH:
Daniel Dunbar26266882009-11-12 23:52:32 +0000556 if (FEOpts.OutputFile.empty() || FEOpts.OutputFile == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000557 // FIXME: Don't fail this way.
558 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000559 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000560 ::exit(1);
561 }
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000562 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, true, OutPath));
Ted Kremenek85888962008-10-21 00:54:44 +0000563 break;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000564
Chris Lattnercc7dea82009-04-27 22:02:30 +0000565 case PrintPreprocessedInput:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000566 case ParsePrintCallbacks:
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000567 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +0000568 case RewriteTest:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000569 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, true, OutPath));
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000570 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000571 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000572
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000573 // Check if we want a fix-it rewriter.
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000574 if (FEOpts.FixItAll || !FEOpts.FixItLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000575 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000576 PP.getSourceManager(),
577 PP.getLangOptions());
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000578 if (!FEOpts.FixItLocations.empty() &&
579 !AddFixItLocations(FixItRewrite, PP.getFileManager(),
580 FEOpts.FixItLocations)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000581 // All of the fix-it locations were bad. Don't fix anything.
582 delete FixItRewrite;
583 FixItRewrite = 0;
584 }
585 }
586
587 llvm::OwningPtr<ASTContext> ContextOwner;
Daniel Dunbar66068642009-11-12 02:53:13 +0000588 llvm::OwningPtr<ExternalASTSource> Source;
589 const std::string &ImplicitPCHInclude =
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000590 CI.getPreprocessorOpts().getImplicitPCHInclude();
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000591 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000592 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
593 PP.getSourceManager(),
594 PP.getTargetInfo(),
595 PP.getIdentifierTable(),
596 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000597 PP.getBuiltinInfo(),
Daniel Dunbar26266882009-11-12 23:52:32 +0000598 /* FreeMemory = */ !FEOpts.DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000599 /* size_reserve = */0));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000600
601 if (!ImplicitPCHInclude.empty()) {
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000602 Source.reset(ReadPCHFile(ImplicitPCHInclude,
603 CI.getHeaderSearchOpts().Sysroot, PP,
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000604 *ContextOwner));
605 if (!Source)
606 return;
607
608 // Attach the PCH reader to the AST context as an external AST source, so
609 // that declarations will be deserialized from the PCH file as needed.
610 ContextOwner->setExternalSource(Source);
611 } else {
612 // Initialize builtin info when not using PCH.
613 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
614 PP.getLangOptions().NoBuiltin);
615 }
616
617 // Initialize the main file entry. This needs to be delayed until after PCH
618 // has loaded.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000619 if (InitializeSourceManager(PP, CI.getFrontendOpts(), InFile))
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000620 return;
621
Douglas Gregor81b747b2009-09-17 21:32:03 +0000622 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
Daniel Dunbar914474c2009-11-13 01:02:10 +0000623 void *CreateCodeCompleterData = (void*) &FEOpts;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000624
Daniel Dunbar914474c2009-11-13 01:02:10 +0000625 if (!FEOpts.CodeCompletionAt.FileName.empty()) {
Douglas Gregorb657f112009-09-22 21:11:38 +0000626 // Tell the source manager to chop off the given file at a specific
627 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000628 if (const FileEntry *Entry
Daniel Dunbar914474c2009-11-13 01:02:10 +0000629 = PP.getFileManager().getFile(FEOpts.CodeCompletionAt.FileName)) {
Douglas Gregorb657f112009-09-22 21:11:38 +0000630 // Truncate the named file at the given line/column.
Daniel Dunbar914474c2009-11-13 01:02:10 +0000631 PP.getSourceManager().truncateFileAt(Entry,
632 FEOpts.CodeCompletionAt.Line,
633 FEOpts.CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000634
Douglas Gregorb657f112009-09-22 21:11:38 +0000635 // Set up the creation routine for code-completion.
636 CreateCodeCompleter = BuildPrintingCodeCompleter;
637 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000638 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Daniel Dunbar914474c2009-11-13 01:02:10 +0000639 << FEOpts.CodeCompletionAt.FileName;
Douglas Gregorb657f112009-09-22 21:11:38 +0000640 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000641 }
642
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000643 // Run the AST consumer action.
Daniel Dunbar26266882009-11-12 23:52:32 +0000644 ParseAST(PP, Consumer.get(), *ContextOwner.get(), FEOpts.ShowStats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000645 CompleteTranslationUnit,
646 CreateCodeCompleter, CreateCodeCompleterData);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000647 } else {
648 // Initialize builtin info.
649 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
650 PP.getLangOptions().NoBuiltin);
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000651
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000652 // Initialize the main file entry. This needs to be delayed until after PCH
653 // has loaded.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000654 if (InitializeSourceManager(PP, CI.getFrontendOpts(), InFile))
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000655 return;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000656
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000657 // Run the preprocessor actions.
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000658 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000659 switch (PA) {
660 default:
661 assert(0 && "unexpected program action");
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000662
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000663 case DumpRawTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000664 SourceManager &SM = PP.getSourceManager();
665 // Start lexing the specified input file.
666 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
667 RawLex.SetKeepWhitespaceMode(true);
668
669 Token RawTok;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000670 RawLex.LexFromRawLexer(RawTok);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000671 while (RawTok.isNot(tok::eof)) {
672 PP.DumpToken(RawTok, true);
673 fprintf(stderr, "\n");
674 RawLex.LexFromRawLexer(RawTok);
675 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000676 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000677 }
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000678
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000679 case DumpTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000680 Token Tok;
681 // Start preprocessing the specified input file.
682 PP.EnterMainSourceFile();
683 do {
684 PP.Lex(Tok);
685 PP.DumpToken(Tok, true);
686 fprintf(stderr, "\n");
687 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000688 break;
689 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000690
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000691 case GeneratePTH:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000692 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000693 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000694
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000695 case ParseNoop:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000696 ParseFile(PP, new MinimalAction(PP));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000697 break;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000698
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000699 case ParsePrintCallbacks:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000700 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000701 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000702
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000703 case PrintPreprocessedInput:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000704 DoPrintPreprocessedInput(PP, OS.get(), CI.getPreprocessorOutputOpts());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000705 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000706
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000707 case RewriteMacros:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000708 RewriteMacrosInInput(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000709 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000710
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000711 case RewriteTest:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000712 DoRewriteTest(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000713 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000714
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000715 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000716 Token Tok;
717 // Start parsing the specified input file.
718 PP.EnterMainSourceFile();
719 do {
720 PP.Lex(Tok);
721 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000722 break;
723 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000724 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000725 }
726
Chris Lattner1aee61a2009-04-27 21:25:27 +0000727 if (FixItRewrite)
Daniel Dunbar26266882009-11-12 23:52:32 +0000728 FixItRewrite->WriteFixedFile(InFile, FEOpts.OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000729
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000730 // Release the consumer and the AST, in that order since the consumer may
731 // perform actions in its destructor which require the context.
Daniel Dunbar26266882009-11-12 23:52:32 +0000732 if (FEOpts.DisableFree) {
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000733 Consumer.take();
Chris Lattner1aee61a2009-04-27 21:25:27 +0000734 ContextOwner.take();
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000735 } else {
736 Consumer.reset();
737 ContextOwner.reset();
738 }
Eli Friedman66d6f042009-05-18 22:20:00 +0000739
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000740 if (CI.getDiagnosticOpts().VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000741 if (CheckDiagnostics(PP))
742 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000743
Daniel Dunbar26266882009-11-12 23:52:32 +0000744 if (FEOpts.ShowStats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000745 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 PP.PrintStats();
747 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000748 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000749 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 fprintf(stderr, "\n");
751 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000752
Eli Friedman66d6f042009-05-18 22:20:00 +0000753 // Always delete the output stream because we don't want to leak file
754 // handles. Also, we don't want to try to erase an open file.
755 OS.reset();
756
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000757 // If we had errors, try to erase the output file.
758 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000759 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000760}
761
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000762/// ProcessInputFile - Process a single AST input file with the specified state.
763///
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000764static void ProcessASTInputFile(CompilerInstance &CI, const std::string &InFile,
765 ProgActions PA, FileManager &FileMgr) {
766 const FrontendOptions &FEOpts = CI.getFrontendOpts();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000767 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000768 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000769 if (!AST) {
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000770 CI.getDiagnostics().Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000771 return;
772 }
773
774 Preprocessor &PP = AST->getPreprocessor();
775
776 llvm::OwningPtr<llvm::raw_ostream> OS;
777 llvm::sys::Path OutPath;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000778 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CI, PP, InFile, PA,
779 OS, OutPath));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000780 if (!Consumer.get()) {
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000781 CI.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000782 return;
783 }
784
Daniel Dunbara674bf42009-09-21 03:03:56 +0000785 // Set the main file ID to an empty file.
786 //
787 // FIXME: We probably shouldn't need this, but for now this is the simplest
788 // way to reuse the logic in ParseAST.
789 const char *EmptyStr = "";
790 llvm::MemoryBuffer *SB =
791 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
792 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000793
Daniel Dunbara674bf42009-09-21 03:03:56 +0000794 // Stream the input AST to the consumer.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000795 CI.getDiagnostics().getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbar26266882009-11-12 23:52:32 +0000796 ParseAST(PP, Consumer.get(), AST->getASTContext(), FEOpts.ShowStats);
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000797 CI.getDiagnostics().getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000798
799 // Release the consumer and the AST, in that order since the consumer may
800 // perform actions in its destructor which require the context.
Daniel Dunbar26266882009-11-12 23:52:32 +0000801 if (FEOpts.DisableFree) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000802 Consumer.take();
803 AST.take();
804 } else {
805 Consumer.reset();
806 AST.reset();
807 }
808
809 // Always delete the output stream because we don't want to leak file
810 // handles. Also, we don't want to try to erase an open file.
811 OS.reset();
812
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000813 // If we had errors, try to erase the output file.
814 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000815 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000816}
817
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000818static void LLVMErrorHandler(void *UserData, const std::string &Message) {
819 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
820
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000821 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000822
823 // We cannot recover from llvm errors.
824 exit(1);
825}
826
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000827static TargetInfo *
828ConstructCompilerInvocation(CompilerInvocation &Opts, Diagnostic &Diags,
829 const char *Argv0,
830 const DiagnosticOptions &DiagOpts, bool &IsAST) {
Daniel Dunbar227b2382009-11-09 22:45:57 +0000831 Opts.getDiagnosticOpts() = DiagOpts;
832
Daniel Dunbar26266882009-11-12 23:52:32 +0000833 // Initialize frontend options.
834 InitializeFrontendOptions(Opts.getFrontendOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000835
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000836 // Initialize base triple. If a -triple option has been specified, use
837 // that triple. Otherwise, default to the host triple.
838 llvm::Triple Triple(Opts.getFrontendOpts().TargetTriple);
839 if (Triple.getTriple().empty())
840 Triple = llvm::Triple(llvm::sys::getHostTriple());
841
842 // Get information about the target being compiled for.
843 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple.getTriple());
844 if (!Target) {
845 Diags.Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
846 return 0;
847 }
848
849 // Set the target ABI if specified.
850 if (!Opts.getFrontendOpts().TargetABI.empty() &&
851 !Target->setABI(Opts.getFrontendOpts().TargetABI)) {
852 Diags.Report(diag::err_fe_unknown_target_abi)
853 << Opts.getFrontendOpts().TargetABI;
854 return 0;
855 }
856
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +0000857 // Initialize backend options, which may also be used to key some language
858 // options.
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000859 InitializeCodeGenOptions(Opts.getCodeGenOpts(), *Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +0000860
Daniel Dunbarfbe2faf2009-11-13 02:06:12 +0000861 // Determine the input language, we currently require all files to match.
862 FrontendOptions::InputKind IK = Opts.getFrontendOpts().Inputs[0].first;
863 for (unsigned i = 1, e = Opts.getFrontendOpts().Inputs.size(); i != e; ++i) {
864 if (Opts.getFrontendOpts().Inputs[i].first != IK) {
865 llvm::errs() << "error: cannot have multiple input files of distinct "
866 << "language kinds without -x\n";
867 return 0;
868 }
869 }
870
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000871 // Initialize language options.
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000872 //
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000873 // FIXME: These aren't used during operations on ASTs. Split onto a separate
874 // code path to make this obvious.
Daniel Dunbarfbe2faf2009-11-13 02:06:12 +0000875 IsAST = (IK == FrontendOptions::IK_AST);
Daniel Dunbar26266882009-11-12 23:52:32 +0000876 if (!IsAST)
Daniel Dunbarfbe2faf2009-11-13 02:06:12 +0000877 InitializeLangOptions(Opts.getLangOpts(), IK, *Target,
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000878 Opts.getCodeGenOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000879
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000880 // Initialize the static analyzer options.
881 InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
882
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000883 // Initialize the dependency output options (-M...).
884 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
885
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000886 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +0000887 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
888 GetBuiltinIncludePath(Argv0),
Daniel Dunbarf7973292009-11-11 08:13:32 +0000889 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000890
891 // Initialize the other preprocessor options.
892 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000893
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000894 // Initialize the preprocessed output options.
895 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
896
Daniel Dunbar26266882009-11-12 23:52:32 +0000897 // Finalize some code generation options which are derived from other places.
898 if (Opts.getLangOpts().NoBuiltin)
899 Opts.getCodeGenOpts().SimplifyLibCalls = 0;
900 if (Opts.getLangOpts().CPlusPlus)
901 Opts.getCodeGenOpts().NoCommon = 1;
902 Opts.getCodeGenOpts().TimePasses = Opts.getFrontendOpts().ShowTimers;
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000903
904 return Target;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000905}
906
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +0000907static Diagnostic *CreateDiagnosticEngine(const DiagnosticOptions &Opts,
908 int argc, char **argv) {
909 // Create the diagnostic client for reporting errors or for
910 // implementing -verify.
911 llvm::OwningPtr<DiagnosticClient> DiagClient;
Daniel Dunbar26266882009-11-12 23:52:32 +0000912 if (Opts.VerifyDiagnostics) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +0000913 // When checking diagnostics, just buffer them up.
914 DiagClient.reset(new TextDiagnosticBuffer());
915 } else {
916 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
917 }
918
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000919 if (!Opts.DumpBuildInformation.empty())
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +0000920 SetUpBuildDumpLog(Opts, argc, argv, DiagClient);
921
922 // Configure our handling of diagnostics.
923 Diagnostic *Diags = new Diagnostic(DiagClient.take());
Daniel Dunbar69079432009-11-12 07:28:44 +0000924 if (ProcessWarningOptions(*Diags, Opts))
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +0000925 return 0;
926
927 // Set an error handler, so that any LLVM backend diagnostics go through our
928 // error handler.
929 llvm::llvm_install_error_handler(LLVMErrorHandler,
930 static_cast<void*>(Diags));
931
932 return Diags;
933}
934
Reid Spencer5f016e22007-07-11 17:01:13 +0000935int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +0000937 llvm::PrettyStackTraceProgram X(argc, argv);
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000938 CompilerInstance Clang(&llvm::getGlobalContext(), false);
Daniel Dunbard6970812009-09-02 23:20:15 +0000939
Daniel Dunbar4d861512009-09-03 04:54:12 +0000940 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +0000941 llvm::InitializeAllTargets();
942 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +0000943
944 llvm::cl::ParseCommandLineOptions(argc, argv,
945 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +0000947 // Construct the diagnostic engine first, so that we can build a diagnostic
948 // client to use for any errors during option handling.
Daniel Dunbar227b2382009-11-09 22:45:57 +0000949 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000950 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000951 Clang.setDiagnostics(CreateDiagnosticEngine(DiagOpts, argc, argv));
952 if (!&Clang.getDiagnostics())
Sebastian Redl63a9e0f2009-03-06 17:41:35 +0000953 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +0000954
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +0000955 // FIXME: Hack to make sure we release the diagnostic client, the engine
956 // should (optionally?) take ownership of it.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000957 Clang.setDiagnosticClient(Clang.getDiagnostics().getClient());
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000958
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000959 // Now that we have initialized the diagnostics engine, create the target and
960 // the compiler invocation object.
Daniel Dunbar227b2382009-11-09 22:45:57 +0000961 //
962 // FIXME: We should move .ast inputs to taking a separate path, they are
963 // really quite different.
Daniel Dunbar26266882009-11-12 23:52:32 +0000964 bool IsAST;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000965 Clang.setTarget(
966 ConstructCompilerInvocation(Clang.getInvocation(), Clang.getDiagnostics(),
967 argv[0], DiagOpts, IsAST));
968 if (!&Clang.getTarget())
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000969 return 1;
Daniel Dunbar26266882009-11-12 23:52:32 +0000970
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000971 // Validate/process some options
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000972 if (Clang.getHeaderSearchOpts().Verbose)
Daniel Dunbar1417c742009-11-12 23:52:46 +0000973 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
974 << " based upon " << PACKAGE_STRING
975 << " hosted on " << llvm::sys::getHostTriple() << "\n";
976
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000977 if (Clang.getFrontendOpts().ShowTimers)
Daniel Dunbar26266882009-11-12 23:52:32 +0000978 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
979
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000980 if (Clang.getDiagnosticOpts().VerifyDiagnostics &&
981 Clang.getFrontendOpts().Inputs.size() > 1) {
Daniel Dunbar26266882009-11-12 23:52:32 +0000982 fprintf(stderr, "-verify only works on single input files.\n");
983 return 1;
984 }
985
986 // C++ visualization?
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000987 if (!Clang.getFrontendOpts().ViewClassInheritance.empty())
Daniel Dunbar26266882009-11-12 23:52:32 +0000988 ProgAction = InheritanceView;
Daniel Dunbar227b2382009-11-09 22:45:57 +0000989
Daniel Dunbar4cc1a252009-11-05 01:53:23 +0000990 // Create the source manager.
991 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Chris Lattner2c78b872009-04-14 23:22:57 +0000993 // Create a file manager object to provide access to and cache the filesystem.
994 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000995
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000996 for (unsigned i = 0, e = Clang.getFrontendOpts().Inputs.size(); i != e; ++i) {
997 const std::string &InFile = Clang.getFrontendOpts().Inputs[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000999 // AST inputs are handled specially.
Daniel Dunbar26266882009-11-12 23:52:32 +00001000 if (IsAST) {
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001001 ProcessASTInputFile(Clang, InFile, ProgAction, FileMgr);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001002 continue;
1003 }
1004
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001005 // Reset the ID tables if we are reusing the SourceManager.
1006 if (i)
1007 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattnerf63aea32009-03-04 21:40:56 +00001009 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001010 llvm::OwningPtr<Preprocessor>
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001011 PP(CreatePreprocessor(Clang.getDiagnostics(), Clang.getLangOpts(),
1012 Clang.getPreprocessorOpts(),
1013 Clang.getHeaderSearchOpts(),
1014 Clang.getDependencyOutputOpts(),
1015 Clang.getTarget(), SourceMgr, FileMgr));
Daniel Dunbar5814e652009-11-11 21:44:21 +00001016
Chris Lattnerf63aea32009-03-04 21:40:56 +00001017 // Process the source file.
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001018 Clang.getDiagnostics().getClient()->BeginSourceFile(Clang.getLangOpts());
1019 ProcessInputFile(Clang, *PP, InFile, ProgAction);
1020 Clang.getDiagnostics().getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001021 }
Chris Lattner11215192008-03-14 06:12:05 +00001022
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001023 if (Clang.getDiagnosticOpts().ShowCarets)
1024 if (unsigned NumDiagnostics = Clang.getDiagnostics().getNumDiagnostics())
Mike Stumpfc0fed32009-04-28 01:19:10 +00001025 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1026 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001028 if (Clang.getFrontendOpts().ShowStats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 FileMgr.PrintStats();
1030 fprintf(stderr, "\n");
1031 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001032
1033 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Daniel Dunbar276373d2008-10-27 22:10:13 +00001035 // If verifying diagnostics and we reached here, all is well.
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001036 if (Clang.getDiagnosticOpts().VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001037 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001039 // Managed static deconstruction. Useful for making things like
1040 // -time-passes usable.
1041 llvm::llvm_shutdown();
1042
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001043 return (Clang.getDiagnostics().getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001044}