blob: dea698d5931bdf765d02bd24122d2d0e2bc0a0cf [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"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000030#include "llvm/LLVMContext.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000031#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000032#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000033#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000034#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000035#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-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. Spencer3a321e22010-12-09 17:36:38 +000040#include "llvm/Support/system_error.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000041using namespace clang;
42
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000043CompilerInstance::CompilerInstance()
Sebastian Redlffaab3e2010-07-30 00:29:29 +000044 : Invocation(new CompilerInvocation()) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000045}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000046
47CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000048}
49
50void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
51 LLVMContext.reset(Value);
Daniel Dunbar2a79e162009-11-13 03:51:44 +000052}
Daniel Dunbar16b74492009-11-13 04:12:06 +000053
Daniel Dunbar6228ca02010-01-30 21:47:07 +000054void CompilerInstance::setInvocation(CompilerInvocation *Value) {
55 Invocation.reset(Value);
56}
57
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000058void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000059 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000060}
61
Daniel Dunbar8a9f5692009-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 Gregorf18d0d82010-08-12 23:31:19 +000082void CompilerInstance::setSema(Sema *S) {
83 TheSema.reset(S);
84}
85
Daniel Dunbar12ce6942009-11-14 02:47:17 +000086void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
87 Consumer.reset(Value);
88}
89
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000090void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
91 CompletionConsumer.reset(Value);
92}
93
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000094// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000095static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +000096 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000097 Diagnostic &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000098 std::string ErrorInfo;
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +000099 llvm::OwningPtr<llvm::raw_ostream> OS(
100 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000101 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000102 Diags.Report(diag::err_fe_unable_to_open_logfile)
103 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000104 return;
105 }
106
Daniel Dunbardd63b282009-12-11 23:04:35 +0000107 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-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 Rajaratnam69247132010-03-17 09:47:30 +0000114 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000115 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000116}
117
Douglas Gregore47be3e2010-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 Dunbar0fbb3d92009-11-13 05:52:34 +0000121}
122
Douglas Gregor28019772010-04-05 23:52:57 +0000123llvm::IntrusiveRefCntPtr<Diagnostic>
124CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000125 int Argc, const char* const *Argv,
126 DiagnosticClient *Client) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000127 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
128 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000129
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000130 // Create the diagnostic client for reporting errors or for
131 // implementing -verify.
Douglas Gregore47be3e2010-11-11 00:39:14 +0000132 if (Client)
133 Diags->setClient(Client);
134 else
135 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000136
137 // Chain in -verify checker, if requested.
138 if (Opts.VerifyDiagnostics)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000139 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000140
141 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000142 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000143
144 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000145 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000146
Douglas Gregor28019772010-04-05 23:52:57 +0000147 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000148}
149
150// File Manager
151
Daniel Dunbar16b74492009-11-13 04:12:06 +0000152void CompilerInstance::createFileManager() {
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000153 FileMgr.reset(new FileManager(getFileSystemOpts()));
Daniel Dunbar16b74492009-11-13 04:12:06 +0000154}
155
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000156// Source Manager
157
Chris Lattner39b49bc2010-11-23 08:35:12 +0000158void CompilerInstance::createSourceManager(FileManager &FileMgr) {
159 SourceMgr.reset(new SourceManager(getDiagnostics(), FileMgr));
Daniel Dunbar16b74492009-11-13 04:12:06 +0000160}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000161
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000162// Preprocessor
163
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000164void CompilerInstance::createPreprocessor() {
165 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
166 getPreprocessorOpts(), getHeaderSearchOpts(),
167 getDependencyOutputOpts(), getTarget(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000168 getFrontendOpts(), getSourceManager(),
169 getFileManager()));
Daniel Dunbar22dacfa2009-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 Jahanian7d957472010-01-13 18:51:17 +0000179 const FrontendOptions &FEOpts,
Daniel Dunbar22dacfa2009-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 Dunbar049d3a02009-11-17 05:52:41 +0000184 if (!PPOpts.TokenCache.empty())
Chris Lattner681c74a2010-11-23 09:01:31 +0000185 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000186
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000187 // Create the Preprocessor.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000188 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar22dacfa2009-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 Gregor94dc8f62010-03-19 16:15:56 +0000201 if (PPOpts.DetailedRecord)
202 PP->createPreprocessingRecord();
203
Chris Lattner39b49bc2010-11-23 08:35:12 +0000204 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000205
206 // Handle generating dependencies, if requested.
207 if (!DepOpts.OutputFile.empty())
208 AttachDependencyFileGen(*PP, DepOpts);
209
Daniel Dunbareef63e02011-02-02 15:41:17 +0000210 // Handle generating header include information, if requested.
211 if (DepOpts.ShowHeaderIncludes)
212 AttachHeaderIncludeGen(*PP);
213
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000214 return PP;
215}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000216
217// ASTContext
218
219void CompilerInstance::createASTContext() {
220 Preprocessor &PP = getPreprocessor();
221 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
222 getTarget(), PP.getIdentifierTable(),
223 PP.getSelectorTable(), PP.getBuiltinInfo(),
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000224 /*size_reserve=*/ 0));
225}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000226
227// ExternalASTSource
228
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000229void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000230 bool DisablePCHValidation,
231 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000232 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000233 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000234 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000235 DisablePCHValidation,
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,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000246 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000247 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000248 void *DeserializationListener,
249 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000250 llvm::OwningPtr<ASTReader> Reader;
251 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000252 Sysroot.empty() ? 0 : Sysroot.c_str(),
253 DisablePCHValidation));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000254
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000255 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000256 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000257 switch (Reader->ReadAST(Path,
258 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000259 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000260 // Set the predefines buffer as suggested by the PCH reader. Typically, the
261 // predefines buffer will be empty.
262 PP.setPredefines(Reader->getSuggestedPredefines());
263 return Reader.take();
264
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000265 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000266 // Unrecoverable failure: don't even try to process the input file.
267 break;
268
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000269 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000270 // No suitable PCH file could be found. Return an error.
271 break;
272 }
273
274 return 0;
275}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000276
277// Code Completion
278
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000279static bool EnableCodeCompletion(Preprocessor &PP,
280 const std::string &Filename,
281 unsigned Line,
282 unsigned Column) {
283 // Tell the source manager to chop off the given file at a specific
284 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000285 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000286 if (!Entry) {
287 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
288 << Filename;
289 return true;
290 }
291
292 // Truncate the named file at the given line/column.
293 PP.SetCodeCompletionPoint(Entry, Line, Column);
294 return false;
295}
296
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000297void CompilerInstance::createCodeCompletionConsumer() {
298 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000299 if (!CompletionConsumer) {
300 CompletionConsumer.reset(
301 createCodeCompletionConsumer(getPreprocessor(),
302 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000303 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000304 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000305 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000306 llvm::outs()));
307 if (!CompletionConsumer)
308 return;
309 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
310 Loc.Line, Loc.Column)) {
311 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000312 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000313 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000314
315 if (CompletionConsumer->isOutputBinary() &&
316 llvm::sys::Program::ChangeStdoutToBinary()) {
317 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
318 CompletionConsumer.reset();
319 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000320}
321
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000322void CompilerInstance::createFrontendTimer() {
323 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
324}
325
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000326CodeCompleteConsumer *
327CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
328 const std::string &Filename,
329 unsigned Line,
330 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000331 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000332 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000333 bool ShowGlobals,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000334 llvm::raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000335 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000336 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000337
338 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000339 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000340 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000341}
Daniel Dunbara9204832009-11-13 10:37:48 +0000342
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000343void CompilerInstance::createSema(bool CompleteTranslationUnit,
344 CodeCompleteConsumer *CompletionConsumer) {
345 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
346 CompleteTranslationUnit, CompletionConsumer));
347}
348
Daniel Dunbara9204832009-11-13 10:37:48 +0000349// Output Files
350
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000351void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
352 assert(OutFile.OS && "Attempt to add empty stream to output list!");
353 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000354}
355
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000356void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000357 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000358 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000359 delete it->OS;
360 if (!it->TempFilename.empty()) {
361 llvm::sys::Path TempPath(it->TempFilename);
362 if (EraseFiles)
363 TempPath.eraseFromDisk();
364 else {
365 std::string Error;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000366 llvm::sys::Path NewOutFile(it->Filename);
367 // If '-working-directory' was passed, the output filename should be
368 // relative to that.
369 FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts());
370 if (TempPath.renamePathOnDisk(NewOutFile, &Error)) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000371 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
372 << it->TempFilename << it->Filename << Error;
373 TempPath.eraseFromDisk();
374 }
375 }
376 } else if (!it->Filename.empty() && EraseFiles)
377 llvm::sys::Path(it->Filename).eraseFromDisk();
378
Daniel Dunbara9204832009-11-13 10:37:48 +0000379 }
380 OutputFiles.clear();
381}
382
Daniel Dunbarf482d592009-11-13 18:32:08 +0000383llvm::raw_fd_ostream *
384CompilerInstance::createDefaultOutputFile(bool Binary,
385 llvm::StringRef InFile,
386 llvm::StringRef Extension) {
387 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000388 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000389}
390
391llvm::raw_fd_ostream *
392CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000393 bool Binary, bool RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000394 llvm::StringRef InFile,
395 llvm::StringRef Extension) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000396 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000397 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000398 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000399 InFile, Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000400 &OutputPathName,
401 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000402 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000403 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
404 << OutputPath << Error;
405 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000406 }
407
408 // Add the output file -- but don't try to remove "-", since this means we are
409 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000410 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
411 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000412
413 return OS;
414}
415
416llvm::raw_fd_ostream *
417CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
418 std::string &Error,
419 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000420 bool RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000421 llvm::StringRef InFile,
422 llvm::StringRef Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000423 std::string *ResultPathName,
424 std::string *TempPathName) {
425 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000426 if (!OutputPath.empty()) {
427 OutFile = OutputPath;
428 } else if (InFile == "-") {
429 OutFile = "-";
430 } else if (!Extension.empty()) {
431 llvm::sys::Path Path(InFile);
432 Path.eraseSuffix();
433 Path.appendSuffix(Extension);
434 OutFile = Path.str();
435 } else {
436 OutFile = "-";
437 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000438
439 if (OutFile != "-") {
440 llvm::sys::Path OutPath(OutFile);
441 // Only create the temporary if we can actually write to OutPath, otherwise
442 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000443 bool Exists;
444 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000445 (OutPath.isRegularFile() && OutPath.canWrite())) {
446 // Create a temporary file.
447 llvm::sys::Path TempPath(OutFile);
448 if (!TempPath.createTemporaryFileOnDisk())
449 TempFile = TempPath.str();
450 }
451 }
452
453 std::string OSFile = OutFile;
454 if (!TempFile.empty())
455 OSFile = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000456
Daniel Dunbarfc971022009-11-20 22:32:38 +0000457 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000458 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000459 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
460 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000461 return 0;
462
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000463 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000464 if (RemoveFileOnSignal)
465 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000466
Daniel Dunbarf482d592009-11-13 18:32:08 +0000467 if (ResultPathName)
468 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000469 if (TempPathName)
470 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000471
Daniel Dunbarfc971022009-11-20 22:32:38 +0000472 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000473}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000474
475// Initialization Utilities
476
477bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
478 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
479 getSourceManager(), getFrontendOpts());
480}
481
482bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
483 Diagnostic &Diags,
484 FileManager &FileMgr,
485 SourceManager &SourceMgr,
486 const FrontendOptions &Opts) {
Douglas Gregor414cb642010-11-30 05:23:00 +0000487 // Figure out where to get and map in the main file, unless it's already
488 // been created (e.g., by a precompiled preamble).
489 if (!SourceMgr.getMainFileID().isInvalid()) {
490 // Do nothing: the main file has already been set.
491 } else if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000492 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000493 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000494 Diags.Report(diag::err_fe_error_reading) << InputFile;
495 return false;
496 }
Dan Gohman694137c2010-10-26 21:13:51 +0000497 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000498 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000499 llvm::OwningPtr<llvm::MemoryBuffer> SB;
500 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000501 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000502 Diags.Report(diag::err_fe_error_reading_stdin);
503 return false;
504 }
Dan Gohman90d90812010-10-26 23:21:25 +0000505 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000506 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000507 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000508 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000509 }
510
Dan Gohman694137c2010-10-26 21:13:51 +0000511 assert(!SourceMgr.getMainFileID().isInvalid() &&
512 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000513 return true;
514}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000515
516// High-Level Operations
517
518bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
519 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
520 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
521 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
522
523 // FIXME: Take this as an argument, once all the APIs we used have moved to
524 // taking it as an input instead of hard-coding llvm::errs.
525 llvm::raw_ostream &OS = llvm::errs();
526
527 // Create the target instance.
528 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
529 if (!hasTarget())
530 return false;
531
532 // Inform the target of the language options.
533 //
534 // FIXME: We shouldn't need to do this, the target should be immutable once
535 // created. This complexity should be lifted elsewhere.
536 getTarget().setForcedLangOptions(getLangOpts());
537
538 // Validate/process some options.
539 if (getHeaderSearchOpts().Verbose)
540 OS << "clang -cc1 version " CLANG_VERSION_STRING
541 << " based upon " << PACKAGE_STRING
542 << " hosted on " << llvm::sys::getHostTriple() << "\n";
543
544 if (getFrontendOpts().ShowTimers)
545 createFrontendTimer();
546
Douglas Gregor95dd5582010-03-30 17:33:59 +0000547 if (getFrontendOpts().ShowStats)
548 llvm::EnableStatistics();
549
Daniel Dunbar0397af22010-01-13 00:48:06 +0000550 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
551 const std::string &InFile = getFrontendOpts().Inputs[i].second;
552
Daniel Dunbar20560482010-06-07 23:23:50 +0000553 // Reset the ID tables if we are reusing the SourceManager.
554 if (hasSourceManager())
555 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000556
Daniel Dunbard3598a62010-06-07 23:23:06 +0000557 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000558 Act.Execute();
559 Act.EndSourceFile();
560 }
561 }
562
Chris Lattner53eee7b2010-04-07 18:47:42 +0000563 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000564 // We can have multiple diagnostics sharing one diagnostic client.
565 // Get the total number of warnings/errors from the client.
566 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
567 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000568
569 if (NumWarnings)
570 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
571 if (NumWarnings && NumErrors)
572 OS << " and ";
573 if (NumErrors)
574 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
575 if (NumWarnings || NumErrors)
576 OS << " generated.\n";
577 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000578
Daniel Dunbar20560482010-06-07 23:23:50 +0000579 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000580 getFileManager().PrintStats();
581 OS << "\n";
582 }
583
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000584 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000585}
586
587