blob: f53d0b064cb5bdc29fc12745c972c165428e4a7b [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 Dunbar9df23492011-04-07 18:31:10 +000025#include "clang/Frontend/LogDiagnosticPrinter.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbarf79dced2009-11-14 03:24:39 +000027#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000028#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000030#include "clang/Sema/CodeCompleteConsumer.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"
Dylan Noblesmith16266012011-06-23 12:20:57 +000041#include "llvm/Config/config.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000042using namespace clang;
43
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000044CompilerInstance::CompilerInstance()
Douglas Gregorf62d43d2011-07-19 16:10:42 +000045 : Invocation(new CompilerInvocation()), ModuleManager(0) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000046}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000047
48CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000049}
50
Daniel Dunbar6228ca02010-01-30 21:47:07 +000051void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000052 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000053}
54
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000055void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000056 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000057}
58
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000059void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000060 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000061}
62
63void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000064 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000065}
66
Ted Kremenek4f327862011-03-21 18:40:17 +000067void CompilerInstance::setSourceManager(SourceManager *Value) {
68 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000069}
70
Ted Kremenek4f327862011-03-21 18:40:17 +000071void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000072
Ted Kremenek4f327862011-03-21 18:40:17 +000073void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000074
Douglas Gregorf18d0d82010-08-12 23:31:19 +000075void CompilerInstance::setSema(Sema *S) {
76 TheSema.reset(S);
77}
78
Daniel Dunbar12ce6942009-11-14 02:47:17 +000079void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
80 Consumer.reset(Value);
81}
82
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000083void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
84 CompletionConsumer.reset(Value);
85}
86
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000087// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000088static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +000089 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000090 Diagnostic &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000091 std::string ErrorInfo;
Chris Lattner5f9e2722011-07-23 10:55:15 +000092 llvm::OwningPtr<raw_ostream> OS(
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +000093 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000094 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000095 Diags.Report(diag::err_fe_unable_to_open_logfile)
96 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000097 return;
98 }
99
Daniel Dunbardd63b282009-12-11 23:04:35 +0000100 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000101 for (unsigned i = 0; i != argc; ++i)
102 (*OS) << argv[i] << ' ';
103 (*OS) << '\n';
104
105 // Chain in a diagnostic client which will log the diagnostics.
106 DiagnosticClient *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000107 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000108 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000109}
110
Daniel Dunbar9df23492011-04-07 18:31:10 +0000111static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000112 const CodeGenOptions *CodeGenOpts,
Daniel Dunbar9df23492011-04-07 18:31:10 +0000113 Diagnostic &Diags) {
114 std::string ErrorInfo;
115 bool OwnsStream = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 raw_ostream *OS = &llvm::errs();
Daniel Dunbar9df23492011-04-07 18:31:10 +0000117 if (DiagOpts.DiagnosticLogFile != "-") {
118 // Create the output stream.
119 llvm::raw_fd_ostream *FileOS(
120 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbare01eceb2011-04-07 20:19:21 +0000121 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000122 if (!ErrorInfo.empty()) {
123 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
124 << DiagOpts.DumpBuildInformation << ErrorInfo;
125 } else {
126 FileOS->SetUnbuffered();
127 FileOS->SetUseAtomicWrites(true);
128 OS = FileOS;
129 OwnsStream = true;
130 }
131 }
132
133 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000134 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
135 OwnsStream);
136 if (CodeGenOpts)
137 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
Daniel Dunbar9df23492011-04-07 18:31:10 +0000138 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
139}
140
Douglas Gregore47be3e2010-11-11 00:39:14 +0000141void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
142 DiagnosticClient *Client) {
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000143 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
144 &getCodeGenOpts());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000145}
146
Douglas Gregor28019772010-04-05 23:52:57 +0000147llvm::IntrusiveRefCntPtr<Diagnostic>
148CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000149 int Argc, const char* const *Argv,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000150 DiagnosticClient *Client,
151 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000152 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
153 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000154
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000155 // Create the diagnostic client for reporting errors or for
156 // implementing -verify.
Douglas Gregore47be3e2010-11-11 00:39:14 +0000157 if (Client)
158 Diags->setClient(Client);
159 else
160 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000161
162 // Chain in -verify checker, if requested.
163 if (Opts.VerifyDiagnostics)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000164 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000165
Daniel Dunbar9df23492011-04-07 18:31:10 +0000166 // Chain in -diagnostic-log-file dumper, if requested.
167 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000168 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
Daniel Dunbar9df23492011-04-07 18:31:10 +0000169
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000170 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000171 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000172
173 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000174 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000175
Douglas Gregor28019772010-04-05 23:52:57 +0000176 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000177}
178
179// File Manager
180
Daniel Dunbar16b74492009-11-13 04:12:06 +0000181void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000182 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000183}
184
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000185// Source Manager
186
Chris Lattner39b49bc2010-11-23 08:35:12 +0000187void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000188 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000189}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000190
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000191// Preprocessor
192
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000193void CompilerInstance::createPreprocessor() {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000194 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
195
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000196 // Create a PTH manager if we are using some form of a token cache.
197 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000198 if (!PPOpts.TokenCache.empty())
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000199 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
200
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000201 // Create the Preprocessor.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000202 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager());
203 PP = new Preprocessor(getDiagnostics(), getLangOpts(), getTarget(),
204 getSourceManager(), *HeaderInfo, *this, PTHMgr,
205 /*OwnsHeaderSearch=*/true);
206
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000207 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
208 // That argument is used as the IdentifierInfoLookup argument to
209 // IdentifierTable's ctor.
210 if (PTHMgr) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000211 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000212 PP->setPTHManager(PTHMgr);
213 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000214
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000215 if (PPOpts.DetailedRecord)
Douglas Gregordca8ee82011-05-06 16:33:08 +0000216 PP->createPreprocessingRecord(
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000217 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000218
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000219 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
220
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000221 // Handle generating dependencies, if requested.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000222 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000223 if (!DepOpts.OutputFile.empty())
224 AttachDependencyFileGen(*PP, DepOpts);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000225
Daniel Dunbareef63e02011-02-02 15:41:17 +0000226 // Handle generating header include information, if requested.
227 if (DepOpts.ShowHeaderIncludes)
228 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000229 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000230 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000231 if (OutputPath == "-")
232 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000233 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
234 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000235 }
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000236}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000237
238// ASTContext
239
240void CompilerInstance::createASTContext() {
241 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000242 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
243 getTarget(), PP.getIdentifierTable(),
244 PP.getSelectorTable(), PP.getBuiltinInfo(),
245 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000246}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000247
248// ExternalASTSource
249
Chris Lattner5f9e2722011-07-23 10:55:15 +0000250void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000251 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000252 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000253 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000254 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000255 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000256 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000257 DisablePCHValidation,
258 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000259 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000260 DeserializationListener,
261 Preamble));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000262 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar0f800392009-11-13 08:21:10 +0000263 getASTContext().setExternalSource(Source);
264}
265
266ExternalASTSource *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000267CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000268 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000269 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000270 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000271 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000272 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000273 void *DeserializationListener,
274 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000275 llvm::OwningPtr<ASTReader> Reader;
276 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregor832d6202011-07-22 16:35:34 +0000277 Sysroot.empty() ? "" : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000278 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000279
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000280 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000281 static_cast<ASTDeserializationListener *>(DeserializationListener));
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000282 switch (Reader->ReadAST(Path,
283 Preamble ? serialization::MK_Preamble
284 : serialization::MK_PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000285 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000286 // Set the predefines buffer as suggested by the PCH reader. Typically, the
287 // predefines buffer will be empty.
288 PP.setPredefines(Reader->getSuggestedPredefines());
289 return Reader.take();
290
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000291 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000292 // Unrecoverable failure: don't even try to process the input file.
293 break;
294
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000295 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000296 // No suitable PCH file could be found. Return an error.
297 break;
298 }
299
300 return 0;
301}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000302
303// Code Completion
304
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000305static bool EnableCodeCompletion(Preprocessor &PP,
306 const std::string &Filename,
307 unsigned Line,
308 unsigned Column) {
309 // Tell the source manager to chop off the given file at a specific
310 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000311 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000312 if (!Entry) {
313 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
314 << Filename;
315 return true;
316 }
317
318 // Truncate the named file at the given line/column.
319 PP.SetCodeCompletionPoint(Entry, Line, Column);
320 return false;
321}
322
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000323void CompilerInstance::createCodeCompletionConsumer() {
324 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000325 if (!CompletionConsumer) {
326 CompletionConsumer.reset(
327 createCodeCompletionConsumer(getPreprocessor(),
328 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000329 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000330 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000331 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000332 llvm::outs()));
333 if (!CompletionConsumer)
334 return;
335 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
336 Loc.Line, Loc.Column)) {
337 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000338 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000339 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000340
341 if (CompletionConsumer->isOutputBinary() &&
342 llvm::sys::Program::ChangeStdoutToBinary()) {
343 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
344 CompletionConsumer.reset();
345 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000346}
347
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000348void CompilerInstance::createFrontendTimer() {
349 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
350}
351
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000352CodeCompleteConsumer *
353CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
354 const std::string &Filename,
355 unsigned Line,
356 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000357 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000358 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000359 bool ShowGlobals,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000360 raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000361 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000362 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000363
364 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000365 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000366 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000367}
Daniel Dunbara9204832009-11-13 10:37:48 +0000368
Douglas Gregor467dc882011-08-25 22:30:56 +0000369void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000370 CodeCompleteConsumer *CompletionConsumer) {
371 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor467dc882011-08-25 22:30:56 +0000372 TUKind, CompletionConsumer));
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000373}
374
Daniel Dunbara9204832009-11-13 10:37:48 +0000375// Output Files
376
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000377void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
378 assert(OutFile.OS && "Attempt to add empty stream to output list!");
379 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000380}
381
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000382void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000383 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000384 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000385 delete it->OS;
386 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000387 if (EraseFiles) {
388 bool existed;
389 llvm::sys::fs::remove(it->TempFilename, existed);
390 } else {
391 llvm::SmallString<128> NewOutFile(it->Filename);
392
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000393 // If '-working-directory' was passed, the output filename should be
394 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000395 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000396 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
397 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000398 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000399 << it->TempFilename << it->Filename << ec.message();
400
401 bool existed;
402 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000403 }
404 }
405 } else if (!it->Filename.empty() && EraseFiles)
406 llvm::sys::Path(it->Filename).eraseFromDisk();
407
Daniel Dunbara9204832009-11-13 10:37:48 +0000408 }
409 OutputFiles.clear();
410}
411
Daniel Dunbarf482d592009-11-13 18:32:08 +0000412llvm::raw_fd_ostream *
413CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000414 StringRef InFile,
415 StringRef Extension) {
Daniel Dunbarf482d592009-11-13 18:32:08 +0000416 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000417 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000418}
419
420llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000421CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000422 bool Binary, bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000423 StringRef InFile,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000424 StringRef Extension,
425 bool UseTemporary) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000426 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000427 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000428 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000429 InFile, Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000430 UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000431 &OutputPathName,
432 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000433 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000434 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
435 << OutputPath << Error;
436 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000437 }
438
439 // Add the output file -- but don't try to remove "-", since this means we are
440 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000441 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
442 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000443
444 return OS;
445}
446
447llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000448CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000449 std::string &Error,
450 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000451 bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000452 StringRef InFile,
453 StringRef Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000454 bool UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000455 std::string *ResultPathName,
456 std::string *TempPathName) {
457 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000458 if (!OutputPath.empty()) {
459 OutFile = OutputPath;
460 } else if (InFile == "-") {
461 OutFile = "-";
462 } else if (!Extension.empty()) {
463 llvm::sys::Path Path(InFile);
464 Path.eraseSuffix();
465 Path.appendSuffix(Extension);
466 OutFile = Path.str();
467 } else {
468 OutFile = "-";
469 }
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000470
471 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
472 std::string OSFile;
473
474 if (UseTemporary && OutFile != "-") {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000475 llvm::sys::Path OutPath(OutFile);
476 // Only create the temporary if we can actually write to OutPath, otherwise
477 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000478 bool Exists;
479 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000480 (OutPath.isRegularFile() && OutPath.canWrite())) {
481 // Create a temporary file.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000482 llvm::SmallString<128> TempPath;
483 TempPath = OutFile;
484 TempPath += "-%%%%%%%%";
485 int fd;
486 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
487 /*makeAbsolute=*/false) == llvm::errc::success) {
488 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
489 OSFile = TempFile = TempPath.str();
490 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000491 }
492 }
493
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000494 if (!OS) {
495 OSFile = OutFile;
496 OS.reset(
497 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
498 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
499 if (!Error.empty())
500 return 0;
501 }
Daniel Dunbarf482d592009-11-13 18:32:08 +0000502
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000503 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000504 if (RemoveFileOnSignal)
505 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000506
Daniel Dunbarf482d592009-11-13 18:32:08 +0000507 if (ResultPathName)
508 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000509 if (TempPathName)
510 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000511
Daniel Dunbarfc971022009-11-20 22:32:38 +0000512 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000513}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000514
515// Initialization Utilities
516
Chris Lattner5f9e2722011-07-23 10:55:15 +0000517bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000518 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
519 getSourceManager(), getFrontendOpts());
520}
521
Chris Lattner5f9e2722011-07-23 10:55:15 +0000522bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000523 Diagnostic &Diags,
524 FileManager &FileMgr,
525 SourceManager &SourceMgr,
526 const FrontendOptions &Opts) {
Douglas Gregor414cb642010-11-30 05:23:00 +0000527 // Figure out where to get and map in the main file, unless it's already
528 // been created (e.g., by a precompiled preamble).
529 if (!SourceMgr.getMainFileID().isInvalid()) {
530 // Do nothing: the main file has already been set.
531 } else if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000532 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000533 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000534 Diags.Report(diag::err_fe_error_reading) << InputFile;
535 return false;
536 }
Dan Gohman694137c2010-10-26 21:13:51 +0000537 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000538 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000539 llvm::OwningPtr<llvm::MemoryBuffer> SB;
540 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000541 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000542 Diags.Report(diag::err_fe_error_reading_stdin);
543 return false;
544 }
Dan Gohman90d90812010-10-26 23:21:25 +0000545 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000546 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000547 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000548 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000549 }
550
Dan Gohman694137c2010-10-26 21:13:51 +0000551 assert(!SourceMgr.getMainFileID().isInvalid() &&
552 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000553 return true;
554}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000555
556// High-Level Operations
557
558bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
559 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
560 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
561 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
562
563 // FIXME: Take this as an argument, once all the APIs we used have moved to
564 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000565 raw_ostream &OS = llvm::errs();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000566
567 // Create the target instance.
568 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
569 if (!hasTarget())
570 return false;
571
572 // Inform the target of the language options.
573 //
574 // FIXME: We shouldn't need to do this, the target should be immutable once
575 // created. This complexity should be lifted elsewhere.
576 getTarget().setForcedLangOptions(getLangOpts());
577
578 // Validate/process some options.
579 if (getHeaderSearchOpts().Verbose)
580 OS << "clang -cc1 version " CLANG_VERSION_STRING
581 << " based upon " << PACKAGE_STRING
582 << " hosted on " << llvm::sys::getHostTriple() << "\n";
583
584 if (getFrontendOpts().ShowTimers)
585 createFrontendTimer();
586
Douglas Gregor95dd5582010-03-30 17:33:59 +0000587 if (getFrontendOpts().ShowStats)
588 llvm::EnableStatistics();
589
Daniel Dunbar0397af22010-01-13 00:48:06 +0000590 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
591 const std::string &InFile = getFrontendOpts().Inputs[i].second;
592
Daniel Dunbar20560482010-06-07 23:23:50 +0000593 // Reset the ID tables if we are reusing the SourceManager.
594 if (hasSourceManager())
595 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000596
Daniel Dunbard3598a62010-06-07 23:23:06 +0000597 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000598 Act.Execute();
599 Act.EndSourceFile();
600 }
601 }
602
Chris Lattner53eee7b2010-04-07 18:47:42 +0000603 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000604 // We can have multiple diagnostics sharing one diagnostic client.
605 // Get the total number of warnings/errors from the client.
606 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
607 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000608
609 if (NumWarnings)
610 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
611 if (NumWarnings && NumErrors)
612 OS << " and ";
613 if (NumErrors)
614 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
615 if (NumWarnings || NumErrors)
616 OS << " generated.\n";
617 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000618
Daniel Dunbar20560482010-06-07 23:23:50 +0000619 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000620 getFileManager().PrintStats();
621 OS << "\n";
622 }
623
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000624 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000625}
626
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000627ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
628 IdentifierInfo &ModuleName,
629 SourceLocation ModuleNameLoc) {
630 // Determine what file we're searching from.
631 SourceManager &SourceMgr = getSourceManager();
632 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
633 const FileEntry *CurFile
634 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
635 if (!CurFile)
636 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
637
638 // Search for a module with the given name.
639 std::string Filename = ModuleName.getName().str();
640 Filename += ".pcm";
641 const DirectoryLookup *CurDir = 0;
642 const FileEntry *ModuleFile
643 = PP->getHeaderSearchInfo().LookupFile(Filename, /*isAngled=*/false,
644 /*FromDir=*/0, CurDir, CurFile,
645 /*SearchPath=*/0,
646 /*RelativePath=*/0);
647 if (!ModuleFile) {
648 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_not_found)
649 << ModuleName.getName()
650 << SourceRange(ImportLoc, ModuleNameLoc);
651 return 0;
652 }
653
654 // If we don't already have an ASTReader, create one now.
655 if (!ModuleManager) {
656 std::string Sysroot = getHeaderSearchOpts().Sysroot;
657 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
658 ModuleManager = new ASTReader(getPreprocessor(), &*Context,
659 Sysroot.empty() ? "" : Sysroot.c_str(),
660 PPOpts.DisablePCHValidation,
661 PPOpts.DisableStatCache);
662 ModuleManager->setDeserializationListener(
663 getASTConsumer().GetASTDeserializationListener());
664 getASTContext().setASTMutationListener(
665 getASTConsumer().GetASTMutationListener());
666 llvm::OwningPtr<ExternalASTSource> Source;
667 Source.reset(ModuleManager);
668 getASTContext().setExternalSource(Source);
669 ModuleManager->InitializeSema(getSema());
670 }
671
672 // Try to load the module we found.
673 switch (ModuleManager->ReadAST(ModuleFile->getName(),
674 serialization::MK_Module)) {
675 case ASTReader::Success:
676 break;
677
678 case ASTReader::IgnorePCH:
679 // FIXME: The ASTReader will already have complained, but can we showhorn
680 // that diagnostic information into a more useful form?
681 return 0;
682
683 case ASTReader::Failure:
684 // Already complained.
685 return 0;
686 }
687
688 // FIXME: The module file's FileEntry makes a poor key indeed!
689 return (ModuleKey)ModuleFile;
690}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000691