blob: d97e8c77277b0cc020aeadd7773cbf1d6e4024d1 [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"
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
49void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
50 LLVMContext.reset(Value);
Daniel Dunbar2a79e162009-11-13 03:51:44 +000051}
Daniel Dunbar16b74492009-11-13 04:12:06 +000052
Daniel Dunbar6228ca02010-01-30 21:47:07 +000053void CompilerInstance::setInvocation(CompilerInvocation *Value) {
54 Invocation.reset(Value);
55}
56
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000057void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000058 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000059}
60
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000061void CompilerInstance::setTarget(TargetInfo *Value) {
62 Target.reset(Value);
63}
64
65void CompilerInstance::setFileManager(FileManager *Value) {
66 FileMgr.reset(Value);
67}
68
69void CompilerInstance::setSourceManager(SourceManager *Value) {
70 SourceMgr.reset(Value);
71}
72
73void CompilerInstance::setPreprocessor(Preprocessor *Value) {
74 PP.reset(Value);
75}
76
77void CompilerInstance::setASTContext(ASTContext *Value) {
78 Context.reset(Value);
79}
80
Douglas Gregorf18d0d82010-08-12 23:31:19 +000081void CompilerInstance::setSema(Sema *S) {
82 TheSema.reset(S);
83}
84
Daniel Dunbar12ce6942009-11-14 02:47:17 +000085void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
86 Consumer.reset(Value);
87}
88
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000089void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
90 CompletionConsumer.reset(Value);
91}
92
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000093// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000094static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +000095 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000096 Diagnostic &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000097 std::string ErrorInfo;
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +000098 llvm::OwningPtr<llvm::raw_ostream> OS(
99 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000100 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000101 Diags.Report(diag::err_fe_unable_to_open_logfile)
102 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000103 return;
104 }
105
Daniel Dunbardd63b282009-12-11 23:04:35 +0000106 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000107 for (unsigned i = 0; i != argc; ++i)
108 (*OS) << argv[i] << ' ';
109 (*OS) << '\n';
110
111 // Chain in a diagnostic client which will log the diagnostics.
112 DiagnosticClient *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000113 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000114 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000115}
116
Douglas Gregore47be3e2010-11-11 00:39:14 +0000117void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
118 DiagnosticClient *Client) {
119 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000120}
121
Douglas Gregor28019772010-04-05 23:52:57 +0000122llvm::IntrusiveRefCntPtr<Diagnostic>
123CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000124 int Argc, const char* const *Argv,
125 DiagnosticClient *Client) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000126 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
127 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000128
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000129 // Create the diagnostic client for reporting errors or for
130 // implementing -verify.
Douglas Gregore47be3e2010-11-11 00:39:14 +0000131 if (Client)
132 Diags->setClient(Client);
133 else
134 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000135
136 // Chain in -verify checker, if requested.
137 if (Opts.VerifyDiagnostics)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000138 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000139
140 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000141 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000142
143 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000144 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000145
Douglas Gregor28019772010-04-05 23:52:57 +0000146 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000147}
148
149// File Manager
150
Daniel Dunbar16b74492009-11-13 04:12:06 +0000151void CompilerInstance::createFileManager() {
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000152 FileMgr.reset(new FileManager(getFileSystemOpts()));
Daniel Dunbar16b74492009-11-13 04:12:06 +0000153}
154
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000155// Source Manager
156
Chris Lattner39b49bc2010-11-23 08:35:12 +0000157void CompilerInstance::createSourceManager(FileManager &FileMgr) {
158 SourceMgr.reset(new SourceManager(getDiagnostics(), FileMgr));
Daniel Dunbar16b74492009-11-13 04:12:06 +0000159}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000160
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000161// Preprocessor
162
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000163void CompilerInstance::createPreprocessor() {
164 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
165 getPreprocessorOpts(), getHeaderSearchOpts(),
166 getDependencyOutputOpts(), getTarget(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000167 getFrontendOpts(), getSourceManager(),
168 getFileManager()));
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000169}
170
171Preprocessor *
172CompilerInstance::createPreprocessor(Diagnostic &Diags,
173 const LangOptions &LangInfo,
174 const PreprocessorOptions &PPOpts,
175 const HeaderSearchOptions &HSOpts,
176 const DependencyOutputOptions &DepOpts,
177 const TargetInfo &Target,
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000178 const FrontendOptions &FEOpts,
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000179 SourceManager &SourceMgr,
180 FileManager &FileMgr) {
181 // Create a PTH manager if we are using some form of a token cache.
182 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000183 if (!PPOpts.TokenCache.empty())
Chris Lattner681c74a2010-11-23 09:01:31 +0000184 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000185
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000186 // Create the Preprocessor.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000187 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000188 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
189 SourceMgr, *HeaderInfo, PTHMgr,
190 /*OwnsHeaderSearch=*/true);
191
192 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
193 // That argument is used as the IdentifierInfoLookup argument to
194 // IdentifierTable's ctor.
195 if (PTHMgr) {
196 PTHMgr->setPreprocessor(PP);
197 PP->setPTHManager(PTHMgr);
198 }
199
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000200 if (PPOpts.DetailedRecord)
201 PP->createPreprocessingRecord();
202
Chris Lattner39b49bc2010-11-23 08:35:12 +0000203 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000204
205 // Handle generating dependencies, if requested.
206 if (!DepOpts.OutputFile.empty())
207 AttachDependencyFileGen(*PP, DepOpts);
208
209 return PP;
210}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000211
212// ASTContext
213
214void CompilerInstance::createASTContext() {
215 Preprocessor &PP = getPreprocessor();
216 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
217 getTarget(), PP.getIdentifierTable(),
218 PP.getSelectorTable(), PP.getBuiltinInfo(),
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000219 /*size_reserve=*/ 0));
220}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000221
222// ExternalASTSource
223
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000224void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000225 bool DisablePCHValidation,
226 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000227 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000228 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000229 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000230 DisablePCHValidation,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000231 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000232 DeserializationListener,
233 Preamble));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000234 getASTContext().setExternalSource(Source);
235}
236
237ExternalASTSource *
238CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
239 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000240 bool DisablePCHValidation,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000241 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000242 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000243 void *DeserializationListener,
244 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000245 llvm::OwningPtr<ASTReader> Reader;
246 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000247 Sysroot.empty() ? 0 : Sysroot.c_str(),
248 DisablePCHValidation));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000249
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000250 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000251 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000252 switch (Reader->ReadAST(Path,
253 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000254 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000255 // Set the predefines buffer as suggested by the PCH reader. Typically, the
256 // predefines buffer will be empty.
257 PP.setPredefines(Reader->getSuggestedPredefines());
258 return Reader.take();
259
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000260 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000261 // Unrecoverable failure: don't even try to process the input file.
262 break;
263
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000264 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000265 // No suitable PCH file could be found. Return an error.
266 break;
267 }
268
269 return 0;
270}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000271
272// Code Completion
273
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000274static bool EnableCodeCompletion(Preprocessor &PP,
275 const std::string &Filename,
276 unsigned Line,
277 unsigned Column) {
278 // Tell the source manager to chop off the given file at a specific
279 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000280 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000281 if (!Entry) {
282 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
283 << Filename;
284 return true;
285 }
286
287 // Truncate the named file at the given line/column.
288 PP.SetCodeCompletionPoint(Entry, Line, Column);
289 return false;
290}
291
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000292void CompilerInstance::createCodeCompletionConsumer() {
293 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000294 if (!CompletionConsumer) {
295 CompletionConsumer.reset(
296 createCodeCompletionConsumer(getPreprocessor(),
297 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000298 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000299 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000300 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000301 llvm::outs()));
302 if (!CompletionConsumer)
303 return;
304 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
305 Loc.Line, Loc.Column)) {
306 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000307 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000308 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000309
310 if (CompletionConsumer->isOutputBinary() &&
311 llvm::sys::Program::ChangeStdoutToBinary()) {
312 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
313 CompletionConsumer.reset();
314 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000315}
316
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000317void CompilerInstance::createFrontendTimer() {
318 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
319}
320
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000321CodeCompleteConsumer *
322CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
323 const std::string &Filename,
324 unsigned Line,
325 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000326 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000327 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000328 bool ShowGlobals,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000329 llvm::raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000330 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000331 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000332
333 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000334 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000335 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000336}
Daniel Dunbara9204832009-11-13 10:37:48 +0000337
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000338void CompilerInstance::createSema(bool CompleteTranslationUnit,
339 CodeCompleteConsumer *CompletionConsumer) {
340 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
341 CompleteTranslationUnit, CompletionConsumer));
342}
343
Daniel Dunbara9204832009-11-13 10:37:48 +0000344// Output Files
345
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000346void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
347 assert(OutFile.OS && "Attempt to add empty stream to output list!");
348 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000349}
350
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000351void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000352 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000353 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000354 delete it->OS;
355 if (!it->TempFilename.empty()) {
356 llvm::sys::Path TempPath(it->TempFilename);
357 if (EraseFiles)
358 TempPath.eraseFromDisk();
359 else {
360 std::string Error;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000361 llvm::sys::Path NewOutFile(it->Filename);
362 // If '-working-directory' was passed, the output filename should be
363 // relative to that.
364 FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts());
365 if (TempPath.renamePathOnDisk(NewOutFile, &Error)) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000366 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
367 << it->TempFilename << it->Filename << Error;
368 TempPath.eraseFromDisk();
369 }
370 }
371 } else if (!it->Filename.empty() && EraseFiles)
372 llvm::sys::Path(it->Filename).eraseFromDisk();
373
Daniel Dunbara9204832009-11-13 10:37:48 +0000374 }
375 OutputFiles.clear();
376}
377
Daniel Dunbarf482d592009-11-13 18:32:08 +0000378llvm::raw_fd_ostream *
379CompilerInstance::createDefaultOutputFile(bool Binary,
380 llvm::StringRef InFile,
381 llvm::StringRef Extension) {
382 return createOutputFile(getFrontendOpts().OutputFile, Binary,
383 InFile, Extension);
384}
385
386llvm::raw_fd_ostream *
387CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
388 bool Binary,
389 llvm::StringRef InFile,
390 llvm::StringRef Extension) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000391 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000392 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
393 InFile, Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000394 &OutputPathName,
395 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000396 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000397 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
398 << OutputPath << Error;
399 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000400 }
401
402 // Add the output file -- but don't try to remove "-", since this means we are
403 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000404 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
405 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000406
407 return OS;
408}
409
410llvm::raw_fd_ostream *
411CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
412 std::string &Error,
413 bool Binary,
414 llvm::StringRef InFile,
415 llvm::StringRef Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000416 std::string *ResultPathName,
417 std::string *TempPathName) {
418 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000419 if (!OutputPath.empty()) {
420 OutFile = OutputPath;
421 } else if (InFile == "-") {
422 OutFile = "-";
423 } else if (!Extension.empty()) {
424 llvm::sys::Path Path(InFile);
425 Path.eraseSuffix();
426 Path.appendSuffix(Extension);
427 OutFile = Path.str();
428 } else {
429 OutFile = "-";
430 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000431
432 if (OutFile != "-") {
433 llvm::sys::Path OutPath(OutFile);
434 // Only create the temporary if we can actually write to OutPath, otherwise
435 // we want to fail early.
436 if (!OutPath.exists() ||
437 (OutPath.isRegularFile() && OutPath.canWrite())) {
438 // Create a temporary file.
439 llvm::sys::Path TempPath(OutFile);
440 if (!TempPath.createTemporaryFileOnDisk())
441 TempFile = TempPath.str();
442 }
443 }
444
445 std::string OSFile = OutFile;
446 if (!TempFile.empty())
447 OSFile = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000448
Daniel Dunbarfc971022009-11-20 22:32:38 +0000449 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000450 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000451 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
452 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000453 return 0;
454
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000455 // Make sure the out stream file gets removed if we crash.
456 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
457
Daniel Dunbarf482d592009-11-13 18:32:08 +0000458 if (ResultPathName)
459 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000460 if (TempPathName)
461 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000462
Daniel Dunbarfc971022009-11-20 22:32:38 +0000463 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000464}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000465
466// Initialization Utilities
467
468bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
469 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
470 getSourceManager(), getFrontendOpts());
471}
472
473bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
474 Diagnostic &Diags,
475 FileManager &FileMgr,
476 SourceManager &SourceMgr,
477 const FrontendOptions &Opts) {
Douglas Gregor414cb642010-11-30 05:23:00 +0000478 // Figure out where to get and map in the main file, unless it's already
479 // been created (e.g., by a precompiled preamble).
480 if (!SourceMgr.getMainFileID().isInvalid()) {
481 // Do nothing: the main file has already been set.
482 } else if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000483 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000484 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000485 Diags.Report(diag::err_fe_error_reading) << InputFile;
486 return false;
487 }
Dan Gohman694137c2010-10-26 21:13:51 +0000488 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000489 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000490 llvm::OwningPtr<llvm::MemoryBuffer> SB;
491 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000492 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000493 Diags.Report(diag::err_fe_error_reading_stdin);
494 return false;
495 }
Dan Gohman90d90812010-10-26 23:21:25 +0000496 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000497 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000498 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000499 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000500 }
501
Dan Gohman694137c2010-10-26 21:13:51 +0000502 assert(!SourceMgr.getMainFileID().isInvalid() &&
503 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000504 return true;
505}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000506
507// High-Level Operations
508
509bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
510 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
511 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
512 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
513
514 // FIXME: Take this as an argument, once all the APIs we used have moved to
515 // taking it as an input instead of hard-coding llvm::errs.
516 llvm::raw_ostream &OS = llvm::errs();
517
518 // Create the target instance.
519 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
520 if (!hasTarget())
521 return false;
522
523 // Inform the target of the language options.
524 //
525 // FIXME: We shouldn't need to do this, the target should be immutable once
526 // created. This complexity should be lifted elsewhere.
527 getTarget().setForcedLangOptions(getLangOpts());
528
529 // Validate/process some options.
530 if (getHeaderSearchOpts().Verbose)
531 OS << "clang -cc1 version " CLANG_VERSION_STRING
532 << " based upon " << PACKAGE_STRING
533 << " hosted on " << llvm::sys::getHostTriple() << "\n";
534
535 if (getFrontendOpts().ShowTimers)
536 createFrontendTimer();
537
Douglas Gregor95dd5582010-03-30 17:33:59 +0000538 if (getFrontendOpts().ShowStats)
539 llvm::EnableStatistics();
540
Daniel Dunbar0397af22010-01-13 00:48:06 +0000541 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
542 const std::string &InFile = getFrontendOpts().Inputs[i].second;
543
Daniel Dunbar20560482010-06-07 23:23:50 +0000544 // Reset the ID tables if we are reusing the SourceManager.
545 if (hasSourceManager())
546 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000547
Daniel Dunbard3598a62010-06-07 23:23:06 +0000548 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000549 Act.Execute();
550 Act.EndSourceFile();
551 }
552 }
553
Chris Lattner53eee7b2010-04-07 18:47:42 +0000554 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000555 // We can have multiple diagnostics sharing one diagnostic client.
556 // Get the total number of warnings/errors from the client.
557 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
558 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000559
560 if (NumWarnings)
561 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
562 if (NumWarnings && NumErrors)
563 OS << " and ";
564 if (NumErrors)
565 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
566 if (NumWarnings || NumErrors)
567 OS << " generated.\n";
568 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000569
Daniel Dunbar20560482010-06-07 23:23:50 +0000570 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000571 getFileManager().PrintStats();
572 OS << "\n";
573 }
574
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000575 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000576}
577
578