blob: 26d40e4f80b215421254276a6101cba465a80935 [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"
Michael J. Spencerf6efe582011-01-10 02:34:13 +000030#include "llvm/Support/FileSystem.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"
Michael J. Spencer8aaf4992010-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. Spencerf25faaa2010-12-09 17:36:38 +000039#include "llvm/Support/system_error.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000040using namespace clang;
41
Daniel Dunbare922d9b2010-02-16 01:54:47 +000042CompilerInstance::CompilerInstance()
Sebastian Redl07a89a82010-07-30 00:29:29 +000043 : Invocation(new CompilerInvocation()) {
Daniel Dunbar68242252010-01-30 21:47:07 +000044}
Daniel Dunbar636404a2009-11-13 03:51:44 +000045
46CompilerInstance::~CompilerInstance() {
Daniel Dunbare922d9b2010-02-16 01:54:47 +000047}
48
Daniel Dunbar68242252010-01-30 21:47:07 +000049void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000050 Invocation = Value;
Daniel Dunbar68242252010-01-30 21:47:07 +000051}
52
Daniel Dunbare01dc862009-11-14 01:20:40 +000053void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor7f95d262010-04-05 23:52:57 +000054 Diagnostics = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000055}
56
Daniel Dunbare01dc862009-11-14 01:20:40 +000057void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000058 Target = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000059}
60
61void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000062 FileMgr = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000063}
64
Ted Kremenek5e14d392011-03-21 18:40:17 +000065void CompilerInstance::setSourceManager(SourceManager *Value) {
66 SourceMgr = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000067}
68
Ted Kremenek5e14d392011-03-21 18:40:17 +000069void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbare01dc862009-11-14 01:20:40 +000070
Ted Kremenek5e14d392011-03-21 18:40:17 +000071void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbare01dc862009-11-14 01:20:40 +000072
Douglas Gregor0e93f012010-08-12 23:31:19 +000073void CompilerInstance::setSema(Sema *S) {
74 TheSema.reset(S);
75}
76
Daniel Dunbar56d9c292009-11-14 02:47:17 +000077void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
78 Consumer.reset(Value);
79}
80
Daniel Dunbare01dc862009-11-14 01:20:40 +000081void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
82 CompletionConsumer.reset(Value);
83}
84
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000085// Diagnostics
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000086static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann89c31492010-10-11 09:13:46 +000087 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +000088 Diagnostic &Diags) {
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000089 std::string ErrorInfo;
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +000090 llvm::OwningPtr<llvm::raw_ostream> OS(
91 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000092 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +000093 Diags.Report(diag::err_fe_unable_to_open_logfile)
94 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000095 return;
96 }
97
Daniel Dunbar520d1e62009-12-11 23:04:35 +000098 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000099 for (unsigned i = 0; i != argc; ++i)
100 (*OS) << argv[i] << ' ';
101 (*OS) << '\n';
102
103 // Chain in a diagnostic client which will log the diagnostics.
104 DiagnosticClient *Logger =
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +0000105 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000106 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000107}
108
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000109void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
110 DiagnosticClient *Client) {
111 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000112}
113
Douglas Gregor7f95d262010-04-05 23:52:57 +0000114llvm::IntrusiveRefCntPtr<Diagnostic>
115CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000116 int Argc, const char* const *Argv,
117 DiagnosticClient *Client) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000118 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
119 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000120
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000121 // Create the diagnostic client for reporting errors or for
122 // implementing -verify.
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000123 if (Client)
124 Diags->setClient(Client);
125 else
126 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbar50ec0da2009-11-14 03:24:39 +0000127
128 // Chain in -verify checker, if requested.
129 if (Opts.VerifyDiagnostics)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000130 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000131
132 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +0000133 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000134
135 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam9ff84d92010-03-17 09:36:02 +0000136 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000137
Douglas Gregor7f95d262010-04-05 23:52:57 +0000138 return Diags;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000139}
140
141// File Manager
142
Daniel Dunbar546a6762009-11-13 04:12:06 +0000143void CompilerInstance::createFileManager() {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000144 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar546a6762009-11-13 04:12:06 +0000145}
146
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000147// Source Manager
148
Chris Lattner5159f612010-11-23 08:35:12 +0000149void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000150 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar546a6762009-11-13 04:12:06 +0000151}
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000152
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000153// Preprocessor
154
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000155void CompilerInstance::createPreprocessor() {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000156 PP = createPreprocessor(getDiagnostics(), getLangOpts(),
157 getPreprocessorOpts(), getHeaderSearchOpts(),
158 getDependencyOutputOpts(), getTarget(),
159 getFrontendOpts(), getSourceManager(),
160 getFileManager());
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000161}
162
163Preprocessor *
164CompilerInstance::createPreprocessor(Diagnostic &Diags,
165 const LangOptions &LangInfo,
166 const PreprocessorOptions &PPOpts,
167 const HeaderSearchOptions &HSOpts,
168 const DependencyOutputOptions &DepOpts,
169 const TargetInfo &Target,
Fariborz Jahanian3f7b8b22010-01-13 18:51:17 +0000170 const FrontendOptions &FEOpts,
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000171 SourceManager &SourceMgr,
172 FileManager &FileMgr) {
173 // Create a PTH manager if we are using some form of a token cache.
174 PTHManager *PTHMgr = 0;
Daniel Dunbard6ea9022009-11-17 05:52:41 +0000175 if (!PPOpts.TokenCache.empty())
Chris Lattner7219a5d2010-11-23 09:01:31 +0000176 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000177
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000178 // Create the Preprocessor.
Chris Lattner5159f612010-11-23 08:35:12 +0000179 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000180 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
181 SourceMgr, *HeaderInfo, PTHMgr,
182 /*OwnsHeaderSearch=*/true);
183
184 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
185 // That argument is used as the IdentifierInfoLookup argument to
186 // IdentifierTable's ctor.
187 if (PTHMgr) {
188 PTHMgr->setPreprocessor(PP);
189 PP->setPTHManager(PTHMgr);
190 }
191
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000192 if (PPOpts.DetailedRecord)
193 PP->createPreprocessingRecord();
194
Chris Lattner5159f612010-11-23 08:35:12 +0000195 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000196
197 // Handle generating dependencies, if requested.
198 if (!DepOpts.OutputFile.empty())
199 AttachDependencyFileGen(*PP, DepOpts);
200
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000201 // Handle generating header include information, if requested.
202 if (DepOpts.ShowHeaderIncludes)
203 AttachHeaderIncludeGen(*PP);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000204 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
205 llvm::StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
206 if (OutputPath == "-")
207 OutputPath = "";
208 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath);
209 }
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000210
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000211 return PP;
212}
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000213
214// ASTContext
215
216void CompilerInstance::createASTContext() {
217 Preprocessor &PP = getPreprocessor();
Ted Kremenek5e14d392011-03-21 18:40:17 +0000218 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
219 getTarget(), PP.getIdentifierTable(),
220 PP.getSelectorTable(), PP.getBuiltinInfo(),
221 /*size_reserve=*/ 0);
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000222}
Daniel Dunbar599313e2009-11-13 08:21:10 +0000223
224// ExternalASTSource
225
Douglas Gregorce3a8292010-07-27 00:27:13 +0000226void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000227 bool DisablePCHValidation,
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000228 bool DisableStatCache,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000229 void *DeserializationListener){
Daniel Dunbar599313e2009-11-13 08:21:10 +0000230 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl009e7f22010-10-05 16:15:19 +0000231 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar599313e2009-11-13 08:21:10 +0000232 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000233 DisablePCHValidation,
234 DisableStatCache,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000235 getPreprocessor(), getASTContext(),
Sebastian Redl009e7f22010-10-05 16:15:19 +0000236 DeserializationListener,
237 Preamble));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000238 getASTContext().setExternalSource(Source);
239}
240
241ExternalASTSource *
242CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
243 const std::string &Sysroot,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000244 bool DisablePCHValidation,
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000245 bool DisableStatCache,
Daniel Dunbar599313e2009-11-13 08:21:10 +0000246 Preprocessor &PP,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000247 ASTContext &Context,
Sebastian Redl009e7f22010-10-05 16:15:19 +0000248 void *DeserializationListener,
249 bool Preamble) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000250 llvm::OwningPtr<ASTReader> Reader;
251 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000252 Sysroot.empty() ? 0 : Sysroot.c_str(),
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000253 DisablePCHValidation, DisableStatCache));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000254
Sebastian Redl07a89a82010-07-30 00:29:29 +0000255 Reader->setDeserializationListener(
Sebastian Redl3e31c722010-08-18 23:56:56 +0000256 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl009e7f22010-10-05 16:15:19 +0000257 switch (Reader->ReadAST(Path,
258 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000259 case ASTReader::Success:
Daniel Dunbar599313e2009-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 Redl2c499f62010-08-18 23:56:43 +0000265 case ASTReader::Failure:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000266 // Unrecoverable failure: don't even try to process the input file.
267 break;
268
Sebastian Redl2c499f62010-08-18 23:56:43 +0000269 case ASTReader::IgnorePCH:
Daniel Dunbar599313e2009-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 Dunbarf7093b52009-11-13 09:36:05 +0000276
277// Code Completion
278
Douglas Gregor8e984da2010-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 Lattner5159f612010-11-23 08:35:12 +0000285 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor8e984da2010-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 Dunbarf7093b52009-11-13 09:36:05 +0000297void CompilerInstance::createCodeCompletionConsumer() {
298 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000299 if (!CompletionConsumer) {
300 CompletionConsumer.reset(
301 createCodeCompletionConsumer(getPreprocessor(),
302 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000303 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000304 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +0000305 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor8e984da2010-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 Gregor00a0cf72010-03-16 06:04:47 +0000312 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000313 }
Douglas Gregorf09935f2009-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 Dunbarf7093b52009-11-13 09:36:05 +0000320}
321
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000322void CompilerInstance::createFrontendTimer() {
323 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
324}
325
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000326CodeCompleteConsumer *
327CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
328 const std::string &Filename,
329 unsigned Line,
330 unsigned Column,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000331 bool ShowMacros,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000332 bool ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000333 bool ShowGlobals,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000334 llvm::raw_ostream &OS) {
Douglas Gregor8e984da2010-08-04 16:47:14 +0000335 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000336 return 0;
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000337
338 // Set up the creation routine for code-completion.
Douglas Gregorb9ab0ed2010-10-11 22:12:15 +0000339 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000340 ShowGlobals, OS);
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000341}
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000342
Douglas Gregor0e93f012010-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 Dunbar566eeb22009-11-13 10:37:48 +0000349// Output Files
350
Argyrios Kyrtzidisd0599972010-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 Dunbar566eeb22009-11-13 10:37:48 +0000354}
355
Kovarththanan Rajaratnam1c558cd2010-03-06 12:07:48 +0000356void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000357 for (std::list<OutputFile>::iterator
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000358 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000359 delete it->OS;
360 if (!it->TempFilename.empty()) {
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000361 if (EraseFiles) {
362 bool existed;
363 llvm::sys::fs::remove(it->TempFilename, existed);
364 } else {
365 llvm::SmallString<128> NewOutFile(it->Filename);
366
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000367 // If '-working-directory' was passed, the output filename should be
368 // relative to that.
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000369 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000370 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
371 NewOutFile.str())) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000372 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000373 << it->TempFilename << it->Filename << ec.message();
374
375 bool existed;
376 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000377 }
378 }
379 } else if (!it->Filename.empty() && EraseFiles)
380 llvm::sys::Path(it->Filename).eraseFromDisk();
381
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000382 }
383 OutputFiles.clear();
384}
385
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000386llvm::raw_fd_ostream *
387CompilerInstance::createDefaultOutputFile(bool Binary,
388 llvm::StringRef InFile,
389 llvm::StringRef Extension) {
390 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000391 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000392}
393
394llvm::raw_fd_ostream *
395CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000396 bool Binary, bool RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000397 llvm::StringRef InFile,
398 llvm::StringRef Extension) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000399 std::string Error, OutputPathName, TempPathName;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000400 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000401 RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000402 InFile, Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000403 &OutputPathName,
404 &TempPathName);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000405 if (!OS) {
Daniel Dunbar75546992009-12-03 09:13:30 +0000406 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
407 << OutputPath << Error;
408 return 0;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000409 }
410
411 // Add the output file -- but don't try to remove "-", since this means we are
412 // using stdin.
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000413 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
414 TempPathName, OS));
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000415
416 return OS;
417}
418
419llvm::raw_fd_ostream *
420CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
421 std::string &Error,
422 bool Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000423 bool RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000424 llvm::StringRef InFile,
425 llvm::StringRef Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000426 std::string *ResultPathName,
427 std::string *TempPathName) {
428 std::string OutFile, TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000429 if (!OutputPath.empty()) {
430 OutFile = OutputPath;
431 } else if (InFile == "-") {
432 OutFile = "-";
433 } else if (!Extension.empty()) {
434 llvm::sys::Path Path(InFile);
435 Path.eraseSuffix();
436 Path.appendSuffix(Extension);
437 OutFile = Path.str();
438 } else {
439 OutFile = "-";
440 }
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000441
442 if (OutFile != "-") {
443 llvm::sys::Path OutPath(OutFile);
444 // Only create the temporary if we can actually write to OutPath, otherwise
445 // we want to fail early.
Michael J. Spencerf6efe582011-01-10 02:34:13 +0000446 bool Exists;
447 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000448 (OutPath.isRegularFile() && OutPath.canWrite())) {
449 // Create a temporary file.
450 llvm::sys::Path TempPath(OutFile);
451 if (!TempPath.createTemporaryFileOnDisk())
452 TempFile = TempPath.str();
453 }
454 }
455
456 std::string OSFile = OutFile;
457 if (!TempFile.empty())
458 OSFile = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000459
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000460 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000461 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000462 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
463 if (!Error.empty())
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000464 return 0;
465
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000466 // Make sure the out stream file gets removed if we crash.
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000467 if (RemoveFileOnSignal)
468 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000469
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000470 if (ResultPathName)
471 *ResultPathName = OutFile;
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000472 if (TempPathName)
473 *TempPathName = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000474
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000475 return OS.take();
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000476}
Daniel Dunbar409e8902009-11-14 07:53:04 +0000477
478// Initialization Utilities
479
480bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
481 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
482 getSourceManager(), getFrontendOpts());
483}
484
485bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
486 Diagnostic &Diags,
487 FileManager &FileMgr,
488 SourceManager &SourceMgr,
489 const FrontendOptions &Opts) {
Douglas Gregor936a5b42010-11-30 05:23:00 +0000490 // Figure out where to get and map in the main file, unless it's already
491 // been created (e.g., by a precompiled preamble).
492 if (!SourceMgr.getMainFileID().isInvalid()) {
493 // Do nothing: the main file has already been set.
494 } else if (InputFile != "-") {
Chris Lattner5159f612010-11-23 08:35:12 +0000495 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman52765212010-10-26 21:13:51 +0000496 if (!File) {
Daniel Dunbar409e8902009-11-14 07:53:04 +0000497 Diags.Report(diag::err_fe_error_reading) << InputFile;
498 return false;
499 }
Dan Gohman52765212010-10-26 21:13:51 +0000500 SourceMgr.createMainFileID(File);
Daniel Dunbar409e8902009-11-14 07:53:04 +0000501 } else {
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000502 llvm::OwningPtr<llvm::MemoryBuffer> SB;
503 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000504 // FIXME: Give ec.message() in this diag.
Daniel Dunbar409e8902009-11-14 07:53:04 +0000505 Diags.Report(diag::err_fe_error_reading_stdin);
506 return false;
507 }
Dan Gohman2f76cd72010-10-26 23:21:25 +0000508 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner5159f612010-11-23 08:35:12 +0000509 SB->getBufferSize(), 0);
Dan Gohman2f76cd72010-10-26 23:21:25 +0000510 SourceMgr.createMainFileID(File);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000511 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbar409e8902009-11-14 07:53:04 +0000512 }
513
Dan Gohman52765212010-10-26 21:13:51 +0000514 assert(!SourceMgr.getMainFileID().isInvalid() &&
515 "Couldn't establish MainFileID!");
Daniel Dunbar409e8902009-11-14 07:53:04 +0000516 return true;
517}
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000518
519// High-Level Operations
520
521bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
522 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
523 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
524 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
525
526 // FIXME: Take this as an argument, once all the APIs we used have moved to
527 // taking it as an input instead of hard-coding llvm::errs.
528 llvm::raw_ostream &OS = llvm::errs();
529
530 // Create the target instance.
531 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
532 if (!hasTarget())
533 return false;
534
535 // Inform the target of the language options.
536 //
537 // FIXME: We shouldn't need to do this, the target should be immutable once
538 // created. This complexity should be lifted elsewhere.
539 getTarget().setForcedLangOptions(getLangOpts());
540
541 // Validate/process some options.
542 if (getHeaderSearchOpts().Verbose)
543 OS << "clang -cc1 version " CLANG_VERSION_STRING
544 << " based upon " << PACKAGE_STRING
545 << " hosted on " << llvm::sys::getHostTriple() << "\n";
546
547 if (getFrontendOpts().ShowTimers)
548 createFrontendTimer();
549
Douglas Gregor171b7802010-03-30 17:33:59 +0000550 if (getFrontendOpts().ShowStats)
551 llvm::EnableStatistics();
552
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000553 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
554 const std::string &InFile = getFrontendOpts().Inputs[i].second;
555
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000556 // Reset the ID tables if we are reusing the SourceManager.
557 if (hasSourceManager())
558 getSourceManager().clearIDTables();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000559
Daniel Dunbar86546382010-06-07 23:23:06 +0000560 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000561 Act.Execute();
562 Act.EndSourceFile();
563 }
564 }
565
Chris Lattner198cb4d2010-04-07 18:47:42 +0000566 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000567 // We can have multiple diagnostics sharing one diagnostic client.
568 // Get the total number of warnings/errors from the client.
569 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
570 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner198cb4d2010-04-07 18:47:42 +0000571
572 if (NumWarnings)
573 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
574 if (NumWarnings && NumErrors)
575 OS << " and ";
576 if (NumErrors)
577 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
578 if (NumWarnings || NumErrors)
579 OS << " generated.\n";
580 }
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000581
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000582 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000583 getFileManager().PrintStats();
584 OS << "\n";
585 }
586
Argyrios Kyrtzidisbc467932010-11-18 21:13:57 +0000587 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000588}
589
590