blob: bbdfcaf57e03efa6992b3cb7cd501d03bf7c894a [file] [log] [blame]
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001//===--- CompilerInstance.cpp ---------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/CompilerInstance.h"
Douglas Gregorf18d0d82010-08-12 23:31:19 +000011#include "clang/Sema/Sema.h"
Daniel Dunbar12ce6942009-11-14 02:47:17 +000012#include "clang/AST/ASTConsumer.h"
Daniel Dunbar5eb81002009-11-13 08:20:47 +000013#include "clang/AST/ASTContext.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000014#include "clang/Basic/Diagnostic.h"
Daniel Dunbar16b74492009-11-13 04:12:06 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000018#include "clang/Basic/Version.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/PTHManager.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000022#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000024#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000025#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbarf79dced2009-11-14 03:24:39 +000026#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000027#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000029#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000030#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000031#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000033#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000034#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000035#include "llvm/Support/Host.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Program.h"
38#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000039#include "llvm/Support/system_error.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000040using namespace clang;
41
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000042CompilerInstance::CompilerInstance()
Sebastian Redlffaab3e2010-07-30 00:29:29 +000043 : Invocation(new CompilerInvocation()) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000044}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000045
46CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000047}
48
Daniel Dunbar6228ca02010-01-30 21:47:07 +000049void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000050 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000051}
52
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000053void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000054 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000055}
56
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000057void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000058 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000059}
60
61void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000062 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000063}
64
Ted Kremenek4f327862011-03-21 18:40:17 +000065void CompilerInstance::setSourceManager(SourceManager *Value) {
66 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000067}
68
Ted Kremenek4f327862011-03-21 18:40:17 +000069void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000070
Ted Kremenek4f327862011-03-21 18:40:17 +000071void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000072
Douglas Gregorf18d0d82010-08-12 23:31:19 +000073void CompilerInstance::setSema(Sema *S) {
74 TheSema.reset(S);
75}
76
Daniel Dunbar12ce6942009-11-14 02:47:17 +000077void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
78 Consumer.reset(Value);
79}
80
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000081void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
82 CompletionConsumer.reset(Value);
83}
84
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000085// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000086static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +000087 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000088 Diagnostic &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000089 std::string ErrorInfo;
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +000090 llvm::OwningPtr<llvm::raw_ostream> OS(
91 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000092 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000093 Diags.Report(diag::err_fe_unable_to_open_logfile)
94 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000095 return;
96 }
97
Daniel Dunbardd63b282009-12-11 23:04:35 +000098 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000099 for (unsigned i = 0; i != argc; ++i)
100 (*OS) << argv[i] << ' ';
101 (*OS) << '\n';
102
103 // Chain in a diagnostic client which will log the diagnostics.
104 DiagnosticClient *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000105 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000106 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000107}
108
Douglas Gregore47be3e2010-11-11 00:39:14 +0000109void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
110 DiagnosticClient *Client) {
111 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000112}
113
Douglas Gregor28019772010-04-05 23:52:57 +0000114llvm::IntrusiveRefCntPtr<Diagnostic>
115CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000116 int Argc, const char* const *Argv,
117 DiagnosticClient *Client) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000118 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
119 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000120
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000121 // Create the diagnostic client for reporting errors or for
122 // implementing -verify.
Douglas Gregore47be3e2010-11-11 00:39:14 +0000123 if (Client)
124 Diags->setClient(Client);
125 else
126 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000127
128 // Chain in -verify checker, if requested.
129 if (Opts.VerifyDiagnostics)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000130 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000131
132 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000133 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000134
135 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000136 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000137
Douglas Gregor28019772010-04-05 23:52:57 +0000138 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000139}
140
141// File Manager
142
Daniel Dunbar16b74492009-11-13 04:12:06 +0000143void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000144 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000145}
146
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000147// Source Manager
148
Chris Lattner39b49bc2010-11-23 08:35:12 +0000149void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000150 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000151}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000152
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000153// Preprocessor
154
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000155void CompilerInstance::createPreprocessor() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000156 PP = createPreprocessor(getDiagnostics(), getLangOpts(),
157 getPreprocessorOpts(), getHeaderSearchOpts(),
158 getDependencyOutputOpts(), getTarget(),
159 getFrontendOpts(), getSourceManager(),
160 getFileManager());
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000161}
162
163Preprocessor *
164CompilerInstance::createPreprocessor(Diagnostic &Diags,
165 const LangOptions &LangInfo,
166 const PreprocessorOptions &PPOpts,
167 const HeaderSearchOptions &HSOpts,
168 const DependencyOutputOptions &DepOpts,
169 const TargetInfo &Target,
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000170 const FrontendOptions &FEOpts,
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000171 SourceManager &SourceMgr,
172 FileManager &FileMgr) {
173 // Create a PTH manager if we are using some form of a token cache.
174 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000175 if (!PPOpts.TokenCache.empty())
Chris Lattner681c74a2010-11-23 09:01:31 +0000176 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000177
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000178 // Create the Preprocessor.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000179 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000180 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
181 SourceMgr, *HeaderInfo, PTHMgr,
182 /*OwnsHeaderSearch=*/true);
183
184 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
185 // That argument is used as the IdentifierInfoLookup argument to
186 // IdentifierTable's ctor.
187 if (PTHMgr) {
188 PTHMgr->setPreprocessor(PP);
189 PP->setPTHManager(PTHMgr);
190 }
191
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000192 if (PPOpts.DetailedRecord)
193 PP->createPreprocessingRecord();
194
Chris Lattner39b49bc2010-11-23 08:35:12 +0000195 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000196
197 // Handle generating dependencies, if requested.
198 if (!DepOpts.OutputFile.empty())
199 AttachDependencyFileGen(*PP, DepOpts);
200
Daniel Dunbareef63e02011-02-02 15:41:17 +0000201 // Handle generating header include information, if requested.
202 if (DepOpts.ShowHeaderIncludes)
203 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000204 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
205 llvm::StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
206 if (OutputPath == "-")
207 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000208 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
209 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000210 }
Daniel Dunbareef63e02011-02-02 15:41:17 +0000211
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000212 return PP;
213}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000214
215// ASTContext
216
217void CompilerInstance::createASTContext() {
218 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000219 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
220 getTarget(), PP.getIdentifierTable(),
221 PP.getSelectorTable(), PP.getBuiltinInfo(),
222 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000223}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000224
225// ExternalASTSource
226
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000227void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000228 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000229 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000230 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000231 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000232 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000233 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000234 DisablePCHValidation,
235 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000236 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000237 DeserializationListener,
238 Preamble));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000239 getASTContext().setExternalSource(Source);
240}
241
242ExternalASTSource *
243CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
244 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000245 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000246 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000247 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000248 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000249 void *DeserializationListener,
250 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000251 llvm::OwningPtr<ASTReader> Reader;
252 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000253 Sysroot.empty() ? 0 : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000254 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000255
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000256 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000257 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000258 switch (Reader->ReadAST(Path,
259 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000260 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000261 // Set the predefines buffer as suggested by the PCH reader. Typically, the
262 // predefines buffer will be empty.
263 PP.setPredefines(Reader->getSuggestedPredefines());
264 return Reader.take();
265
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000266 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000267 // Unrecoverable failure: don't even try to process the input file.
268 break;
269
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000270 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000271 // No suitable PCH file could be found. Return an error.
272 break;
273 }
274
275 return 0;
276}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000277
278// Code Completion
279
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000280static bool EnableCodeCompletion(Preprocessor &PP,
281 const std::string &Filename,
282 unsigned Line,
283 unsigned Column) {
284 // Tell the source manager to chop off the given file at a specific
285 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000286 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000287 if (!Entry) {
288 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
289 << Filename;
290 return true;
291 }
292
293 // Truncate the named file at the given line/column.
294 PP.SetCodeCompletionPoint(Entry, Line, Column);
295 return false;
296}
297
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000298void CompilerInstance::createCodeCompletionConsumer() {
299 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000300 if (!CompletionConsumer) {
301 CompletionConsumer.reset(
302 createCodeCompletionConsumer(getPreprocessor(),
303 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000304 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000305 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000306 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000307 llvm::outs()));
308 if (!CompletionConsumer)
309 return;
310 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
311 Loc.Line, Loc.Column)) {
312 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000313 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000314 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000315
316 if (CompletionConsumer->isOutputBinary() &&
317 llvm::sys::Program::ChangeStdoutToBinary()) {
318 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
319 CompletionConsumer.reset();
320 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000321}
322
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000323void CompilerInstance::createFrontendTimer() {
324 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
325}
326
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000327CodeCompleteConsumer *
328CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
329 const std::string &Filename,
330 unsigned Line,
331 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000332 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000333 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000334 bool ShowGlobals,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000335 llvm::raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000336 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000337 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000338
339 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000340 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000341 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000342}
Daniel Dunbara9204832009-11-13 10:37:48 +0000343
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000344void CompilerInstance::createSema(bool CompleteTranslationUnit,
345 CodeCompleteConsumer *CompletionConsumer) {
346 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
347 CompleteTranslationUnit, CompletionConsumer));
348}
349
Daniel Dunbara9204832009-11-13 10:37:48 +0000350// Output Files
351
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000352void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
353 assert(OutFile.OS && "Attempt to add empty stream to output list!");
354 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000355}
356
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000357void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000358 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000359 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000360 delete it->OS;
361 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000362 if (EraseFiles) {
363 bool existed;
364 llvm::sys::fs::remove(it->TempFilename, existed);
365 } else {
366 llvm::SmallString<128> NewOutFile(it->Filename);
367
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000368 // If '-working-directory' was passed, the output filename should be
369 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000370 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000371 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
372 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000373 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000374 << it->TempFilename << it->Filename << ec.message();
375
376 bool existed;
377 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000378 }
379 }
380 } else if (!it->Filename.empty() && EraseFiles)
381 llvm::sys::Path(it->Filename).eraseFromDisk();
382
Daniel Dunbara9204832009-11-13 10:37:48 +0000383 }
384 OutputFiles.clear();
385}
386
Daniel Dunbarf482d592009-11-13 18:32:08 +0000387llvm::raw_fd_ostream *
388CompilerInstance::createDefaultOutputFile(bool Binary,
389 llvm::StringRef InFile,
390 llvm::StringRef Extension) {
391 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000392 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000393}
394
395llvm::raw_fd_ostream *
396CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000397 bool Binary, bool RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000398 llvm::StringRef InFile,
399 llvm::StringRef Extension) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000400 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000401 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000402 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000403 InFile, Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000404 &OutputPathName,
405 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000406 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000407 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
408 << OutputPath << Error;
409 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000410 }
411
412 // Add the output file -- but don't try to remove "-", since this means we are
413 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000414 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
415 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000416
417 return OS;
418}
419
420llvm::raw_fd_ostream *
421CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
422 std::string &Error,
423 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000424 bool RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000425 llvm::StringRef InFile,
426 llvm::StringRef Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000427 std::string *ResultPathName,
428 std::string *TempPathName) {
429 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000430 if (!OutputPath.empty()) {
431 OutFile = OutputPath;
432 } else if (InFile == "-") {
433 OutFile = "-";
434 } else if (!Extension.empty()) {
435 llvm::sys::Path Path(InFile);
436 Path.eraseSuffix();
437 Path.appendSuffix(Extension);
438 OutFile = Path.str();
439 } else {
440 OutFile = "-";
441 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000442
443 if (OutFile != "-") {
444 llvm::sys::Path OutPath(OutFile);
445 // Only create the temporary if we can actually write to OutPath, otherwise
446 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000447 bool Exists;
448 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000449 (OutPath.isRegularFile() && OutPath.canWrite())) {
450 // Create a temporary file.
451 llvm::sys::Path TempPath(OutFile);
452 if (!TempPath.createTemporaryFileOnDisk())
453 TempFile = TempPath.str();
454 }
455 }
456
457 std::string OSFile = OutFile;
458 if (!TempFile.empty())
459 OSFile = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000460
Daniel Dunbarfc971022009-11-20 22:32:38 +0000461 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000462 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000463 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
464 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000465 return 0;
466
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000467 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000468 if (RemoveFileOnSignal)
469 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000470
Daniel Dunbarf482d592009-11-13 18:32:08 +0000471 if (ResultPathName)
472 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000473 if (TempPathName)
474 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000475
Daniel Dunbarfc971022009-11-20 22:32:38 +0000476 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000477}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000478
479// Initialization Utilities
480
481bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
482 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
483 getSourceManager(), getFrontendOpts());
484}
485
486bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
487 Diagnostic &Diags,
488 FileManager &FileMgr,
489 SourceManager &SourceMgr,
490 const FrontendOptions &Opts) {
Douglas Gregor414cb642010-11-30 05:23:00 +0000491 // Figure out where to get and map in the main file, unless it's already
492 // been created (e.g., by a precompiled preamble).
493 if (!SourceMgr.getMainFileID().isInvalid()) {
494 // Do nothing: the main file has already been set.
495 } else if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000496 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000497 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000498 Diags.Report(diag::err_fe_error_reading) << InputFile;
499 return false;
500 }
Dan Gohman694137c2010-10-26 21:13:51 +0000501 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000502 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000503 llvm::OwningPtr<llvm::MemoryBuffer> SB;
504 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000505 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000506 Diags.Report(diag::err_fe_error_reading_stdin);
507 return false;
508 }
Dan Gohman90d90812010-10-26 23:21:25 +0000509 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000510 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000511 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000512 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000513 }
514
Dan Gohman694137c2010-10-26 21:13:51 +0000515 assert(!SourceMgr.getMainFileID().isInvalid() &&
516 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000517 return true;
518}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000519
520// High-Level Operations
521
522bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
523 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
524 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
525 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
526
527 // FIXME: Take this as an argument, once all the APIs we used have moved to
528 // taking it as an input instead of hard-coding llvm::errs.
529 llvm::raw_ostream &OS = llvm::errs();
530
531 // Create the target instance.
532 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
533 if (!hasTarget())
534 return false;
535
536 // Inform the target of the language options.
537 //
538 // FIXME: We shouldn't need to do this, the target should be immutable once
539 // created. This complexity should be lifted elsewhere.
540 getTarget().setForcedLangOptions(getLangOpts());
541
542 // Validate/process some options.
543 if (getHeaderSearchOpts().Verbose)
544 OS << "clang -cc1 version " CLANG_VERSION_STRING
545 << " based upon " << PACKAGE_STRING
546 << " hosted on " << llvm::sys::getHostTriple() << "\n";
547
548 if (getFrontendOpts().ShowTimers)
549 createFrontendTimer();
550
Douglas Gregor95dd5582010-03-30 17:33:59 +0000551 if (getFrontendOpts().ShowStats)
552 llvm::EnableStatistics();
553
Daniel Dunbar0397af22010-01-13 00:48:06 +0000554 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
555 const std::string &InFile = getFrontendOpts().Inputs[i].second;
556
Daniel Dunbar20560482010-06-07 23:23:50 +0000557 // Reset the ID tables if we are reusing the SourceManager.
558 if (hasSourceManager())
559 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000560
Daniel Dunbard3598a62010-06-07 23:23:06 +0000561 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000562 Act.Execute();
563 Act.EndSourceFile();
564 }
565 }
566
Chris Lattner53eee7b2010-04-07 18:47:42 +0000567 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000568 // We can have multiple diagnostics sharing one diagnostic client.
569 // Get the total number of warnings/errors from the client.
570 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
571 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000572
573 if (NumWarnings)
574 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
575 if (NumWarnings && NumErrors)
576 OS << " and ";
577 if (NumErrors)
578 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
579 if (NumWarnings || NumErrors)
580 OS << " generated.\n";
581 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000582
Daniel Dunbar20560482010-06-07 23:23:50 +0000583 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000584 getFileManager().PrintStats();
585 OS << "\n";
586 }
587
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000588 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000589}
590
591