blob: 07c0248b6c319bbb79eaf7ac8f50c3b897199023 [file] [log] [blame]
Daniel Dunbar636404a2009-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"
Daniel Dunbar56d9c292009-11-14 02:47:17 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbardf3e30c2009-11-13 08:20:47 +000012#include "clang/AST/ASTContext.h"
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000013#include "clang/AST/Decl.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000014#include "clang/Basic/Diagnostic.h"
Daniel Dunbar546a6762009-11-13 04:12:06 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000018#include "clang/Basic/Version.h"
David Blaikie8b00dcb2011-09-26 00:21:47 +000019#include "clang/Frontend/ChainedDiagnosticConsumer.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000020#include "clang/Frontend/FrontendAction.h"
Douglas Gregorfaeb1d42011-09-12 23:31:24 +000021#include "clang/Frontend/FrontendActions.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar2083c322011-04-07 18:31:10 +000023#include "clang/Frontend/LogDiagnosticPrinter.h"
Ted Kremenek4610ea22011-10-29 00:12:39 +000024#include "clang/Frontend/SerializedDiagnosticPrinter.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000025#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbaraaa148f2009-11-13 05:52:11 +000026#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Frontend/VerifyDiagnosticConsumer.h"
28#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/PTHManager.h"
30#include "clang/Lex/Preprocessor.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000031#include "clang/Sema/CodeCompleteConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Sema.h"
33#include "clang/Serialization/ASTReader.h"
Douglas Gregor171b7802010-03-30 17:33:59 +000034#include "llvm/ADT/Statistic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "llvm/Config/config.h"
36#include "llvm/Support/CrashRecoveryContext.h"
37#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000038#include "llvm/Support/Host.h"
Douglas Gregore2124892012-01-29 20:15:24 +000039#include "llvm/Support/LockFileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000041#include "llvm/Support/Path.h"
42#include "llvm/Support/Program.h"
43#include "llvm/Support/Signals.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000044#include "llvm/Support/Timer.h"
45#include "llvm/Support/raw_ostream.h"
Michael J. Spencerf25faaa2010-12-09 17:36:38 +000046#include "llvm/Support/system_error.h"
Douglas Gregor54a88812011-10-05 14:53:30 +000047
Daniel Dunbar636404a2009-11-13 03:51:44 +000048using namespace clang;
49
Daniel Dunbare922d9b2010-02-16 01:54:47 +000050CompilerInstance::CompilerInstance()
Douglas Gregor5e306b12013-01-23 22:38:11 +000051 : Invocation(new CompilerInvocation()), ModuleManager(0),
52 BuildGlobalModuleIndex(false) {
Daniel Dunbar68242252010-01-30 21:47:07 +000053}
Daniel Dunbar636404a2009-11-13 03:51:44 +000054
55CompilerInstance::~CompilerInstance() {
Benjamin Kramer3c717b42012-10-14 19:21:21 +000056 assert(OutputFiles.empty() && "Still output files in flight?");
Daniel Dunbare922d9b2010-02-16 01:54:47 +000057}
58
Daniel Dunbar68242252010-01-30 21:47:07 +000059void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000060 Invocation = Value;
Daniel Dunbar68242252010-01-30 21:47:07 +000061}
62
David Blaikie9c902b52011-09-25 23:23:43 +000063void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Douglas Gregor7f95d262010-04-05 23:52:57 +000064 Diagnostics = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000065}
66
Daniel Dunbare01dc862009-11-14 01:20:40 +000067void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000068 Target = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000069}
70
71void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000072 FileMgr = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000073}
74
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000075void CompilerInstance::setSourceManager(SourceManager *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000076 SourceMgr = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000077}
78
Ted Kremenek5e14d392011-03-21 18:40:17 +000079void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbare01dc862009-11-14 01:20:40 +000080
Ted Kremenek5e14d392011-03-21 18:40:17 +000081void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbare01dc862009-11-14 01:20:40 +000082
Douglas Gregor0e93f012010-08-12 23:31:19 +000083void CompilerInstance::setSema(Sema *S) {
84 TheSema.reset(S);
85}
86
Daniel Dunbar56d9c292009-11-14 02:47:17 +000087void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
88 Consumer.reset(Value);
89}
90
Daniel Dunbare01dc862009-11-14 01:20:40 +000091void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
92 CompletionConsumer.reset(Value);
93}
94
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000095// Diagnostics
Douglas Gregor811db4e2012-10-23 22:26:28 +000096static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
Daniel Dunbar7b833062011-04-07 18:59:02 +000097 const CodeGenOptions *CodeGenOpts,
David Blaikie9c902b52011-09-25 23:23:43 +000098 DiagnosticsEngine &Diags) {
Daniel Dunbar2083c322011-04-07 18:31:10 +000099 std::string ErrorInfo;
100 bool OwnsStream = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000101 raw_ostream *OS = &llvm::errs();
Douglas Gregor811db4e2012-10-23 22:26:28 +0000102 if (DiagOpts->DiagnosticLogFile != "-") {
Daniel Dunbar2083c322011-04-07 18:31:10 +0000103 // Create the output stream.
104 llvm::raw_fd_ostream *FileOS(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000105 new llvm::raw_fd_ostream(DiagOpts->DiagnosticLogFile.c_str(),
Daniel Dunbar44d9ef72011-04-07 20:19:21 +0000106 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar2083c322011-04-07 18:31:10 +0000107 if (!ErrorInfo.empty()) {
108 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
Sean Silva2118a5c2013-01-20 01:58:26 +0000109 << DiagOpts->DiagnosticLogFile << ErrorInfo;
Daniel Dunbar2083c322011-04-07 18:31:10 +0000110 } else {
111 FileOS->SetUnbuffered();
112 FileOS->SetUseAtomicWrites(true);
113 OS = FileOS;
114 OwnsStream = true;
115 }
116 }
117
118 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbar7b833062011-04-07 18:59:02 +0000119 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
120 OwnsStream);
121 if (CodeGenOpts)
122 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
David Blaikie8b00dcb2011-09-26 00:21:47 +0000123 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar2083c322011-04-07 18:31:10 +0000124}
125
Douglas Gregor811db4e2012-10-23 22:26:28 +0000126static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
Ted Kremenek4610ea22011-10-29 00:12:39 +0000127 DiagnosticsEngine &Diags,
128 StringRef OutputFile) {
129 std::string ErrorInfo;
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000130 OwningPtr<llvm::raw_fd_ostream> OS;
Ted Kremenek4610ea22011-10-29 00:12:39 +0000131 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
132 llvm::raw_fd_ostream::F_Binary));
133
134 if (!ErrorInfo.empty()) {
135 Diags.Report(diag::warn_fe_serialized_diag_failure)
136 << OutputFile << ErrorInfo;
137 return;
138 }
139
140 DiagnosticConsumer *SerializedConsumer =
Ted Kremenek4548e042011-12-17 05:26:11 +0000141 clang::serialized_diags::create(OS.take(), DiagOpts);
Ted Kremenek4610ea22011-10-29 00:12:39 +0000142
143
144 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
145 SerializedConsumer));
146}
147
Sean Silvaf1b49e22013-01-20 01:58:28 +0000148void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000149 bool ShouldOwnClient,
150 bool ShouldCloneClient) {
Sean Silvaf1b49e22013-01-20 01:58:28 +0000151 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000152 ShouldOwnClient, ShouldCloneClient,
153 &getCodeGenOpts());
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000154}
155
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000156IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor811db4e2012-10-23 22:26:28 +0000157CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
David Blaikiee2eefae2011-09-25 23:39:51 +0000158 DiagnosticConsumer *Client,
Douglas Gregor2b9b4642011-09-13 01:26:44 +0000159 bool ShouldOwnClient,
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000160 bool ShouldCloneClient,
Daniel Dunbar7b833062011-04-07 18:59:02 +0000161 const CodeGenOptions *CodeGenOpts) {
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000162 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
163 IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor811db4e2012-10-23 22:26:28 +0000164 Diags(new DiagnosticsEngine(DiagID, Opts));
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000165
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000166 // Create the diagnostic client for reporting errors or for
167 // implementing -verify.
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000168 if (Client) {
169 if (ShouldCloneClient)
170 Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
171 else
172 Diags->setClient(Client, ShouldOwnClient);
173 } else
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000174 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbar50ec0da2009-11-14 03:24:39 +0000175
176 // Chain in -verify checker, if requested.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000177 if (Opts->VerifyDiagnostics)
David Blaikie69609dc2011-09-26 00:38:03 +0000178 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000179
Daniel Dunbar2083c322011-04-07 18:31:10 +0000180 // Chain in -diagnostic-log-file dumper, if requested.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000181 if (!Opts->DiagnosticLogFile.empty())
Daniel Dunbar7b833062011-04-07 18:59:02 +0000182 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000183
Douglas Gregor811db4e2012-10-23 22:26:28 +0000184 if (!Opts->DiagnosticSerializationFile.empty())
Ted Kremenek4610ea22011-10-29 00:12:39 +0000185 SetupSerializedDiagnostics(Opts, *Diags,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000186 Opts->DiagnosticSerializationFile);
Ted Kremenek4610ea22011-10-29 00:12:39 +0000187
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000188 // Configure our handling of diagnostics.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000189 ProcessWarningOptions(*Diags, *Opts);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000190
Douglas Gregor7f95d262010-04-05 23:52:57 +0000191 return Diags;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000192}
193
194// File Manager
195
Daniel Dunbar546a6762009-11-13 04:12:06 +0000196void CompilerInstance::createFileManager() {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000197 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar546a6762009-11-13 04:12:06 +0000198}
199
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000200// Source Manager
201
Chris Lattner5159f612010-11-23 08:35:12 +0000202void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000203 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar546a6762009-11-13 04:12:06 +0000204}
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000205
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000206// Preprocessor
207
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000208void CompilerInstance::createPreprocessor() {
Douglas Gregor08142532011-08-26 23:56:07 +0000209 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000210
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000211 // Create a PTH manager if we are using some form of a token cache.
212 PTHManager *PTHMgr = 0;
Daniel Dunbard6ea9022009-11-17 05:52:41 +0000213 if (!PPOpts.TokenCache.empty())
Douglas Gregor08142532011-08-26 23:56:07 +0000214 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000215
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000216 // Create the Preprocessor.
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000217 HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
218 getFileManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000219 getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000220 getLangOpts(),
221 &getTarget());
Douglas Gregor1452ff12012-10-24 17:46:57 +0000222 PP = new Preprocessor(&getPreprocessorOpts(),
223 getDiagnostics(), getLangOpts(), &getTarget(),
Douglas Gregor08142532011-08-26 23:56:07 +0000224 getSourceManager(), *HeaderInfo, *this, PTHMgr,
225 /*OwnsHeaderSearch=*/true);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000226
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000227 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
228 // That argument is used as the IdentifierInfoLookup argument to
229 // IdentifierTable's ctor.
230 if (PTHMgr) {
Douglas Gregor08142532011-08-26 23:56:07 +0000231 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000232 PP->setPTHManager(PTHMgr);
233 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000234
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000235 if (PPOpts.DetailedRecord)
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000236 PP->createPreprocessingRecord();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000237
Douglas Gregor08142532011-08-26 23:56:07 +0000238 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000239
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000240 // Set up the module path, including the hash for the
241 // module-creation options.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000242 SmallString<256> SpecificModuleCache(
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000243 getHeaderSearchOpts().ModuleCachePath);
244 if (!getHeaderSearchOpts().DisableModuleHash)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000245 llvm::sys::path::append(SpecificModuleCache,
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000246 getInvocation().getModuleHash());
Douglas Gregor2537a362011-12-08 17:01:29 +0000247 PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000248
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000249 // Handle generating dependencies, if requested.
Douglas Gregor08142532011-08-26 23:56:07 +0000250 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000251 if (!DepOpts.OutputFile.empty())
252 AttachDependencyFileGen(*PP, DepOpts);
Douglas Gregor2e129652012-02-02 23:45:13 +0000253 if (!DepOpts.DOTOutputFile.empty())
254 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
Douglas Gregor83d46be2012-02-02 00:54:52 +0000255 getHeaderSearchOpts().Sysroot);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000256
Douglas Gregor83d46be2012-02-02 00:54:52 +0000257
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000258 // Handle generating header include information, if requested.
259 if (DepOpts.ShowHeaderIncludes)
260 AttachHeaderIncludeGen(*PP);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000261 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000262 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000263 if (OutputPath == "-")
264 OutputPath = "";
Daniel Dunbarfe908a82011-03-21 19:37:38 +0000265 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
266 /*ShowDepth=*/false);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000267 }
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000268}
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000269
270// ASTContext
271
272void CompilerInstance::createASTContext() {
273 Preprocessor &PP = getPreprocessor();
Ted Kremenek5e14d392011-03-21 18:40:17 +0000274 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000275 &getTarget(), PP.getIdentifierTable(),
Ted Kremenek5e14d392011-03-21 18:40:17 +0000276 PP.getSelectorTable(), PP.getBuiltinInfo(),
277 /*size_reserve=*/ 0);
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000278}
Daniel Dunbar599313e2009-11-13 08:21:10 +0000279
280// ExternalASTSource
281
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000282void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000283 bool DisablePCHValidation,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000284 bool AllowPCHWithCompilerErrors,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000285 void *DeserializationListener){
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000286 OwningPtr<ExternalASTSource> Source;
Sebastian Redl009e7f22010-10-05 16:15:19 +0000287 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar599313e2009-11-13 08:21:10 +0000288 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000289 DisablePCHValidation,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000290 AllowPCHWithCompilerErrors,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000291 getPreprocessor(), getASTContext(),
Sebastian Redl009e7f22010-10-05 16:15:19 +0000292 DeserializationListener,
293 Preamble));
Douglas Gregor925296b2011-07-19 16:10:42 +0000294 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar599313e2009-11-13 08:21:10 +0000295 getASTContext().setExternalSource(Source);
296}
297
298ExternalASTSource *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000299CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar599313e2009-11-13 08:21:10 +0000300 const std::string &Sysroot,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000301 bool DisablePCHValidation,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000302 bool AllowPCHWithCompilerErrors,
Daniel Dunbar599313e2009-11-13 08:21:10 +0000303 Preprocessor &PP,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000304 ASTContext &Context,
Sebastian Redl009e7f22010-10-05 16:15:19 +0000305 void *DeserializationListener,
306 bool Preamble) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000307 OwningPtr<ASTReader> Reader;
Douglas Gregor8835e032011-09-02 00:26:20 +0000308 Reader.reset(new ASTReader(PP, Context,
Douglas Gregorc567ba22011-07-22 16:35:34 +0000309 Sysroot.empty() ? "" : Sysroot.c_str(),
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +0000310 DisablePCHValidation,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000311 AllowPCHWithCompilerErrors));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000312
Sebastian Redl07a89a82010-07-30 00:29:29 +0000313 Reader->setDeserializationListener(
Sebastian Redl3e31c722010-08-18 23:56:56 +0000314 static_cast<ASTDeserializationListener *>(DeserializationListener));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000315 switch (Reader->ReadAST(Path,
316 Preamble ? serialization::MK_Preamble
Douglas Gregor4b29c162012-10-22 23:51:00 +0000317 : serialization::MK_PCH,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000318 SourceLocation(),
Douglas Gregor4b29c162012-10-22 23:51:00 +0000319 ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000320 case ASTReader::Success:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000321 // Set the predefines buffer as suggested by the PCH reader. Typically, the
322 // predefines buffer will be empty.
323 PP.setPredefines(Reader->getSuggestedPredefines());
324 return Reader.take();
325
Sebastian Redl2c499f62010-08-18 23:56:43 +0000326 case ASTReader::Failure:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000327 // Unrecoverable failure: don't even try to process the input file.
328 break;
329
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000330 case ASTReader::OutOfDate:
331 case ASTReader::VersionMismatch:
332 case ASTReader::ConfigurationMismatch:
333 case ASTReader::HadErrors:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000334 // No suitable PCH file could be found. Return an error.
335 break;
336 }
337
338 return 0;
339}
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000340
341// Code Completion
342
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000343static bool EnableCodeCompletion(Preprocessor &PP,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000344 const std::string &Filename,
345 unsigned Line,
346 unsigned Column) {
347 // Tell the source manager to chop off the given file at a specific
348 // line and column.
Chris Lattner5159f612010-11-23 08:35:12 +0000349 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000350 if (!Entry) {
351 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
352 << Filename;
353 return true;
354 }
355
356 // Truncate the named file at the given line/column.
357 PP.SetCodeCompletionPoint(Entry, Line, Column);
358 return false;
359}
360
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000361void CompilerInstance::createCodeCompletionConsumer() {
362 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000363 if (!CompletionConsumer) {
Erik Verbruggen2fca3c22012-04-12 10:31:12 +0000364 setCodeCompletionConsumer(
Douglas Gregor8e984da2010-08-04 16:47:14 +0000365 createCodeCompletionConsumer(getPreprocessor(),
366 Loc.FileName, Loc.Line, Loc.Column,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000367 getFrontendOpts().CodeCompleteOpts,
Douglas Gregor8e984da2010-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)) {
Erik Verbruggen2fca3c22012-04-12 10:31:12 +0000373 setCodeCompletionConsumer(0);
Douglas Gregor00a0cf72010-03-16 06:04:47 +0000374 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000375 }
Douglas Gregorf09935f2009-12-01 05:55:20 +0000376
377 if (CompletionConsumer->isOutputBinary() &&
378 llvm::sys::Program::ChangeStdoutToBinary()) {
379 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
Erik Verbruggen2fca3c22012-04-12 10:31:12 +0000380 setCodeCompletionConsumer(0);
Douglas Gregorf09935f2009-12-01 05:55:20 +0000381 }
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000382}
383
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000384void CompilerInstance::createFrontendTimer() {
385 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
386}
387
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000388CodeCompleteConsumer *
389CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
390 const std::string &Filename,
391 unsigned Line,
392 unsigned Column,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000393 const CodeCompleteOptions &Opts,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000394 raw_ostream &OS) {
Douglas Gregor8e984da2010-08-04 16:47:14 +0000395 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000396 return 0;
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000397
398 // Set up the creation routine for code-completion.
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000399 return new PrintingCodeCompleteConsumer(Opts, OS);
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000400}
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000401
Douglas Gregor69f74f82011-08-25 22:30:56 +0000402void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregor0e93f012010-08-12 23:31:19 +0000403 CodeCompleteConsumer *CompletionConsumer) {
404 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000405 TUKind, CompletionConsumer));
Douglas Gregor0e93f012010-08-12 23:31:19 +0000406}
407
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000408// Output Files
409
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000410void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
411 assert(OutFile.OS && "Attempt to add empty stream to output list!");
412 OutputFiles.push_back(OutFile);
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000413}
414
Kovarththanan Rajaratnam1c558cd2010-03-06 12:07:48 +0000415void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000416 for (std::list<OutputFile>::iterator
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000417 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000418 delete it->OS;
419 if (!it->TempFilename.empty()) {
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000420 if (EraseFiles) {
421 bool existed;
422 llvm::sys::fs::remove(it->TempFilename, existed);
423 } else {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000424 SmallString<128> NewOutFile(it->Filename);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000425
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000426 // If '-working-directory' was passed, the output filename should be
427 // relative to that.
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000428 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000429 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
430 NewOutFile.str())) {
Manuel Klimek3ef9c442012-05-16 20:55:58 +0000431 getDiagnostics().Report(diag::err_unable_to_rename_temp)
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000432 << it->TempFilename << it->Filename << ec.message();
433
434 bool existed;
435 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000436 }
437 }
438 } else if (!it->Filename.empty() && EraseFiles)
439 llvm::sys::Path(it->Filename).eraseFromDisk();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000440
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000441 }
442 OutputFiles.clear();
443}
444
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000445llvm::raw_fd_ostream *
446CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000447 StringRef InFile,
448 StringRef Extension) {
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000449 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarae77b3d2012-03-03 00:36:06 +0000450 /*RemoveFileOnSignal=*/true, InFile, Extension,
451 /*UseTemporary=*/true);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000452}
453
454llvm::raw_fd_ostream *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000455CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000456 bool Binary, bool RemoveFileOnSignal,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000457 StringRef InFile,
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000458 StringRef Extension,
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000459 bool UseTemporary,
460 bool CreateMissingDirectories) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000461 std::string Error, OutputPathName, TempPathName;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000462 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000463 RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000464 InFile, Extension,
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000465 UseTemporary,
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000466 CreateMissingDirectories,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000467 &OutputPathName,
468 &TempPathName);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000469 if (!OS) {
Daniel Dunbar75546992009-12-03 09:13:30 +0000470 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
471 << OutputPath << Error;
472 return 0;
Daniel Dunbar420b0f12009-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 Kyrtzidisd0599972010-09-17 17:38:48 +0000477 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
478 TempPathName, OS));
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000479
480 return OS;
481}
482
483llvm::raw_fd_ostream *
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000484CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000485 std::string &Error,
486 bool Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000487 bool RemoveFileOnSignal,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 StringRef InFile,
489 StringRef Extension,
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000490 bool UseTemporary,
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000491 bool CreateMissingDirectories,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000492 std::string *ResultPathName,
493 std::string *TempPathName) {
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000494 assert((!CreateMissingDirectories || UseTemporary) &&
495 "CreateMissingDirectories is only allowed when using temporary files");
496
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000497 std::string OutFile, TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000498 if (!OutputPath.empty()) {
499 OutFile = OutputPath;
500 } else if (InFile == "-") {
501 OutFile = "-";
502 } else if (!Extension.empty()) {
503 llvm::sys::Path Path(InFile);
504 Path.eraseSuffix();
505 Path.appendSuffix(Extension);
506 OutFile = Path.str();
507 } else {
508 OutFile = "-";
509 }
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000510
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000511 OwningPtr<llvm::raw_fd_ostream> OS;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000512 std::string OSFile;
513
514 if (UseTemporary && OutFile != "-") {
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000515 // Only create the temporary if the parent directory exists (or create
516 // missing directories is true) and we can actually write to OutPath,
517 // otherwise we want to fail early.
518 SmallString<256> AbsPath(OutputPath);
519 llvm::sys::fs::make_absolute(AbsPath);
520 llvm::sys::Path OutPath(AbsPath);
521 bool ParentExists = false;
522 if (llvm::sys::fs::exists(llvm::sys::path::parent_path(AbsPath.str()),
523 ParentExists))
524 ParentExists = false;
Michael J. Spencerf6efe582011-01-10 02:34:13 +0000525 bool Exists;
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000526 if ((CreateMissingDirectories || ParentExists) &&
527 ((llvm::sys::fs::exists(AbsPath.str(), Exists) || !Exists) ||
528 (OutPath.isRegularFile() && OutPath.canWrite()))) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000529 // Create a temporary file.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000530 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000531 TempPath = OutFile;
532 TempPath += "-%%%%%%%%";
533 int fd;
534 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
Eric Christopherf6a63462012-05-11 00:10:07 +0000535 /*makeAbsolute=*/false, 0664)
536 == llvm::errc::success) {
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000537 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
538 OSFile = TempFile = TempPath.str();
539 }
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000540 }
541 }
542
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000543 if (!OS) {
544 OSFile = OutFile;
545 OS.reset(
546 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
547 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
548 if (!Error.empty())
549 return 0;
550 }
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000551
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000552 // Make sure the out stream file gets removed if we crash.
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000553 if (RemoveFileOnSignal)
554 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000555
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000556 if (ResultPathName)
557 *ResultPathName = OutFile;
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000558 if (TempPathName)
559 *TempPathName = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000560
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000561 return OS.take();
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000562}
Daniel Dunbar409e8902009-11-14 07:53:04 +0000563
564// Initialization Utilities
565
Argyrios Kyrtzidis1b3240b2012-11-09 19:40:33 +0000566bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
567 return InitializeSourceManager(Input, getDiagnostics(),
Douglas Gregora686e1b2012-01-27 19:52:33 +0000568 getFileManager(), getSourceManager(),
569 getFrontendOpts());
Daniel Dunbar409e8902009-11-14 07:53:04 +0000570}
571
Argyrios Kyrtzidis1b3240b2012-11-09 19:40:33 +0000572bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
David Blaikie9c902b52011-09-25 23:23:43 +0000573 DiagnosticsEngine &Diags,
Daniel Dunbar409e8902009-11-14 07:53:04 +0000574 FileManager &FileMgr,
575 SourceManager &SourceMgr,
576 const FrontendOptions &Opts) {
Argyrios Kyrtzidis1b3240b2012-11-09 19:40:33 +0000577 SrcMgr::CharacteristicKind
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000578 Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
Argyrios Kyrtzidis1b3240b2012-11-09 19:40:33 +0000579
Argyrios Kyrtzidis6566e232012-11-09 19:40:45 +0000580 if (Input.isBuffer()) {
581 SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind);
582 assert(!SourceMgr.getMainFileID().isInvalid() &&
583 "Couldn't establish MainFileID!");
584 return true;
585 }
586
587 StringRef InputFile = Input.getFile();
588
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +0000589 // Figure out where to get and map in the main file.
590 if (InputFile != "-") {
Chris Lattner5159f612010-11-23 08:35:12 +0000591 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman52765212010-10-26 21:13:51 +0000592 if (!File) {
Daniel Dunbar409e8902009-11-14 07:53:04 +0000593 Diags.Report(diag::err_fe_error_reading) << InputFile;
594 return false;
595 }
Daniel Dunbare2951f42012-11-05 22:53:33 +0000596
597 // The natural SourceManager infrastructure can't currently handle named
598 // pipes, but we would at least like to accept them for the main
599 // file. Detect them here, read them with the more generic MemoryBuffer
600 // function, and simply override their contents as we do for STDIN.
601 if (File->isNamedPipe()) {
602 OwningPtr<llvm::MemoryBuffer> MB;
603 if (llvm::error_code ec = llvm::MemoryBuffer::getFile(InputFile, MB)) {
604 Diags.Report(diag::err_cannot_open_file) << InputFile << ec.message();
605 return false;
606 }
Daniel Dunbardb0745a2012-11-27 00:04:16 +0000607
608 // Create a new virtual file that will have the correct size.
609 File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0);
Daniel Dunbare2951f42012-11-05 22:53:33 +0000610 SourceMgr.overrideFileContents(File, MB.take());
611 }
Daniel Dunbardb0745a2012-11-27 00:04:16 +0000612
613 SourceMgr.createMainFileID(File, Kind);
Daniel Dunbar409e8902009-11-14 07:53:04 +0000614 } else {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000615 OwningPtr<llvm::MemoryBuffer> SB;
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000616 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000617 // FIXME: Give ec.message() in this diag.
Daniel Dunbar409e8902009-11-14 07:53:04 +0000618 Diags.Report(diag::err_fe_error_reading_stdin);
619 return false;
620 }
Dan Gohman2f76cd72010-10-26 23:21:25 +0000621 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner5159f612010-11-23 08:35:12 +0000622 SB->getBufferSize(), 0);
Douglas Gregora686e1b2012-01-27 19:52:33 +0000623 SourceMgr.createMainFileID(File, Kind);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000624 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbar409e8902009-11-14 07:53:04 +0000625 }
626
Dan Gohman52765212010-10-26 21:13:51 +0000627 assert(!SourceMgr.getMainFileID().isInvalid() &&
628 "Couldn't establish MainFileID!");
Daniel Dunbar409e8902009-11-14 07:53:04 +0000629 return true;
630}
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000631
632// High-Level Operations
633
634bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
635 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
636 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
637 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
638
639 // FIXME: Take this as an argument, once all the APIs we used have moved to
640 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000641 raw_ostream &OS = llvm::errs();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000642
643 // Create the target instance.
Douglas Gregorf8715de2012-11-16 04:24:59 +0000644 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), &getTargetOpts()));
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000645 if (!hasTarget())
646 return false;
647
648 // Inform the target of the language options.
649 //
650 // FIXME: We shouldn't need to do this, the target should be immutable once
651 // created. This complexity should be lifted elsewhere.
652 getTarget().setForcedLangOptions(getLangOpts());
653
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000654 // rewriter project will change target built-in bool type from its default.
655 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
656 getTarget().noSignedCharForObjCBool();
657
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000658 // Validate/process some options.
659 if (getHeaderSearchOpts().Verbose)
660 OS << "clang -cc1 version " CLANG_VERSION_STRING
661 << " based upon " << PACKAGE_STRING
Sebastian Pop8188c8a2011-11-01 21:33:06 +0000662 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000663
664 if (getFrontendOpts().ShowTimers)
665 createFrontendTimer();
666
Douglas Gregor171b7802010-03-30 17:33:59 +0000667 if (getFrontendOpts().ShowStats)
668 llvm::EnableStatistics();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000669
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000670 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000671 // Reset the ID tables if we are reusing the SourceManager.
672 if (hasSourceManager())
673 getSourceManager().clearIDTables();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000674
Douglas Gregor32fbe312012-01-20 16:28:04 +0000675 if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000676 Act.Execute();
677 Act.EndSourceFile();
678 }
679 }
680
Argyrios Kyrtzidis7910d7b2011-12-07 05:52:12 +0000681 // Notify the diagnostic client that all files were processed.
682 getDiagnostics().getClient()->finish();
683
Chris Lattner198cb4d2010-04-07 18:47:42 +0000684 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000685 // We can have multiple diagnostics sharing one diagnostic client.
686 // Get the total number of warnings/errors from the client.
687 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
688 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000689
Chris Lattner198cb4d2010-04-07 18:47:42 +0000690 if (NumWarnings)
691 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
692 if (NumWarnings && NumErrors)
693 OS << " and ";
694 if (NumErrors)
695 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
696 if (NumWarnings || NumErrors)
697 OS << " generated.\n";
698 }
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000699
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000700 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000701 getFileManager().PrintStats();
702 OS << "\n";
703 }
704
Argyrios Kyrtzidisbc467932010-11-18 21:13:57 +0000705 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000706}
707
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000708/// \brief Determine the appropriate source input kind based on language
709/// options.
710static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
711 if (LangOpts.OpenCL)
712 return IK_OpenCL;
713 if (LangOpts.CUDA)
714 return IK_CUDA;
715 if (LangOpts.ObjC1)
716 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
717 return LangOpts.CPlusPlus? IK_CXX : IK_C;
718}
719
Douglas Gregor51e0b542011-10-04 00:21:21 +0000720namespace {
Douglas Gregor514b6362011-11-29 19:06:37 +0000721 struct CompileModuleMapData {
722 CompilerInstance &Instance;
723 GenerateModuleAction &CreateModuleAction;
724 };
725}
726
727/// \brief Helper function that executes the module-generating action under
728/// a crash recovery context.
729static void doCompileMapModule(void *UserData) {
730 CompileModuleMapData &Data
731 = *reinterpret_cast<CompileModuleMapData *>(UserData);
732 Data.Instance.ExecuteAction(Data.CreateModuleAction);
733}
734
Douglas Gregor514b6362011-11-29 19:06:37 +0000735/// \brief Compile a module file for the given module, using the options
736/// provided by the importing compiler instance.
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000737static void compileModule(CompilerInstance &ImportingInstance,
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000738 SourceLocation ImportLoc,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000739 Module *Module,
Douglas Gregor6dc57922011-11-29 18:31:39 +0000740 StringRef ModuleFileName) {
Douglas Gregore2124892012-01-29 20:15:24 +0000741 llvm::LockFileManager Locked(ModuleFileName);
Douglas Gregor54a88812011-10-05 14:53:30 +0000742 switch (Locked) {
Douglas Gregore2124892012-01-29 20:15:24 +0000743 case llvm::LockFileManager::LFS_Error:
Douglas Gregor54a88812011-10-05 14:53:30 +0000744 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000745
Douglas Gregore2124892012-01-29 20:15:24 +0000746 case llvm::LockFileManager::LFS_Owned:
Douglas Gregor54a88812011-10-05 14:53:30 +0000747 // We're responsible for building the module ourselves. Do so below.
748 break;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000749
Douglas Gregore2124892012-01-29 20:15:24 +0000750 case llvm::LockFileManager::LFS_Shared:
Douglas Gregor54a88812011-10-05 14:53:30 +0000751 // Someone else is responsible for building the module. Wait for them to
752 // finish.
753 Locked.waitForUnlock();
Douglas Gregor188dbef2012-11-07 17:46:15 +0000754 return;
Douglas Gregor54a88812011-10-05 14:53:30 +0000755 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000756
Douglas Gregor514b6362011-11-29 19:06:37 +0000757 ModuleMap &ModMap
758 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
759
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000760 // Construct a compiler invocation for creating this module.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000761 IntrusiveRefCntPtr<CompilerInvocation> Invocation
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000762 (new CompilerInvocation(ImportingInstance.getInvocation()));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000763
Douglas Gregorf545f672011-11-29 21:59:16 +0000764 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
765
Douglas Gregor44bf68d2011-09-15 20:53:28 +0000766 // For any options that aren't intended to affect how a module is built,
767 // reset them to their default values.
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000768 Invocation->getLangOpts()->resetNonModularOptions();
Douglas Gregorf545f672011-11-29 21:59:16 +0000769 PPOpts.resetNonModularOptions();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000770
Douglas Gregor7d106e42011-11-15 19:35:01 +0000771 // Note the name of the module we're building.
Douglas Gregor6dc57922011-11-29 18:31:39 +0000772 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
Douglas Gregor7d106e42011-11-15 19:35:01 +0000773
Douglas Gregor7a626572012-11-29 23:55:25 +0000774 // Make sure that the failed-module structure has been allocated in
775 // the importing instance, and propagate the pointer to the newly-created
776 // instance.
777 PreprocessorOptions &ImportingPPOpts
778 = ImportingInstance.getInvocation().getPreprocessorOpts();
779 if (!ImportingPPOpts.FailedModules)
780 ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
781 PPOpts.FailedModules = ImportingPPOpts.FailedModules;
782
Douglas Gregorf545f672011-11-29 21:59:16 +0000783 // If there is a module map file, build the module using the module map.
Douglas Gregor44bf68d2011-09-15 20:53:28 +0000784 // Set up the inputs/outputs so that we build the module from its umbrella
785 // header.
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000786 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
Douglas Gregor1735f4e2011-09-13 23:15:45 +0000787 FrontendOpts.OutputFile = ModuleFileName.str();
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000788 FrontendOpts.DisableFree = false;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000789 FrontendOpts.GenerateModuleIndex = false;
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000790 FrontendOpts.Inputs.clear();
Douglas Gregorf545f672011-11-29 21:59:16 +0000791 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000792
Douglas Gregorf545f672011-11-29 21:59:16 +0000793 // Get or create the module map that we'll use to build this module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000794 SmallString<128> TempModuleMapFileName;
Douglas Gregorf545f672011-11-29 21:59:16 +0000795 if (const FileEntry *ModuleMapFile
796 = ModMap.getContainingModuleMapFile(Module)) {
797 // Use the module map where this module resides.
Douglas Gregor32fbe312012-01-20 16:28:04 +0000798 FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName(),
799 IK));
Douglas Gregorf545f672011-11-29 21:59:16 +0000800 } else {
801 // Create a temporary module map file.
802 TempModuleMapFileName = Module->Name;
803 TempModuleMapFileName += "-%%%%%%%%.map";
804 int FD;
805 if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
806 TempModuleMapFileName,
Douglas Gregor19f9f7b2011-12-06 22:05:29 +0000807 /*makeAbsolute=*/true)
Douglas Gregor2f554c42011-12-06 23:04:08 +0000808 != llvm::errc::success) {
Douglas Gregoree78d3e2011-12-07 00:54:14 +0000809 ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
810 << TempModuleMapFileName;
Douglas Gregorf545f672011-11-29 21:59:16 +0000811 return;
Douglas Gregor2f554c42011-12-06 23:04:08 +0000812 }
Douglas Gregorf545f672011-11-29 21:59:16 +0000813 // Print the module map to this file.
814 llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
815 Module->print(OS);
816 FrontendOpts.Inputs.push_back(
Douglas Gregor32fbe312012-01-20 16:28:04 +0000817 FrontendInputFile(TempModuleMapFileName.str().str(), IK));
Douglas Gregorf545f672011-11-29 21:59:16 +0000818 }
819
820 // Don't free the remapped file buffers; they are owned by our caller.
821 PPOpts.RetainRemappedFileBuffers = true;
822
Douglas Gregor2b9b4642011-09-13 01:26:44 +0000823 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
Douglas Gregor3728ea72011-09-13 23:20:27 +0000824 assert(ImportingInstance.getInvocation().getModuleHash() ==
Douglas Gregorf545f672011-11-29 21:59:16 +0000825 Invocation->getModuleHash() && "Module hash mismatch!");
826
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000827 // Construct a compiler instance that will be used to actually create the
828 // module.
829 CompilerInstance Instance;
830 Instance.setInvocation(&*Invocation);
Sean Silvaf1b49e22013-01-20 01:58:28 +0000831 Instance.createDiagnostics(&ImportingInstance.getDiagnosticClient(),
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000832 /*ShouldOwnClient=*/true,
833 /*ShouldCloneClient=*/true);
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000834
Douglas Gregor63365432012-11-30 22:11:57 +0000835 // Note that this module is part of the module build stack, so that we
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000836 // can detect cycles in the module graph.
837 Instance.createFileManager(); // FIXME: Adopt file manager from importer?
838 Instance.createSourceManager(Instance.getFileManager());
839 SourceManager &SourceMgr = Instance.getSourceManager();
Douglas Gregor63365432012-11-30 22:11:57 +0000840 SourceMgr.setModuleBuildStack(
841 ImportingInstance.getSourceManager().getModuleBuildStack());
842 SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000843 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
844
845
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000846 // Construct a module-generating action.
Douglas Gregorf545f672011-11-29 21:59:16 +0000847 GenerateModuleAction CreateModuleAction;
848
Douglas Gregor51e0b542011-10-04 00:21:21 +0000849 // Execute the action to actually build the module in-place. Use a separate
850 // thread so that we get a stack large enough.
851 const unsigned ThreadStackSize = 8 << 20;
852 llvm::CrashRecoveryContext CRC;
Douglas Gregorf545f672011-11-29 21:59:16 +0000853 CompileModuleMapData Data = { Instance, CreateModuleAction };
854 CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
855
856 // Delete the temporary module map file.
857 // FIXME: Even though we're executing under crash protection, it would still
858 // be nice to do this with RemoveFileOnSignal when we can. However, that
859 // doesn't make sense for all clients, so clean this up manually.
Benjamin Kramer13afbf42012-10-14 19:50:53 +0000860 Instance.clearOutputFiles(/*EraseFiles=*/true);
Douglas Gregorf545f672011-11-29 21:59:16 +0000861 if (!TempModuleMapFileName.empty())
862 llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
Douglas Gregor5e306b12013-01-23 22:38:11 +0000863
864 // We've rebuilt a module. If we're allowed to generate or update the global
865 // module index, record that fact in the importing compiler instance.
866 if (ImportingInstance.getFrontendOpts().GenerateModuleIndex) {
867 ImportingInstance.setBuildGlobalModuleIndex(true);
868 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000869}
Douglas Gregorfaeb1d42011-09-12 23:31:24 +0000870
Douglas Gregor7a626572012-11-29 23:55:25 +0000871ModuleLoadResult
872CompilerInstance::loadModule(SourceLocation ImportLoc,
873 ModuleIdPath Path,
874 Module::NameVisibilityKind Visibility,
875 bool IsInclusionDirective) {
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000876 // If we've already handled this import, just return the cached result.
877 // This one-element cache is important to eliminate redundant diagnostics
878 // when both the preprocessor and parser see the same import declaration.
Douglas Gregorff2be532011-12-01 17:11:21 +0000879 if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
880 // Make the named module visible.
881 if (LastModuleImportResult)
882 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
Douglas Gregor69021972011-11-30 17:33:56 +0000883 return LastModuleImportResult;
Douglas Gregorff2be532011-12-01 17:11:21 +0000884 }
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000885
Douglas Gregor08142532011-08-26 23:56:07 +0000886 // Determine what file we're searching from.
Douglas Gregor71944202011-11-30 00:36:36 +0000887 StringRef ModuleName = Path[0].first->getName();
888 SourceLocation ModuleNameLoc = Path[0].second;
Douglas Gregor5196bc62011-11-30 04:03:44 +0000889
Douglas Gregorde3ef502011-11-30 23:21:26 +0000890 clang::Module *Module = 0;
Douglas Gregor71944202011-11-30 00:36:36 +0000891
Douglas Gregor5196bc62011-11-30 04:03:44 +0000892 // If we don't already have information on this module, load the module now.
Douglas Gregorde3ef502011-11-30 23:21:26 +0000893 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
Douglas Gregor69021972011-11-30 17:33:56 +0000894 = KnownModules.find(Path[0].first);
Douglas Gregor2537a362011-12-08 17:01:29 +0000895 if (Known != KnownModules.end()) {
896 // Retrieve the cached top-level module.
897 Module = Known->second;
898 } else if (ModuleName == getLangOpts().CurrentModule) {
899 // This is the module we're building.
900 Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
901 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
902 } else {
Douglas Gregor5196bc62011-11-30 04:03:44 +0000903 // Search for a module with the given name.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000904 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
Douglas Gregor5196bc62011-11-30 04:03:44 +0000905 std::string ModuleFileName;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000906 if (Module)
907 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module);
908 else
909 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(ModuleName);
Douglas Gregor7a626572012-11-29 23:55:25 +0000910
Douglas Gregor279a6c32012-01-29 17:08:11 +0000911 if (ModuleFileName.empty()) {
912 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
913 << ModuleName
914 << SourceRange(ImportLoc, ModuleNameLoc);
915 LastModuleImportLoc = ImportLoc;
Douglas Gregor7a626572012-11-29 23:55:25 +0000916 LastModuleImportResult = ModuleLoadResult();
917 return LastModuleImportResult;
Douglas Gregor279a6c32012-01-29 17:08:11 +0000918 }
919
920 const FileEntry *ModuleFile
921 = getFileManager().getFile(ModuleFileName, /*OpenFile=*/false,
922 /*CacheFailure=*/false);
Douglas Gregor5196bc62011-11-30 04:03:44 +0000923 bool BuildingModule = false;
924 if (!ModuleFile && Module) {
925 // The module is not cached, but we have a module map from which we can
926 // build the module.
927
928 // Check whether there is a cycle in the module graph.
Douglas Gregor63365432012-11-30 22:11:57 +0000929 ModuleBuildStack Path = getSourceManager().getModuleBuildStack();
930 ModuleBuildStack::iterator Pos = Path.begin(), PosEnd = Path.end();
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000931 for (; Pos != PosEnd; ++Pos) {
932 if (Pos->first == ModuleName)
933 break;
934 }
935
936 if (Pos != PosEnd) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000937 SmallString<256> CyclePath;
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000938 for (; Pos != PosEnd; ++Pos) {
939 CyclePath += Pos->first;
Douglas Gregor5196bc62011-11-30 04:03:44 +0000940 CyclePath += " -> ";
941 }
942 CyclePath += ModuleName;
943
944 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
945 << ModuleName << CyclePath;
Douglas Gregor7a626572012-11-29 23:55:25 +0000946 return ModuleLoadResult();
947 }
948
949 // Check whether we have already attempted to build this module (but
950 // failed).
951 if (getPreprocessorOpts().FailedModules &&
952 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
953 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
954 << ModuleName
955 << SourceRange(ImportLoc, ModuleNameLoc);
956
957 return ModuleLoadResult();
Douglas Gregordff0e892011-09-15 20:40:10 +0000958 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000959
Douglas Gregor5196bc62011-11-30 04:03:44 +0000960 BuildingModule = true;
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000961 compileModule(*this, ModuleNameLoc, Module, ModuleFileName);
Douglas Gregor5196bc62011-11-30 04:03:44 +0000962 ModuleFile = FileMgr->getFile(ModuleFileName);
Douglas Gregor7a626572012-11-29 23:55:25 +0000963
Douglas Gregor0f2b4632013-01-10 02:04:18 +0000964 if (!ModuleFile && getPreprocessorOpts().FailedModules)
Douglas Gregor7a626572012-11-29 23:55:25 +0000965 getPreprocessorOpts().FailedModules->addFailed(ModuleName);
Douglas Gregor5196bc62011-11-30 04:03:44 +0000966 }
967
968 if (!ModuleFile) {
969 getDiagnostics().Report(ModuleNameLoc,
970 BuildingModule? diag::err_module_not_built
971 : diag::err_module_not_found)
972 << ModuleName
973 << SourceRange(ImportLoc, ModuleNameLoc);
Douglas Gregor7a626572012-11-29 23:55:25 +0000974 return ModuleLoadResult();
Douglas Gregordff0e892011-09-15 20:40:10 +0000975 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000976
Douglas Gregor5196bc62011-11-30 04:03:44 +0000977 // If we don't already have an ASTReader, create one now.
978 if (!ModuleManager) {
979 if (!hasASTContext())
980 createASTContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000981
Douglas Gregor5196bc62011-11-30 04:03:44 +0000982 std::string Sysroot = getHeaderSearchOpts().Sysroot;
983 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
984 ModuleManager = new ASTReader(getPreprocessor(), *Context,
985 Sysroot.empty() ? "" : Sysroot.c_str(),
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +0000986 PPOpts.DisablePCHValidation);
Douglas Gregor5196bc62011-11-30 04:03:44 +0000987 if (hasASTConsumer()) {
988 ModuleManager->setDeserializationListener(
989 getASTConsumer().GetASTDeserializationListener());
990 getASTContext().setASTMutationListener(
991 getASTConsumer().GetASTMutationListener());
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000992 getPreprocessor().setPPMutationListener(
993 getASTConsumer().GetPPMutationListener());
Douglas Gregor5196bc62011-11-30 04:03:44 +0000994 }
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000995 OwningPtr<ExternalASTSource> Source;
Douglas Gregor5196bc62011-11-30 04:03:44 +0000996 Source.reset(ModuleManager);
997 getASTContext().setExternalSource(Source);
998 if (hasSema())
999 ModuleManager->InitializeSema(getSema());
1000 if (hasASTConsumer())
1001 ModuleManager->StartTranslationUnit(&getASTConsumer());
Douglas Gregor21931ef2011-09-14 23:13:09 +00001002 }
Douglas Gregor5196bc62011-11-30 04:03:44 +00001003
1004 // Try to load the module we found.
Douglas Gregor188dbef2012-11-07 17:46:15 +00001005 unsigned ARRFlags = ASTReader::ARR_None;
1006 if (Module)
1007 ARRFlags |= ASTReader::ARR_OutOfDate;
Douglas Gregor5196bc62011-11-30 04:03:44 +00001008 switch (ModuleManager->ReadAST(ModuleFile->getName(),
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +00001009 serialization::MK_Module, ImportLoc,
Douglas Gregor188dbef2012-11-07 17:46:15 +00001010 ARRFlags)) {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001011 case ASTReader::Success:
1012 break;
1013
Douglas Gregor188dbef2012-11-07 17:46:15 +00001014 case ASTReader::OutOfDate: {
1015 // The module file is out-of-date. Rebuild it.
1016 getFileManager().invalidateCache(ModuleFile);
1017 bool Existed;
1018 llvm::sys::fs::remove(ModuleFileName, Existed);
Douglas Gregor7a626572012-11-29 23:55:25 +00001019
1020 // Check whether we have already attempted to build this module (but
1021 // failed).
1022 if (getPreprocessorOpts().FailedModules &&
1023 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1024 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1025 << ModuleName
1026 << SourceRange(ImportLoc, ModuleNameLoc);
1027
1028 return ModuleLoadResult();
1029 }
1030
Douglas Gregoraf8f0262012-11-30 18:38:50 +00001031 compileModule(*this, ModuleNameLoc, Module, ModuleFileName);
Douglas Gregor188dbef2012-11-07 17:46:15 +00001032
1033 // Try loading the module again.
1034 ModuleFile = FileMgr->getFile(ModuleFileName);
1035 if (!ModuleFile ||
1036 ModuleManager->ReadAST(ModuleFileName,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +00001037 serialization::MK_Module, ImportLoc,
Douglas Gregor188dbef2012-11-07 17:46:15 +00001038 ASTReader::ARR_None) != ASTReader::Success) {
Douglas Gregor0f2b4632013-01-10 02:04:18 +00001039 if (getPreprocessorOpts().FailedModules)
1040 getPreprocessorOpts().FailedModules->addFailed(ModuleName);
Douglas Gregor188dbef2012-11-07 17:46:15 +00001041 KnownModules[Path[0].first] = 0;
Douglas Gregor7a626572012-11-29 23:55:25 +00001042 return ModuleLoadResult();
Douglas Gregor188dbef2012-11-07 17:46:15 +00001043 }
1044
1045 // Okay, we've rebuilt and now loaded the module.
1046 break;
1047 }
1048
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +00001049 case ASTReader::VersionMismatch:
1050 case ASTReader::ConfigurationMismatch:
1051 case ASTReader::HadErrors:
Douglas Gregor5196bc62011-11-30 04:03:44 +00001052 // FIXME: The ASTReader will already have complained, but can we showhorn
1053 // that diagnostic information into a more useful form?
Douglas Gregor69021972011-11-30 17:33:56 +00001054 KnownModules[Path[0].first] = 0;
Douglas Gregor7a626572012-11-29 23:55:25 +00001055 return ModuleLoadResult();
Douglas Gregor5196bc62011-11-30 04:03:44 +00001056
1057 case ASTReader::Failure:
Douglas Gregor69021972011-11-30 17:33:56 +00001058 // Already complained, but note now that we failed.
1059 KnownModules[Path[0].first] = 0;
Douglas Gregor7a626572012-11-29 23:55:25 +00001060 return ModuleLoadResult();
Douglas Gregor5196bc62011-11-30 04:03:44 +00001061 }
1062
Douglas Gregor69021972011-11-30 17:33:56 +00001063 if (!Module) {
1064 // If we loaded the module directly, without finding a module map first,
1065 // we'll have loaded the module's information from the module itself.
1066 Module = PP->getHeaderSearchInfo().getModuleMap()
1067 .findModule((Path[0].first->getName()));
1068 }
Argyrios Kyrtzidis43af5132012-09-29 01:06:04 +00001069
1070 if (Module)
1071 Module->setASTFile(ModuleFile);
Douglas Gregor69021972011-11-30 17:33:56 +00001072
1073 // Cache the result of this top-level module lookup for later.
1074 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
Douglas Gregor08142532011-08-26 23:56:07 +00001075 }
Douglas Gregor5196bc62011-11-30 04:03:44 +00001076
Douglas Gregor69021972011-11-30 17:33:56 +00001077 // If we never found the module, fail.
1078 if (!Module)
Douglas Gregor7a626572012-11-29 23:55:25 +00001079 return ModuleLoadResult();
Douglas Gregor69021972011-11-30 17:33:56 +00001080
Douglas Gregor5196bc62011-11-30 04:03:44 +00001081 // Verify that the rest of the module path actually corresponds to
1082 // a submodule.
Douglas Gregor69021972011-11-30 17:33:56 +00001083 if (Path.size() > 1) {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001084 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1085 StringRef Name = Path[I].first->getName();
Douglas Gregoreb90e832012-01-04 23:32:19 +00001086 clang::Module *Sub = Module->findSubmodule(Name);
Douglas Gregor5196bc62011-11-30 04:03:44 +00001087
Douglas Gregoreb90e832012-01-04 23:32:19 +00001088 if (!Sub) {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001089 // Attempt to perform typo correction to find a module name that works.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001090 SmallVector<StringRef, 2> Best;
Douglas Gregor5196bc62011-11-30 04:03:44 +00001091 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1092
Douglas Gregoreb90e832012-01-04 23:32:19 +00001093 for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1094 JEnd = Module->submodule_end();
Matt Beaumont-Gayeb44eda2011-11-30 19:41:21 +00001095 J != JEnd; ++J) {
Douglas Gregoreb90e832012-01-04 23:32:19 +00001096 unsigned ED = Name.edit_distance((*J)->Name,
Douglas Gregor5196bc62011-11-30 04:03:44 +00001097 /*AllowReplacements=*/true,
1098 BestEditDistance);
1099 if (ED <= BestEditDistance) {
Douglas Gregoreb90e832012-01-04 23:32:19 +00001100 if (ED < BestEditDistance) {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001101 Best.clear();
Douglas Gregoreb90e832012-01-04 23:32:19 +00001102 BestEditDistance = ED;
1103 }
1104
1105 Best.push_back((*J)->Name);
Douglas Gregor5196bc62011-11-30 04:03:44 +00001106 }
1107 }
1108
1109 // If there was a clear winner, user it.
1110 if (Best.size() == 1) {
1111 getDiagnostics().Report(Path[I].second,
1112 diag::err_no_submodule_suggest)
Douglas Gregor69021972011-11-30 17:33:56 +00001113 << Path[I].first << Module->getFullModuleName() << Best[0]
Douglas Gregor5196bc62011-11-30 04:03:44 +00001114 << SourceRange(Path[0].second, Path[I-1].second)
1115 << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1116 Best[0]);
Douglas Gregoreb90e832012-01-04 23:32:19 +00001117
1118 Sub = Module->findSubmodule(Best[0]);
Douglas Gregor5196bc62011-11-30 04:03:44 +00001119 }
1120 }
1121
Douglas Gregoreb90e832012-01-04 23:32:19 +00001122 if (!Sub) {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001123 // No submodule by this name. Complain, and don't look for further
1124 // submodules.
1125 getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
Douglas Gregor69021972011-11-30 17:33:56 +00001126 << Path[I].first << Module->getFullModuleName()
Douglas Gregor5196bc62011-11-30 04:03:44 +00001127 << SourceRange(Path[0].second, Path[I-1].second);
1128 break;
1129 }
1130
Douglas Gregoreb90e832012-01-04 23:32:19 +00001131 Module = Sub;
Douglas Gregor5196bc62011-11-30 04:03:44 +00001132 }
Douglas Gregor08142532011-08-26 23:56:07 +00001133 }
Douglas Gregor5196bc62011-11-30 04:03:44 +00001134
Douglas Gregor2537a362011-12-08 17:01:29 +00001135 // Make the named module visible, if it's not already part of the module
1136 // we are parsing.
Douglas Gregor98a52db2011-12-20 00:28:52 +00001137 if (ModuleName != getLangOpts().CurrentModule) {
1138 if (!Module->IsFromModuleFile) {
1139 // We have an umbrella header or directory that doesn't actually include
1140 // all of the headers within the directory it covers. Complain about
1141 // this missing submodule and recover by forgetting that we ever saw
1142 // this submodule.
1143 // FIXME: Should we detect this at module load time? It seems fairly
1144 // expensive (and rare).
1145 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1146 << Module->getFullModuleName()
1147 << SourceRange(Path.front().second, Path.back().second);
1148
Douglas Gregor7a626572012-11-29 23:55:25 +00001149 return ModuleLoadResult(0, true);
Douglas Gregor98a52db2011-12-20 00:28:52 +00001150 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00001151
1152 // Check whether this module is available.
1153 StringRef Feature;
Douglas Gregor89929282012-01-30 06:01:29 +00001154 if (!Module->isAvailable(getLangOpts(), getTarget(), Feature)) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00001155 getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1156 << Module->getFullModuleName()
1157 << Feature
1158 << SourceRange(Path.front().second, Path.back().second);
1159 LastModuleImportLoc = ImportLoc;
Douglas Gregor7a626572012-11-29 23:55:25 +00001160 LastModuleImportResult = ModuleLoadResult();
1161 return ModuleLoadResult();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00001162 }
1163
Douglas Gregor2537a362011-12-08 17:01:29 +00001164 ModuleManager->makeModuleVisible(Module, Visibility);
Douglas Gregor98a52db2011-12-20 00:28:52 +00001165 }
1166
Douglas Gregorbcfc7d02011-12-02 23:42:12 +00001167 // If this module import was due to an inclusion directive, create an
1168 // implicit import declaration to capture it in the AST.
1169 if (IsInclusionDirective && hasASTContext()) {
1170 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
Argyrios Kyrtzidis72d1aa32012-10-03 01:58:37 +00001171 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
1172 ImportLoc, Module,
1173 Path.back().second);
1174 TU->addDecl(ImportD);
1175 if (Consumer)
1176 Consumer->HandleImplicitImportDecl(ImportD);
Douglas Gregorbcfc7d02011-12-02 23:42:12 +00001177 }
Douglas Gregor5196bc62011-11-30 04:03:44 +00001178
Douglas Gregor1805b8a2011-11-30 04:26:53 +00001179 LastModuleImportLoc = ImportLoc;
Douglas Gregor7a626572012-11-29 23:55:25 +00001180 LastModuleImportResult = ModuleLoadResult(Module, false);
1181 return LastModuleImportResult;
Douglas Gregor08142532011-08-26 23:56:07 +00001182}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00001183
1184void CompilerInstance::makeModuleVisible(Module *Mod,
1185 Module::NameVisibilityKind Visibility){
1186 ModuleManager->makeModuleVisible(Mod, Visibility);
1187}
1188