blob: 901f8fa92764e4ab2424133978c71924b7bffcdf [file] [log] [blame]
Daniel Dunbar636404a2009-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 Gregor0e93f012010-08-12 23:31:19 +000011#include "clang/Sema/Sema.h"
Daniel Dunbar56d9c292009-11-14 02:47:17 +000012#include "clang/AST/ASTConsumer.h"
Daniel Dunbardf3e30c2009-11-13 08:20:47 +000013#include "clang/AST/ASTContext.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000014#include "clang/Basic/Diagnostic.h"
Daniel Dunbar546a6762009-11-13 04:12:06 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000018#include "clang/Basic/Version.h"
Daniel Dunbaraaa148f2009-11-13 05:52:11 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/PTHManager.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000022#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000024#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000025#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbar50ec0da2009-11-14 03:24:39 +000026#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbaraaa148f2009-11-13 05:52:11 +000027#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000029#include "clang/Sema/CodeCompleteConsumer.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000030#include "llvm/LLVMContext.h"
Michael J. Spencerf6efe582011-01-10 02:34:13 +000031#include "llvm/Support/FileSystem.h"
Daniel Dunbar409e8902009-11-14 07:53:04 +000032#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000033#include "llvm/Support/raw_ostream.h"
Douglas Gregor171b7802010-03-30 17:33:59 +000034#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +000035#include "llvm/Support/Timer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000036#include "llvm/Support/Host.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/Program.h"
39#include "llvm/Support/Signals.h"
Michael J. Spencerf25faaa2010-12-09 17:36:38 +000040#include "llvm/Support/system_error.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000041using namespace clang;
42
Daniel Dunbare922d9b2010-02-16 01:54:47 +000043CompilerInstance::CompilerInstance()
Sebastian Redl07a89a82010-07-30 00:29:29 +000044 : Invocation(new CompilerInvocation()) {
Daniel Dunbar68242252010-01-30 21:47:07 +000045}
Daniel Dunbar636404a2009-11-13 03:51:44 +000046
47CompilerInstance::~CompilerInstance() {
Daniel Dunbare922d9b2010-02-16 01:54:47 +000048}
49
50void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
51 LLVMContext.reset(Value);
Daniel Dunbar636404a2009-11-13 03:51:44 +000052}
Daniel Dunbar546a6762009-11-13 04:12:06 +000053
Daniel Dunbar68242252010-01-30 21:47:07 +000054void CompilerInstance::setInvocation(CompilerInvocation *Value) {
55 Invocation.reset(Value);
56}
57
Daniel Dunbare01dc862009-11-14 01:20:40 +000058void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor7f95d262010-04-05 23:52:57 +000059 Diagnostics = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000060}
61
Daniel Dunbare01dc862009-11-14 01:20:40 +000062void CompilerInstance::setTarget(TargetInfo *Value) {
63 Target.reset(Value);
64}
65
66void CompilerInstance::setFileManager(FileManager *Value) {
67 FileMgr.reset(Value);
68}
69
70void CompilerInstance::setSourceManager(SourceManager *Value) {
71 SourceMgr.reset(Value);
72}
73
74void CompilerInstance::setPreprocessor(Preprocessor *Value) {
75 PP.reset(Value);
76}
77
78void CompilerInstance::setASTContext(ASTContext *Value) {
79 Context.reset(Value);
80}
81
Douglas Gregor0e93f012010-08-12 23:31:19 +000082void CompilerInstance::setSema(Sema *S) {
83 TheSema.reset(S);
84}
85
Daniel Dunbar56d9c292009-11-14 02:47:17 +000086void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
87 Consumer.reset(Value);
88}
89
Daniel Dunbare01dc862009-11-14 01:20:40 +000090void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
91 CompletionConsumer.reset(Value);
92}
93
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000094// Diagnostics
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000095static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann89c31492010-10-11 09:13:46 +000096 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +000097 Diagnostic &Diags) {
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000098 std::string ErrorInfo;
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +000099 llvm::OwningPtr<llvm::raw_ostream> OS(
100 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000101 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +0000102 Diags.Report(diag::err_fe_unable_to_open_logfile)
103 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000104 return;
105 }
106
Daniel Dunbar520d1e62009-12-11 23:04:35 +0000107 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000108 for (unsigned i = 0; i != argc; ++i)
109 (*OS) << argv[i] << ' ';
110 (*OS) << '\n';
111
112 // Chain in a diagnostic client which will log the diagnostics.
113 DiagnosticClient *Logger =
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +0000114 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000115 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000116}
117
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000118void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
119 DiagnosticClient *Client) {
120 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000121}
122
Douglas Gregor7f95d262010-04-05 23:52:57 +0000123llvm::IntrusiveRefCntPtr<Diagnostic>
124CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000125 int Argc, const char* const *Argv,
126 DiagnosticClient *Client) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000127 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
128 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000129
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000130 // Create the diagnostic client for reporting errors or for
131 // implementing -verify.
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000132 if (Client)
133 Diags->setClient(Client);
134 else
135 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbar50ec0da2009-11-14 03:24:39 +0000136
137 // Chain in -verify checker, if requested.
138 if (Opts.VerifyDiagnostics)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000139 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000140
141 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +0000142 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000143
144 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam9ff84d92010-03-17 09:36:02 +0000145 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000146
Douglas Gregor7f95d262010-04-05 23:52:57 +0000147 return Diags;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000148}
149
150// File Manager
151
Daniel Dunbar546a6762009-11-13 04:12:06 +0000152void CompilerInstance::createFileManager() {
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000153 FileMgr.reset(new FileManager(getFileSystemOpts()));
Daniel Dunbar546a6762009-11-13 04:12:06 +0000154}
155
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000156// Source Manager
157
Chris Lattner5159f612010-11-23 08:35:12 +0000158void CompilerInstance::createSourceManager(FileManager &FileMgr) {
159 SourceMgr.reset(new SourceManager(getDiagnostics(), FileMgr));
Daniel Dunbar546a6762009-11-13 04:12:06 +0000160}
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000161
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000162// Preprocessor
163
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000164void CompilerInstance::createPreprocessor() {
165 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
166 getPreprocessorOpts(), getHeaderSearchOpts(),
167 getDependencyOutputOpts(), getTarget(),
Chris Lattner5159f612010-11-23 08:35:12 +0000168 getFrontendOpts(), getSourceManager(),
169 getFileManager()));
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000170}
171
172Preprocessor *
173CompilerInstance::createPreprocessor(Diagnostic &Diags,
174 const LangOptions &LangInfo,
175 const PreprocessorOptions &PPOpts,
176 const HeaderSearchOptions &HSOpts,
177 const DependencyOutputOptions &DepOpts,
178 const TargetInfo &Target,
Fariborz Jahanian3f7b8b22010-01-13 18:51:17 +0000179 const FrontendOptions &FEOpts,
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000180 SourceManager &SourceMgr,
181 FileManager &FileMgr) {
182 // Create a PTH manager if we are using some form of a token cache.
183 PTHManager *PTHMgr = 0;
Daniel Dunbard6ea9022009-11-17 05:52:41 +0000184 if (!PPOpts.TokenCache.empty())
Chris Lattner7219a5d2010-11-23 09:01:31 +0000185 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000186
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000187 // Create the Preprocessor.
Chris Lattner5159f612010-11-23 08:35:12 +0000188 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000189 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
190 SourceMgr, *HeaderInfo, PTHMgr,
191 /*OwnsHeaderSearch=*/true);
192
193 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
194 // That argument is used as the IdentifierInfoLookup argument to
195 // IdentifierTable's ctor.
196 if (PTHMgr) {
197 PTHMgr->setPreprocessor(PP);
198 PP->setPTHManager(PTHMgr);
199 }
200
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000201 if (PPOpts.DetailedRecord)
202 PP->createPreprocessingRecord();
203
Chris Lattner5159f612010-11-23 08:35:12 +0000204 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000205
206 // Handle generating dependencies, if requested.
207 if (!DepOpts.OutputFile.empty())
208 AttachDependencyFileGen(*PP, DepOpts);
209
210 return PP;
211}
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000212
213// ASTContext
214
215void CompilerInstance::createASTContext() {
216 Preprocessor &PP = getPreprocessor();
217 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
218 getTarget(), PP.getIdentifierTable(),
219 PP.getSelectorTable(), PP.getBuiltinInfo(),
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000220 /*size_reserve=*/ 0));
221}
Daniel Dunbar599313e2009-11-13 08:21:10 +0000222
223// ExternalASTSource
224
Douglas Gregorce3a8292010-07-27 00:27:13 +0000225void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000226 bool DisablePCHValidation,
227 void *DeserializationListener){
Daniel Dunbar599313e2009-11-13 08:21:10 +0000228 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl009e7f22010-10-05 16:15:19 +0000229 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar599313e2009-11-13 08:21:10 +0000230 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000231 DisablePCHValidation,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000232 getPreprocessor(), getASTContext(),
Sebastian Redl009e7f22010-10-05 16:15:19 +0000233 DeserializationListener,
234 Preamble));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000235 getASTContext().setExternalSource(Source);
236}
237
238ExternalASTSource *
239CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
240 const std::string &Sysroot,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000241 bool DisablePCHValidation,
Daniel Dunbar599313e2009-11-13 08:21:10 +0000242 Preprocessor &PP,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000243 ASTContext &Context,
Sebastian Redl009e7f22010-10-05 16:15:19 +0000244 void *DeserializationListener,
245 bool Preamble) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000246 llvm::OwningPtr<ASTReader> Reader;
247 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000248 Sysroot.empty() ? 0 : Sysroot.c_str(),
249 DisablePCHValidation));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000250
Sebastian Redl07a89a82010-07-30 00:29:29 +0000251 Reader->setDeserializationListener(
Sebastian Redl3e31c722010-08-18 23:56:56 +0000252 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl009e7f22010-10-05 16:15:19 +0000253 switch (Reader->ReadAST(Path,
254 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000255 case ASTReader::Success:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000256 // Set the predefines buffer as suggested by the PCH reader. Typically, the
257 // predefines buffer will be empty.
258 PP.setPredefines(Reader->getSuggestedPredefines());
259 return Reader.take();
260
Sebastian Redl2c499f62010-08-18 23:56:43 +0000261 case ASTReader::Failure:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000262 // Unrecoverable failure: don't even try to process the input file.
263 break;
264
Sebastian Redl2c499f62010-08-18 23:56:43 +0000265 case ASTReader::IgnorePCH:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000266 // No suitable PCH file could be found. Return an error.
267 break;
268 }
269
270 return 0;
271}
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000272
273// Code Completion
274
Douglas Gregor8e984da2010-08-04 16:47:14 +0000275static bool EnableCodeCompletion(Preprocessor &PP,
276 const std::string &Filename,
277 unsigned Line,
278 unsigned Column) {
279 // Tell the source manager to chop off the given file at a specific
280 // line and column.
Chris Lattner5159f612010-11-23 08:35:12 +0000281 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000282 if (!Entry) {
283 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
284 << Filename;
285 return true;
286 }
287
288 // Truncate the named file at the given line/column.
289 PP.SetCodeCompletionPoint(Entry, Line, Column);
290 return false;
291}
292
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000293void CompilerInstance::createCodeCompletionConsumer() {
294 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000295 if (!CompletionConsumer) {
296 CompletionConsumer.reset(
297 createCodeCompletionConsumer(getPreprocessor(),
298 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000299 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000300 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +0000301 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000302 llvm::outs()));
303 if (!CompletionConsumer)
304 return;
305 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
306 Loc.Line, Loc.Column)) {
307 CompletionConsumer.reset();
Douglas Gregor00a0cf72010-03-16 06:04:47 +0000308 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000309 }
Douglas Gregorf09935f2009-12-01 05:55:20 +0000310
311 if (CompletionConsumer->isOutputBinary() &&
312 llvm::sys::Program::ChangeStdoutToBinary()) {
313 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
314 CompletionConsumer.reset();
315 }
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000316}
317
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000318void CompilerInstance::createFrontendTimer() {
319 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
320}
321
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000322CodeCompleteConsumer *
323CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
324 const std::string &Filename,
325 unsigned Line,
326 unsigned Column,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000327 bool ShowMacros,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000328 bool ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000329 bool ShowGlobals,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000330 llvm::raw_ostream &OS) {
Douglas Gregor8e984da2010-08-04 16:47:14 +0000331 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000332 return 0;
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000333
334 // Set up the creation routine for code-completion.
Douglas Gregorb9ab0ed2010-10-11 22:12:15 +0000335 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000336 ShowGlobals, OS);
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000337}
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000338
Douglas Gregor0e93f012010-08-12 23:31:19 +0000339void CompilerInstance::createSema(bool CompleteTranslationUnit,
340 CodeCompleteConsumer *CompletionConsumer) {
341 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
342 CompleteTranslationUnit, CompletionConsumer));
343}
344
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000345// Output Files
346
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000347void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
348 assert(OutFile.OS && "Attempt to add empty stream to output list!");
349 OutputFiles.push_back(OutFile);
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000350}
351
Kovarththanan Rajaratnam1c558cd2010-03-06 12:07:48 +0000352void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000353 for (std::list<OutputFile>::iterator
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000354 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000355 delete it->OS;
356 if (!it->TempFilename.empty()) {
357 llvm::sys::Path TempPath(it->TempFilename);
358 if (EraseFiles)
359 TempPath.eraseFromDisk();
360 else {
361 std::string Error;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000362 llvm::sys::Path NewOutFile(it->Filename);
363 // If '-working-directory' was passed, the output filename should be
364 // relative to that.
365 FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts());
366 if (TempPath.renamePathOnDisk(NewOutFile, &Error)) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000367 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
368 << it->TempFilename << it->Filename << Error;
369 TempPath.eraseFromDisk();
370 }
371 }
372 } else if (!it->Filename.empty() && EraseFiles)
373 llvm::sys::Path(it->Filename).eraseFromDisk();
374
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000375 }
376 OutputFiles.clear();
377}
378
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000379llvm::raw_fd_ostream *
380CompilerInstance::createDefaultOutputFile(bool Binary,
381 llvm::StringRef InFile,
382 llvm::StringRef Extension) {
383 return createOutputFile(getFrontendOpts().OutputFile, Binary,
384 InFile, Extension);
385}
386
387llvm::raw_fd_ostream *
388CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
389 bool Binary,
390 llvm::StringRef InFile,
391 llvm::StringRef Extension) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000392 std::string Error, OutputPathName, TempPathName;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000393 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
394 InFile, Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000395 &OutputPathName,
396 &TempPathName);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000397 if (!OS) {
Daniel Dunbar75546992009-12-03 09:13:30 +0000398 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
399 << OutputPath << Error;
400 return 0;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000401 }
402
403 // Add the output file -- but don't try to remove "-", since this means we are
404 // using stdin.
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000405 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
406 TempPathName, OS));
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000407
408 return OS;
409}
410
411llvm::raw_fd_ostream *
412CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
413 std::string &Error,
414 bool Binary,
415 llvm::StringRef InFile,
416 llvm::StringRef Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000417 std::string *ResultPathName,
418 std::string *TempPathName) {
419 std::string OutFile, TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000420 if (!OutputPath.empty()) {
421 OutFile = OutputPath;
422 } else if (InFile == "-") {
423 OutFile = "-";
424 } else if (!Extension.empty()) {
425 llvm::sys::Path Path(InFile);
426 Path.eraseSuffix();
427 Path.appendSuffix(Extension);
428 OutFile = Path.str();
429 } else {
430 OutFile = "-";
431 }
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000432
433 if (OutFile != "-") {
434 llvm::sys::Path OutPath(OutFile);
435 // Only create the temporary if we can actually write to OutPath, otherwise
436 // we want to fail early.
Michael J. Spencerf6efe582011-01-10 02:34:13 +0000437 bool Exists;
438 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000439 (OutPath.isRegularFile() && OutPath.canWrite())) {
440 // Create a temporary file.
441 llvm::sys::Path TempPath(OutFile);
442 if (!TempPath.createTemporaryFileOnDisk())
443 TempFile = TempPath.str();
444 }
445 }
446
447 std::string OSFile = OutFile;
448 if (!TempFile.empty())
449 OSFile = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000450
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000451 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000452 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000453 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
454 if (!Error.empty())
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000455 return 0;
456
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000457 // Make sure the out stream file gets removed if we crash.
458 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
459
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000460 if (ResultPathName)
461 *ResultPathName = OutFile;
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000462 if (TempPathName)
463 *TempPathName = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000464
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000465 return OS.take();
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000466}
Daniel Dunbar409e8902009-11-14 07:53:04 +0000467
468// Initialization Utilities
469
470bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
471 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
472 getSourceManager(), getFrontendOpts());
473}
474
475bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
476 Diagnostic &Diags,
477 FileManager &FileMgr,
478 SourceManager &SourceMgr,
479 const FrontendOptions &Opts) {
Douglas Gregor936a5b42010-11-30 05:23:00 +0000480 // Figure out where to get and map in the main file, unless it's already
481 // been created (e.g., by a precompiled preamble).
482 if (!SourceMgr.getMainFileID().isInvalid()) {
483 // Do nothing: the main file has already been set.
484 } else if (InputFile != "-") {
Chris Lattner5159f612010-11-23 08:35:12 +0000485 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman52765212010-10-26 21:13:51 +0000486 if (!File) {
Daniel Dunbar409e8902009-11-14 07:53:04 +0000487 Diags.Report(diag::err_fe_error_reading) << InputFile;
488 return false;
489 }
Dan Gohman52765212010-10-26 21:13:51 +0000490 SourceMgr.createMainFileID(File);
Daniel Dunbar409e8902009-11-14 07:53:04 +0000491 } else {
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000492 llvm::OwningPtr<llvm::MemoryBuffer> SB;
493 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000494 // FIXME: Give ec.message() in this diag.
Daniel Dunbar409e8902009-11-14 07:53:04 +0000495 Diags.Report(diag::err_fe_error_reading_stdin);
496 return false;
497 }
Dan Gohman2f76cd72010-10-26 23:21:25 +0000498 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner5159f612010-11-23 08:35:12 +0000499 SB->getBufferSize(), 0);
Dan Gohman2f76cd72010-10-26 23:21:25 +0000500 SourceMgr.createMainFileID(File);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000501 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbar409e8902009-11-14 07:53:04 +0000502 }
503
Dan Gohman52765212010-10-26 21:13:51 +0000504 assert(!SourceMgr.getMainFileID().isInvalid() &&
505 "Couldn't establish MainFileID!");
Daniel Dunbar409e8902009-11-14 07:53:04 +0000506 return true;
507}
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000508
509// High-Level Operations
510
511bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
512 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
513 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
514 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
515
516 // FIXME: Take this as an argument, once all the APIs we used have moved to
517 // taking it as an input instead of hard-coding llvm::errs.
518 llvm::raw_ostream &OS = llvm::errs();
519
520 // Create the target instance.
521 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
522 if (!hasTarget())
523 return false;
524
525 // Inform the target of the language options.
526 //
527 // FIXME: We shouldn't need to do this, the target should be immutable once
528 // created. This complexity should be lifted elsewhere.
529 getTarget().setForcedLangOptions(getLangOpts());
530
531 // Validate/process some options.
532 if (getHeaderSearchOpts().Verbose)
533 OS << "clang -cc1 version " CLANG_VERSION_STRING
534 << " based upon " << PACKAGE_STRING
535 << " hosted on " << llvm::sys::getHostTriple() << "\n";
536
537 if (getFrontendOpts().ShowTimers)
538 createFrontendTimer();
539
Douglas Gregor171b7802010-03-30 17:33:59 +0000540 if (getFrontendOpts().ShowStats)
541 llvm::EnableStatistics();
542
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000543 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
544 const std::string &InFile = getFrontendOpts().Inputs[i].second;
545
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000546 // Reset the ID tables if we are reusing the SourceManager.
547 if (hasSourceManager())
548 getSourceManager().clearIDTables();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000549
Daniel Dunbar86546382010-06-07 23:23:06 +0000550 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000551 Act.Execute();
552 Act.EndSourceFile();
553 }
554 }
555
Chris Lattner198cb4d2010-04-07 18:47:42 +0000556 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000557 // We can have multiple diagnostics sharing one diagnostic client.
558 // Get the total number of warnings/errors from the client.
559 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
560 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner198cb4d2010-04-07 18:47:42 +0000561
562 if (NumWarnings)
563 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
564 if (NumWarnings && NumErrors)
565 OS << " and ";
566 if (NumErrors)
567 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
568 if (NumWarnings || NumErrors)
569 OS << " generated.\n";
570 }
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000571
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000572 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000573 getFileManager().PrintStats();
574 OS << "\n";
575 }
576
Argyrios Kyrtzidisbc467932010-11-18 21:13:57 +0000577 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000578}
579
580