blob: fd593de560c02a7231a0fd605f8508c6e9476073 [file] [log] [blame]
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001//===--- CompilerInstance.cpp ---------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/CompilerInstance.h"
Douglas Gregorf18d0d82010-08-12 23:31:19 +000011#include "clang/Sema/Sema.h"
Daniel Dunbar12ce6942009-11-14 02:47:17 +000012#include "clang/AST/ASTConsumer.h"
Daniel Dunbar5eb81002009-11-13 08:20:47 +000013#include "clang/AST/ASTContext.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000014#include "clang/Basic/Diagnostic.h"
Daniel Dunbar16b74492009-11-13 04:12:06 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000018#include "clang/Basic/Version.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/PTHManager.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000022#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000024#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000025#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbarf79dced2009-11-14 03:24:39 +000026#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000027#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000029#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000030#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000031#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000033#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000034#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000035#include "llvm/Support/Host.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Program.h"
38#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000039#include "llvm/Support/system_error.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000040using namespace clang;
41
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000042CompilerInstance::CompilerInstance()
Sebastian Redlffaab3e2010-07-30 00:29:29 +000043 : Invocation(new CompilerInvocation()) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000044}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000045
46CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000047}
48
Daniel Dunbar6228ca02010-01-30 21:47:07 +000049void CompilerInstance::setInvocation(CompilerInvocation *Value) {
50 Invocation.reset(Value);
51}
52
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000053void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000054 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000055}
56
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000057void CompilerInstance::setTarget(TargetInfo *Value) {
58 Target.reset(Value);
59}
60
61void CompilerInstance::setFileManager(FileManager *Value) {
62 FileMgr.reset(Value);
63}
64
65void CompilerInstance::setSourceManager(SourceManager *Value) {
66 SourceMgr.reset(Value);
67}
68
69void CompilerInstance::setPreprocessor(Preprocessor *Value) {
70 PP.reset(Value);
71}
72
73void CompilerInstance::setASTContext(ASTContext *Value) {
74 Context.reset(Value);
75}
76
Douglas Gregorf18d0d82010-08-12 23:31:19 +000077void CompilerInstance::setSema(Sema *S) {
78 TheSema.reset(S);
79}
80
Daniel Dunbar12ce6942009-11-14 02:47:17 +000081void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
82 Consumer.reset(Value);
83}
84
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000085void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
86 CompletionConsumer.reset(Value);
87}
88
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000089// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000090static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +000091 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000092 Diagnostic &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000093 std::string ErrorInfo;
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +000094 llvm::OwningPtr<llvm::raw_ostream> OS(
95 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000096 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000097 Diags.Report(diag::err_fe_unable_to_open_logfile)
98 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000099 return;
100 }
101
Daniel Dunbardd63b282009-12-11 23:04:35 +0000102 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000103 for (unsigned i = 0; i != argc; ++i)
104 (*OS) << argv[i] << ' ';
105 (*OS) << '\n';
106
107 // Chain in a diagnostic client which will log the diagnostics.
108 DiagnosticClient *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000109 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000110 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000111}
112
Douglas Gregore47be3e2010-11-11 00:39:14 +0000113void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
114 DiagnosticClient *Client) {
115 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000116}
117
Douglas Gregor28019772010-04-05 23:52:57 +0000118llvm::IntrusiveRefCntPtr<Diagnostic>
119CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000120 int Argc, const char* const *Argv,
121 DiagnosticClient *Client) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000122 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
123 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000124
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000125 // Create the diagnostic client for reporting errors or for
126 // implementing -verify.
Douglas Gregore47be3e2010-11-11 00:39:14 +0000127 if (Client)
128 Diags->setClient(Client);
129 else
130 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000131
132 // Chain in -verify checker, if requested.
133 if (Opts.VerifyDiagnostics)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000134 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000135
136 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000137 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000138
139 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000140 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000141
Douglas Gregor28019772010-04-05 23:52:57 +0000142 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000143}
144
145// File Manager
146
Daniel Dunbar16b74492009-11-13 04:12:06 +0000147void CompilerInstance::createFileManager() {
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000148 FileMgr.reset(new FileManager(getFileSystemOpts()));
Daniel Dunbar16b74492009-11-13 04:12:06 +0000149}
150
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000151// Source Manager
152
Chris Lattner39b49bc2010-11-23 08:35:12 +0000153void CompilerInstance::createSourceManager(FileManager &FileMgr) {
154 SourceMgr.reset(new SourceManager(getDiagnostics(), FileMgr));
Daniel Dunbar16b74492009-11-13 04:12:06 +0000155}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000156
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000157// Preprocessor
158
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000159void CompilerInstance::createPreprocessor() {
160 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
161 getPreprocessorOpts(), getHeaderSearchOpts(),
162 getDependencyOutputOpts(), getTarget(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000163 getFrontendOpts(), getSourceManager(),
164 getFileManager()));
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000165}
166
167Preprocessor *
168CompilerInstance::createPreprocessor(Diagnostic &Diags,
169 const LangOptions &LangInfo,
170 const PreprocessorOptions &PPOpts,
171 const HeaderSearchOptions &HSOpts,
172 const DependencyOutputOptions &DepOpts,
173 const TargetInfo &Target,
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000174 const FrontendOptions &FEOpts,
Daniel Dunbar22dacfa2009-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 Dunbar049d3a02009-11-17 05:52:41 +0000179 if (!PPOpts.TokenCache.empty())
Chris Lattner681c74a2010-11-23 09:01:31 +0000180 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000181
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000182 // Create the Preprocessor.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000183 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar22dacfa2009-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 Gregor94dc8f62010-03-19 16:15:56 +0000196 if (PPOpts.DetailedRecord)
197 PP->createPreprocessingRecord();
198
Chris Lattner39b49bc2010-11-23 08:35:12 +0000199 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000200
201 // Handle generating dependencies, if requested.
202 if (!DepOpts.OutputFile.empty())
203 AttachDependencyFileGen(*PP, DepOpts);
204
Daniel Dunbareef63e02011-02-02 15:41:17 +0000205 // Handle generating header include information, if requested.
206 if (DepOpts.ShowHeaderIncludes)
207 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000208 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
209 llvm::StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
210 if (OutputPath == "-")
211 OutputPath = "";
212 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath);
213 }
Daniel Dunbareef63e02011-02-02 15:41:17 +0000214
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000215 return PP;
216}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000217
218// ASTContext
219
220void CompilerInstance::createASTContext() {
221 Preprocessor &PP = getPreprocessor();
222 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
223 getTarget(), PP.getIdentifierTable(),
224 PP.getSelectorTable(), PP.getBuiltinInfo(),
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000225 /*size_reserve=*/ 0));
226}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000227
228// ExternalASTSource
229
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000230void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000231 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000232 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000233 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000234 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000235 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000236 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000237 DisablePCHValidation,
238 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000239 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000240 DeserializationListener,
241 Preamble));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000242 getASTContext().setExternalSource(Source);
243}
244
245ExternalASTSource *
246CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
247 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000248 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000249 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000250 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000251 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000252 void *DeserializationListener,
253 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000254 llvm::OwningPtr<ASTReader> Reader;
255 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000256 Sysroot.empty() ? 0 : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000257 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000258
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000259 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000260 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000261 switch (Reader->ReadAST(Path,
262 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000263 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000264 // Set the predefines buffer as suggested by the PCH reader. Typically, the
265 // predefines buffer will be empty.
266 PP.setPredefines(Reader->getSuggestedPredefines());
267 return Reader.take();
268
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000269 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000270 // Unrecoverable failure: don't even try to process the input file.
271 break;
272
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000273 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000274 // No suitable PCH file could be found. Return an error.
275 break;
276 }
277
278 return 0;
279}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000280
281// Code Completion
282
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000283static bool EnableCodeCompletion(Preprocessor &PP,
284 const std::string &Filename,
285 unsigned Line,
286 unsigned Column) {
287 // Tell the source manager to chop off the given file at a specific
288 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000289 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000290 if (!Entry) {
291 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
292 << Filename;
293 return true;
294 }
295
296 // Truncate the named file at the given line/column.
297 PP.SetCodeCompletionPoint(Entry, Line, Column);
298 return false;
299}
300
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000301void CompilerInstance::createCodeCompletionConsumer() {
302 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000303 if (!CompletionConsumer) {
304 CompletionConsumer.reset(
305 createCodeCompletionConsumer(getPreprocessor(),
306 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000307 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000308 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000309 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000310 llvm::outs()));
311 if (!CompletionConsumer)
312 return;
313 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
314 Loc.Line, Loc.Column)) {
315 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000316 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000317 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000318
319 if (CompletionConsumer->isOutputBinary() &&
320 llvm::sys::Program::ChangeStdoutToBinary()) {
321 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
322 CompletionConsumer.reset();
323 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000324}
325
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000326void CompilerInstance::createFrontendTimer() {
327 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
328}
329
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000330CodeCompleteConsumer *
331CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
332 const std::string &Filename,
333 unsigned Line,
334 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000335 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000336 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000337 bool ShowGlobals,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000338 llvm::raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000339 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000340 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000341
342 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000343 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000344 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000345}
Daniel Dunbara9204832009-11-13 10:37:48 +0000346
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000347void CompilerInstance::createSema(bool CompleteTranslationUnit,
348 CodeCompleteConsumer *CompletionConsumer) {
349 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
350 CompleteTranslationUnit, CompletionConsumer));
351}
352
Daniel Dunbara9204832009-11-13 10:37:48 +0000353// Output Files
354
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000355void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
356 assert(OutFile.OS && "Attempt to add empty stream to output list!");
357 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000358}
359
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000360void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000361 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000362 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000363 delete it->OS;
364 if (!it->TempFilename.empty()) {
365 llvm::sys::Path TempPath(it->TempFilename);
366 if (EraseFiles)
367 TempPath.eraseFromDisk();
368 else {
369 std::string Error;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000370 llvm::sys::Path NewOutFile(it->Filename);
371 // If '-working-directory' was passed, the output filename should be
372 // relative to that.
373 FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts());
374 if (TempPath.renamePathOnDisk(NewOutFile, &Error)) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000375 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
376 << it->TempFilename << it->Filename << Error;
377 TempPath.eraseFromDisk();
378 }
379 }
380 } else if (!it->Filename.empty() && EraseFiles)
381 llvm::sys::Path(it->Filename).eraseFromDisk();
382
Daniel Dunbara9204832009-11-13 10:37:48 +0000383 }
384 OutputFiles.clear();
385}
386
Daniel Dunbarf482d592009-11-13 18:32:08 +0000387llvm::raw_fd_ostream *
388CompilerInstance::createDefaultOutputFile(bool Binary,
389 llvm::StringRef InFile,
390 llvm::StringRef Extension) {
391 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000392 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000393}
394
395llvm::raw_fd_ostream *
396CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000397 bool Binary, bool RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000398 llvm::StringRef InFile,
399 llvm::StringRef Extension) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000400 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000401 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000402 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000403 InFile, Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000404 &OutputPathName,
405 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000406 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000407 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
408 << OutputPath << Error;
409 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000410 }
411
412 // Add the output file -- but don't try to remove "-", since this means we are
413 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000414 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
415 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000416
417 return OS;
418}
419
420llvm::raw_fd_ostream *
421CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
422 std::string &Error,
423 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000424 bool RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000425 llvm::StringRef InFile,
426 llvm::StringRef Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000427 std::string *ResultPathName,
428 std::string *TempPathName) {
429 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000430 if (!OutputPath.empty()) {
431 OutFile = OutputPath;
432 } else if (InFile == "-") {
433 OutFile = "-";
434 } else if (!Extension.empty()) {
435 llvm::sys::Path Path(InFile);
436 Path.eraseSuffix();
437 Path.appendSuffix(Extension);
438 OutFile = Path.str();
439 } else {
440 OutFile = "-";
441 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000442
443 if (OutFile != "-") {
444 llvm::sys::Path OutPath(OutFile);
445 // Only create the temporary if we can actually write to OutPath, otherwise
446 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000447 bool Exists;
448 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000449 (OutPath.isRegularFile() && OutPath.canWrite())) {
450 // Create a temporary file.
451 llvm::sys::Path TempPath(OutFile);
452 if (!TempPath.createTemporaryFileOnDisk())
453 TempFile = TempPath.str();
454 }
455 }
456
457 std::string OSFile = OutFile;
458 if (!TempFile.empty())
459 OSFile = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000460
Daniel Dunbarfc971022009-11-20 22:32:38 +0000461 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000462 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000463 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
464 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000465 return 0;
466
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000467 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000468 if (RemoveFileOnSignal)
469 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000470
Daniel Dunbarf482d592009-11-13 18:32:08 +0000471 if (ResultPathName)
472 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000473 if (TempPathName)
474 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000475
Daniel Dunbarfc971022009-11-20 22:32:38 +0000476 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000477}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000478
479// Initialization Utilities
480
481bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
482 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
483 getSourceManager(), getFrontendOpts());
484}
485
486bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
487 Diagnostic &Diags,
488 FileManager &FileMgr,
489 SourceManager &SourceMgr,
490 const FrontendOptions &Opts) {
Douglas Gregor414cb642010-11-30 05:23:00 +0000491 // Figure out where to get and map in the main file, unless it's already
492 // been created (e.g., by a precompiled preamble).
493 if (!SourceMgr.getMainFileID().isInvalid()) {
494 // Do nothing: the main file has already been set.
495 } else if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000496 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000497 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000498 Diags.Report(diag::err_fe_error_reading) << InputFile;
499 return false;
500 }
Dan Gohman694137c2010-10-26 21:13:51 +0000501 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000502 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000503 llvm::OwningPtr<llvm::MemoryBuffer> SB;
504 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000505 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000506 Diags.Report(diag::err_fe_error_reading_stdin);
507 return false;
508 }
Dan Gohman90d90812010-10-26 23:21:25 +0000509 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000510 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000511 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000512 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000513 }
514
Dan Gohman694137c2010-10-26 21:13:51 +0000515 assert(!SourceMgr.getMainFileID().isInvalid() &&
516 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000517 return true;
518}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000519
520// High-Level Operations
521
522bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
523 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
524 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
525 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
526
527 // FIXME: Take this as an argument, once all the APIs we used have moved to
528 // taking it as an input instead of hard-coding llvm::errs.
529 llvm::raw_ostream &OS = llvm::errs();
530
531 // Create the target instance.
532 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
533 if (!hasTarget())
534 return false;
535
536 // Inform the target of the language options.
537 //
538 // FIXME: We shouldn't need to do this, the target should be immutable once
539 // created. This complexity should be lifted elsewhere.
540 getTarget().setForcedLangOptions(getLangOpts());
541
542 // Validate/process some options.
543 if (getHeaderSearchOpts().Verbose)
544 OS << "clang -cc1 version " CLANG_VERSION_STRING
545 << " based upon " << PACKAGE_STRING
546 << " hosted on " << llvm::sys::getHostTriple() << "\n";
547
548 if (getFrontendOpts().ShowTimers)
549 createFrontendTimer();
550
Douglas Gregor95dd5582010-03-30 17:33:59 +0000551 if (getFrontendOpts().ShowStats)
552 llvm::EnableStatistics();
553
Daniel Dunbar0397af22010-01-13 00:48:06 +0000554 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
555 const std::string &InFile = getFrontendOpts().Inputs[i].second;
556
Daniel Dunbar20560482010-06-07 23:23:50 +0000557 // Reset the ID tables if we are reusing the SourceManager.
558 if (hasSourceManager())
559 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000560
Daniel Dunbard3598a62010-06-07 23:23:06 +0000561 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000562 Act.Execute();
563 Act.EndSourceFile();
564 }
565 }
566
Chris Lattner53eee7b2010-04-07 18:47:42 +0000567 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000568 // We can have multiple diagnostics sharing one diagnostic client.
569 // Get the total number of warnings/errors from the client.
570 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
571 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000572
573 if (NumWarnings)
574 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
575 if (NumWarnings && NumErrors)
576 OS << " and ";
577 if (NumErrors)
578 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
579 if (NumWarnings || NumErrors)
580 OS << " generated.\n";
581 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000582
Daniel Dunbar20560482010-06-07 23:23:50 +0000583 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000584 getFileManager().PrintStats();
585 OS << "\n";
586 }
587
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000588 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000589}
590
591