blob: 412e7111e4801bc8bca1a7da227020487f885f68 [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);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000213 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
214 llvm::StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
215 if (OutputPath == "-")
216 OutputPath = "";
217 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath);
218 }
Daniel Dunbareef63e02011-02-02 15:41:17 +0000219
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000220 return PP;
221}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000222
223// ASTContext
224
225void CompilerInstance::createASTContext() {
226 Preprocessor &PP = getPreprocessor();
227 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
228 getTarget(), PP.getIdentifierTable(),
229 PP.getSelectorTable(), PP.getBuiltinInfo(),
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000230 /*size_reserve=*/ 0));
231}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000232
233// ExternalASTSource
234
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000235void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000236 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000237 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000238 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000239 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000240 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000241 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000242 DisablePCHValidation,
243 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000244 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000245 DeserializationListener,
246 Preamble));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000247 getASTContext().setExternalSource(Source);
248}
249
250ExternalASTSource *
251CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
252 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000253 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000254 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000255 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000256 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000257 void *DeserializationListener,
258 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000259 llvm::OwningPtr<ASTReader> Reader;
260 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000261 Sysroot.empty() ? 0 : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000262 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000263
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000264 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000265 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000266 switch (Reader->ReadAST(Path,
267 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000268 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000269 // Set the predefines buffer as suggested by the PCH reader. Typically, the
270 // predefines buffer will be empty.
271 PP.setPredefines(Reader->getSuggestedPredefines());
272 return Reader.take();
273
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000274 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000275 // Unrecoverable failure: don't even try to process the input file.
276 break;
277
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000278 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000279 // No suitable PCH file could be found. Return an error.
280 break;
281 }
282
283 return 0;
284}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000285
286// Code Completion
287
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000288static bool EnableCodeCompletion(Preprocessor &PP,
289 const std::string &Filename,
290 unsigned Line,
291 unsigned Column) {
292 // Tell the source manager to chop off the given file at a specific
293 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000294 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000295 if (!Entry) {
296 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
297 << Filename;
298 return true;
299 }
300
301 // Truncate the named file at the given line/column.
302 PP.SetCodeCompletionPoint(Entry, Line, Column);
303 return false;
304}
305
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000306void CompilerInstance::createCodeCompletionConsumer() {
307 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000308 if (!CompletionConsumer) {
309 CompletionConsumer.reset(
310 createCodeCompletionConsumer(getPreprocessor(),
311 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000312 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000313 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000314 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000315 llvm::outs()));
316 if (!CompletionConsumer)
317 return;
318 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
319 Loc.Line, Loc.Column)) {
320 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000321 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000322 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000323
324 if (CompletionConsumer->isOutputBinary() &&
325 llvm::sys::Program::ChangeStdoutToBinary()) {
326 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
327 CompletionConsumer.reset();
328 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000329}
330
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000331void CompilerInstance::createFrontendTimer() {
332 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
333}
334
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000335CodeCompleteConsumer *
336CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
337 const std::string &Filename,
338 unsigned Line,
339 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000340 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000341 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000342 bool ShowGlobals,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000343 llvm::raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000344 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000345 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000346
347 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000348 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000349 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000350}
Daniel Dunbara9204832009-11-13 10:37:48 +0000351
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000352void CompilerInstance::createSema(bool CompleteTranslationUnit,
353 CodeCompleteConsumer *CompletionConsumer) {
354 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
355 CompleteTranslationUnit, CompletionConsumer));
356}
357
Daniel Dunbara9204832009-11-13 10:37:48 +0000358// Output Files
359
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000360void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
361 assert(OutFile.OS && "Attempt to add empty stream to output list!");
362 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000363}
364
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000365void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000366 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000367 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000368 delete it->OS;
369 if (!it->TempFilename.empty()) {
370 llvm::sys::Path TempPath(it->TempFilename);
371 if (EraseFiles)
372 TempPath.eraseFromDisk();
373 else {
374 std::string Error;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000375 llvm::sys::Path NewOutFile(it->Filename);
376 // If '-working-directory' was passed, the output filename should be
377 // relative to that.
378 FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts());
379 if (TempPath.renamePathOnDisk(NewOutFile, &Error)) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000380 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
381 << it->TempFilename << it->Filename << Error;
382 TempPath.eraseFromDisk();
383 }
384 }
385 } else if (!it->Filename.empty() && EraseFiles)
386 llvm::sys::Path(it->Filename).eraseFromDisk();
387
Daniel Dunbara9204832009-11-13 10:37:48 +0000388 }
389 OutputFiles.clear();
390}
391
Daniel Dunbarf482d592009-11-13 18:32:08 +0000392llvm::raw_fd_ostream *
393CompilerInstance::createDefaultOutputFile(bool Binary,
394 llvm::StringRef InFile,
395 llvm::StringRef Extension) {
396 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000397 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000398}
399
400llvm::raw_fd_ostream *
401CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000402 bool Binary, bool RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000403 llvm::StringRef InFile,
404 llvm::StringRef Extension) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000405 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000406 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000407 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000408 InFile, Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000409 &OutputPathName,
410 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000411 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000412 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
413 << OutputPath << Error;
414 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000415 }
416
417 // Add the output file -- but don't try to remove "-", since this means we are
418 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000419 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
420 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000421
422 return OS;
423}
424
425llvm::raw_fd_ostream *
426CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
427 std::string &Error,
428 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000429 bool RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000430 llvm::StringRef InFile,
431 llvm::StringRef Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000432 std::string *ResultPathName,
433 std::string *TempPathName) {
434 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000435 if (!OutputPath.empty()) {
436 OutFile = OutputPath;
437 } else if (InFile == "-") {
438 OutFile = "-";
439 } else if (!Extension.empty()) {
440 llvm::sys::Path Path(InFile);
441 Path.eraseSuffix();
442 Path.appendSuffix(Extension);
443 OutFile = Path.str();
444 } else {
445 OutFile = "-";
446 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000447
448 if (OutFile != "-") {
449 llvm::sys::Path OutPath(OutFile);
450 // Only create the temporary if we can actually write to OutPath, otherwise
451 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000452 bool Exists;
453 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000454 (OutPath.isRegularFile() && OutPath.canWrite())) {
455 // Create a temporary file.
456 llvm::sys::Path TempPath(OutFile);
457 if (!TempPath.createTemporaryFileOnDisk())
458 TempFile = TempPath.str();
459 }
460 }
461
462 std::string OSFile = OutFile;
463 if (!TempFile.empty())
464 OSFile = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000465
Daniel Dunbarfc971022009-11-20 22:32:38 +0000466 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000467 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000468 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
469 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000470 return 0;
471
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000472 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000473 if (RemoveFileOnSignal)
474 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000475
Daniel Dunbarf482d592009-11-13 18:32:08 +0000476 if (ResultPathName)
477 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000478 if (TempPathName)
479 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000480
Daniel Dunbarfc971022009-11-20 22:32:38 +0000481 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000482}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000483
484// Initialization Utilities
485
486bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
487 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
488 getSourceManager(), getFrontendOpts());
489}
490
491bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
492 Diagnostic &Diags,
493 FileManager &FileMgr,
494 SourceManager &SourceMgr,
495 const FrontendOptions &Opts) {
Douglas Gregor414cb642010-11-30 05:23:00 +0000496 // Figure out where to get and map in the main file, unless it's already
497 // been created (e.g., by a precompiled preamble).
498 if (!SourceMgr.getMainFileID().isInvalid()) {
499 // Do nothing: the main file has already been set.
500 } else if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000501 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000502 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000503 Diags.Report(diag::err_fe_error_reading) << InputFile;
504 return false;
505 }
Dan Gohman694137c2010-10-26 21:13:51 +0000506 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000507 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000508 llvm::OwningPtr<llvm::MemoryBuffer> SB;
509 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000510 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000511 Diags.Report(diag::err_fe_error_reading_stdin);
512 return false;
513 }
Dan Gohman90d90812010-10-26 23:21:25 +0000514 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000515 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000516 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000517 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000518 }
519
Dan Gohman694137c2010-10-26 21:13:51 +0000520 assert(!SourceMgr.getMainFileID().isInvalid() &&
521 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000522 return true;
523}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000524
525// High-Level Operations
526
527bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
528 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
529 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
530 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
531
532 // FIXME: Take this as an argument, once all the APIs we used have moved to
533 // taking it as an input instead of hard-coding llvm::errs.
534 llvm::raw_ostream &OS = llvm::errs();
535
536 // Create the target instance.
537 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
538 if (!hasTarget())
539 return false;
540
541 // Inform the target of the language options.
542 //
543 // FIXME: We shouldn't need to do this, the target should be immutable once
544 // created. This complexity should be lifted elsewhere.
545 getTarget().setForcedLangOptions(getLangOpts());
546
547 // Validate/process some options.
548 if (getHeaderSearchOpts().Verbose)
549 OS << "clang -cc1 version " CLANG_VERSION_STRING
550 << " based upon " << PACKAGE_STRING
551 << " hosted on " << llvm::sys::getHostTriple() << "\n";
552
553 if (getFrontendOpts().ShowTimers)
554 createFrontendTimer();
555
Douglas Gregor95dd5582010-03-30 17:33:59 +0000556 if (getFrontendOpts().ShowStats)
557 llvm::EnableStatistics();
558
Daniel Dunbar0397af22010-01-13 00:48:06 +0000559 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
560 const std::string &InFile = getFrontendOpts().Inputs[i].second;
561
Daniel Dunbar20560482010-06-07 23:23:50 +0000562 // Reset the ID tables if we are reusing the SourceManager.
563 if (hasSourceManager())
564 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000565
Daniel Dunbard3598a62010-06-07 23:23:06 +0000566 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000567 Act.Execute();
568 Act.EndSourceFile();
569 }
570 }
571
Chris Lattner53eee7b2010-04-07 18:47:42 +0000572 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000573 // We can have multiple diagnostics sharing one diagnostic client.
574 // Get the total number of warnings/errors from the client.
575 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
576 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000577
578 if (NumWarnings)
579 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
580 if (NumWarnings && NumErrors)
581 OS << " and ";
582 if (NumErrors)
583 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
584 if (NumWarnings || NumErrors)
585 OS << " generated.\n";
586 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000587
Daniel Dunbar20560482010-06-07 23:23:50 +0000588 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000589 getFileManager().PrintStats();
590 OS << "\n";
591 }
592
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000593 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000594}
595
596