blob: c5e5d7f90a0131f8ecd78d3c230f8ebebfbec389 [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"
Daniel Dunbar409e8902009-11-14 07:53:04 +000031#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregor171b7802010-03-30 17:33:59 +000033#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +000034#include "llvm/Support/Timer.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000035#include "llvm/System/Host.h"
Daniel Dunbar566eeb22009-11-13 10:37:48 +000036#include "llvm/System/Path.h"
Douglas Gregorf09935f2009-12-01 05:55:20 +000037#include "llvm/System/Program.h"
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +000038#include "llvm/System/Signals.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000039using namespace clang;
40
Daniel Dunbare922d9b2010-02-16 01:54:47 +000041CompilerInstance::CompilerInstance()
Sebastian Redl07a89a82010-07-30 00:29:29 +000042 : Invocation(new CompilerInvocation()) {
Daniel Dunbar68242252010-01-30 21:47:07 +000043}
Daniel Dunbar636404a2009-11-13 03:51:44 +000044
45CompilerInstance::~CompilerInstance() {
Daniel Dunbare922d9b2010-02-16 01:54:47 +000046}
47
48void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
49 LLVMContext.reset(Value);
Daniel Dunbar636404a2009-11-13 03:51:44 +000050}
Daniel Dunbar546a6762009-11-13 04:12:06 +000051
Daniel Dunbar68242252010-01-30 21:47:07 +000052void CompilerInstance::setInvocation(CompilerInvocation *Value) {
53 Invocation.reset(Value);
54}
55
Daniel Dunbare01dc862009-11-14 01:20:40 +000056void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor7f95d262010-04-05 23:52:57 +000057 Diagnostics = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000058}
59
Daniel Dunbare01dc862009-11-14 01:20:40 +000060void CompilerInstance::setTarget(TargetInfo *Value) {
61 Target.reset(Value);
62}
63
64void CompilerInstance::setFileManager(FileManager *Value) {
65 FileMgr.reset(Value);
66}
67
68void CompilerInstance::setSourceManager(SourceManager *Value) {
69 SourceMgr.reset(Value);
70}
71
72void CompilerInstance::setPreprocessor(Preprocessor *Value) {
73 PP.reset(Value);
74}
75
76void CompilerInstance::setASTContext(ASTContext *Value) {
77 Context.reset(Value);
78}
79
Douglas Gregor0e93f012010-08-12 23:31:19 +000080void CompilerInstance::setSema(Sema *S) {
81 TheSema.reset(S);
82}
83
Daniel Dunbar56d9c292009-11-14 02:47:17 +000084void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
85 Consumer.reset(Value);
86}
87
Daniel Dunbare01dc862009-11-14 01:20:40 +000088void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
89 CompletionConsumer.reset(Value);
90}
91
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000092// Diagnostics
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000093static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann89c31492010-10-11 09:13:46 +000094 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +000095 Diagnostic &Diags) {
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000096 std::string ErrorInfo;
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +000097 llvm::OwningPtr<llvm::raw_ostream> OS(
98 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000099 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +0000100 Diags.Report(diag::err_fe_unable_to_open_logfile)
101 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000102 return;
103 }
104
Daniel Dunbar520d1e62009-12-11 23:04:35 +0000105 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000106 for (unsigned i = 0; i != argc; ++i)
107 (*OS) << argv[i] << ' ';
108 (*OS) << '\n';
109
110 // Chain in a diagnostic client which will log the diagnostics.
111 DiagnosticClient *Logger =
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +0000112 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000113 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000114}
115
Axel Naumann89c31492010-10-11 09:13:46 +0000116void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv) {
Douglas Gregor7f95d262010-04-05 23:52:57 +0000117 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000118}
119
Douglas Gregor7f95d262010-04-05 23:52:57 +0000120llvm::IntrusiveRefCntPtr<Diagnostic>
121CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Axel Naumann89c31492010-10-11 09:13:46 +0000122 int Argc, const char* const *Argv) {
Douglas Gregor7f95d262010-04-05 23:52:57 +0000123 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic());
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000124
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000125 // Create the diagnostic client for reporting errors or for
126 // implementing -verify.
Douglas Gregorac0605e2010-01-28 06:00:51 +0000127 llvm::OwningPtr<DiagnosticClient> DiagClient;
Douglas Gregor4e0f15a2010-10-11 22:02:06 +0000128 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbar50ec0da2009-11-14 03:24:39 +0000129
130 // Chain in -verify checker, if requested.
131 if (Opts.VerifyDiagnostics)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000132 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000133
134 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +0000135 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000136
137 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam9ff84d92010-03-17 09:36:02 +0000138 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000139
Douglas Gregor7f95d262010-04-05 23:52:57 +0000140 return Diags;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000141}
142
143// File Manager
144
Daniel Dunbar546a6762009-11-13 04:12:06 +0000145void CompilerInstance::createFileManager() {
146 FileMgr.reset(new FileManager());
147}
148
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000149// Source Manager
150
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000151void CompilerInstance::createSourceManager(FileManager &FileMgr,
152 const FileSystemOptions &FSOpts) {
153 SourceMgr.reset(new SourceManager(getDiagnostics(), FileMgr, FSOpts));
Daniel Dunbar546a6762009-11-13 04:12:06 +0000154}
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000155
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000156// Preprocessor
157
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000158void CompilerInstance::createPreprocessor() {
159 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
160 getPreprocessorOpts(), getHeaderSearchOpts(),
161 getDependencyOutputOpts(), getTarget(),
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000162 getFrontendOpts(), getFileSystemOpts(),
163 getSourceManager(), getFileManager()));
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000164}
165
166Preprocessor *
167CompilerInstance::createPreprocessor(Diagnostic &Diags,
168 const LangOptions &LangInfo,
169 const PreprocessorOptions &PPOpts,
170 const HeaderSearchOptions &HSOpts,
171 const DependencyOutputOptions &DepOpts,
172 const TargetInfo &Target,
Fariborz Jahanian3f7b8b22010-01-13 18:51:17 +0000173 const FrontendOptions &FEOpts,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000174 const FileSystemOptions &FSOpts,
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000175 SourceManager &SourceMgr,
176 FileManager &FileMgr) {
177 // Create a PTH manager if we are using some form of a token cache.
178 PTHManager *PTHMgr = 0;
Daniel Dunbard6ea9022009-11-17 05:52:41 +0000179 if (!PPOpts.TokenCache.empty())
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000180 PTHMgr = PTHManager::Create(PPOpts.TokenCache, FileMgr, FSOpts, Diags);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000181
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000182 // Create the Preprocessor.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000183 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr, FSOpts);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000184 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
185 SourceMgr, *HeaderInfo, PTHMgr,
186 /*OwnsHeaderSearch=*/true);
187
188 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
189 // That argument is used as the IdentifierInfoLookup argument to
190 // IdentifierTable's ctor.
191 if (PTHMgr) {
192 PTHMgr->setPreprocessor(PP);
193 PP->setPTHManager(PTHMgr);
194 }
195
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000196 if (PPOpts.DetailedRecord)
197 PP->createPreprocessingRecord();
198
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000199 InitializePreprocessor(*PP, FSOpts, PPOpts, HSOpts, FEOpts);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000200
201 // Handle generating dependencies, if requested.
202 if (!DepOpts.OutputFile.empty())
203 AttachDependencyFileGen(*PP, DepOpts);
204
205 return PP;
206}
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000207
208// ASTContext
209
210void CompilerInstance::createASTContext() {
211 Preprocessor &PP = getPreprocessor();
212 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
213 getTarget(), PP.getIdentifierTable(),
214 PP.getSelectorTable(), PP.getBuiltinInfo(),
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000215 /*size_reserve=*/ 0));
216}
Daniel Dunbar599313e2009-11-13 08:21:10 +0000217
218// ExternalASTSource
219
Douglas Gregorce3a8292010-07-27 00:27:13 +0000220void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000221 bool DisablePCHValidation,
222 void *DeserializationListener){
Daniel Dunbar599313e2009-11-13 08:21:10 +0000223 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl009e7f22010-10-05 16:15:19 +0000224 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar599313e2009-11-13 08:21:10 +0000225 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000226 DisablePCHValidation,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000227 getPreprocessor(), getASTContext(),
Sebastian Redl009e7f22010-10-05 16:15:19 +0000228 DeserializationListener,
229 Preamble));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000230 getASTContext().setExternalSource(Source);
231}
232
233ExternalASTSource *
234CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
235 const std::string &Sysroot,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000236 bool DisablePCHValidation,
Daniel Dunbar599313e2009-11-13 08:21:10 +0000237 Preprocessor &PP,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000238 ASTContext &Context,
Sebastian Redl009e7f22010-10-05 16:15:19 +0000239 void *DeserializationListener,
240 bool Preamble) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000241 llvm::OwningPtr<ASTReader> Reader;
242 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000243 Sysroot.empty() ? 0 : Sysroot.c_str(),
244 DisablePCHValidation));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000245
Sebastian Redl07a89a82010-07-30 00:29:29 +0000246 Reader->setDeserializationListener(
Sebastian Redl3e31c722010-08-18 23:56:56 +0000247 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl009e7f22010-10-05 16:15:19 +0000248 switch (Reader->ReadAST(Path,
249 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000250 case ASTReader::Success:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000251 // Set the predefines buffer as suggested by the PCH reader. Typically, the
252 // predefines buffer will be empty.
253 PP.setPredefines(Reader->getSuggestedPredefines());
254 return Reader.take();
255
Sebastian Redl2c499f62010-08-18 23:56:43 +0000256 case ASTReader::Failure:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000257 // Unrecoverable failure: don't even try to process the input file.
258 break;
259
Sebastian Redl2c499f62010-08-18 23:56:43 +0000260 case ASTReader::IgnorePCH:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000261 // No suitable PCH file could be found. Return an error.
262 break;
263 }
264
265 return 0;
266}
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000267
268// Code Completion
269
Douglas Gregor8e984da2010-08-04 16:47:14 +0000270static bool EnableCodeCompletion(Preprocessor &PP,
271 const std::string &Filename,
272 unsigned Line,
273 unsigned Column) {
274 // Tell the source manager to chop off the given file at a specific
275 // line and column.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000276 const FileEntry *Entry = PP.getFileManager().getFile(Filename,
277 PP.getFileSystemOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000278 if (!Entry) {
279 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
280 << Filename;
281 return true;
282 }
283
284 // Truncate the named file at the given line/column.
285 PP.SetCodeCompletionPoint(Entry, Line, Column);
286 return false;
287}
288
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000289void CompilerInstance::createCodeCompletionConsumer() {
290 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000291 if (!CompletionConsumer) {
292 CompletionConsumer.reset(
293 createCodeCompletionConsumer(getPreprocessor(),
294 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000295 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000296 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +0000297 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000298 llvm::outs()));
299 if (!CompletionConsumer)
300 return;
301 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
302 Loc.Line, Loc.Column)) {
303 CompletionConsumer.reset();
Douglas Gregor00a0cf72010-03-16 06:04:47 +0000304 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000305 }
Douglas Gregorf09935f2009-12-01 05:55:20 +0000306
307 if (CompletionConsumer->isOutputBinary() &&
308 llvm::sys::Program::ChangeStdoutToBinary()) {
309 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
310 CompletionConsumer.reset();
311 }
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000312}
313
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000314void CompilerInstance::createFrontendTimer() {
315 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
316}
317
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000318CodeCompleteConsumer *
319CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
320 const std::string &Filename,
321 unsigned Line,
322 unsigned Column,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000323 bool ShowMacros,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000324 bool ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000325 bool ShowGlobals,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000326 llvm::raw_ostream &OS) {
Douglas Gregor8e984da2010-08-04 16:47:14 +0000327 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000328 return 0;
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000329
330 // Set up the creation routine for code-completion.
Douglas Gregorb9ab0ed2010-10-11 22:12:15 +0000331 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000332 ShowGlobals, OS);
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000333}
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000334
Douglas Gregor0e93f012010-08-12 23:31:19 +0000335void CompilerInstance::createSema(bool CompleteTranslationUnit,
336 CodeCompleteConsumer *CompletionConsumer) {
337 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
338 CompleteTranslationUnit, CompletionConsumer));
339}
340
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000341// Output Files
342
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000343void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
344 assert(OutFile.OS && "Attempt to add empty stream to output list!");
345 OutputFiles.push_back(OutFile);
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000346}
347
Kovarththanan Rajaratnam1c558cd2010-03-06 12:07:48 +0000348void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000349 for (std::list<OutputFile>::iterator
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000350 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000351 delete it->OS;
352 if (!it->TempFilename.empty()) {
353 llvm::sys::Path TempPath(it->TempFilename);
354 if (EraseFiles)
355 TempPath.eraseFromDisk();
356 else {
357 std::string Error;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000358 llvm::sys::Path NewOutFile(it->Filename);
359 // If '-working-directory' was passed, the output filename should be
360 // relative to that.
361 FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts());
362 if (TempPath.renamePathOnDisk(NewOutFile, &Error)) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000363 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
364 << it->TempFilename << it->Filename << Error;
365 TempPath.eraseFromDisk();
366 }
367 }
368 } else if (!it->Filename.empty() && EraseFiles)
369 llvm::sys::Path(it->Filename).eraseFromDisk();
370
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000371 }
372 OutputFiles.clear();
373}
374
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000375llvm::raw_fd_ostream *
376CompilerInstance::createDefaultOutputFile(bool Binary,
377 llvm::StringRef InFile,
378 llvm::StringRef Extension) {
379 return createOutputFile(getFrontendOpts().OutputFile, Binary,
380 InFile, Extension);
381}
382
383llvm::raw_fd_ostream *
384CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
385 bool Binary,
386 llvm::StringRef InFile,
387 llvm::StringRef Extension) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000388 std::string Error, OutputPathName, TempPathName;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000389 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
390 InFile, Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000391 &OutputPathName,
392 &TempPathName);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000393 if (!OS) {
Daniel Dunbar75546992009-12-03 09:13:30 +0000394 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
395 << OutputPath << Error;
396 return 0;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000397 }
398
399 // Add the output file -- but don't try to remove "-", since this means we are
400 // using stdin.
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000401 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
402 TempPathName, OS));
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000403
404 return OS;
405}
406
407llvm::raw_fd_ostream *
408CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
409 std::string &Error,
410 bool Binary,
411 llvm::StringRef InFile,
412 llvm::StringRef Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000413 std::string *ResultPathName,
414 std::string *TempPathName) {
415 std::string OutFile, TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000416 if (!OutputPath.empty()) {
417 OutFile = OutputPath;
418 } else if (InFile == "-") {
419 OutFile = "-";
420 } else if (!Extension.empty()) {
421 llvm::sys::Path Path(InFile);
422 Path.eraseSuffix();
423 Path.appendSuffix(Extension);
424 OutFile = Path.str();
425 } else {
426 OutFile = "-";
427 }
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000428
429 if (OutFile != "-") {
430 llvm::sys::Path OutPath(OutFile);
431 // Only create the temporary if we can actually write to OutPath, otherwise
432 // we want to fail early.
433 if (!OutPath.exists() ||
434 (OutPath.isRegularFile() && OutPath.canWrite())) {
435 // Create a temporary file.
436 llvm::sys::Path TempPath(OutFile);
437 if (!TempPath.createTemporaryFileOnDisk())
438 TempFile = TempPath.str();
439 }
440 }
441
442 std::string OSFile = OutFile;
443 if (!TempFile.empty())
444 OSFile = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000445
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000446 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000447 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000448 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
449 if (!Error.empty())
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000450 return 0;
451
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000452 // Make sure the out stream file gets removed if we crash.
453 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
454
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000455 if (ResultPathName)
456 *ResultPathName = OutFile;
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000457 if (TempPathName)
458 *TempPathName = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000459
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000460 return OS.take();
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000461}
Daniel Dunbar409e8902009-11-14 07:53:04 +0000462
463// Initialization Utilities
464
465bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
466 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000467 getFileSystemOpts(),
Daniel Dunbar409e8902009-11-14 07:53:04 +0000468 getSourceManager(), getFrontendOpts());
469}
470
471bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
472 Diagnostic &Diags,
473 FileManager &FileMgr,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000474 const FileSystemOptions &FSOpts,
Daniel Dunbar409e8902009-11-14 07:53:04 +0000475 SourceManager &SourceMgr,
476 const FrontendOptions &Opts) {
477 // Figure out where to get and map in the main file.
Daniel Dunbar1c201fb2010-03-19 19:44:04 +0000478 if (InputFile != "-") {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000479 const FileEntry *File = FileMgr.getFile(InputFile, FSOpts);
Dan Gohman52765212010-10-26 21:13:51 +0000480 if (!File) {
Daniel Dunbar409e8902009-11-14 07:53:04 +0000481 Diags.Report(diag::err_fe_error_reading) << InputFile;
482 return false;
483 }
Dan Gohman52765212010-10-26 21:13:51 +0000484 SourceMgr.createMainFileID(File);
Daniel Dunbar409e8902009-11-14 07:53:04 +0000485 } else {
486 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Dan Gohman52765212010-10-26 21:13:51 +0000487 if (!SB) {
Daniel Dunbar409e8902009-11-14 07:53:04 +0000488 Diags.Report(diag::err_fe_error_reading_stdin);
489 return false;
490 }
Dan Gohman2f76cd72010-10-26 23:21:25 +0000491 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000492 SB->getBufferSize(), 0,
493 FSOpts);
Dan Gohman2f76cd72010-10-26 23:21:25 +0000494 SourceMgr.createMainFileID(File);
495 SourceMgr.overrideFileContents(File, SB);
Daniel Dunbar409e8902009-11-14 07:53:04 +0000496 }
497
Dan Gohman52765212010-10-26 21:13:51 +0000498 assert(!SourceMgr.getMainFileID().isInvalid() &&
499 "Couldn't establish MainFileID!");
Daniel Dunbar409e8902009-11-14 07:53:04 +0000500 return true;
501}
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000502
503// High-Level Operations
504
505bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
506 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
507 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
508 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
509
510 // FIXME: Take this as an argument, once all the APIs we used have moved to
511 // taking it as an input instead of hard-coding llvm::errs.
512 llvm::raw_ostream &OS = llvm::errs();
513
514 // Create the target instance.
515 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
516 if (!hasTarget())
517 return false;
518
519 // Inform the target of the language options.
520 //
521 // FIXME: We shouldn't need to do this, the target should be immutable once
522 // created. This complexity should be lifted elsewhere.
523 getTarget().setForcedLangOptions(getLangOpts());
524
525 // Validate/process some options.
526 if (getHeaderSearchOpts().Verbose)
527 OS << "clang -cc1 version " CLANG_VERSION_STRING
528 << " based upon " << PACKAGE_STRING
529 << " hosted on " << llvm::sys::getHostTriple() << "\n";
530
531 if (getFrontendOpts().ShowTimers)
532 createFrontendTimer();
533
Douglas Gregor171b7802010-03-30 17:33:59 +0000534 if (getFrontendOpts().ShowStats)
535 llvm::EnableStatistics();
536
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000537 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
538 const std::string &InFile = getFrontendOpts().Inputs[i].second;
539
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000540 // Reset the ID tables if we are reusing the SourceManager.
541 if (hasSourceManager())
542 getSourceManager().clearIDTables();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000543
Daniel Dunbar86546382010-06-07 23:23:06 +0000544 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000545 Act.Execute();
546 Act.EndSourceFile();
547 }
548 }
549
Chris Lattner198cb4d2010-04-07 18:47:42 +0000550 if (getDiagnosticOpts().ShowCarets) {
551 unsigned NumWarnings = getDiagnostics().getNumWarnings();
Douglas Gregor2d2d9072010-04-14 22:19:45 +0000552 unsigned NumErrors = getDiagnostics().getNumErrors() -
553 getDiagnostics().getNumErrorsSuppressed();
Chris Lattner198cb4d2010-04-07 18:47:42 +0000554
555 if (NumWarnings)
556 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
557 if (NumWarnings && NumErrors)
558 OS << " and ";
559 if (NumErrors)
560 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
561 if (NumWarnings || NumErrors)
562 OS << " generated.\n";
563 }
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000564
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000565 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000566 getFileManager().PrintStats();
567 OS << "\n";
568 }
569
570 // Return the appropriate status when verifying diagnostics.
571 //
572 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
573 // this.
574 if (getDiagnosticOpts().VerifyDiagnostics)
575 return !static_cast<VerifyDiagnosticsClient&>(
576 getDiagnosticClient()).HadErrors();
577
578 return !getDiagnostics().getNumErrors();
579}
580
581