blob: 55264870b8b56ee1bdd49cd2bdaeccb33ff401d7 [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"
David Blaikie4e85b8a2011-09-26 00:21:47 +000022#include "clang/Frontend/ChainedDiagnosticConsumer.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Douglas Gregor21cae202011-09-12 23:31:24 +000024#include "clang/Frontend/FrontendActions.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar9df23492011-04-07 18:31:10 +000026#include "clang/Frontend/LogDiagnosticPrinter.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000027#include "clang/Frontend/TextDiagnosticPrinter.h"
David Blaikie621bc692011-09-26 00:38:03 +000028#include "clang/Frontend/VerifyDiagnosticConsumer.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000029#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000030#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000031#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000032#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000033#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000034#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000035#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000036#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000037#include "llvm/Support/Host.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Program.h"
40#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000041#include "llvm/Support/system_error.h"
Douglas Gregor0ced7992011-10-04 00:21:21 +000042#include "llvm/Support/CrashRecoveryContext.h"
Dylan Noblesmith16266012011-06-23 12:20:57 +000043#include "llvm/Config/config.h"
Douglas Gregor2bc75072011-10-05 14:53:30 +000044
45// Support for FileLockManager
46#include <fstream>
47#include <sys/types.h>
48#include <sys/stat.h>
49
Douglas Gregor25728492011-10-05 14:59:36 +000050#if LLVM_ON_WIN32
51#include <windows.h>
52#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +000053#if LLVM_ON_UNIX
54#include <unistd.h>
55#endif
56
Daniel Dunbar2a79e162009-11-13 03:51:44 +000057using namespace clang;
58
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000059CompilerInstance::CompilerInstance()
Douglas Gregorf62d43d2011-07-19 16:10:42 +000060 : Invocation(new CompilerInvocation()), ModuleManager(0) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000061}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000062
63CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000064}
65
Daniel Dunbar6228ca02010-01-30 21:47:07 +000066void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000067 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000068}
69
David Blaikied6471f72011-09-25 23:23:43 +000070void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000071 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000072}
73
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000074void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000075 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000076}
77
78void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000079 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000080}
81
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000082void CompilerInstance::setSourceManager(SourceManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000083 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000084}
85
Ted Kremenek4f327862011-03-21 18:40:17 +000086void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000087
Ted Kremenek4f327862011-03-21 18:40:17 +000088void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000089
Douglas Gregorf18d0d82010-08-12 23:31:19 +000090void CompilerInstance::setSema(Sema *S) {
91 TheSema.reset(S);
92}
93
Daniel Dunbar12ce6942009-11-14 02:47:17 +000094void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
95 Consumer.reset(Value);
96}
97
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000098void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
99 CompletionConsumer.reset(Value);
100}
101
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000102// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000103static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +0000104 unsigned argc, const char* const *argv,
David Blaikied6471f72011-09-25 23:23:43 +0000105 DiagnosticsEngine &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000106 std::string ErrorInfo;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000107 llvm::OwningPtr<raw_ostream> OS(
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000108 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000109 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000110 Diags.Report(diag::err_fe_unable_to_open_logfile)
111 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000112 return;
113 }
114
Daniel Dunbardd63b282009-12-11 23:04:35 +0000115 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000116 for (unsigned i = 0; i != argc; ++i)
117 (*OS) << argv[i] << ' ';
118 (*OS) << '\n';
119
120 // Chain in a diagnostic client which will log the diagnostics.
David Blaikie78ad0b92011-09-25 23:39:51 +0000121 DiagnosticConsumer *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000122 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000123 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000124}
125
Daniel Dunbar9df23492011-04-07 18:31:10 +0000126static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000127 const CodeGenOptions *CodeGenOpts,
David Blaikied6471f72011-09-25 23:23:43 +0000128 DiagnosticsEngine &Diags) {
Daniel Dunbar9df23492011-04-07 18:31:10 +0000129 std::string ErrorInfo;
130 bool OwnsStream = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 raw_ostream *OS = &llvm::errs();
Daniel Dunbar9df23492011-04-07 18:31:10 +0000132 if (DiagOpts.DiagnosticLogFile != "-") {
133 // Create the output stream.
134 llvm::raw_fd_ostream *FileOS(
135 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbare01eceb2011-04-07 20:19:21 +0000136 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000137 if (!ErrorInfo.empty()) {
138 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
139 << DiagOpts.DumpBuildInformation << ErrorInfo;
140 } else {
141 FileOS->SetUnbuffered();
142 FileOS->SetUseAtomicWrites(true);
143 OS = FileOS;
144 OwnsStream = true;
145 }
146 }
147
148 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000149 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
150 OwnsStream);
151 if (CodeGenOpts)
152 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000153 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000154}
155
Douglas Gregore47be3e2010-11-11 00:39:14 +0000156void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000157 DiagnosticConsumer *Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000158 bool ShouldOwnClient,
159 bool ShouldCloneClient) {
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000160 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000161 ShouldOwnClient, ShouldCloneClient,
162 &getCodeGenOpts());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000163}
164
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000165llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor28019772010-04-05 23:52:57 +0000166CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000167 int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000168 DiagnosticConsumer *Client,
Douglas Gregor78243652011-09-13 01:26:44 +0000169 bool ShouldOwnClient,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000170 bool ShouldCloneClient,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000171 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000172 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikied6471f72011-09-25 23:23:43 +0000173 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
174 Diags(new DiagnosticsEngine(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000175
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000176 // Create the diagnostic client for reporting errors or for
177 // implementing -verify.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000178 if (Client) {
179 if (ShouldCloneClient)
180 Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
181 else
182 Diags->setClient(Client, ShouldOwnClient);
183 } else
Douglas Gregore47be3e2010-11-11 00:39:14 +0000184 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000185
186 // Chain in -verify checker, if requested.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000187 if (Opts.VerifyDiagnostics)
David Blaikie621bc692011-09-26 00:38:03 +0000188 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000189
Daniel Dunbar9df23492011-04-07 18:31:10 +0000190 // Chain in -diagnostic-log-file dumper, if requested.
191 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000192 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000193
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000194 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000195 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000196
197 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000198 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000199
Douglas Gregor28019772010-04-05 23:52:57 +0000200 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000201}
202
203// File Manager
204
Daniel Dunbar16b74492009-11-13 04:12:06 +0000205void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000206 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000207}
208
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000209// Source Manager
210
Chris Lattner39b49bc2010-11-23 08:35:12 +0000211void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000212 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000213}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000214
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000215// Preprocessor
216
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000217void CompilerInstance::createPreprocessor() {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000218 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000219
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000220 // Create a PTH manager if we are using some form of a token cache.
221 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000222 if (!PPOpts.TokenCache.empty())
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000223 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000224
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000225 // Create the Preprocessor.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000226 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager());
Douglas Gregor998b3d32011-09-01 23:39:15 +0000227 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000228 getSourceManager(), *HeaderInfo, *this, PTHMgr,
229 /*OwnsHeaderSearch=*/true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000230
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000231 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
232 // That argument is used as the IdentifierInfoLookup argument to
233 // IdentifierTable's ctor.
234 if (PTHMgr) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000235 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000236 PP->setPTHManager(PTHMgr);
237 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000238
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000239 if (PPOpts.DetailedRecord)
Douglas Gregordca8ee82011-05-06 16:33:08 +0000240 PP->createPreprocessingRecord(
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000241 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000242
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000243 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000244
Douglas Gregor6e975c42011-09-13 23:15:45 +0000245 // Set up the module path, including the hash for the
246 // module-creation options.
247 llvm::SmallString<256> SpecificModuleCache(
248 getHeaderSearchOpts().ModuleCachePath);
249 if (!getHeaderSearchOpts().DisableModuleHash)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000250 llvm::sys::path::append(SpecificModuleCache,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000251 getInvocation().getModuleHash());
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000252 PP->getHeaderSearchInfo().configureModules(SpecificModuleCache,
253 getPreprocessorOpts().ModuleBuildPath.empty()
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000254 ? std::string()
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000255 : getPreprocessorOpts().ModuleBuildPath.back());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000256
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000257 // Handle generating dependencies, if requested.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000258 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000259 if (!DepOpts.OutputFile.empty())
260 AttachDependencyFileGen(*PP, DepOpts);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000261
Daniel Dunbareef63e02011-02-02 15:41:17 +0000262 // Handle generating header include information, if requested.
263 if (DepOpts.ShowHeaderIncludes)
264 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000265 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000266 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000267 if (OutputPath == "-")
268 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000269 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
270 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000271 }
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000272}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000273
274// ASTContext
275
276void CompilerInstance::createASTContext() {
277 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000278 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000279 &getTarget(), PP.getIdentifierTable(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000280 PP.getSelectorTable(), PP.getBuiltinInfo(),
281 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000282}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000283
284// ExternalASTSource
285
Chris Lattner5f9e2722011-07-23 10:55:15 +0000286void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000287 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000288 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000289 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000290 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000291 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000292 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000293 DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000294 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000295 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000296 DeserializationListener,
297 Preamble));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000298 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar0f800392009-11-13 08:21:10 +0000299 getASTContext().setExternalSource(Source);
300}
301
302ExternalASTSource *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000303CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000304 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000305 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000306 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000307 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000308 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000309 void *DeserializationListener,
310 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000311 llvm::OwningPtr<ASTReader> Reader;
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000312 Reader.reset(new ASTReader(PP, Context,
Douglas Gregor832d6202011-07-22 16:35:34 +0000313 Sysroot.empty() ? "" : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000314 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000315
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000316 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000317 static_cast<ASTDeserializationListener *>(DeserializationListener));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000318 switch (Reader->ReadAST(Path,
319 Preamble ? serialization::MK_Preamble
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000320 : serialization::MK_PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000321 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000322 // Set the predefines buffer as suggested by the PCH reader. Typically, the
323 // predefines buffer will be empty.
324 PP.setPredefines(Reader->getSuggestedPredefines());
325 return Reader.take();
326
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000327 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000328 // Unrecoverable failure: don't even try to process the input file.
329 break;
330
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000331 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000332 // No suitable PCH file could be found. Return an error.
333 break;
334 }
335
336 return 0;
337}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000338
339// Code Completion
340
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000341static bool EnableCodeCompletion(Preprocessor &PP,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000342 const std::string &Filename,
343 unsigned Line,
344 unsigned Column) {
345 // Tell the source manager to chop off the given file at a specific
346 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000347 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000348 if (!Entry) {
349 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
350 << Filename;
351 return true;
352 }
353
354 // Truncate the named file at the given line/column.
355 PP.SetCodeCompletionPoint(Entry, Line, Column);
356 return false;
357}
358
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000359void CompilerInstance::createCodeCompletionConsumer() {
360 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000361 if (!CompletionConsumer) {
362 CompletionConsumer.reset(
363 createCodeCompletionConsumer(getPreprocessor(),
364 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000365 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000366 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000367 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000368 llvm::outs()));
369 if (!CompletionConsumer)
370 return;
371 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
372 Loc.Line, Loc.Column)) {
373 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000374 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000375 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000376
377 if (CompletionConsumer->isOutputBinary() &&
378 llvm::sys::Program::ChangeStdoutToBinary()) {
379 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
380 CompletionConsumer.reset();
381 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000382}
383
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000384void CompilerInstance::createFrontendTimer() {
385 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
386}
387
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000388CodeCompleteConsumer *
389CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
390 const std::string &Filename,
391 unsigned Line,
392 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000393 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000394 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000395 bool ShowGlobals,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000396 raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000397 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000398 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000399
400 // Set up the creation routine for code-completion.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000401 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000402 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000403}
Daniel Dunbara9204832009-11-13 10:37:48 +0000404
Douglas Gregor467dc882011-08-25 22:30:56 +0000405void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000406 CodeCompleteConsumer *CompletionConsumer) {
407 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor467dc882011-08-25 22:30:56 +0000408 TUKind, CompletionConsumer));
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000409}
410
Daniel Dunbara9204832009-11-13 10:37:48 +0000411// Output Files
412
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000413void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
414 assert(OutFile.OS && "Attempt to add empty stream to output list!");
415 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000416}
417
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000418void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000419 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000420 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000421 delete it->OS;
422 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000423 if (EraseFiles) {
424 bool existed;
425 llvm::sys::fs::remove(it->TempFilename, existed);
426 } else {
427 llvm::SmallString<128> NewOutFile(it->Filename);
428
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000429 // If '-working-directory' was passed, the output filename should be
430 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000431 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000432 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
433 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000434 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000435 << it->TempFilename << it->Filename << ec.message();
436
437 bool existed;
438 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000439 }
440 }
441 } else if (!it->Filename.empty() && EraseFiles)
442 llvm::sys::Path(it->Filename).eraseFromDisk();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000443
Daniel Dunbara9204832009-11-13 10:37:48 +0000444 }
445 OutputFiles.clear();
446}
447
Daniel Dunbarf482d592009-11-13 18:32:08 +0000448llvm::raw_fd_ostream *
449CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000450 StringRef InFile,
451 StringRef Extension) {
Daniel Dunbarf482d592009-11-13 18:32:08 +0000452 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000453 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000454}
455
456llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000457CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000458 bool Binary, bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000459 StringRef InFile,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000460 StringRef Extension,
461 bool UseTemporary) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000462 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000463 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000464 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000465 InFile, Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000466 UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000467 &OutputPathName,
468 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000469 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000470 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
471 << OutputPath << Error;
472 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000473 }
474
475 // Add the output file -- but don't try to remove "-", since this means we are
476 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000477 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
478 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000479
480 return OS;
481}
482
483llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000484CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000485 std::string &Error,
486 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000487 bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000488 StringRef InFile,
489 StringRef Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000490 bool UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000491 std::string *ResultPathName,
492 std::string *TempPathName) {
493 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000494 if (!OutputPath.empty()) {
495 OutFile = OutputPath;
496 } else if (InFile == "-") {
497 OutFile = "-";
498 } else if (!Extension.empty()) {
499 llvm::sys::Path Path(InFile);
500 Path.eraseSuffix();
501 Path.appendSuffix(Extension);
502 OutFile = Path.str();
503 } else {
504 OutFile = "-";
505 }
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000506
507 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
508 std::string OSFile;
509
510 if (UseTemporary && OutFile != "-") {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000511 llvm::sys::Path OutPath(OutFile);
512 // Only create the temporary if we can actually write to OutPath, otherwise
513 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000514 bool Exists;
515 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000516 (OutPath.isRegularFile() && OutPath.canWrite())) {
517 // Create a temporary file.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000518 llvm::SmallString<128> TempPath;
519 TempPath = OutFile;
520 TempPath += "-%%%%%%%%";
521 int fd;
522 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
523 /*makeAbsolute=*/false) == llvm::errc::success) {
524 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
525 OSFile = TempFile = TempPath.str();
526 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000527 }
528 }
529
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000530 if (!OS) {
531 OSFile = OutFile;
532 OS.reset(
533 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
534 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
535 if (!Error.empty())
536 return 0;
537 }
Daniel Dunbarf482d592009-11-13 18:32:08 +0000538
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000539 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000540 if (RemoveFileOnSignal)
541 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000542
Daniel Dunbarf482d592009-11-13 18:32:08 +0000543 if (ResultPathName)
544 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000545 if (TempPathName)
546 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000547
Daniel Dunbarfc971022009-11-20 22:32:38 +0000548 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000549}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000550
551// Initialization Utilities
552
Chris Lattner5f9e2722011-07-23 10:55:15 +0000553bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000554 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
555 getSourceManager(), getFrontendOpts());
556}
557
Chris Lattner5f9e2722011-07-23 10:55:15 +0000558bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
David Blaikied6471f72011-09-25 23:23:43 +0000559 DiagnosticsEngine &Diags,
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000560 FileManager &FileMgr,
561 SourceManager &SourceMgr,
562 const FrontendOptions &Opts) {
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +0000563 // Figure out where to get and map in the main file.
564 if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000565 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000566 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000567 Diags.Report(diag::err_fe_error_reading) << InputFile;
568 return false;
569 }
Dan Gohman694137c2010-10-26 21:13:51 +0000570 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000571 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000572 llvm::OwningPtr<llvm::MemoryBuffer> SB;
573 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000574 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000575 Diags.Report(diag::err_fe_error_reading_stdin);
576 return false;
577 }
Dan Gohman90d90812010-10-26 23:21:25 +0000578 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000579 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000580 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000581 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000582 }
583
Dan Gohman694137c2010-10-26 21:13:51 +0000584 assert(!SourceMgr.getMainFileID().isInvalid() &&
585 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000586 return true;
587}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000588
589// High-Level Operations
590
591bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
592 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
593 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
594 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
595
596 // FIXME: Take this as an argument, once all the APIs we used have moved to
597 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000598 raw_ostream &OS = llvm::errs();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000599
600 // Create the target instance.
601 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
602 if (!hasTarget())
603 return false;
604
605 // Inform the target of the language options.
606 //
607 // FIXME: We shouldn't need to do this, the target should be immutable once
608 // created. This complexity should be lifted elsewhere.
609 getTarget().setForcedLangOptions(getLangOpts());
610
611 // Validate/process some options.
612 if (getHeaderSearchOpts().Verbose)
613 OS << "clang -cc1 version " CLANG_VERSION_STRING
614 << " based upon " << PACKAGE_STRING
615 << " hosted on " << llvm::sys::getHostTriple() << "\n";
616
617 if (getFrontendOpts().ShowTimers)
618 createFrontendTimer();
619
Douglas Gregor95dd5582010-03-30 17:33:59 +0000620 if (getFrontendOpts().ShowStats)
621 llvm::EnableStatistics();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000622
Daniel Dunbar0397af22010-01-13 00:48:06 +0000623 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
624 const std::string &InFile = getFrontendOpts().Inputs[i].second;
625
Daniel Dunbar20560482010-06-07 23:23:50 +0000626 // Reset the ID tables if we are reusing the SourceManager.
627 if (hasSourceManager())
628 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000629
Daniel Dunbard3598a62010-06-07 23:23:06 +0000630 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000631 Act.Execute();
632 Act.EndSourceFile();
633 }
634 }
635
Chris Lattner53eee7b2010-04-07 18:47:42 +0000636 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000637 // We can have multiple diagnostics sharing one diagnostic client.
638 // Get the total number of warnings/errors from the client.
639 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
640 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000641
Chris Lattner53eee7b2010-04-07 18:47:42 +0000642 if (NumWarnings)
643 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
644 if (NumWarnings && NumErrors)
645 OS << " and ";
646 if (NumErrors)
647 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
648 if (NumWarnings || NumErrors)
649 OS << " generated.\n";
650 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000651
Daniel Dunbar20560482010-06-07 23:23:50 +0000652 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000653 getFileManager().PrintStats();
654 OS << "\n";
655 }
656
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000657 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000658}
659
Douglas Gregor21cae202011-09-12 23:31:24 +0000660/// \brief Determine the appropriate source input kind based on language
661/// options.
662static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
663 if (LangOpts.OpenCL)
664 return IK_OpenCL;
665 if (LangOpts.CUDA)
666 return IK_CUDA;
667 if (LangOpts.ObjC1)
668 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
669 return LangOpts.CPlusPlus? IK_CXX : IK_C;
670}
671
Douglas Gregor0ced7992011-10-04 00:21:21 +0000672namespace {
673 struct CompileModuleData {
674 CompilerInstance &Instance;
675 GeneratePCHAction &CreateModuleAction;
676 };
677}
678
679/// \brief Helper function that executes the module-generating action under
680/// a crash recovery context.
681static void doCompileModule(void *UserData) {
682 CompileModuleData &Data = *reinterpret_cast<CompileModuleData *>(UserData);
683 Data.Instance.ExecuteAction(Data.CreateModuleAction);
684}
685
Douglas Gregor2bc75072011-10-05 14:53:30 +0000686namespace {
687 /// \brief Class that manages the creation of a lock file to aid
688 /// implicit coordination between different processes.
689 ///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000690 /// The implicit coordination works by creating a ".lock" file alongside
Douglas Gregor2bc75072011-10-05 14:53:30 +0000691 /// the file that we're coordinating for, using the atomicity of the file
692 /// system to ensure that only a single process can create that ".lock" file.
693 /// When the lock file is removed, the owning process has finished the
694 /// operation.
695 class LockFileManager {
696 public:
697 /// \brief Describes the state of a lock file.
698 enum LockFileState {
699 /// \brief The lock file has been created and is owned by this instance
700 /// of the object.
701 LFS_Owned,
702 /// \brief The lock file already exists and is owned by some other
703 /// instance.
704 LFS_Shared,
705 /// \brief An error occurred while trying to create or find the lock
706 /// file.
707 LFS_Error
708 };
709
710 private:
711 llvm::SmallString<128> LockFileName;
712 llvm::SmallString<128> UniqueLockFileName;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000713
Douglas Gregor2bc75072011-10-05 14:53:30 +0000714 llvm::Optional<std::pair<std::string, int> > Owner;
715 llvm::Optional<llvm::error_code> Error;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000716
Douglas Gregor2bc75072011-10-05 14:53:30 +0000717 LockFileManager(const LockFileManager &);
718 LockFileManager &operator=(const LockFileManager &);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000719
720 static llvm::Optional<std::pair<std::string, int> >
Douglas Gregor2bc75072011-10-05 14:53:30 +0000721 readLockFile(StringRef LockFileName);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000722
Douglas Gregor2bc75072011-10-05 14:53:30 +0000723 static bool processStillExecuting(StringRef Hostname, int PID);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000724
Douglas Gregor2bc75072011-10-05 14:53:30 +0000725 public:
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000726
Douglas Gregor2bc75072011-10-05 14:53:30 +0000727 LockFileManager(StringRef FileName);
728 ~LockFileManager();
729
730 /// \brief Determine the state of the lock file.
731 LockFileState getState() const;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000732
Douglas Gregor2bc75072011-10-05 14:53:30 +0000733 operator LockFileState() const { return getState(); }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000734
Douglas Gregor2bc75072011-10-05 14:53:30 +0000735 /// \brief For a shared lock, wait until the owner releases the lock.
736 void waitForUnlock();
737 };
738}
739
740/// \brief Attempt to read the lock file with the given name, if it exists.
741///
742/// \param LockFileName The name of the lock file to read.
743///
744/// \returns The process ID of the process that owns this lock file
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000745llvm::Optional<std::pair<std::string, int> >
Douglas Gregor2bc75072011-10-05 14:53:30 +0000746LockFileManager::readLockFile(StringRef LockFileName) {
747 // Check whether the lock file exists. If not, clearly there's nothing
748 // to read, so we just return.
749 bool Exists = false;
750 if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists)
751 return llvm::Optional<std::pair<std::string, int> >();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000752
Douglas Gregor2bc75072011-10-05 14:53:30 +0000753 // Read the owning host and PID out of the lock file. If it appears that the
754 // owning process is dead, the lock file is invalid.
755 int PID = 0;
756 std::string Hostname;
757 std::ifstream Input(LockFileName.str().c_str());
758 if (Input >> Hostname >> PID && PID > 0 &&
759 processStillExecuting(Hostname, PID))
760 return std::make_pair(Hostname, PID);
761
762 // Delete the lock file. It's invalid anyway.
763 bool Existed;
764 llvm::sys::fs::remove(LockFileName, Existed);
765 return llvm::Optional<std::pair<std::string, int> >();
766}
767
768bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
769#if LLVM_ON_UNIX
770 char MyHostname[256];
771 MyHostname[255] = 0;
772 MyHostname[0] = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000773 gethostname(MyHostname, 255);
Douglas Gregor2bc75072011-10-05 14:53:30 +0000774 // Check whether the process is dead. If so, we're done.
775 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
776 return false;
777#endif
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000778
Douglas Gregor2bc75072011-10-05 14:53:30 +0000779 return true;
780}
781
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000782LockFileManager::LockFileManager(StringRef FileName)
Douglas Gregor2bc75072011-10-05 14:53:30 +0000783{
784 LockFileName = FileName;
785 LockFileName += ".lock";
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000786
Douglas Gregor2bc75072011-10-05 14:53:30 +0000787 // If the lock file already exists, don't bother to try to create our own
788 // lock file; it won't work anyway. Just figure out who owns this lock file.
789 if ((Owner = readLockFile(LockFileName)))
790 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000791
Douglas Gregor2bc75072011-10-05 14:53:30 +0000792 // Create a lock file that is unique to this instance.
793 UniqueLockFileName = LockFileName;
794 UniqueLockFileName += "-%%%%%%%%";
795 int UniqueLockFileID;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000796 if (llvm::error_code EC
797 = llvm::sys::fs::unique_file(UniqueLockFileName.str(),
Douglas Gregor2bc75072011-10-05 14:53:30 +0000798 UniqueLockFileID,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000799 UniqueLockFileName,
Douglas Gregor2bc75072011-10-05 14:53:30 +0000800 /*makeAbsolute=*/false)) {
801 Error = EC;
802 return;
803 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000804
Douglas Gregor2bc75072011-10-05 14:53:30 +0000805 // Write our process ID to our unique lock file.
806 {
807 llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000808
Douglas Gregor2bc75072011-10-05 14:53:30 +0000809#if LLVM_ON_UNIX
810 // FIXME: move getpid() call into LLVM
811 char hostname[256];
812 hostname[255] = 0;
813 hostname[0] = 0;
814 gethostname(hostname, 255);
815 Out << hostname << ' ' << getpid();
816#else
817 Out << "localhost 1";
818#endif
819 Out.close();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000820
Douglas Gregor2bc75072011-10-05 14:53:30 +0000821 if (Out.has_error()) {
822 // We failed to write out PID, so make up an excuse, remove the
823 // unique lock file, and fail.
824 Error = llvm::make_error_code(llvm::errc::no_space_on_device);
825 bool Existed;
826 llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed);
827 return;
828 }
829 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000830
Douglas Gregor2bc75072011-10-05 14:53:30 +0000831 // Create a hard link from the lock file name. If this succeeds, we're done.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000832 llvm::error_code EC
833 = llvm::sys::fs::create_hard_link(UniqueLockFileName.str(),
Douglas Gregor2bc75072011-10-05 14:53:30 +0000834 LockFileName.str());
835 if (EC == llvm::errc::success)
836 return;
837
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000838 // Creating the hard link failed.
839
Douglas Gregor2bc75072011-10-05 14:53:30 +0000840#ifdef LLVM_ON_UNIX
841 // The creation of the hard link may appear to fail, but if stat'ing the
842 // unique file returns a link count of 2, then we can still declare success.
843 struct stat StatBuf;
844 if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
845 StatBuf.st_nlink == 2)
846 return;
847#endif
848
849 // Someone else managed to create the lock file first. Wipe out our unique
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000850 // lock file (it's useless now) and read the process ID from the lock file.
Douglas Gregor2bc75072011-10-05 14:53:30 +0000851 bool Existed;
852 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
853 if ((Owner = readLockFile(LockFileName)))
854 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000855
Douglas Gregor2bc75072011-10-05 14:53:30 +0000856 // There is a lock file that nobody owns; try to clean it up and report
857 // an error.
858 llvm::sys::fs::remove(LockFileName.str(), Existed);
859 Error = EC;
860}
861
862LockFileManager::LockFileState LockFileManager::getState() const {
863 if (Owner)
864 return LFS_Shared;
865
866 if (Error)
867 return LFS_Error;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000868
Douglas Gregor2bc75072011-10-05 14:53:30 +0000869 return LFS_Owned;
870}
871
872LockFileManager::~LockFileManager() {
873 if (getState() != LFS_Owned)
874 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000875
Douglas Gregor2bc75072011-10-05 14:53:30 +0000876 // Since we own the lock, remove the lock file and our own unique lock file.
877 bool Existed;
878 llvm::sys::fs::remove(LockFileName.str(), Existed);
879 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
880}
881
882void LockFileManager::waitForUnlock() {
883 if (getState() != LFS_Shared)
884 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000885
Douglas Gregor1872e792011-10-05 14:58:46 +0000886#if LLVM_ON_WIN32
887 unsigned long Interval = 1;
888#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000889 struct timespec Interval;
890 Interval.tv_sec = 0;
891 Interval.tv_nsec = 1000000;
Douglas Gregor1872e792011-10-05 14:58:46 +0000892#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +0000893 // Don't wait more than an hour for the file to appear.
894 const unsigned MaxSeconds = 3600;
895 do {
896 // Sleep for the designated interval, to allow the owning process time to
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000897 // finish up and
Douglas Gregor2bc75072011-10-05 14:53:30 +0000898 // FIXME: Should we hook in to system APIs to get a notification when the
899 // lock file is deleted?
Douglas Gregor25728492011-10-05 14:59:36 +0000900#if LLVM_ON_WIN32
901 Sleep(Interval);
902#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000903 nanosleep(&Interval, NULL);
Douglas Gregor25728492011-10-05 14:59:36 +0000904#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +0000905 // If the file no longer exists, we're done.
906 bool Exists = false;
907 if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists)
908 return;
909
910 if (!processStillExecuting((*Owner).first, (*Owner).second))
911 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000912
Douglas Gregor2bc75072011-10-05 14:53:30 +0000913 // Exponentially increase the time we wait for the lock to be removed.
Douglas Gregor1872e792011-10-05 14:58:46 +0000914#if LLVM_ON_WIN32
915 Interval *= 2;
916#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000917 Interval.tv_sec *= 2;
918 Interval.tv_nsec *= 2;
919 if (Interval.tv_nsec >= 1000000000) {
920 ++Interval.tv_sec;
921 Interval.tv_nsec -= 1000000000;
922 }
Douglas Gregor1872e792011-10-05 14:58:46 +0000923#endif
924 } while (
925#if LLVM_ON_WIN32
926 Interval < MaxSeconds * 1000
927#else
NAKAMURA Takumi0caed282011-10-08 11:31:58 +0000928 Interval.tv_sec < (time_t)MaxSeconds
Douglas Gregor1872e792011-10-05 14:58:46 +0000929#endif
930 );
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000931
Douglas Gregor2bc75072011-10-05 14:53:30 +0000932 // Give up.
933}
934
Douglas Gregor21cae202011-09-12 23:31:24 +0000935/// \brief Compile a module file for the given module name with the given
936/// umbrella header, using the options provided by the importing compiler
937/// instance.
938static void compileModule(CompilerInstance &ImportingInstance,
939 StringRef ModuleName,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000940 StringRef ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +0000941 StringRef UmbrellaHeader) {
Douglas Gregor2bc75072011-10-05 14:53:30 +0000942 LockFileManager Locked(ModuleFileName);
943 switch (Locked) {
944 case LockFileManager::LFS_Error:
945 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000946
Douglas Gregor2bc75072011-10-05 14:53:30 +0000947 case LockFileManager::LFS_Owned:
948 // We're responsible for building the module ourselves. Do so below.
949 break;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000950
Douglas Gregor2bc75072011-10-05 14:53:30 +0000951 case LockFileManager::LFS_Shared:
952 // Someone else is responsible for building the module. Wait for them to
953 // finish.
954 Locked.waitForUnlock();
955 break;
956 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000957
Douglas Gregor21cae202011-09-12 23:31:24 +0000958 // Construct a compiler invocation for creating this module.
959 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
960 (new CompilerInvocation(ImportingInstance.getInvocation()));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000961
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000962 // For any options that aren't intended to affect how a module is built,
963 // reset them to their default values.
Douglas Gregor1c7e0472011-09-13 20:44:41 +0000964 Invocation->getLangOpts().resetNonModularOptions();
965 Invocation->getPreprocessorOpts().resetNonModularOptions();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000966
967 // Note that this module is part of the module build path, so that we
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000968 // can detect cycles in the module graph.
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000969 Invocation->getPreprocessorOpts().ModuleBuildPath.push_back(ModuleName);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000970
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000971 // Set up the inputs/outputs so that we build the module from its umbrella
972 // header.
Douglas Gregor21cae202011-09-12 23:31:24 +0000973 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
Douglas Gregor6e975c42011-09-13 23:15:45 +0000974 FrontendOpts.OutputFile = ModuleFileName.str();
Douglas Gregor21cae202011-09-12 23:31:24 +0000975 FrontendOpts.DisableFree = false;
976 FrontendOpts.Inputs.clear();
977 FrontendOpts.Inputs.push_back(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000978 std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()),
Douglas Gregor21cae202011-09-12 23:31:24 +0000979 UmbrellaHeader));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000980
Douglas Gregor78243652011-09-13 01:26:44 +0000981 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000982
983
Douglas Gregor76d991e2011-09-13 23:20:27 +0000984 assert(ImportingInstance.getInvocation().getModuleHash() ==
985 Invocation->getModuleHash() && "Module hash mismatch!");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000986
Douglas Gregor21cae202011-09-12 23:31:24 +0000987 // Construct a compiler instance that will be used to actually create the
988 // module.
989 CompilerInstance Instance;
990 Instance.setInvocation(&*Invocation);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000991 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
Douglas Gregor78243652011-09-13 01:26:44 +0000992 &ImportingInstance.getDiagnosticClient(),
Douglas Gregoraee526e2011-09-29 00:38:00 +0000993 /*ShouldOwnClient=*/true,
994 /*ShouldCloneClient=*/true);
Douglas Gregor21cae202011-09-12 23:31:24 +0000995
996 // Construct a module-generating action.
997 GeneratePCHAction CreateModuleAction(true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000998
Douglas Gregor0ced7992011-10-04 00:21:21 +0000999 // Execute the action to actually build the module in-place. Use a separate
1000 // thread so that we get a stack large enough.
1001 const unsigned ThreadStackSize = 8 << 20;
1002 llvm::CrashRecoveryContext CRC;
1003 CompileModuleData Data = { Instance, CreateModuleAction };
1004 CRC.RunSafelyOnThread(&doCompileModule, &Data, ThreadStackSize);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001005}
Douglas Gregor21cae202011-09-12 23:31:24 +00001006
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001007ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001008 IdentifierInfo &ModuleName,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001009 SourceLocation ModuleNameLoc) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001010 // Determine what file we're searching from.
1011 SourceManager &SourceMgr = getSourceManager();
1012 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
1013 const FileEntry *CurFile
1014 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
1015 if (!CurFile)
1016 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1017
1018 // Search for a module with the given name.
Douglas Gregor21cae202011-09-12 23:31:24 +00001019 std::string UmbrellaHeader;
Douglas Gregor6e975c42011-09-13 23:15:45 +00001020 std::string ModuleFileName;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001021 const FileEntry *ModuleFile
Douglas Gregor21cae202011-09-12 23:31:24 +00001022 = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
Douglas Gregor6e975c42011-09-13 23:15:45 +00001023 &ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +00001024 &UmbrellaHeader);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001025
Douglas Gregor21cae202011-09-12 23:31:24 +00001026 bool BuildingModule = false;
1027 if (!ModuleFile && !UmbrellaHeader.empty()) {
1028 // We didn't find the module, but there is an umbrella header that
1029 // can be used to create the module file. Create a separate compilation
1030 // module to do so.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001031
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001032 // Check whether there is a cycle in the module graph.
1033 SmallVectorImpl<std::string> &ModuleBuildPath
1034 = getPreprocessorOpts().ModuleBuildPath;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001035 SmallVectorImpl<std::string>::iterator Pos
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001036 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(),
1037 ModuleName.getName());
1038 if (Pos != ModuleBuildPath.end()) {
1039 llvm::SmallString<256> CyclePath;
1040 for (; Pos != ModuleBuildPath.end(); ++Pos) {
1041 CyclePath += *Pos;
1042 CyclePath += " -> ";
1043 }
1044 CyclePath += ModuleName.getName();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001045
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001046 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1047 << ModuleName.getName() << CyclePath;
1048 return 0;
1049 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001050
Douglas Gregor08d6acf2011-09-29 00:52:27 +00001051 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
1052 << ModuleName.getName();
Douglas Gregor21cae202011-09-12 23:31:24 +00001053 BuildingModule = true;
Douglas Gregor6e975c42011-09-13 23:15:45 +00001054 compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader);
Douglas Gregor21cae202011-09-12 23:31:24 +00001055 ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName());
1056 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001057
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001058 if (!ModuleFile) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001059 getDiagnostics().Report(ModuleNameLoc,
Douglas Gregor21cae202011-09-12 23:31:24 +00001060 BuildingModule? diag::err_module_not_built
1061 : diag::err_module_not_found)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001062 << ModuleName.getName()
1063 << SourceRange(ImportLoc, ModuleNameLoc);
1064 return 0;
1065 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001066
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001067 // If we don't already have an ASTReader, create one now.
1068 if (!ModuleManager) {
Douglas Gregorde8a9052011-09-14 23:13:09 +00001069 if (!hasASTContext())
1070 createASTContext();
1071
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001072 std::string Sysroot = getHeaderSearchOpts().Sysroot;
1073 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
Douglas Gregorf8a1e512011-09-02 00:26:20 +00001074 ModuleManager = new ASTReader(getPreprocessor(), *Context,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001075 Sysroot.empty() ? "" : Sysroot.c_str(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001076 PPOpts.DisablePCHValidation,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001077 PPOpts.DisableStatCache);
Douglas Gregorde8a9052011-09-14 23:13:09 +00001078 if (hasASTConsumer()) {
1079 ModuleManager->setDeserializationListener(
1080 getASTConsumer().GetASTDeserializationListener());
1081 getASTContext().setASTMutationListener(
1082 getASTConsumer().GetASTMutationListener());
1083 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001084 llvm::OwningPtr<ExternalASTSource> Source;
1085 Source.reset(ModuleManager);
1086 getASTContext().setExternalSource(Source);
Douglas Gregorde8a9052011-09-14 23:13:09 +00001087 if (hasSema())
1088 ModuleManager->InitializeSema(getSema());
Douglas Gregor1a995dd2011-09-15 18:47:32 +00001089 if (hasASTConsumer())
1090 ModuleManager->StartTranslationUnit(&getASTConsumer());
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001091 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001092
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001093 // Try to load the module we found.
1094 switch (ModuleManager->ReadAST(ModuleFile->getName(),
1095 serialization::MK_Module)) {
1096 case ASTReader::Success:
1097 break;
1098
1099 case ASTReader::IgnorePCH:
1100 // FIXME: The ASTReader will already have complained, but can we showhorn
1101 // that diagnostic information into a more useful form?
1102 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001103
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001104 case ASTReader::Failure:
1105 // Already complained.
1106 return 0;
1107 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001108
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001109 // FIXME: The module file's FileEntry makes a poor key indeed!
1110 return (ModuleKey)ModuleFile;
1111}
Daniel Dunbar0397af22010-01-13 00:48:06 +00001112