blob: 84df382e27335ddb12933da7642683732de1b673 [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"
Douglas Gregor93ebfa62011-12-02 23:42:12 +000014#include "clang/AST/Decl.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000015#include "clang/Basic/Diagnostic.h"
Daniel Dunbar16b74492009-11-13 04:12:06 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/SourceManager.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000018#include "clang/Basic/TargetInfo.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000019#include "clang/Basic/Version.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000020#include "clang/Lex/HeaderSearch.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/PTHManager.h"
David Blaikie4e85b8a2011-09-26 00:21:47 +000023#include "clang/Frontend/ChainedDiagnosticConsumer.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000024#include "clang/Frontend/FrontendAction.h"
Douglas Gregor21cae202011-09-12 23:31:24 +000025#include "clang/Frontend/FrontendActions.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar9df23492011-04-07 18:31:10 +000027#include "clang/Frontend/LogDiagnosticPrinter.h"
Ted Kremenek78002122011-10-29 00:12:39 +000028#include "clang/Frontend/SerializedDiagnosticPrinter.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000029#include "clang/Frontend/TextDiagnosticPrinter.h"
David Blaikie621bc692011-09-26 00:38:03 +000030#include "clang/Frontend/VerifyDiagnosticConsumer.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000031#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000032#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000033#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000034#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000035#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000036#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000037#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000038#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000039#include "llvm/Support/Host.h"
40#include "llvm/Support/Path.h"
41#include "llvm/Support/Program.h"
42#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000043#include "llvm/Support/system_error.h"
Douglas Gregor0ced7992011-10-04 00:21:21 +000044#include "llvm/Support/CrashRecoveryContext.h"
Dylan Noblesmith16266012011-06-23 12:20:57 +000045#include "llvm/Config/config.h"
Douglas Gregor2bc75072011-10-05 14:53:30 +000046
47// Support for FileLockManager
48#include <fstream>
49#include <sys/types.h>
50#include <sys/stat.h>
51
Douglas Gregor25728492011-10-05 14:59:36 +000052#if LLVM_ON_WIN32
53#include <windows.h>
54#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +000055#if LLVM_ON_UNIX
56#include <unistd.h>
57#endif
58
Daniel Dunbar2a79e162009-11-13 03:51:44 +000059using namespace clang;
60
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000061CompilerInstance::CompilerInstance()
Douglas Gregorf62d43d2011-07-19 16:10:42 +000062 : Invocation(new CompilerInvocation()), ModuleManager(0) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000063}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000064
65CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000066}
67
Daniel Dunbar6228ca02010-01-30 21:47:07 +000068void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000069 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000070}
71
David Blaikied6471f72011-09-25 23:23:43 +000072void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000073 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000074}
75
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000076void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000077 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000078}
79
80void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000081 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000082}
83
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000084void CompilerInstance::setSourceManager(SourceManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000085 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000086}
87
Ted Kremenek4f327862011-03-21 18:40:17 +000088void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000089
Ted Kremenek4f327862011-03-21 18:40:17 +000090void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000091
Douglas Gregorf18d0d82010-08-12 23:31:19 +000092void CompilerInstance::setSema(Sema *S) {
93 TheSema.reset(S);
94}
95
Daniel Dunbar12ce6942009-11-14 02:47:17 +000096void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
97 Consumer.reset(Value);
98}
99
Daniel Dunbar8a9f5692009-11-14 01:20:40 +0000100void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
101 CompletionConsumer.reset(Value);
102}
103
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000104// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000105static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +0000106 unsigned argc, const char* const *argv,
David Blaikied6471f72011-09-25 23:23:43 +0000107 DiagnosticsEngine &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000108 std::string ErrorInfo;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000109 llvm::OwningPtr<raw_ostream> OS(
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000110 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000111 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000112 Diags.Report(diag::err_fe_unable_to_open_logfile)
113 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000114 return;
115 }
116
Daniel Dunbardd63b282009-12-11 23:04:35 +0000117 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000118 for (unsigned i = 0; i != argc; ++i)
119 (*OS) << argv[i] << ' ';
120 (*OS) << '\n';
121
122 // Chain in a diagnostic client which will log the diagnostics.
David Blaikie78ad0b92011-09-25 23:39:51 +0000123 DiagnosticConsumer *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000124 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000125 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000126}
127
Daniel Dunbar9df23492011-04-07 18:31:10 +0000128static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000129 const CodeGenOptions *CodeGenOpts,
David Blaikied6471f72011-09-25 23:23:43 +0000130 DiagnosticsEngine &Diags) {
Daniel Dunbar9df23492011-04-07 18:31:10 +0000131 std::string ErrorInfo;
132 bool OwnsStream = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 raw_ostream *OS = &llvm::errs();
Daniel Dunbar9df23492011-04-07 18:31:10 +0000134 if (DiagOpts.DiagnosticLogFile != "-") {
135 // Create the output stream.
136 llvm::raw_fd_ostream *FileOS(
137 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbare01eceb2011-04-07 20:19:21 +0000138 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000139 if (!ErrorInfo.empty()) {
140 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
141 << DiagOpts.DumpBuildInformation << ErrorInfo;
142 } else {
143 FileOS->SetUnbuffered();
144 FileOS->SetUseAtomicWrites(true);
145 OS = FileOS;
146 OwnsStream = true;
147 }
148 }
149
150 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000151 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
152 OwnsStream);
153 if (CodeGenOpts)
154 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000155 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000156}
157
Ted Kremenek78002122011-10-29 00:12:39 +0000158static void SetupSerializedDiagnostics(const DiagnosticOptions &DiagOpts,
159 DiagnosticsEngine &Diags,
160 StringRef OutputFile) {
161 std::string ErrorInfo;
162 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
163 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
164 llvm::raw_fd_ostream::F_Binary));
165
166 if (!ErrorInfo.empty()) {
167 Diags.Report(diag::warn_fe_serialized_diag_failure)
168 << OutputFile << ErrorInfo;
169 return;
170 }
171
172 DiagnosticConsumer *SerializedConsumer =
Argyrios Kyrtzidis29f27872011-12-07 05:52:12 +0000173 clang::serialized_diags::create(OS.take());
Ted Kremenek78002122011-10-29 00:12:39 +0000174
175
176 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
177 SerializedConsumer));
178}
179
Douglas Gregore47be3e2010-11-11 00:39:14 +0000180void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000181 DiagnosticConsumer *Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000182 bool ShouldOwnClient,
183 bool ShouldCloneClient) {
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000184 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000185 ShouldOwnClient, ShouldCloneClient,
186 &getCodeGenOpts());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000187}
188
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000189llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor28019772010-04-05 23:52:57 +0000190CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000191 int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000192 DiagnosticConsumer *Client,
Douglas Gregor78243652011-09-13 01:26:44 +0000193 bool ShouldOwnClient,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000194 bool ShouldCloneClient,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000195 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000196 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikied6471f72011-09-25 23:23:43 +0000197 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
198 Diags(new DiagnosticsEngine(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000199
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000200 // Create the diagnostic client for reporting errors or for
201 // implementing -verify.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000202 if (Client) {
203 if (ShouldCloneClient)
204 Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
205 else
206 Diags->setClient(Client, ShouldOwnClient);
207 } else
Douglas Gregore47be3e2010-11-11 00:39:14 +0000208 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000209
210 // Chain in -verify checker, if requested.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000211 if (Opts.VerifyDiagnostics)
David Blaikie621bc692011-09-26 00:38:03 +0000212 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000213
Daniel Dunbar9df23492011-04-07 18:31:10 +0000214 // Chain in -diagnostic-log-file dumper, if requested.
215 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000216 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000217
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000218 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000219 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000220
Ted Kremenek78002122011-10-29 00:12:39 +0000221 if (!Opts.DiagnosticSerializationFile.empty())
222 SetupSerializedDiagnostics(Opts, *Diags,
223 Opts.DiagnosticSerializationFile);
224
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000225 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000226 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000227
Douglas Gregor28019772010-04-05 23:52:57 +0000228 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000229}
230
231// File Manager
232
Daniel Dunbar16b74492009-11-13 04:12:06 +0000233void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000234 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000235}
236
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000237// Source Manager
238
Chris Lattner39b49bc2010-11-23 08:35:12 +0000239void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000240 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000241}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000242
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000243// Preprocessor
244
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000245void CompilerInstance::createPreprocessor() {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000246 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000247
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000248 // Create a PTH manager if we are using some form of a token cache.
249 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000250 if (!PPOpts.TokenCache.empty())
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000251 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000252
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000253 // Create the Preprocessor.
Douglas Gregor8e238062011-11-11 00:35:06 +0000254 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager(),
255 getDiagnostics());
Douglas Gregor998b3d32011-09-01 23:39:15 +0000256 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000257 getSourceManager(), *HeaderInfo, *this, PTHMgr,
258 /*OwnsHeaderSearch=*/true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000259
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000260 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
261 // That argument is used as the IdentifierInfoLookup argument to
262 // IdentifierTable's ctor.
263 if (PTHMgr) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000264 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000265 PP->setPTHManager(PTHMgr);
266 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000267
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000268 if (PPOpts.DetailedRecord)
Douglas Gregordca8ee82011-05-06 16:33:08 +0000269 PP->createPreprocessingRecord(
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000270 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000271
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000272 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000273
Douglas Gregor6e975c42011-09-13 23:15:45 +0000274 // Set up the module path, including the hash for the
275 // module-creation options.
276 llvm::SmallString<256> SpecificModuleCache(
277 getHeaderSearchOpts().ModuleCachePath);
278 if (!getHeaderSearchOpts().DisableModuleHash)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000279 llvm::sys::path::append(SpecificModuleCache,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000280 getInvocation().getModuleHash());
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000281 PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000282
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000283 // Handle generating dependencies, if requested.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000284 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000285 if (!DepOpts.OutputFile.empty())
286 AttachDependencyFileGen(*PP, DepOpts);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000287
Daniel Dunbareef63e02011-02-02 15:41:17 +0000288 // Handle generating header include information, if requested.
289 if (DepOpts.ShowHeaderIncludes)
290 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000291 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000292 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000293 if (OutputPath == "-")
294 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000295 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
296 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000297 }
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000298}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000299
300// ASTContext
301
302void CompilerInstance::createASTContext() {
303 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000304 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000305 &getTarget(), PP.getIdentifierTable(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000306 PP.getSelectorTable(), PP.getBuiltinInfo(),
307 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000308}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000309
310// ExternalASTSource
311
Chris Lattner5f9e2722011-07-23 10:55:15 +0000312void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000313 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000314 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000315 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000316 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000317 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000318 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000319 DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000320 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000321 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000322 DeserializationListener,
323 Preamble));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000324 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar0f800392009-11-13 08:21:10 +0000325 getASTContext().setExternalSource(Source);
326}
327
328ExternalASTSource *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000329CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000330 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000331 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000332 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000333 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000334 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000335 void *DeserializationListener,
336 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000337 llvm::OwningPtr<ASTReader> Reader;
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000338 Reader.reset(new ASTReader(PP, Context,
Douglas Gregor832d6202011-07-22 16:35:34 +0000339 Sysroot.empty() ? "" : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000340 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000341
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000342 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000343 static_cast<ASTDeserializationListener *>(DeserializationListener));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000344 switch (Reader->ReadAST(Path,
345 Preamble ? serialization::MK_Preamble
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000346 : serialization::MK_PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000347 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000348 // Set the predefines buffer as suggested by the PCH reader. Typically, the
349 // predefines buffer will be empty.
350 PP.setPredefines(Reader->getSuggestedPredefines());
351 return Reader.take();
352
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000353 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000354 // Unrecoverable failure: don't even try to process the input file.
355 break;
356
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000357 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000358 // No suitable PCH file could be found. Return an error.
359 break;
360 }
361
362 return 0;
363}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000364
365// Code Completion
366
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000367static bool EnableCodeCompletion(Preprocessor &PP,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000368 const std::string &Filename,
369 unsigned Line,
370 unsigned Column) {
371 // Tell the source manager to chop off the given file at a specific
372 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000373 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000374 if (!Entry) {
375 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
376 << Filename;
377 return true;
378 }
379
380 // Truncate the named file at the given line/column.
381 PP.SetCodeCompletionPoint(Entry, Line, Column);
382 return false;
383}
384
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000385void CompilerInstance::createCodeCompletionConsumer() {
386 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000387 if (!CompletionConsumer) {
388 CompletionConsumer.reset(
389 createCodeCompletionConsumer(getPreprocessor(),
390 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000391 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000392 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000393 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000394 llvm::outs()));
395 if (!CompletionConsumer)
396 return;
397 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
398 Loc.Line, Loc.Column)) {
399 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000400 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000401 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000402
403 if (CompletionConsumer->isOutputBinary() &&
404 llvm::sys::Program::ChangeStdoutToBinary()) {
405 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
406 CompletionConsumer.reset();
407 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000408}
409
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000410void CompilerInstance::createFrontendTimer() {
411 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
412}
413
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000414CodeCompleteConsumer *
415CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
416 const std::string &Filename,
417 unsigned Line,
418 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000419 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000420 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000421 bool ShowGlobals,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000422 raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000423 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000424 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000425
426 // Set up the creation routine for code-completion.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000427 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000428 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000429}
Daniel Dunbara9204832009-11-13 10:37:48 +0000430
Douglas Gregor467dc882011-08-25 22:30:56 +0000431void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000432 CodeCompleteConsumer *CompletionConsumer) {
433 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor467dc882011-08-25 22:30:56 +0000434 TUKind, CompletionConsumer));
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000435}
436
Daniel Dunbara9204832009-11-13 10:37:48 +0000437// Output Files
438
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000439void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
440 assert(OutFile.OS && "Attempt to add empty stream to output list!");
441 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000442}
443
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000444void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000445 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000446 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000447 delete it->OS;
448 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000449 if (EraseFiles) {
450 bool existed;
451 llvm::sys::fs::remove(it->TempFilename, existed);
452 } else {
453 llvm::SmallString<128> NewOutFile(it->Filename);
454
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000455 // If '-working-directory' was passed, the output filename should be
456 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000457 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000458 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
459 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000460 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000461 << it->TempFilename << it->Filename << ec.message();
462
463 bool existed;
464 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000465 }
466 }
467 } else if (!it->Filename.empty() && EraseFiles)
468 llvm::sys::Path(it->Filename).eraseFromDisk();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000469
Daniel Dunbara9204832009-11-13 10:37:48 +0000470 }
471 OutputFiles.clear();
472}
473
Daniel Dunbarf482d592009-11-13 18:32:08 +0000474llvm::raw_fd_ostream *
475CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000476 StringRef InFile,
477 StringRef Extension) {
Daniel Dunbarf482d592009-11-13 18:32:08 +0000478 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000479 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000480}
481
482llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000483CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000484 bool Binary, bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485 StringRef InFile,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000486 StringRef Extension,
487 bool UseTemporary) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000488 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000489 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000490 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000491 InFile, Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000492 UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000493 &OutputPathName,
494 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000495 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000496 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
497 << OutputPath << Error;
498 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000499 }
500
501 // Add the output file -- but don't try to remove "-", since this means we are
502 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000503 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
504 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000505
506 return OS;
507}
508
509llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000510CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000511 std::string &Error,
512 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000513 bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000514 StringRef InFile,
515 StringRef Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000516 bool UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000517 std::string *ResultPathName,
518 std::string *TempPathName) {
519 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000520 if (!OutputPath.empty()) {
521 OutFile = OutputPath;
522 } else if (InFile == "-") {
523 OutFile = "-";
524 } else if (!Extension.empty()) {
525 llvm::sys::Path Path(InFile);
526 Path.eraseSuffix();
527 Path.appendSuffix(Extension);
528 OutFile = Path.str();
529 } else {
530 OutFile = "-";
531 }
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000532
533 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
534 std::string OSFile;
535
536 if (UseTemporary && OutFile != "-") {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000537 llvm::sys::Path OutPath(OutFile);
538 // Only create the temporary if we can actually write to OutPath, otherwise
539 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000540 bool Exists;
541 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000542 (OutPath.isRegularFile() && OutPath.canWrite())) {
543 // Create a temporary file.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000544 llvm::SmallString<128> TempPath;
545 TempPath = OutFile;
546 TempPath += "-%%%%%%%%";
547 int fd;
548 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
549 /*makeAbsolute=*/false) == llvm::errc::success) {
550 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
551 OSFile = TempFile = TempPath.str();
552 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000553 }
554 }
555
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000556 if (!OS) {
557 OSFile = OutFile;
558 OS.reset(
559 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
560 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
561 if (!Error.empty())
562 return 0;
563 }
Daniel Dunbarf482d592009-11-13 18:32:08 +0000564
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000565 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000566 if (RemoveFileOnSignal)
567 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000568
Daniel Dunbarf482d592009-11-13 18:32:08 +0000569 if (ResultPathName)
570 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000571 if (TempPathName)
572 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000573
Daniel Dunbarfc971022009-11-20 22:32:38 +0000574 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000575}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000576
577// Initialization Utilities
578
Chris Lattner5f9e2722011-07-23 10:55:15 +0000579bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000580 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
581 getSourceManager(), getFrontendOpts());
582}
583
Chris Lattner5f9e2722011-07-23 10:55:15 +0000584bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
David Blaikied6471f72011-09-25 23:23:43 +0000585 DiagnosticsEngine &Diags,
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000586 FileManager &FileMgr,
587 SourceManager &SourceMgr,
588 const FrontendOptions &Opts) {
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +0000589 // Figure out where to get and map in the main file.
590 if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000591 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000592 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000593 Diags.Report(diag::err_fe_error_reading) << InputFile;
594 return false;
595 }
Dan Gohman694137c2010-10-26 21:13:51 +0000596 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000597 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000598 llvm::OwningPtr<llvm::MemoryBuffer> SB;
599 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000600 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000601 Diags.Report(diag::err_fe_error_reading_stdin);
602 return false;
603 }
Dan Gohman90d90812010-10-26 23:21:25 +0000604 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000605 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000606 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000607 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000608 }
609
Dan Gohman694137c2010-10-26 21:13:51 +0000610 assert(!SourceMgr.getMainFileID().isInvalid() &&
611 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000612 return true;
613}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000614
615// High-Level Operations
616
617bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
618 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
619 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
620 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
621
622 // FIXME: Take this as an argument, once all the APIs we used have moved to
623 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000624 raw_ostream &OS = llvm::errs();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000625
626 // Create the target instance.
627 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
628 if (!hasTarget())
629 return false;
630
631 // Inform the target of the language options.
632 //
633 // FIXME: We shouldn't need to do this, the target should be immutable once
634 // created. This complexity should be lifted elsewhere.
635 getTarget().setForcedLangOptions(getLangOpts());
636
637 // Validate/process some options.
638 if (getHeaderSearchOpts().Verbose)
639 OS << "clang -cc1 version " CLANG_VERSION_STRING
640 << " based upon " << PACKAGE_STRING
Sebastian Pop5d8b9542011-11-01 21:33:06 +0000641 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
Daniel Dunbar0397af22010-01-13 00:48:06 +0000642
643 if (getFrontendOpts().ShowTimers)
644 createFrontendTimer();
645
Douglas Gregor95dd5582010-03-30 17:33:59 +0000646 if (getFrontendOpts().ShowStats)
647 llvm::EnableStatistics();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000648
Daniel Dunbar0397af22010-01-13 00:48:06 +0000649 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
Douglas Gregord2536a62011-11-15 22:58:25 +0000650 const std::string &InFile = getFrontendOpts().Inputs[i].second;
651
Daniel Dunbar20560482010-06-07 23:23:50 +0000652 // Reset the ID tables if we are reusing the SourceManager.
653 if (hasSourceManager())
654 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000655
Douglas Gregord2536a62011-11-15 22:58:25 +0000656 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000657 Act.Execute();
658 Act.EndSourceFile();
659 }
660 }
661
Argyrios Kyrtzidis29f27872011-12-07 05:52:12 +0000662 // Notify the diagnostic client that all files were processed.
663 getDiagnostics().getClient()->finish();
664
Chris Lattner53eee7b2010-04-07 18:47:42 +0000665 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000666 // We can have multiple diagnostics sharing one diagnostic client.
667 // Get the total number of warnings/errors from the client.
668 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
669 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000670
Chris Lattner53eee7b2010-04-07 18:47:42 +0000671 if (NumWarnings)
672 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
673 if (NumWarnings && NumErrors)
674 OS << " and ";
675 if (NumErrors)
676 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
677 if (NumWarnings || NumErrors)
678 OS << " generated.\n";
679 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000680
Daniel Dunbar20560482010-06-07 23:23:50 +0000681 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000682 getFileManager().PrintStats();
683 OS << "\n";
684 }
685
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000686 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000687}
688
Douglas Gregor21cae202011-09-12 23:31:24 +0000689/// \brief Determine the appropriate source input kind based on language
690/// options.
691static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
692 if (LangOpts.OpenCL)
693 return IK_OpenCL;
694 if (LangOpts.CUDA)
695 return IK_CUDA;
696 if (LangOpts.ObjC1)
697 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
698 return LangOpts.CPlusPlus? IK_CXX : IK_C;
699}
700
Douglas Gregor0ced7992011-10-04 00:21:21 +0000701namespace {
Douglas Gregorf9e357d2011-11-29 19:06:37 +0000702 struct CompileModuleMapData {
703 CompilerInstance &Instance;
704 GenerateModuleAction &CreateModuleAction;
705 };
706}
707
708/// \brief Helper function that executes the module-generating action under
709/// a crash recovery context.
710static void doCompileMapModule(void *UserData) {
711 CompileModuleMapData &Data
712 = *reinterpret_cast<CompileModuleMapData *>(UserData);
713 Data.Instance.ExecuteAction(Data.CreateModuleAction);
714}
715
716namespace {
Douglas Gregor2bc75072011-10-05 14:53:30 +0000717 /// \brief Class that manages the creation of a lock file to aid
718 /// implicit coordination between different processes.
719 ///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000720 /// The implicit coordination works by creating a ".lock" file alongside
Douglas Gregor2bc75072011-10-05 14:53:30 +0000721 /// the file that we're coordinating for, using the atomicity of the file
722 /// system to ensure that only a single process can create that ".lock" file.
723 /// When the lock file is removed, the owning process has finished the
724 /// operation.
725 class LockFileManager {
726 public:
727 /// \brief Describes the state of a lock file.
728 enum LockFileState {
729 /// \brief The lock file has been created and is owned by this instance
730 /// of the object.
731 LFS_Owned,
732 /// \brief The lock file already exists and is owned by some other
733 /// instance.
734 LFS_Shared,
735 /// \brief An error occurred while trying to create or find the lock
736 /// file.
737 LFS_Error
738 };
739
740 private:
741 llvm::SmallString<128> LockFileName;
742 llvm::SmallString<128> UniqueLockFileName;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000743
Douglas Gregor2bc75072011-10-05 14:53:30 +0000744 llvm::Optional<std::pair<std::string, int> > Owner;
745 llvm::Optional<llvm::error_code> Error;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000746
Douglas Gregor2bc75072011-10-05 14:53:30 +0000747 LockFileManager(const LockFileManager &);
748 LockFileManager &operator=(const LockFileManager &);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000749
750 static llvm::Optional<std::pair<std::string, int> >
Douglas Gregor2bc75072011-10-05 14:53:30 +0000751 readLockFile(StringRef LockFileName);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000752
Douglas Gregor2bc75072011-10-05 14:53:30 +0000753 static bool processStillExecuting(StringRef Hostname, int PID);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000754
Douglas Gregor2bc75072011-10-05 14:53:30 +0000755 public:
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000756
Douglas Gregor2bc75072011-10-05 14:53:30 +0000757 LockFileManager(StringRef FileName);
758 ~LockFileManager();
759
760 /// \brief Determine the state of the lock file.
761 LockFileState getState() const;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000762
Douglas Gregor2bc75072011-10-05 14:53:30 +0000763 operator LockFileState() const { return getState(); }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000764
Douglas Gregor2bc75072011-10-05 14:53:30 +0000765 /// \brief For a shared lock, wait until the owner releases the lock.
766 void waitForUnlock();
767 };
768}
769
770/// \brief Attempt to read the lock file with the given name, if it exists.
771///
772/// \param LockFileName The name of the lock file to read.
773///
774/// \returns The process ID of the process that owns this lock file
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000775llvm::Optional<std::pair<std::string, int> >
Douglas Gregor2bc75072011-10-05 14:53:30 +0000776LockFileManager::readLockFile(StringRef LockFileName) {
777 // Check whether the lock file exists. If not, clearly there's nothing
778 // to read, so we just return.
779 bool Exists = false;
780 if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists)
781 return llvm::Optional<std::pair<std::string, int> >();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000782
Douglas Gregor2bc75072011-10-05 14:53:30 +0000783 // Read the owning host and PID out of the lock file. If it appears that the
784 // owning process is dead, the lock file is invalid.
785 int PID = 0;
786 std::string Hostname;
787 std::ifstream Input(LockFileName.str().c_str());
788 if (Input >> Hostname >> PID && PID > 0 &&
789 processStillExecuting(Hostname, PID))
790 return std::make_pair(Hostname, PID);
791
792 // Delete the lock file. It's invalid anyway.
793 bool Existed;
794 llvm::sys::fs::remove(LockFileName, Existed);
795 return llvm::Optional<std::pair<std::string, int> >();
796}
797
798bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
799#if LLVM_ON_UNIX
800 char MyHostname[256];
801 MyHostname[255] = 0;
802 MyHostname[0] = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000803 gethostname(MyHostname, 255);
Douglas Gregor2bc75072011-10-05 14:53:30 +0000804 // Check whether the process is dead. If so, we're done.
805 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
806 return false;
807#endif
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000808
Douglas Gregor2bc75072011-10-05 14:53:30 +0000809 return true;
810}
811
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000812LockFileManager::LockFileManager(StringRef FileName)
Douglas Gregor2bc75072011-10-05 14:53:30 +0000813{
814 LockFileName = FileName;
815 LockFileName += ".lock";
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000816
Douglas Gregor2bc75072011-10-05 14:53:30 +0000817 // If the lock file already exists, don't bother to try to create our own
818 // lock file; it won't work anyway. Just figure out who owns this lock file.
819 if ((Owner = readLockFile(LockFileName)))
820 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000821
Douglas Gregor2bc75072011-10-05 14:53:30 +0000822 // Create a lock file that is unique to this instance.
823 UniqueLockFileName = LockFileName;
824 UniqueLockFileName += "-%%%%%%%%";
825 int UniqueLockFileID;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000826 if (llvm::error_code EC
827 = llvm::sys::fs::unique_file(UniqueLockFileName.str(),
Douglas Gregor2bc75072011-10-05 14:53:30 +0000828 UniqueLockFileID,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000829 UniqueLockFileName,
Douglas Gregor2bc75072011-10-05 14:53:30 +0000830 /*makeAbsolute=*/false)) {
831 Error = EC;
832 return;
833 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000834
Douglas Gregor2bc75072011-10-05 14:53:30 +0000835 // Write our process ID to our unique lock file.
836 {
837 llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000838
Douglas Gregor2bc75072011-10-05 14:53:30 +0000839#if LLVM_ON_UNIX
840 // FIXME: move getpid() call into LLVM
841 char hostname[256];
842 hostname[255] = 0;
843 hostname[0] = 0;
844 gethostname(hostname, 255);
845 Out << hostname << ' ' << getpid();
846#else
847 Out << "localhost 1";
848#endif
849 Out.close();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000850
Douglas Gregor2bc75072011-10-05 14:53:30 +0000851 if (Out.has_error()) {
852 // We failed to write out PID, so make up an excuse, remove the
853 // unique lock file, and fail.
854 Error = llvm::make_error_code(llvm::errc::no_space_on_device);
855 bool Existed;
856 llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed);
857 return;
858 }
859 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000860
Douglas Gregor2bc75072011-10-05 14:53:30 +0000861 // Create a hard link from the lock file name. If this succeeds, we're done.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000862 llvm::error_code EC
863 = llvm::sys::fs::create_hard_link(UniqueLockFileName.str(),
Douglas Gregor2bc75072011-10-05 14:53:30 +0000864 LockFileName.str());
865 if (EC == llvm::errc::success)
866 return;
867
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000868 // Creating the hard link failed.
869
Douglas Gregor2bc75072011-10-05 14:53:30 +0000870#ifdef LLVM_ON_UNIX
871 // The creation of the hard link may appear to fail, but if stat'ing the
872 // unique file returns a link count of 2, then we can still declare success.
873 struct stat StatBuf;
874 if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
875 StatBuf.st_nlink == 2)
876 return;
877#endif
878
879 // Someone else managed to create the lock file first. Wipe out our unique
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000880 // lock file (it's useless now) and read the process ID from the lock file.
Douglas Gregor2bc75072011-10-05 14:53:30 +0000881 bool Existed;
882 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
883 if ((Owner = readLockFile(LockFileName)))
884 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000885
Douglas Gregor2bc75072011-10-05 14:53:30 +0000886 // There is a lock file that nobody owns; try to clean it up and report
887 // an error.
888 llvm::sys::fs::remove(LockFileName.str(), Existed);
889 Error = EC;
890}
891
892LockFileManager::LockFileState LockFileManager::getState() const {
893 if (Owner)
894 return LFS_Shared;
895
896 if (Error)
897 return LFS_Error;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000898
Douglas Gregor2bc75072011-10-05 14:53:30 +0000899 return LFS_Owned;
900}
901
902LockFileManager::~LockFileManager() {
903 if (getState() != LFS_Owned)
904 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000905
Douglas Gregor2bc75072011-10-05 14:53:30 +0000906 // Since we own the lock, remove the lock file and our own unique lock file.
907 bool Existed;
908 llvm::sys::fs::remove(LockFileName.str(), Existed);
909 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
910}
911
912void LockFileManager::waitForUnlock() {
913 if (getState() != LFS_Shared)
914 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000915
Douglas Gregor1872e792011-10-05 14:58:46 +0000916#if LLVM_ON_WIN32
917 unsigned long Interval = 1;
918#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000919 struct timespec Interval;
920 Interval.tv_sec = 0;
921 Interval.tv_nsec = 1000000;
Douglas Gregor1872e792011-10-05 14:58:46 +0000922#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +0000923 // Don't wait more than an hour for the file to appear.
924 const unsigned MaxSeconds = 3600;
925 do {
926 // Sleep for the designated interval, to allow the owning process time to
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000927 // finish up and
Douglas Gregor2bc75072011-10-05 14:53:30 +0000928 // FIXME: Should we hook in to system APIs to get a notification when the
929 // lock file is deleted?
Douglas Gregor25728492011-10-05 14:59:36 +0000930#if LLVM_ON_WIN32
931 Sleep(Interval);
932#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000933 nanosleep(&Interval, NULL);
Douglas Gregor25728492011-10-05 14:59:36 +0000934#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +0000935 // If the file no longer exists, we're done.
936 bool Exists = false;
937 if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists)
938 return;
939
940 if (!processStillExecuting((*Owner).first, (*Owner).second))
941 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000942
Douglas Gregor2bc75072011-10-05 14:53:30 +0000943 // Exponentially increase the time we wait for the lock to be removed.
Douglas Gregor1872e792011-10-05 14:58:46 +0000944#if LLVM_ON_WIN32
945 Interval *= 2;
946#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000947 Interval.tv_sec *= 2;
948 Interval.tv_nsec *= 2;
949 if (Interval.tv_nsec >= 1000000000) {
950 ++Interval.tv_sec;
951 Interval.tv_nsec -= 1000000000;
952 }
Douglas Gregor1872e792011-10-05 14:58:46 +0000953#endif
954 } while (
955#if LLVM_ON_WIN32
956 Interval < MaxSeconds * 1000
957#else
NAKAMURA Takumi0caed282011-10-08 11:31:58 +0000958 Interval.tv_sec < (time_t)MaxSeconds
Douglas Gregor1872e792011-10-05 14:58:46 +0000959#endif
960 );
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000961
Douglas Gregor2bc75072011-10-05 14:53:30 +0000962 // Give up.
963}
964
Douglas Gregorf9e357d2011-11-29 19:06:37 +0000965/// \brief Compile a module file for the given module, using the options
966/// provided by the importing compiler instance.
Douglas Gregor21cae202011-09-12 23:31:24 +0000967static void compileModule(CompilerInstance &ImportingInstance,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000968 Module *Module,
Douglas Gregor933e7a62011-11-29 18:31:39 +0000969 StringRef ModuleFileName) {
Douglas Gregor2bc75072011-10-05 14:53:30 +0000970 LockFileManager Locked(ModuleFileName);
971 switch (Locked) {
972 case LockFileManager::LFS_Error:
973 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000974
Douglas Gregor2bc75072011-10-05 14:53:30 +0000975 case LockFileManager::LFS_Owned:
976 // We're responsible for building the module ourselves. Do so below.
977 break;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000978
Douglas Gregor2bc75072011-10-05 14:53:30 +0000979 case LockFileManager::LFS_Shared:
980 // Someone else is responsible for building the module. Wait for them to
981 // finish.
982 Locked.waitForUnlock();
983 break;
984 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000985
Douglas Gregorf9e357d2011-11-29 19:06:37 +0000986 ModuleMap &ModMap
987 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
988
Douglas Gregor21cae202011-09-12 23:31:24 +0000989 // Construct a compiler invocation for creating this module.
990 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
991 (new CompilerInvocation(ImportingInstance.getInvocation()));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000992
Douglas Gregor18ee5472011-11-29 21:59:16 +0000993 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
994
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000995 // For any options that aren't intended to affect how a module is built,
996 // reset them to their default values.
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000997 Invocation->getLangOpts()->resetNonModularOptions();
Douglas Gregor18ee5472011-11-29 21:59:16 +0000998 PPOpts.resetNonModularOptions();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000999
Douglas Gregorb86b8dc2011-11-15 19:35:01 +00001000 // Note the name of the module we're building.
Douglas Gregor933e7a62011-11-29 18:31:39 +00001001 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
Douglas Gregorb86b8dc2011-11-15 19:35:01 +00001002
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001003 // Note that this module is part of the module build path, so that we
Douglas Gregorb2d39c22011-09-15 20:53:28 +00001004 // can detect cycles in the module graph.
Douglas Gregor18ee5472011-11-29 21:59:16 +00001005 PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001006
Douglas Gregor18ee5472011-11-29 21:59:16 +00001007 // If there is a module map file, build the module using the module map.
Douglas Gregorb2d39c22011-09-15 20:53:28 +00001008 // Set up the inputs/outputs so that we build the module from its umbrella
1009 // header.
Douglas Gregor21cae202011-09-12 23:31:24 +00001010 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
Douglas Gregor6e975c42011-09-13 23:15:45 +00001011 FrontendOpts.OutputFile = ModuleFileName.str();
Douglas Gregor21cae202011-09-12 23:31:24 +00001012 FrontendOpts.DisableFree = false;
1013 FrontendOpts.Inputs.clear();
Douglas Gregor18ee5472011-11-29 21:59:16 +00001014 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001015
Douglas Gregor18ee5472011-11-29 21:59:16 +00001016 // Get or create the module map that we'll use to build this module.
1017 llvm::SmallString<128> TempModuleMapFileName;
1018 if (const FileEntry *ModuleMapFile
1019 = ModMap.getContainingModuleMapFile(Module)) {
1020 // Use the module map where this module resides.
1021 FrontendOpts.Inputs.push_back(std::make_pair(IK, ModuleMapFile->getName()));
1022 } else {
1023 // Create a temporary module map file.
1024 TempModuleMapFileName = Module->Name;
1025 TempModuleMapFileName += "-%%%%%%%%.map";
1026 int FD;
1027 if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
1028 TempModuleMapFileName,
Douglas Gregor1e821e92011-12-06 22:05:29 +00001029 /*makeAbsolute=*/true)
Douglas Gregore9120292011-12-06 23:04:08 +00001030 != llvm::errc::success) {
Douglas Gregorf64114b2011-12-07 00:54:14 +00001031 ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
1032 << TempModuleMapFileName;
Douglas Gregor18ee5472011-11-29 21:59:16 +00001033 return;
Douglas Gregore9120292011-12-06 23:04:08 +00001034 }
Douglas Gregor18ee5472011-11-29 21:59:16 +00001035 // Print the module map to this file.
1036 llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
1037 Module->print(OS);
1038 FrontendOpts.Inputs.push_back(
1039 std::make_pair(IK, TempModuleMapFileName.str().str()));
1040 }
1041
1042 // Don't free the remapped file buffers; they are owned by our caller.
1043 PPOpts.RetainRemappedFileBuffers = true;
1044
Douglas Gregor78243652011-09-13 01:26:44 +00001045 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
Douglas Gregor76d991e2011-09-13 23:20:27 +00001046 assert(ImportingInstance.getInvocation().getModuleHash() ==
Douglas Gregor18ee5472011-11-29 21:59:16 +00001047 Invocation->getModuleHash() && "Module hash mismatch!");
1048
Douglas Gregor21cae202011-09-12 23:31:24 +00001049 // Construct a compiler instance that will be used to actually create the
1050 // module.
1051 CompilerInstance Instance;
1052 Instance.setInvocation(&*Invocation);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001053 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
Douglas Gregor78243652011-09-13 01:26:44 +00001054 &ImportingInstance.getDiagnosticClient(),
Douglas Gregoraee526e2011-09-29 00:38:00 +00001055 /*ShouldOwnClient=*/true,
1056 /*ShouldCloneClient=*/true);
Douglas Gregor18ee5472011-11-29 21:59:16 +00001057
Douglas Gregor21cae202011-09-12 23:31:24 +00001058 // Construct a module-generating action.
Douglas Gregor18ee5472011-11-29 21:59:16 +00001059 GenerateModuleAction CreateModuleAction;
1060
Douglas Gregor0ced7992011-10-04 00:21:21 +00001061 // Execute the action to actually build the module in-place. Use a separate
1062 // thread so that we get a stack large enough.
1063 const unsigned ThreadStackSize = 8 << 20;
1064 llvm::CrashRecoveryContext CRC;
Douglas Gregor18ee5472011-11-29 21:59:16 +00001065 CompileModuleMapData Data = { Instance, CreateModuleAction };
1066 CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
1067
1068 // Delete the temporary module map file.
1069 // FIXME: Even though we're executing under crash protection, it would still
1070 // be nice to do this with RemoveFileOnSignal when we can. However, that
1071 // doesn't make sense for all clients, so clean this up manually.
1072 if (!TempModuleMapFileName.empty())
1073 llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001074}
Douglas Gregor21cae202011-09-12 23:31:24 +00001075
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001076Module *CompilerInstance::loadModule(SourceLocation ImportLoc,
Douglas Gregor5e356932011-12-01 17:11:21 +00001077 ModuleIdPath Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +00001078 Module::NameVisibilityKind Visibility,
1079 bool IsInclusionDirective) {
Douglas Gregorb514c792011-11-30 04:26:53 +00001080 // If we've already handled this import, just return the cached result.
1081 // This one-element cache is important to eliminate redundant diagnostics
1082 // when both the preprocessor and parser see the same import declaration.
Douglas Gregor5e356932011-12-01 17:11:21 +00001083 if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
1084 // Make the named module visible.
1085 if (LastModuleImportResult)
1086 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001087 return LastModuleImportResult;
Douglas Gregor5e356932011-12-01 17:11:21 +00001088 }
Douglas Gregorb514c792011-11-30 04:26:53 +00001089
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001090 // Determine what file we're searching from.
1091 SourceManager &SourceMgr = getSourceManager();
1092 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
1093 const FileEntry *CurFile
1094 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
1095 if (!CurFile)
1096 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1097
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001098 StringRef ModuleName = Path[0].first->getName();
1099 SourceLocation ModuleNameLoc = Path[0].second;
Douglas Gregor49009ec2011-11-30 04:03:44 +00001100
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001101 clang::Module *Module = 0;
Douglas Gregor49009ec2011-11-30 04:03:44 +00001102 const FileEntry *ModuleFile = 0;
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001103
Douglas Gregor49009ec2011-11-30 04:03:44 +00001104 // If we don't already have information on this module, load the module now.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001105 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001106 = KnownModules.find(Path[0].first);
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001107 if (Known != KnownModules.end()) {
1108 // Retrieve the cached top-level module.
1109 Module = Known->second;
1110 } else if (ModuleName == getLangOpts().CurrentModule) {
1111 // This is the module we're building.
1112 Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
1113 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1114 } else {
Douglas Gregor49009ec2011-11-30 04:03:44 +00001115 // Search for a module with the given name.
1116 std::string ModuleFileName;
1117 ModuleFile
1118 = PP->getHeaderSearchInfo().lookupModule(ModuleName, Module,
1119 &ModuleFileName);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001120
Douglas Gregor49009ec2011-11-30 04:03:44 +00001121 bool BuildingModule = false;
1122 if (!ModuleFile && Module) {
1123 // The module is not cached, but we have a module map from which we can
1124 // build the module.
1125
1126 // Check whether there is a cycle in the module graph.
1127 SmallVectorImpl<std::string> &ModuleBuildPath
1128 = getPreprocessorOpts().ModuleBuildPath;
1129 SmallVectorImpl<std::string>::iterator Pos
1130 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName);
1131 if (Pos != ModuleBuildPath.end()) {
1132 llvm::SmallString<256> CyclePath;
1133 for (; Pos != ModuleBuildPath.end(); ++Pos) {
1134 CyclePath += *Pos;
1135 CyclePath += " -> ";
1136 }
1137 CyclePath += ModuleName;
1138
1139 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1140 << ModuleName << CyclePath;
1141 return 0;
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001142 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001143
Douglas Gregor49009ec2011-11-30 04:03:44 +00001144 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
1145 << ModuleName;
1146 BuildingModule = true;
1147 compileModule(*this, Module, ModuleFileName);
1148 ModuleFile = FileMgr->getFile(ModuleFileName);
1149 }
1150
1151 if (!ModuleFile) {
1152 getDiagnostics().Report(ModuleNameLoc,
1153 BuildingModule? diag::err_module_not_built
1154 : diag::err_module_not_found)
1155 << ModuleName
1156 << SourceRange(ImportLoc, ModuleNameLoc);
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001157 return 0;
1158 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001159
Douglas Gregor49009ec2011-11-30 04:03:44 +00001160 // If we don't already have an ASTReader, create one now.
1161 if (!ModuleManager) {
1162 if (!hasASTContext())
1163 createASTContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001164
Douglas Gregor49009ec2011-11-30 04:03:44 +00001165 std::string Sysroot = getHeaderSearchOpts().Sysroot;
1166 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1167 ModuleManager = new ASTReader(getPreprocessor(), *Context,
1168 Sysroot.empty() ? "" : Sysroot.c_str(),
1169 PPOpts.DisablePCHValidation,
1170 PPOpts.DisableStatCache);
1171 if (hasASTConsumer()) {
1172 ModuleManager->setDeserializationListener(
1173 getASTConsumer().GetASTDeserializationListener());
1174 getASTContext().setASTMutationListener(
1175 getASTConsumer().GetASTMutationListener());
1176 }
1177 llvm::OwningPtr<ExternalASTSource> Source;
1178 Source.reset(ModuleManager);
1179 getASTContext().setExternalSource(Source);
1180 if (hasSema())
1181 ModuleManager->InitializeSema(getSema());
1182 if (hasASTConsumer())
1183 ModuleManager->StartTranslationUnit(&getASTConsumer());
Douglas Gregorde8a9052011-09-14 23:13:09 +00001184 }
Douglas Gregor49009ec2011-11-30 04:03:44 +00001185
1186 // Try to load the module we found.
1187 switch (ModuleManager->ReadAST(ModuleFile->getName(),
1188 serialization::MK_Module)) {
1189 case ASTReader::Success:
1190 break;
1191
1192 case ASTReader::IgnorePCH:
1193 // FIXME: The ASTReader will already have complained, but can we showhorn
1194 // that diagnostic information into a more useful form?
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001195 KnownModules[Path[0].first] = 0;
Douglas Gregor49009ec2011-11-30 04:03:44 +00001196 return 0;
1197
1198 case ASTReader::Failure:
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001199 // Already complained, but note now that we failed.
1200 KnownModules[Path[0].first] = 0;
Douglas Gregor49009ec2011-11-30 04:03:44 +00001201 return 0;
1202 }
1203
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001204 if (!Module) {
1205 // If we loaded the module directly, without finding a module map first,
1206 // we'll have loaded the module's information from the module itself.
1207 Module = PP->getHeaderSearchInfo().getModuleMap()
1208 .findModule((Path[0].first->getName()));
1209 }
1210
1211 // Cache the result of this top-level module lookup for later.
1212 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001213 }
Douglas Gregor49009ec2011-11-30 04:03:44 +00001214
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001215 // If we never found the module, fail.
1216 if (!Module)
1217 return 0;
1218
Douglas Gregor49009ec2011-11-30 04:03:44 +00001219 // Verify that the rest of the module path actually corresponds to
1220 // a submodule.
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001221 if (Path.size() > 1) {
Douglas Gregor49009ec2011-11-30 04:03:44 +00001222 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1223 StringRef Name = Path[I].first->getName();
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001224 llvm::StringMap<clang::Module *>::iterator Pos
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001225 = Module->SubModules.find(Name);
Douglas Gregor49009ec2011-11-30 04:03:44 +00001226
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001227 if (Pos == Module->SubModules.end()) {
Douglas Gregor49009ec2011-11-30 04:03:44 +00001228 // Attempt to perform typo correction to find a module name that works.
1229 llvm::SmallVector<StringRef, 2> Best;
1230 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1231
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001232 for (llvm::StringMap<clang::Module *>::iterator
Matt Beaumont-Gaye25633f2011-11-30 19:41:21 +00001233 J = Module->SubModules.begin(),
1234 JEnd = Module->SubModules.end();
1235 J != JEnd; ++J) {
1236 unsigned ED = Name.edit_distance(J->getValue()->Name,
Douglas Gregor49009ec2011-11-30 04:03:44 +00001237 /*AllowReplacements=*/true,
1238 BestEditDistance);
1239 if (ED <= BestEditDistance) {
1240 if (ED < BestEditDistance)
1241 Best.clear();
Matt Beaumont-Gaye25633f2011-11-30 19:41:21 +00001242 Best.push_back(J->getValue()->Name);
Douglas Gregor49009ec2011-11-30 04:03:44 +00001243 }
1244 }
1245
1246 // If there was a clear winner, user it.
1247 if (Best.size() == 1) {
1248 getDiagnostics().Report(Path[I].second,
1249 diag::err_no_submodule_suggest)
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001250 << Path[I].first << Module->getFullModuleName() << Best[0]
Douglas Gregor49009ec2011-11-30 04:03:44 +00001251 << SourceRange(Path[0].second, Path[I-1].second)
1252 << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1253 Best[0]);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001254 Pos = Module->SubModules.find(Best[0]);
Douglas Gregor49009ec2011-11-30 04:03:44 +00001255 }
1256 }
1257
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001258 if (Pos == Module->SubModules.end()) {
Douglas Gregor49009ec2011-11-30 04:03:44 +00001259 // No submodule by this name. Complain, and don't look for further
1260 // submodules.
1261 getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001262 << Path[I].first << Module->getFullModuleName()
Douglas Gregor49009ec2011-11-30 04:03:44 +00001263 << SourceRange(Path[0].second, Path[I-1].second);
1264 break;
1265 }
1266
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001267 Module = Pos->getValue();
Douglas Gregor49009ec2011-11-30 04:03:44 +00001268 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001269 }
Douglas Gregor49009ec2011-11-30 04:03:44 +00001270
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001271 // Make the named module visible, if it's not already part of the module
1272 // we are parsing.
1273 if (ModuleName != getLangOpts().CurrentModule)
1274 ModuleManager->makeModuleVisible(Module, Visibility);
Douglas Gregor93ebfa62011-12-02 23:42:12 +00001275
1276 // If this module import was due to an inclusion directive, create an
1277 // implicit import declaration to capture it in the AST.
1278 if (IsInclusionDirective && hasASTContext()) {
1279 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1280 TU->addDecl(ImportDecl::CreateImplicit(getASTContext(), TU,
1281 ImportLoc, Module,
1282 Path.back().second));
1283 }
Douglas Gregor49009ec2011-11-30 04:03:44 +00001284
Douglas Gregorb514c792011-11-30 04:26:53 +00001285 LastModuleImportLoc = ImportLoc;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001286 LastModuleImportResult = Module;
1287 return Module;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001288}