blob: 0e3b25168f062c7b696062f30e7afa0d5740ff45 [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"
Ted Kremenek78002122011-10-29 00:12:39 +000027#include "clang/Frontend/SerializedDiagnosticPrinter.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000028#include "clang/Frontend/TextDiagnosticPrinter.h"
David Blaikie621bc692011-09-26 00:38:03 +000029#include "clang/Frontend/VerifyDiagnosticConsumer.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000030#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000032#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000033#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000035#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000036#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000037#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000038#include "llvm/Support/Host.h"
39#include "llvm/Support/Path.h"
40#include "llvm/Support/Program.h"
41#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000042#include "llvm/Support/system_error.h"
Douglas Gregor0ced7992011-10-04 00:21:21 +000043#include "llvm/Support/CrashRecoveryContext.h"
Dylan Noblesmith16266012011-06-23 12:20:57 +000044#include "llvm/Config/config.h"
Douglas Gregor2bc75072011-10-05 14:53:30 +000045
46// Support for FileLockManager
47#include <fstream>
48#include <sys/types.h>
49#include <sys/stat.h>
50
Douglas Gregor25728492011-10-05 14:59:36 +000051#if LLVM_ON_WIN32
52#include <windows.h>
53#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +000054#if LLVM_ON_UNIX
55#include <unistd.h>
56#endif
57
Daniel Dunbar2a79e162009-11-13 03:51:44 +000058using namespace clang;
59
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000060CompilerInstance::CompilerInstance()
Douglas Gregorf62d43d2011-07-19 16:10:42 +000061 : Invocation(new CompilerInvocation()), ModuleManager(0) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000062}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000063
64CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000065}
66
Daniel Dunbar6228ca02010-01-30 21:47:07 +000067void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000068 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000069}
70
David Blaikied6471f72011-09-25 23:23:43 +000071void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000072 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000073}
74
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000075void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000076 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000077}
78
79void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000080 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000081}
82
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000083void CompilerInstance::setSourceManager(SourceManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000084 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000085}
86
Ted Kremenek4f327862011-03-21 18:40:17 +000087void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000088
Ted Kremenek4f327862011-03-21 18:40:17 +000089void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000090
Douglas Gregorf18d0d82010-08-12 23:31:19 +000091void CompilerInstance::setSema(Sema *S) {
92 TheSema.reset(S);
93}
94
Daniel Dunbar12ce6942009-11-14 02:47:17 +000095void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
96 Consumer.reset(Value);
97}
98
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000099void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
100 CompletionConsumer.reset(Value);
101}
102
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000103// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000104static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +0000105 unsigned argc, const char* const *argv,
David Blaikied6471f72011-09-25 23:23:43 +0000106 DiagnosticsEngine &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000107 std::string ErrorInfo;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 llvm::OwningPtr<raw_ostream> OS(
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000109 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000110 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000111 Diags.Report(diag::err_fe_unable_to_open_logfile)
112 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000113 return;
114 }
115
Daniel Dunbardd63b282009-12-11 23:04:35 +0000116 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000117 for (unsigned i = 0; i != argc; ++i)
118 (*OS) << argv[i] << ' ';
119 (*OS) << '\n';
120
121 // Chain in a diagnostic client which will log the diagnostics.
David Blaikie78ad0b92011-09-25 23:39:51 +0000122 DiagnosticConsumer *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000123 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000124 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000125}
126
Daniel Dunbar9df23492011-04-07 18:31:10 +0000127static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000128 const CodeGenOptions *CodeGenOpts,
David Blaikied6471f72011-09-25 23:23:43 +0000129 DiagnosticsEngine &Diags) {
Daniel Dunbar9df23492011-04-07 18:31:10 +0000130 std::string ErrorInfo;
131 bool OwnsStream = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000132 raw_ostream *OS = &llvm::errs();
Daniel Dunbar9df23492011-04-07 18:31:10 +0000133 if (DiagOpts.DiagnosticLogFile != "-") {
134 // Create the output stream.
135 llvm::raw_fd_ostream *FileOS(
136 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbare01eceb2011-04-07 20:19:21 +0000137 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000138 if (!ErrorInfo.empty()) {
139 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
140 << DiagOpts.DumpBuildInformation << ErrorInfo;
141 } else {
142 FileOS->SetUnbuffered();
143 FileOS->SetUseAtomicWrites(true);
144 OS = FileOS;
145 OwnsStream = true;
146 }
147 }
148
149 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000150 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
151 OwnsStream);
152 if (CodeGenOpts)
153 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000154 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000155}
156
Ted Kremenek78002122011-10-29 00:12:39 +0000157static void SetupSerializedDiagnostics(const DiagnosticOptions &DiagOpts,
158 DiagnosticsEngine &Diags,
159 StringRef OutputFile) {
160 std::string ErrorInfo;
161 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
162 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
163 llvm::raw_fd_ostream::F_Binary));
164
165 if (!ErrorInfo.empty()) {
166 Diags.Report(diag::warn_fe_serialized_diag_failure)
167 << OutputFile << ErrorInfo;
168 return;
169 }
170
171 DiagnosticConsumer *SerializedConsumer =
172 clang::serialized_diags::create(OS.take(), Diags);
173
174
175 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
176 SerializedConsumer));
177}
178
Douglas Gregore47be3e2010-11-11 00:39:14 +0000179void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000180 DiagnosticConsumer *Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000181 bool ShouldOwnClient,
182 bool ShouldCloneClient) {
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000183 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000184 ShouldOwnClient, ShouldCloneClient,
185 &getCodeGenOpts());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000186}
187
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000188llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor28019772010-04-05 23:52:57 +0000189CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000190 int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000191 DiagnosticConsumer *Client,
Douglas Gregor78243652011-09-13 01:26:44 +0000192 bool ShouldOwnClient,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000193 bool ShouldCloneClient,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000194 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000195 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikied6471f72011-09-25 23:23:43 +0000196 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
197 Diags(new DiagnosticsEngine(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000198
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000199 // Create the diagnostic client for reporting errors or for
200 // implementing -verify.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000201 if (Client) {
202 if (ShouldCloneClient)
203 Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
204 else
205 Diags->setClient(Client, ShouldOwnClient);
206 } else
Douglas Gregore47be3e2010-11-11 00:39:14 +0000207 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000208
209 // Chain in -verify checker, if requested.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000210 if (Opts.VerifyDiagnostics)
David Blaikie621bc692011-09-26 00:38:03 +0000211 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000212
Daniel Dunbar9df23492011-04-07 18:31:10 +0000213 // Chain in -diagnostic-log-file dumper, if requested.
214 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000215 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000216
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000217 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000218 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000219
Ted Kremenek78002122011-10-29 00:12:39 +0000220 if (!Opts.DiagnosticSerializationFile.empty())
221 SetupSerializedDiagnostics(Opts, *Diags,
222 Opts.DiagnosticSerializationFile);
223
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000224 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000225 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000226
Douglas Gregor28019772010-04-05 23:52:57 +0000227 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000228}
229
230// File Manager
231
Daniel Dunbar16b74492009-11-13 04:12:06 +0000232void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000233 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000234}
235
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000236// Source Manager
237
Chris Lattner39b49bc2010-11-23 08:35:12 +0000238void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000239 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000240}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000241
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000242// Preprocessor
243
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000244void CompilerInstance::createPreprocessor() {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000245 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000246
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000247 // Create a PTH manager if we are using some form of a token cache.
248 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000249 if (!PPOpts.TokenCache.empty())
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000250 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000251
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000252 // Create the Preprocessor.
Douglas Gregor8e238062011-11-11 00:35:06 +0000253 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager(),
254 getDiagnostics());
Douglas Gregor998b3d32011-09-01 23:39:15 +0000255 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000256 getSourceManager(), *HeaderInfo, *this, PTHMgr,
257 /*OwnsHeaderSearch=*/true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000258
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000259 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
260 // That argument is used as the IdentifierInfoLookup argument to
261 // IdentifierTable's ctor.
262 if (PTHMgr) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000263 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000264 PP->setPTHManager(PTHMgr);
265 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000266
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000267 if (PPOpts.DetailedRecord)
Douglas Gregordca8ee82011-05-06 16:33:08 +0000268 PP->createPreprocessingRecord(
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000269 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000270
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000271 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000272
Douglas Gregor6e975c42011-09-13 23:15:45 +0000273 // Set up the module path, including the hash for the
274 // module-creation options.
275 llvm::SmallString<256> SpecificModuleCache(
276 getHeaderSearchOpts().ModuleCachePath);
277 if (!getHeaderSearchOpts().DisableModuleHash)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000278 llvm::sys::path::append(SpecificModuleCache,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000279 getInvocation().getModuleHash());
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000280 PP->getHeaderSearchInfo().configureModules(SpecificModuleCache,
281 getPreprocessorOpts().ModuleBuildPath.empty()
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000282 ? std::string()
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000283 : getPreprocessorOpts().ModuleBuildPath.back());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000284
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000285 // Handle generating dependencies, if requested.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000286 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000287 if (!DepOpts.OutputFile.empty())
288 AttachDependencyFileGen(*PP, DepOpts);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000289
Daniel Dunbareef63e02011-02-02 15:41:17 +0000290 // Handle generating header include information, if requested.
291 if (DepOpts.ShowHeaderIncludes)
292 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000293 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000294 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000295 if (OutputPath == "-")
296 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000297 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
298 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000299 }
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000300}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000301
302// ASTContext
303
304void CompilerInstance::createASTContext() {
305 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000306 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000307 &getTarget(), PP.getIdentifierTable(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000308 PP.getSelectorTable(), PP.getBuiltinInfo(),
309 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000310}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000311
312// ExternalASTSource
313
Chris Lattner5f9e2722011-07-23 10:55:15 +0000314void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000315 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000316 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000317 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000318 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000319 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000320 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000321 DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000322 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000323 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000324 DeserializationListener,
325 Preamble));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000326 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar0f800392009-11-13 08:21:10 +0000327 getASTContext().setExternalSource(Source);
328}
329
330ExternalASTSource *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000331CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000332 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000333 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000334 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000335 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000336 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000337 void *DeserializationListener,
338 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000339 llvm::OwningPtr<ASTReader> Reader;
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000340 Reader.reset(new ASTReader(PP, Context,
Douglas Gregor832d6202011-07-22 16:35:34 +0000341 Sysroot.empty() ? "" : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000342 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000343
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000344 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000345 static_cast<ASTDeserializationListener *>(DeserializationListener));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000346 switch (Reader->ReadAST(Path,
347 Preamble ? serialization::MK_Preamble
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000348 : serialization::MK_PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000349 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000350 // Set the predefines buffer as suggested by the PCH reader. Typically, the
351 // predefines buffer will be empty.
352 PP.setPredefines(Reader->getSuggestedPredefines());
353 return Reader.take();
354
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000355 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000356 // Unrecoverable failure: don't even try to process the input file.
357 break;
358
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000359 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000360 // No suitable PCH file could be found. Return an error.
361 break;
362 }
363
364 return 0;
365}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000366
367// Code Completion
368
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000369static bool EnableCodeCompletion(Preprocessor &PP,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000370 const std::string &Filename,
371 unsigned Line,
372 unsigned Column) {
373 // Tell the source manager to chop off the given file at a specific
374 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000375 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000376 if (!Entry) {
377 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
378 << Filename;
379 return true;
380 }
381
382 // Truncate the named file at the given line/column.
383 PP.SetCodeCompletionPoint(Entry, Line, Column);
384 return false;
385}
386
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000387void CompilerInstance::createCodeCompletionConsumer() {
388 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000389 if (!CompletionConsumer) {
390 CompletionConsumer.reset(
391 createCodeCompletionConsumer(getPreprocessor(),
392 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000393 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000394 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000395 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000396 llvm::outs()));
397 if (!CompletionConsumer)
398 return;
399 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
400 Loc.Line, Loc.Column)) {
401 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000402 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000403 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000404
405 if (CompletionConsumer->isOutputBinary() &&
406 llvm::sys::Program::ChangeStdoutToBinary()) {
407 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
408 CompletionConsumer.reset();
409 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000410}
411
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000412void CompilerInstance::createFrontendTimer() {
413 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
414}
415
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000416CodeCompleteConsumer *
417CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
418 const std::string &Filename,
419 unsigned Line,
420 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000421 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000422 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000423 bool ShowGlobals,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000424 raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000425 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000426 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000427
428 // Set up the creation routine for code-completion.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000429 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000430 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000431}
Daniel Dunbara9204832009-11-13 10:37:48 +0000432
Douglas Gregor467dc882011-08-25 22:30:56 +0000433void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000434 CodeCompleteConsumer *CompletionConsumer) {
435 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor467dc882011-08-25 22:30:56 +0000436 TUKind, CompletionConsumer));
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000437}
438
Daniel Dunbara9204832009-11-13 10:37:48 +0000439// Output Files
440
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000441void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
442 assert(OutFile.OS && "Attempt to add empty stream to output list!");
443 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000444}
445
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000446void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000447 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000448 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000449 delete it->OS;
450 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000451 if (EraseFiles) {
452 bool existed;
453 llvm::sys::fs::remove(it->TempFilename, existed);
454 } else {
455 llvm::SmallString<128> NewOutFile(it->Filename);
456
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000457 // If '-working-directory' was passed, the output filename should be
458 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000459 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000460 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
461 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000462 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000463 << it->TempFilename << it->Filename << ec.message();
464
465 bool existed;
466 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000467 }
468 }
469 } else if (!it->Filename.empty() && EraseFiles)
470 llvm::sys::Path(it->Filename).eraseFromDisk();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000471
Daniel Dunbara9204832009-11-13 10:37:48 +0000472 }
473 OutputFiles.clear();
474}
475
Daniel Dunbarf482d592009-11-13 18:32:08 +0000476llvm::raw_fd_ostream *
477CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000478 StringRef InFile,
479 StringRef Extension) {
Daniel Dunbarf482d592009-11-13 18:32:08 +0000480 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000481 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000482}
483
484llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000486 bool Binary, bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000487 StringRef InFile,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000488 StringRef Extension,
489 bool UseTemporary) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000490 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000491 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000492 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000493 InFile, Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000494 UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000495 &OutputPathName,
496 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000497 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000498 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
499 << OutputPath << Error;
500 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000501 }
502
503 // Add the output file -- but don't try to remove "-", since this means we are
504 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000505 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
506 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000507
508 return OS;
509}
510
511llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000512CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000513 std::string &Error,
514 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000515 bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000516 StringRef InFile,
517 StringRef Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000518 bool UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000519 std::string *ResultPathName,
520 std::string *TempPathName) {
521 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000522 if (!OutputPath.empty()) {
523 OutFile = OutputPath;
524 } else if (InFile == "-") {
525 OutFile = "-";
526 } else if (!Extension.empty()) {
527 llvm::sys::Path Path(InFile);
528 Path.eraseSuffix();
529 Path.appendSuffix(Extension);
530 OutFile = Path.str();
531 } else {
532 OutFile = "-";
533 }
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000534
535 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
536 std::string OSFile;
537
538 if (UseTemporary && OutFile != "-") {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000539 llvm::sys::Path OutPath(OutFile);
540 // Only create the temporary if we can actually write to OutPath, otherwise
541 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000542 bool Exists;
543 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000544 (OutPath.isRegularFile() && OutPath.canWrite())) {
545 // Create a temporary file.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000546 llvm::SmallString<128> TempPath;
547 TempPath = OutFile;
548 TempPath += "-%%%%%%%%";
549 int fd;
550 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
551 /*makeAbsolute=*/false) == llvm::errc::success) {
552 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
553 OSFile = TempFile = TempPath.str();
554 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000555 }
556 }
557
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000558 if (!OS) {
559 OSFile = OutFile;
560 OS.reset(
561 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
562 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
563 if (!Error.empty())
564 return 0;
565 }
Daniel Dunbarf482d592009-11-13 18:32:08 +0000566
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000567 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000568 if (RemoveFileOnSignal)
569 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000570
Daniel Dunbarf482d592009-11-13 18:32:08 +0000571 if (ResultPathName)
572 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000573 if (TempPathName)
574 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000575
Daniel Dunbarfc971022009-11-20 22:32:38 +0000576 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000577}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000578
579// Initialization Utilities
580
Chris Lattner5f9e2722011-07-23 10:55:15 +0000581bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000582 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
583 getSourceManager(), getFrontendOpts());
584}
585
Chris Lattner5f9e2722011-07-23 10:55:15 +0000586bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
David Blaikied6471f72011-09-25 23:23:43 +0000587 DiagnosticsEngine &Diags,
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000588 FileManager &FileMgr,
589 SourceManager &SourceMgr,
590 const FrontendOptions &Opts) {
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +0000591 // Figure out where to get and map in the main file.
592 if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000593 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000594 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000595 Diags.Report(diag::err_fe_error_reading) << InputFile;
596 return false;
597 }
Dan Gohman694137c2010-10-26 21:13:51 +0000598 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000599 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000600 llvm::OwningPtr<llvm::MemoryBuffer> SB;
601 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000602 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000603 Diags.Report(diag::err_fe_error_reading_stdin);
604 return false;
605 }
Dan Gohman90d90812010-10-26 23:21:25 +0000606 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000607 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000608 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000609 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000610 }
611
Dan Gohman694137c2010-10-26 21:13:51 +0000612 assert(!SourceMgr.getMainFileID().isInvalid() &&
613 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000614 return true;
615}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000616
617// High-Level Operations
618
619bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
620 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
621 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
622 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
623
624 // FIXME: Take this as an argument, once all the APIs we used have moved to
625 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000626 raw_ostream &OS = llvm::errs();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000627
628 // Create the target instance.
629 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
630 if (!hasTarget())
631 return false;
632
633 // Inform the target of the language options.
634 //
635 // FIXME: We shouldn't need to do this, the target should be immutable once
636 // created. This complexity should be lifted elsewhere.
637 getTarget().setForcedLangOptions(getLangOpts());
638
639 // Validate/process some options.
640 if (getHeaderSearchOpts().Verbose)
641 OS << "clang -cc1 version " CLANG_VERSION_STRING
642 << " based upon " << PACKAGE_STRING
Sebastian Pop5d8b9542011-11-01 21:33:06 +0000643 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
Daniel Dunbar0397af22010-01-13 00:48:06 +0000644
645 if (getFrontendOpts().ShowTimers)
646 createFrontendTimer();
647
Douglas Gregor95dd5582010-03-30 17:33:59 +0000648 if (getFrontendOpts().ShowStats)
649 llvm::EnableStatistics();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000650
Daniel Dunbar0397af22010-01-13 00:48:06 +0000651 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
652 const std::string &InFile = getFrontendOpts().Inputs[i].second;
653
Daniel Dunbar20560482010-06-07 23:23:50 +0000654 // Reset the ID tables if we are reusing the SourceManager.
655 if (hasSourceManager())
656 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000657
Daniel Dunbard3598a62010-06-07 23:23:06 +0000658 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000659 Act.Execute();
660 Act.EndSourceFile();
661 }
662 }
663
Chris Lattner53eee7b2010-04-07 18:47:42 +0000664 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000665 // We can have multiple diagnostics sharing one diagnostic client.
666 // Get the total number of warnings/errors from the client.
667 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
668 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000669
Chris Lattner53eee7b2010-04-07 18:47:42 +0000670 if (NumWarnings)
671 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
672 if (NumWarnings && NumErrors)
673 OS << " and ";
674 if (NumErrors)
675 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
676 if (NumWarnings || NumErrors)
677 OS << " generated.\n";
678 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000679
Daniel Dunbar20560482010-06-07 23:23:50 +0000680 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000681 getFileManager().PrintStats();
682 OS << "\n";
683 }
684
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000685 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000686}
687
Douglas Gregor21cae202011-09-12 23:31:24 +0000688/// \brief Determine the appropriate source input kind based on language
689/// options.
690static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
691 if (LangOpts.OpenCL)
692 return IK_OpenCL;
693 if (LangOpts.CUDA)
694 return IK_CUDA;
695 if (LangOpts.ObjC1)
696 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
697 return LangOpts.CPlusPlus? IK_CXX : IK_C;
698}
699
Douglas Gregor0ced7992011-10-04 00:21:21 +0000700namespace {
701 struct CompileModuleData {
702 CompilerInstance &Instance;
703 GeneratePCHAction &CreateModuleAction;
704 };
705}
706
707/// \brief Helper function that executes the module-generating action under
708/// a crash recovery context.
709static void doCompileModule(void *UserData) {
710 CompileModuleData &Data = *reinterpret_cast<CompileModuleData *>(UserData);
711 Data.Instance.ExecuteAction(Data.CreateModuleAction);
712}
713
Douglas Gregor2bc75072011-10-05 14:53:30 +0000714namespace {
715 /// \brief Class that manages the creation of a lock file to aid
716 /// implicit coordination between different processes.
717 ///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000718 /// The implicit coordination works by creating a ".lock" file alongside
Douglas Gregor2bc75072011-10-05 14:53:30 +0000719 /// the file that we're coordinating for, using the atomicity of the file
720 /// system to ensure that only a single process can create that ".lock" file.
721 /// When the lock file is removed, the owning process has finished the
722 /// operation.
723 class LockFileManager {
724 public:
725 /// \brief Describes the state of a lock file.
726 enum LockFileState {
727 /// \brief The lock file has been created and is owned by this instance
728 /// of the object.
729 LFS_Owned,
730 /// \brief The lock file already exists and is owned by some other
731 /// instance.
732 LFS_Shared,
733 /// \brief An error occurred while trying to create or find the lock
734 /// file.
735 LFS_Error
736 };
737
738 private:
739 llvm::SmallString<128> LockFileName;
740 llvm::SmallString<128> UniqueLockFileName;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000741
Douglas Gregor2bc75072011-10-05 14:53:30 +0000742 llvm::Optional<std::pair<std::string, int> > Owner;
743 llvm::Optional<llvm::error_code> Error;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000744
Douglas Gregor2bc75072011-10-05 14:53:30 +0000745 LockFileManager(const LockFileManager &);
746 LockFileManager &operator=(const LockFileManager &);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000747
748 static llvm::Optional<std::pair<std::string, int> >
Douglas Gregor2bc75072011-10-05 14:53:30 +0000749 readLockFile(StringRef LockFileName);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000750
Douglas Gregor2bc75072011-10-05 14:53:30 +0000751 static bool processStillExecuting(StringRef Hostname, int PID);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000752
Douglas Gregor2bc75072011-10-05 14:53:30 +0000753 public:
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000754
Douglas Gregor2bc75072011-10-05 14:53:30 +0000755 LockFileManager(StringRef FileName);
756 ~LockFileManager();
757
758 /// \brief Determine the state of the lock file.
759 LockFileState getState() const;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000760
Douglas Gregor2bc75072011-10-05 14:53:30 +0000761 operator LockFileState() const { return getState(); }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000762
Douglas Gregor2bc75072011-10-05 14:53:30 +0000763 /// \brief For a shared lock, wait until the owner releases the lock.
764 void waitForUnlock();
765 };
766}
767
768/// \brief Attempt to read the lock file with the given name, if it exists.
769///
770/// \param LockFileName The name of the lock file to read.
771///
772/// \returns The process ID of the process that owns this lock file
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000773llvm::Optional<std::pair<std::string, int> >
Douglas Gregor2bc75072011-10-05 14:53:30 +0000774LockFileManager::readLockFile(StringRef LockFileName) {
775 // Check whether the lock file exists. If not, clearly there's nothing
776 // to read, so we just return.
777 bool Exists = false;
778 if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists)
779 return llvm::Optional<std::pair<std::string, int> >();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000780
Douglas Gregor2bc75072011-10-05 14:53:30 +0000781 // Read the owning host and PID out of the lock file. If it appears that the
782 // owning process is dead, the lock file is invalid.
783 int PID = 0;
784 std::string Hostname;
785 std::ifstream Input(LockFileName.str().c_str());
786 if (Input >> Hostname >> PID && PID > 0 &&
787 processStillExecuting(Hostname, PID))
788 return std::make_pair(Hostname, PID);
789
790 // Delete the lock file. It's invalid anyway.
791 bool Existed;
792 llvm::sys::fs::remove(LockFileName, Existed);
793 return llvm::Optional<std::pair<std::string, int> >();
794}
795
796bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
797#if LLVM_ON_UNIX
798 char MyHostname[256];
799 MyHostname[255] = 0;
800 MyHostname[0] = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000801 gethostname(MyHostname, 255);
Douglas Gregor2bc75072011-10-05 14:53:30 +0000802 // Check whether the process is dead. If so, we're done.
803 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
804 return false;
805#endif
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000806
Douglas Gregor2bc75072011-10-05 14:53:30 +0000807 return true;
808}
809
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000810LockFileManager::LockFileManager(StringRef FileName)
Douglas Gregor2bc75072011-10-05 14:53:30 +0000811{
812 LockFileName = FileName;
813 LockFileName += ".lock";
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000814
Douglas Gregor2bc75072011-10-05 14:53:30 +0000815 // If the lock file already exists, don't bother to try to create our own
816 // lock file; it won't work anyway. Just figure out who owns this lock file.
817 if ((Owner = readLockFile(LockFileName)))
818 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000819
Douglas Gregor2bc75072011-10-05 14:53:30 +0000820 // Create a lock file that is unique to this instance.
821 UniqueLockFileName = LockFileName;
822 UniqueLockFileName += "-%%%%%%%%";
823 int UniqueLockFileID;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000824 if (llvm::error_code EC
825 = llvm::sys::fs::unique_file(UniqueLockFileName.str(),
Douglas Gregor2bc75072011-10-05 14:53:30 +0000826 UniqueLockFileID,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000827 UniqueLockFileName,
Douglas Gregor2bc75072011-10-05 14:53:30 +0000828 /*makeAbsolute=*/false)) {
829 Error = EC;
830 return;
831 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000832
Douglas Gregor2bc75072011-10-05 14:53:30 +0000833 // Write our process ID to our unique lock file.
834 {
835 llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000836
Douglas Gregor2bc75072011-10-05 14:53:30 +0000837#if LLVM_ON_UNIX
838 // FIXME: move getpid() call into LLVM
839 char hostname[256];
840 hostname[255] = 0;
841 hostname[0] = 0;
842 gethostname(hostname, 255);
843 Out << hostname << ' ' << getpid();
844#else
845 Out << "localhost 1";
846#endif
847 Out.close();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000848
Douglas Gregor2bc75072011-10-05 14:53:30 +0000849 if (Out.has_error()) {
850 // We failed to write out PID, so make up an excuse, remove the
851 // unique lock file, and fail.
852 Error = llvm::make_error_code(llvm::errc::no_space_on_device);
853 bool Existed;
854 llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed);
855 return;
856 }
857 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000858
Douglas Gregor2bc75072011-10-05 14:53:30 +0000859 // Create a hard link from the lock file name. If this succeeds, we're done.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000860 llvm::error_code EC
861 = llvm::sys::fs::create_hard_link(UniqueLockFileName.str(),
Douglas Gregor2bc75072011-10-05 14:53:30 +0000862 LockFileName.str());
863 if (EC == llvm::errc::success)
864 return;
865
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000866 // Creating the hard link failed.
867
Douglas Gregor2bc75072011-10-05 14:53:30 +0000868#ifdef LLVM_ON_UNIX
869 // The creation of the hard link may appear to fail, but if stat'ing the
870 // unique file returns a link count of 2, then we can still declare success.
871 struct stat StatBuf;
872 if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
873 StatBuf.st_nlink == 2)
874 return;
875#endif
876
877 // Someone else managed to create the lock file first. Wipe out our unique
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000878 // lock file (it's useless now) and read the process ID from the lock file.
Douglas Gregor2bc75072011-10-05 14:53:30 +0000879 bool Existed;
880 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
881 if ((Owner = readLockFile(LockFileName)))
882 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000883
Douglas Gregor2bc75072011-10-05 14:53:30 +0000884 // There is a lock file that nobody owns; try to clean it up and report
885 // an error.
886 llvm::sys::fs::remove(LockFileName.str(), Existed);
887 Error = EC;
888}
889
890LockFileManager::LockFileState LockFileManager::getState() const {
891 if (Owner)
892 return LFS_Shared;
893
894 if (Error)
895 return LFS_Error;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000896
Douglas Gregor2bc75072011-10-05 14:53:30 +0000897 return LFS_Owned;
898}
899
900LockFileManager::~LockFileManager() {
901 if (getState() != LFS_Owned)
902 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000903
Douglas Gregor2bc75072011-10-05 14:53:30 +0000904 // Since we own the lock, remove the lock file and our own unique lock file.
905 bool Existed;
906 llvm::sys::fs::remove(LockFileName.str(), Existed);
907 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
908}
909
910void LockFileManager::waitForUnlock() {
911 if (getState() != LFS_Shared)
912 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000913
Douglas Gregor1872e792011-10-05 14:58:46 +0000914#if LLVM_ON_WIN32
915 unsigned long Interval = 1;
916#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000917 struct timespec Interval;
918 Interval.tv_sec = 0;
919 Interval.tv_nsec = 1000000;
Douglas Gregor1872e792011-10-05 14:58:46 +0000920#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +0000921 // Don't wait more than an hour for the file to appear.
922 const unsigned MaxSeconds = 3600;
923 do {
924 // Sleep for the designated interval, to allow the owning process time to
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000925 // finish up and
Douglas Gregor2bc75072011-10-05 14:53:30 +0000926 // FIXME: Should we hook in to system APIs to get a notification when the
927 // lock file is deleted?
Douglas Gregor25728492011-10-05 14:59:36 +0000928#if LLVM_ON_WIN32
929 Sleep(Interval);
930#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000931 nanosleep(&Interval, NULL);
Douglas Gregor25728492011-10-05 14:59:36 +0000932#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +0000933 // If the file no longer exists, we're done.
934 bool Exists = false;
935 if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists)
936 return;
937
938 if (!processStillExecuting((*Owner).first, (*Owner).second))
939 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000940
Douglas Gregor2bc75072011-10-05 14:53:30 +0000941 // Exponentially increase the time we wait for the lock to be removed.
Douglas Gregor1872e792011-10-05 14:58:46 +0000942#if LLVM_ON_WIN32
943 Interval *= 2;
944#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000945 Interval.tv_sec *= 2;
946 Interval.tv_nsec *= 2;
947 if (Interval.tv_nsec >= 1000000000) {
948 ++Interval.tv_sec;
949 Interval.tv_nsec -= 1000000000;
950 }
Douglas Gregor1872e792011-10-05 14:58:46 +0000951#endif
952 } while (
953#if LLVM_ON_WIN32
954 Interval < MaxSeconds * 1000
955#else
NAKAMURA Takumi0caed282011-10-08 11:31:58 +0000956 Interval.tv_sec < (time_t)MaxSeconds
Douglas Gregor1872e792011-10-05 14:58:46 +0000957#endif
958 );
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000959
Douglas Gregor2bc75072011-10-05 14:53:30 +0000960 // Give up.
961}
962
Douglas Gregor21cae202011-09-12 23:31:24 +0000963/// \brief Compile a module file for the given module name with the given
964/// umbrella header, using the options provided by the importing compiler
965/// instance.
966static void compileModule(CompilerInstance &ImportingInstance,
967 StringRef ModuleName,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000968 StringRef ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +0000969 StringRef UmbrellaHeader) {
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 Gregor21cae202011-09-12 23:31:24 +0000986 // Construct a compiler invocation for creating this module.
987 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
988 (new CompilerInvocation(ImportingInstance.getInvocation()));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000989
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000990 // For any options that aren't intended to affect how a module is built,
991 // reset them to their default values.
Douglas Gregor1c7e0472011-09-13 20:44:41 +0000992 Invocation->getLangOpts().resetNonModularOptions();
993 Invocation->getPreprocessorOpts().resetNonModularOptions();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000994
995 // Note that this module is part of the module build path, so that we
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000996 // can detect cycles in the module graph.
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000997 Invocation->getPreprocessorOpts().ModuleBuildPath.push_back(ModuleName);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000998
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000999 // Set up the inputs/outputs so that we build the module from its umbrella
1000 // header.
Douglas Gregor21cae202011-09-12 23:31:24 +00001001 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
Douglas Gregor6e975c42011-09-13 23:15:45 +00001002 FrontendOpts.OutputFile = ModuleFileName.str();
Douglas Gregor21cae202011-09-12 23:31:24 +00001003 FrontendOpts.DisableFree = false;
1004 FrontendOpts.Inputs.clear();
1005 FrontendOpts.Inputs.push_back(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001006 std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()),
Douglas Gregor21cae202011-09-12 23:31:24 +00001007 UmbrellaHeader));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001008
Douglas Gregor78243652011-09-13 01:26:44 +00001009 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001010
1011
Douglas Gregor76d991e2011-09-13 23:20:27 +00001012 assert(ImportingInstance.getInvocation().getModuleHash() ==
1013 Invocation->getModuleHash() && "Module hash mismatch!");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001014
Douglas Gregor21cae202011-09-12 23:31:24 +00001015 // Construct a compiler instance that will be used to actually create the
1016 // module.
1017 CompilerInstance Instance;
1018 Instance.setInvocation(&*Invocation);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001019 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
Douglas Gregor78243652011-09-13 01:26:44 +00001020 &ImportingInstance.getDiagnosticClient(),
Douglas Gregoraee526e2011-09-29 00:38:00 +00001021 /*ShouldOwnClient=*/true,
1022 /*ShouldCloneClient=*/true);
Douglas Gregor21cae202011-09-12 23:31:24 +00001023
1024 // Construct a module-generating action.
1025 GeneratePCHAction CreateModuleAction(true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001026
Douglas Gregor0ced7992011-10-04 00:21:21 +00001027 // Execute the action to actually build the module in-place. Use a separate
1028 // thread so that we get a stack large enough.
1029 const unsigned ThreadStackSize = 8 << 20;
1030 llvm::CrashRecoveryContext CRC;
1031 CompileModuleData Data = { Instance, CreateModuleAction };
1032 CRC.RunSafelyOnThread(&doCompileModule, &Data, ThreadStackSize);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001033}
Douglas Gregor21cae202011-09-12 23:31:24 +00001034
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001035ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001036 IdentifierInfo &ModuleName,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001037 SourceLocation ModuleNameLoc) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001038 // Determine what file we're searching from.
1039 SourceManager &SourceMgr = getSourceManager();
1040 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
1041 const FileEntry *CurFile
1042 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
1043 if (!CurFile)
1044 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1045
1046 // Search for a module with the given name.
Douglas Gregor21cae202011-09-12 23:31:24 +00001047 std::string UmbrellaHeader;
Douglas Gregor6e975c42011-09-13 23:15:45 +00001048 std::string ModuleFileName;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001049 const FileEntry *ModuleFile
Douglas Gregor21cae202011-09-12 23:31:24 +00001050 = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
Douglas Gregor6e975c42011-09-13 23:15:45 +00001051 &ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +00001052 &UmbrellaHeader);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001053
Douglas Gregor21cae202011-09-12 23:31:24 +00001054 bool BuildingModule = false;
1055 if (!ModuleFile && !UmbrellaHeader.empty()) {
1056 // We didn't find the module, but there is an umbrella header that
1057 // can be used to create the module file. Create a separate compilation
1058 // module to do so.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001059
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001060 // Check whether there is a cycle in the module graph.
1061 SmallVectorImpl<std::string> &ModuleBuildPath
1062 = getPreprocessorOpts().ModuleBuildPath;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001063 SmallVectorImpl<std::string>::iterator Pos
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001064 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(),
1065 ModuleName.getName());
1066 if (Pos != ModuleBuildPath.end()) {
1067 llvm::SmallString<256> CyclePath;
1068 for (; Pos != ModuleBuildPath.end(); ++Pos) {
1069 CyclePath += *Pos;
1070 CyclePath += " -> ";
1071 }
1072 CyclePath += ModuleName.getName();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001073
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001074 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1075 << ModuleName.getName() << CyclePath;
1076 return 0;
1077 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001078
Douglas Gregor08d6acf2011-09-29 00:52:27 +00001079 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
1080 << ModuleName.getName();
Douglas Gregor21cae202011-09-12 23:31:24 +00001081 BuildingModule = true;
Douglas Gregor6e975c42011-09-13 23:15:45 +00001082 compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader);
Douglas Gregor21cae202011-09-12 23:31:24 +00001083 ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName());
1084 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001085
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001086 if (!ModuleFile) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001087 getDiagnostics().Report(ModuleNameLoc,
Douglas Gregor21cae202011-09-12 23:31:24 +00001088 BuildingModule? diag::err_module_not_built
1089 : diag::err_module_not_found)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001090 << ModuleName.getName()
1091 << SourceRange(ImportLoc, ModuleNameLoc);
1092 return 0;
1093 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001094
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001095 // If we don't already have an ASTReader, create one now.
1096 if (!ModuleManager) {
Douglas Gregorde8a9052011-09-14 23:13:09 +00001097 if (!hasASTContext())
1098 createASTContext();
1099
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001100 std::string Sysroot = getHeaderSearchOpts().Sysroot;
1101 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
Douglas Gregorf8a1e512011-09-02 00:26:20 +00001102 ModuleManager = new ASTReader(getPreprocessor(), *Context,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001103 Sysroot.empty() ? "" : Sysroot.c_str(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001104 PPOpts.DisablePCHValidation,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001105 PPOpts.DisableStatCache);
Douglas Gregorde8a9052011-09-14 23:13:09 +00001106 if (hasASTConsumer()) {
1107 ModuleManager->setDeserializationListener(
1108 getASTConsumer().GetASTDeserializationListener());
1109 getASTContext().setASTMutationListener(
1110 getASTConsumer().GetASTMutationListener());
1111 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001112 llvm::OwningPtr<ExternalASTSource> Source;
1113 Source.reset(ModuleManager);
1114 getASTContext().setExternalSource(Source);
Douglas Gregorde8a9052011-09-14 23:13:09 +00001115 if (hasSema())
1116 ModuleManager->InitializeSema(getSema());
Douglas Gregor1a995dd2011-09-15 18:47:32 +00001117 if (hasASTConsumer())
1118 ModuleManager->StartTranslationUnit(&getASTConsumer());
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001119 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001120
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001121 // Try to load the module we found.
1122 switch (ModuleManager->ReadAST(ModuleFile->getName(),
1123 serialization::MK_Module)) {
1124 case ASTReader::Success:
1125 break;
1126
1127 case ASTReader::IgnorePCH:
1128 // FIXME: The ASTReader will already have complained, but can we showhorn
1129 // that diagnostic information into a more useful form?
1130 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001131
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001132 case ASTReader::Failure:
1133 // Already complained.
1134 return 0;
1135 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001136
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001137 // FIXME: The module file's FileEntry makes a poor key indeed!
1138 return (ModuleKey)ModuleFile;
1139}
Daniel Dunbar0397af22010-01-13 00:48:06 +00001140