blob: 306d7c08e1fb8731f921bc0501de3dd876b6bcc4 [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"
Richard Smith9565c75b2017-06-19 23:09:36 +000014#include "clang/Basic/CharInfo.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000015#include "clang/Basic/Diagnostic.h"
Daniel Dunbar546a6762009-11-13 04:12:06 +000016#include "clang/Basic/FileManager.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000017#include "clang/Basic/MemoryBufferCache.h"
Daniel Dunbar546a6762009-11-13 04:12:06 +000018#include "clang/Basic/SourceManager.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000019#include "clang/Basic/TargetInfo.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000020#include "clang/Basic/Version.h"
Alp Tokerf988d002014-06-06 10:36:22 +000021#include "clang/Config/config.h"
David Blaikie8b00dcb2011-09-26 00:21:47 +000022#include "clang/Frontend/ChainedDiagnosticConsumer.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Douglas Gregorfaeb1d42011-09-12 23:31:24 +000024#include "clang/Frontend/FrontendActions.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar2083c322011-04-07 18:31:10 +000026#include "clang/Frontend/LogDiagnosticPrinter.h"
Ted Kremenek4610ea22011-10-29 00:12:39 +000027#include "clang/Frontend/SerializedDiagnosticPrinter.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000028#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbaraaa148f2009-11-13 05:52:11 +000029#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Frontend/VerifyDiagnosticConsumer.h"
31#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/PTHManager.h"
33#include "clang/Lex/Preprocessor.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000034#include "clang/Lex/PreprocessorOptions.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000035#include "clang/Sema/CodeCompleteConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Sema/Sema.h"
37#include "clang/Serialization/ASTReader.h"
John Thompson2255f2c2014-04-23 12:57:01 +000038#include "clang/Serialization/GlobalModuleIndex.h"
Douglas Gregor171b7802010-03-30 17:33:59 +000039#include "llvm/ADT/Statistic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/CrashRecoveryContext.h"
Rafael Espindola71de0b62014-06-13 17:20:50 +000041#include "llvm/Support/Errc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000043#include "llvm/Support/Host.h"
Douglas Gregore2124892012-01-29 20:15:24 +000044#include "llvm/Support/LockFileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000046#include "llvm/Support/Path.h"
47#include "llvm/Support/Program.h"
48#include "llvm/Support/Signals.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include "llvm/Support/Timer.h"
50#include "llvm/Support/raw_ostream.h"
Douglas Gregor527b1c92013-03-25 21:19:16 +000051#include <sys/stat.h>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000052#include <system_error>
Douglas Gregor37da3272013-03-25 21:51:16 +000053#include <time.h>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000054#include <utility>
Douglas Gregor54a88812011-10-05 14:53:30 +000055
Daniel Dunbar636404a2009-11-13 03:51:44 +000056using namespace clang;
57
Adrian Prantlbb165fb2015-06-20 18:53:08 +000058CompilerInstance::CompilerInstance(
59 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000060 MemoryBufferCache *SharedPCMCache)
61 : ModuleLoader(/* BuildingModule = */ SharedPCMCache),
62 Invocation(new CompilerInvocation()),
63 PCMCache(SharedPCMCache ? SharedPCMCache : new MemoryBufferCache),
64 ThePCHContainerOperations(std::move(PCHContainerOps)) {
65 // Don't allow this to invalidate buffers in use by others.
66 if (SharedPCMCache)
67 getPCMCache().finalizeCurrentBuffers();
68}
Daniel Dunbar636404a2009-11-13 03:51:44 +000069
70CompilerInstance::~CompilerInstance() {
Benjamin Kramer3c717b42012-10-14 19:21:21 +000071 assert(OutputFiles.empty() && "Still output files in flight?");
Daniel Dunbare922d9b2010-02-16 01:54:47 +000072}
73
David Blaikieea4395e2017-01-06 19:49:01 +000074void CompilerInstance::setInvocation(
75 std::shared_ptr<CompilerInvocation> Value) {
76 Invocation = std::move(Value);
Daniel Dunbar68242252010-01-30 21:47:07 +000077}
78
Douglas Gregorc1bbec82013-01-25 00:45:27 +000079bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
Douglas Gregore060e572013-01-25 01:03:03 +000080 return (BuildGlobalModuleIndex ||
Douglas Gregor11ef0b72013-03-22 21:26:48 +000081 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
82 getFrontendOpts().GenerateGlobalModuleIndex)) &&
Douglas Gregore060e572013-01-25 01:03:03 +000083 !ModuleBuildFailed;
Douglas Gregorc1bbec82013-01-25 00:45:27 +000084}
85
David Blaikie9c902b52011-09-25 23:23:43 +000086void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Douglas Gregor7f95d262010-04-05 23:52:57 +000087 Diagnostics = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000088}
89
Artem Belevichb5bc9232015-09-22 17:23:22 +000090void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
91void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
Daniel Dunbare01dc862009-11-14 01:20:40 +000092
93void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000094 FileMgr = Value;
Ben Langmuirc8130a72014-02-20 21:59:23 +000095 if (Value)
96 VirtualFileSystem = Value->getVirtualFileSystem();
97 else
98 VirtualFileSystem.reset();
Daniel Dunbare01dc862009-11-14 01:20:40 +000099}
100
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000101void CompilerInstance::setSourceManager(SourceManager *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000102 SourceMgr = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +0000103}
104
David Blaikie41565462017-01-05 19:48:07 +0000105void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
106 PP = std::move(Value);
107}
Daniel Dunbare01dc862009-11-14 01:20:40 +0000108
Richard Smith293534b2015-08-18 20:39:29 +0000109void CompilerInstance::setASTContext(ASTContext *Value) {
110 Context = Value;
111
112 if (Context && Consumer)
113 getASTConsumer().Initialize(getASTContext());
114}
Daniel Dunbare01dc862009-11-14 01:20:40 +0000115
Douglas Gregor0e93f012010-08-12 23:31:19 +0000116void CompilerInstance::setSema(Sema *S) {
117 TheSema.reset(S);
118}
119
David Blaikie6beb6aa2014-08-10 19:56:51 +0000120void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
121 Consumer = std::move(Value);
Richard Smith293534b2015-08-18 20:39:29 +0000122
123 if (Context && Consumer)
124 getASTConsumer().Initialize(getASTContext());
Daniel Dunbar56d9c292009-11-14 02:47:17 +0000125}
126
Daniel Dunbare01dc862009-11-14 01:20:40 +0000127void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
128 CompletionConsumer.reset(Value);
129}
David Blaikie61535812014-08-10 20:12:39 +0000130
131std::unique_ptr<Sema> CompilerInstance::takeSema() {
132 return std::move(TheSema);
133}
134
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000135IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
136 return ModuleManager;
137}
138void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000139 assert(PCMCache.get() == &Reader->getModuleManager().getPCMCache() &&
140 "Expected ASTReader to use the same PCM cache");
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000141 ModuleManager = std::move(Reader);
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000142}
Daniel Dunbare01dc862009-11-14 01:20:40 +0000143
Justin Bogner86d12592014-06-19 19:36:03 +0000144std::shared_ptr<ModuleDependencyCollector>
145CompilerInstance::getModuleDepCollector() const {
146 return ModuleDepCollector;
147}
148
149void CompilerInstance::setModuleDepCollector(
150 std::shared_ptr<ModuleDependencyCollector> Collector) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000151 ModuleDepCollector = std::move(Collector);
Justin Bogner86d12592014-06-19 19:36:03 +0000152}
153
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000154static void collectHeaderMaps(const HeaderSearch &HS,
155 std::shared_ptr<ModuleDependencyCollector> MDC) {
156 SmallVector<std::string, 4> HeaderMapFileNames;
157 HS.getHeaderMapFileNames(HeaderMapFileNames);
158 for (auto &Name : HeaderMapFileNames)
159 MDC->addFile(Name);
160}
161
Bruno Cardoso Lopes7aff2bb2016-12-12 19:28:25 +0000162static void collectIncludePCH(CompilerInstance &CI,
163 std::shared_ptr<ModuleDependencyCollector> MDC) {
164 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
165 if (PPOpts.ImplicitPCHInclude.empty())
166 return;
167
168 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
169 FileManager &FileMgr = CI.getFileManager();
170 const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude);
171 if (!PCHDir) {
172 MDC->addFile(PCHInclude);
173 return;
174 }
175
176 std::error_code EC;
177 SmallString<128> DirNative;
178 llvm::sys::path::native(PCHDir->getName(), DirNative);
179 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
180 SimpleASTReaderListener Validator(CI.getPreprocessor());
181 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
182 Dir != DirEnd && !EC; Dir.increment(EC)) {
183 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
184 // used here since we're not interested in validating the PCH at this time,
185 // but only to check whether this is a file containing an AST.
186 if (!ASTReader::readASTFileControlBlock(
187 Dir->getName(), FileMgr, CI.getPCHContainerReader(),
188 /*FindModuleFileExtensions=*/false, Validator,
189 /*ValidateDiagnosticOptions=*/false))
190 MDC->addFile(Dir->getName());
191 }
192}
193
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +0000194static void collectVFSEntries(CompilerInstance &CI,
195 std::shared_ptr<ModuleDependencyCollector> MDC) {
196 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
197 return;
198
199 // Collect all VFS found.
200 SmallVector<vfs::YAMLVFSEntry, 16> VFSEntries;
201 for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
202 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
203 llvm::MemoryBuffer::getFile(VFSFile);
204 if (!Buffer)
205 return;
206 vfs::collectVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr,
207 VFSFile, VFSEntries);
208 }
209
210 for (auto &E : VFSEntries)
211 MDC->addFile(E.VPath, E.RPath);
212}
213
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000214// Diagnostics
Douglas Gregor811db4e2012-10-23 22:26:28 +0000215static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
Daniel Dunbar7b833062011-04-07 18:59:02 +0000216 const CodeGenOptions *CodeGenOpts,
David Blaikie9c902b52011-09-25 23:23:43 +0000217 DiagnosticsEngine &Diags) {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000218 std::error_code EC;
David Blaikie11f8a942014-09-15 17:30:56 +0000219 std::unique_ptr<raw_ostream> StreamOwner;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000220 raw_ostream *OS = &llvm::errs();
Douglas Gregor811db4e2012-10-23 22:26:28 +0000221 if (DiagOpts->DiagnosticLogFile != "-") {
Daniel Dunbar2083c322011-04-07 18:31:10 +0000222 // Create the output stream.
David Blaikie11f8a942014-09-15 17:30:56 +0000223 auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
Rafael Espindoladae941a2014-08-25 18:17:04 +0000224 DiagOpts->DiagnosticLogFile, EC,
David Blaikie11f8a942014-09-15 17:30:56 +0000225 llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
Rafael Espindoladae941a2014-08-25 18:17:04 +0000226 if (EC) {
Daniel Dunbar2083c322011-04-07 18:31:10 +0000227 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
Rafael Espindoladae941a2014-08-25 18:17:04 +0000228 << DiagOpts->DiagnosticLogFile << EC.message();
Daniel Dunbar2083c322011-04-07 18:31:10 +0000229 } else {
230 FileOS->SetUnbuffered();
David Blaikie11f8a942014-09-15 17:30:56 +0000231 OS = FileOS.get();
232 StreamOwner = std::move(FileOS);
Daniel Dunbar2083c322011-04-07 18:31:10 +0000233 }
234 }
235
236 // Chain in the diagnostic client which will log the diagnostics.
David Blaikie7ee25502014-09-15 17:50:10 +0000237 auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
238 std::move(StreamOwner));
Daniel Dunbar7b833062011-04-07 18:59:02 +0000239 if (CodeGenOpts)
240 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
David Blaikie7ee25502014-09-15 17:50:10 +0000241 assert(Diags.ownsClient());
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000242 Diags.setClient(
243 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
Daniel Dunbar2083c322011-04-07 18:31:10 +0000244}
245
Douglas Gregor811db4e2012-10-23 22:26:28 +0000246static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
Ted Kremenek4610ea22011-10-29 00:12:39 +0000247 DiagnosticsEngine &Diags,
248 StringRef OutputFile) {
David Blaikie7ee25502014-09-15 17:50:10 +0000249 auto SerializedConsumer =
Justin Bogner5a6a2fc2014-10-23 22:20:11 +0000250 clang::serialized_diags::create(OutputFile, DiagOpts);
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000251
Alexander Kornienko254b7db2014-11-13 13:08:27 +0000252 if (Diags.ownsClient()) {
253 Diags.setClient(new ChainedDiagnosticConsumer(
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000254 Diags.takeClient(), std::move(SerializedConsumer)));
Alexander Kornienko254b7db2014-11-13 13:08:27 +0000255 } else {
256 Diags.setClient(new ChainedDiagnosticConsumer(
Alexander Kornienko4c0ef3792014-11-17 14:46:28 +0000257 Diags.getClient(), std::move(SerializedConsumer)));
Alexander Kornienko254b7db2014-11-13 13:08:27 +0000258 }
Ted Kremenek4610ea22011-10-29 00:12:39 +0000259}
260
Sean Silvaf1b49e22013-01-20 01:58:28 +0000261void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000262 bool ShouldOwnClient) {
Sean Silvaf1b49e22013-01-20 01:58:28 +0000263 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000264 ShouldOwnClient, &getCodeGenOpts());
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000265}
266
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000267IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor811db4e2012-10-23 22:26:28 +0000268CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
David Blaikiee2eefae2011-09-25 23:39:51 +0000269 DiagnosticConsumer *Client,
Douglas Gregor2b9b4642011-09-13 01:26:44 +0000270 bool ShouldOwnClient,
Daniel Dunbar7b833062011-04-07 18:59:02 +0000271 const CodeGenOptions *CodeGenOpts) {
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000272 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
273 IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor811db4e2012-10-23 22:26:28 +0000274 Diags(new DiagnosticsEngine(DiagID, Opts));
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000275
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000276 // Create the diagnostic client for reporting errors or for
277 // implementing -verify.
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000278 if (Client) {
Douglas Gregor30071cea2013-05-03 23:07:45 +0000279 Diags->setClient(Client, ShouldOwnClient);
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000280 } else
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000281 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbar50ec0da2009-11-14 03:24:39 +0000282
283 // Chain in -verify checker, if requested.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000284 if (Opts->VerifyDiagnostics)
David Blaikie69609dc2011-09-26 00:38:03 +0000285 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000286
Daniel Dunbar2083c322011-04-07 18:31:10 +0000287 // Chain in -diagnostic-log-file dumper, if requested.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000288 if (!Opts->DiagnosticLogFile.empty())
Daniel Dunbar7b833062011-04-07 18:59:02 +0000289 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000290
Douglas Gregor811db4e2012-10-23 22:26:28 +0000291 if (!Opts->DiagnosticSerializationFile.empty())
Ted Kremenek4610ea22011-10-29 00:12:39 +0000292 SetupSerializedDiagnostics(Opts, *Diags,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000293 Opts->DiagnosticSerializationFile);
Ted Kremenek4610ea22011-10-29 00:12:39 +0000294
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000295 // Configure our handling of diagnostics.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000296 ProcessWarningOptions(*Diags, *Opts);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000297
Douglas Gregor7f95d262010-04-05 23:52:57 +0000298 return Diags;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000299}
300
301// File Manager
302
Raphael Isemannabc3d042017-09-12 16:54:53 +0000303FileManager *CompilerInstance::createFileManager() {
Ben Langmuirc8130a72014-02-20 21:59:23 +0000304 if (!hasVirtualFileSystem()) {
Raphael Isemannabc3d042017-09-12 16:54:53 +0000305 if (IntrusiveRefCntPtr<vfs::FileSystem> VFS =
306 createVFSFromCompilerInvocation(getInvocation(), getDiagnostics()))
307 setVirtualFileSystem(VFS);
308 else
309 return nullptr;
Ben Langmuirc8130a72014-02-20 21:59:23 +0000310 }
311 FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
Raphael Isemannabc3d042017-09-12 16:54:53 +0000312 return FileMgr.get();
Daniel Dunbar546a6762009-11-13 04:12:06 +0000313}
314
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000315// Source Manager
316
Chris Lattner5159f612010-11-23 08:35:12 +0000317void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000318 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar546a6762009-11-13 04:12:06 +0000319}
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000320
Alp Tokerc3580002014-07-07 06:05:00 +0000321// Initialize the remapping of files to alternative contents, e.g.,
322// those specified through other files.
323static void InitializeFileRemapping(DiagnosticsEngine &Diags,
324 SourceManager &SourceMgr,
325 FileManager &FileMgr,
326 const PreprocessorOptions &InitOpts) {
327 // Remap files in the source manager (with buffers).
Alp Toker1b070d22014-07-07 07:47:20 +0000328 for (const auto &RB : InitOpts.RemappedFileBuffers) {
Alp Tokerc3580002014-07-07 06:05:00 +0000329 // Create the file entry for the file that we're mapping from.
330 const FileEntry *FromFile =
Alp Toker1b070d22014-07-07 07:47:20 +0000331 FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
Alp Tokerc3580002014-07-07 06:05:00 +0000332 if (!FromFile) {
Alp Toker1b070d22014-07-07 07:47:20 +0000333 Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
Alp Tokerc3580002014-07-07 06:05:00 +0000334 if (!InitOpts.RetainRemappedFileBuffers)
Alp Toker1b070d22014-07-07 07:47:20 +0000335 delete RB.second;
Alp Tokerc3580002014-07-07 06:05:00 +0000336 continue;
337 }
338
339 // Override the contents of the "from" file with the contents of
340 // the "to" file.
Alp Toker1b070d22014-07-07 07:47:20 +0000341 SourceMgr.overrideFileContents(FromFile, RB.second,
Alp Tokerc3580002014-07-07 06:05:00 +0000342 InitOpts.RetainRemappedFileBuffers);
343 }
344
345 // Remap files in the source manager (with other files).
Alp Toker1b070d22014-07-07 07:47:20 +0000346 for (const auto &RF : InitOpts.RemappedFiles) {
Alp Tokerc3580002014-07-07 06:05:00 +0000347 // Find the file that we're mapping to.
Alp Toker1b070d22014-07-07 07:47:20 +0000348 const FileEntry *ToFile = FileMgr.getFile(RF.second);
Alp Tokerc3580002014-07-07 06:05:00 +0000349 if (!ToFile) {
Alp Toker1b070d22014-07-07 07:47:20 +0000350 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
Alp Tokerc3580002014-07-07 06:05:00 +0000351 continue;
352 }
353
354 // Create the file entry for the file that we're mapping from.
355 const FileEntry *FromFile =
Alp Toker1b070d22014-07-07 07:47:20 +0000356 FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
Alp Tokerc3580002014-07-07 06:05:00 +0000357 if (!FromFile) {
Alp Toker1b070d22014-07-07 07:47:20 +0000358 Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
Alp Tokerc3580002014-07-07 06:05:00 +0000359 continue;
360 }
361
362 // Override the contents of the "from" file with the contents of
363 // the "to" file.
364 SourceMgr.overrideFileContents(FromFile, ToFile);
365 }
366
367 SourceMgr.setOverridenFilesKeepOriginalName(
368 InitOpts.RemappedFilesKeepOriginalName);
369}
370
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000371// Preprocessor
372
Argyrios Kyrtzidise1974dc2014-03-07 07:47:58 +0000373void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
Douglas Gregor08142532011-08-26 23:56:07 +0000374 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000375
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000376 // Create a PTH manager if we are using some form of a token cache.
Craig Topper49a27902014-05-22 04:46:25 +0000377 PTHManager *PTHMgr = nullptr;
Daniel Dunbard6ea9022009-11-17 05:52:41 +0000378 if (!PPOpts.TokenCache.empty())
Douglas Gregor08142532011-08-26 23:56:07 +0000379 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000380
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000381 // Create the Preprocessor.
David Blaikie9c28cb32017-01-06 01:04:46 +0000382 HeaderSearch *HeaderInfo =
383 new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
384 getDiagnostics(), getLangOpts(), &getTarget());
David Blaikie41565462017-01-05 19:48:07 +0000385 PP = std::make_shared<Preprocessor>(
386 Invocation->getPreprocessorOptsPtr(), getDiagnostics(), getLangOpts(),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000387 getSourceManager(), getPCMCache(), *HeaderInfo, *this, PTHMgr,
David Blaikie41565462017-01-05 19:48:07 +0000388 /*OwnsHeaderSearch=*/true, TUKind);
Saleem Abdulrasool729379a2017-10-06 23:09:55 +0000389 getTarget().adjust(getLangOpts());
Artem Belevichb5bc9232015-09-22 17:23:22 +0000390 PP->Initialize(getTarget(), getAuxTarget());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000391
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000392 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
393 // That argument is used as the IdentifierInfoLookup argument to
394 // IdentifierTable's ctor.
395 if (PTHMgr) {
Douglas Gregor08142532011-08-26 23:56:07 +0000396 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000397 PP->setPTHManager(PTHMgr);
398 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000399
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000400 if (PPOpts.DetailedRecord)
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000401 PP->createPreprocessingRecord();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000402
Alp Tokerc3580002014-07-07 06:05:00 +0000403 // Apply remappings to the source manager.
404 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
405 PP->getFileManager(), PPOpts);
406
407 // Predefine macros and configure the preprocessor.
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000408 InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000409 getFrontendOpts());
Alp Tokerc3580002014-07-07 06:05:00 +0000410
Justin Lebarf91086b2016-11-18 00:41:27 +0000411 // Initialize the header search object. In CUDA compilations, we use the aux
412 // triple (the host triple) to initialize our header search, since we need to
413 // find the host headers in order to compile the CUDA code.
414 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
415 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
416 PP->getAuxTargetInfo())
417 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
418
Alp Tokerc3580002014-07-07 06:05:00 +0000419 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
Justin Lebarf91086b2016-11-18 00:41:27 +0000420 PP->getLangOpts(), *HeaderSearchTriple);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000421
Jordan Rose17441582013-01-30 01:52:57 +0000422 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
423
Richard Smith3938f0c2015-08-15 00:34:15 +0000424 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
Chandler Carruthff8d9432015-03-28 01:10:44 +0000425 PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000426
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000427 // Handle generating dependencies, if requested.
Douglas Gregor08142532011-08-26 23:56:07 +0000428 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000429 if (!DepOpts.OutputFile.empty())
Ben Langmuircb69b572014-03-07 06:40:32 +0000430 TheDependencyFileGenerator.reset(
431 DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
Douglas Gregor2e129652012-02-02 23:45:13 +0000432 if (!DepOpts.DOTOutputFile.empty())
433 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
Douglas Gregor83d46be2012-02-02 00:54:52 +0000434 getHeaderSearchOpts().Sysroot);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000435
Justin Bogner86d12592014-06-19 19:36:03 +0000436 // If we don't have a collector, but we are collecting module dependencies,
437 // then we're the top level compiler instance and need to create one.
Bruno Cardoso Lopesb1631d92016-03-29 23:47:40 +0000438 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
Justin Bogner86d12592014-06-19 19:36:03 +0000439 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
440 DepOpts.ModuleDependencyOutputDir);
Bruno Cardoso Lopesb1631d92016-03-29 23:47:40 +0000441 }
442
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000443 // If there is a module dep collector, register with other dep collectors
444 // and also (a) collect header maps and (b) TODO: input vfs overlay files.
445 if (ModuleDepCollector) {
Bruno Cardoso Lopesb1631d92016-03-29 23:47:40 +0000446 addDependencyCollector(ModuleDepCollector);
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000447 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
Bruno Cardoso Lopes7aff2bb2016-12-12 19:28:25 +0000448 collectIncludePCH(*this, ModuleDepCollector);
Bruno Cardoso Lopes82ec4fde2016-12-22 07:06:03 +0000449 collectVFSEntries(*this, ModuleDepCollector);
Bruno Cardoso Lopes181225b2016-12-11 04:27:28 +0000450 }
Bruno Cardoso Lopesb1631d92016-03-29 23:47:40 +0000451
452 for (auto &Listener : DependencyCollectors)
453 Listener->attachToPreprocessor(*PP);
Hans Wennborg0fd62072013-08-09 00:32:23 +0000454
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000455 // Handle generating header include information, if requested.
456 if (DepOpts.ShowHeaderIncludes)
Nico Weberf54146c2016-03-23 18:46:57 +0000457 AttachHeaderIncludeGen(*PP, DepOpts);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000458 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000459 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000460 if (OutputPath == "-")
461 OutputPath = "";
Nico Weberf54146c2016-03-23 18:46:57 +0000462 AttachHeaderIncludeGen(*PP, DepOpts,
Ivan Krasin1193f2c2015-08-13 04:04:37 +0000463 /*ShowAllHeaders=*/true, OutputPath,
Daniel Dunbarfe908a82011-03-21 19:37:38 +0000464 /*ShowDepth=*/false);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000465 }
Hans Wennborg0fd62072013-08-09 00:32:23 +0000466
467 if (DepOpts.PrintShowIncludes) {
Nico Weberf54146c2016-03-23 18:46:57 +0000468 AttachHeaderIncludeGen(*PP, DepOpts,
Nico Weber149d95222016-03-23 18:00:22 +0000469 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
Hans Wennborg0fd62072013-08-09 00:32:23 +0000470 /*ShowDepth=*/true, /*MSStyle=*/true);
471 }
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000472}
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000473
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000474std::string CompilerInstance::getSpecificModuleCachePath() {
475 // Set up the module path, including the hash for the
476 // module-creation options.
Richard Smithd520a252015-07-21 18:07:47 +0000477 SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
478 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000479 llvm::sys::path::append(SpecificModuleCache,
480 getInvocation().getModuleHash());
481 return SpecificModuleCache.str();
482}
483
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000484// ASTContext
485
486void CompilerInstance::createASTContext() {
487 Preprocessor &PP = getPreprocessor();
Richard Smith293534b2015-08-18 20:39:29 +0000488 auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
489 PP.getIdentifierTable(), PP.getSelectorTable(),
490 PP.getBuiltinInfo());
Artem Belevichb5bc9232015-09-22 17:23:22 +0000491 Context->InitBuiltinTypes(getTarget(), getAuxTarget());
Richard Smith293534b2015-08-18 20:39:29 +0000492 setASTContext(Context);
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000493}
Daniel Dunbar599313e2009-11-13 08:21:10 +0000494
495// ExternalASTSource
496
Nico Weber824285e2014-05-08 04:26:47 +0000497void CompilerInstance::createPCHExternalASTSource(
498 StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
499 void *DeserializationListener, bool OwnDeserializationListener) {
Sebastian Redl009e7f22010-10-05 16:15:19 +0000500 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Richard Smith4eca9b92015-02-04 23:37:59 +0000501 ModuleManager = createPCHExternalASTSource(
Nico Weber824285e2014-05-08 04:26:47 +0000502 Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
503 AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000504 getPCHContainerReader(),
505 getFrontendOpts().ModuleFileExtensions,
Graydon Hoarece539b52017-03-29 17:33:09 +0000506 TheDependencyFileGenerator.get(),
507 DependencyCollectors,
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000508 DeserializationListener,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000509 OwnDeserializationListener, Preamble,
Nico Weber824285e2014-05-08 04:26:47 +0000510 getFrontendOpts().UseGlobalModuleIndex);
Daniel Dunbar599313e2009-11-13 08:21:10 +0000511}
512
Richard Smith4eca9b92015-02-04 23:37:59 +0000513IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
Yaron Keren5b816062015-07-06 08:47:15 +0000514 StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
Nico Weber824285e2014-05-08 04:26:47 +0000515 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000516 const PCHContainerReader &PCHContainerRdr,
David Blaikie61137e12017-01-05 18:23:18 +0000517 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
Graydon Hoarece539b52017-03-29 17:33:09 +0000518 DependencyFileGenerator *DependencyFile,
519 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
Nico Weber824285e2014-05-08 04:26:47 +0000520 void *DeserializationListener, bool OwnDeserializationListener,
521 bool Preamble, bool UseGlobalModuleIndex) {
Ben Langmuirdcf73862014-03-12 00:06:17 +0000522 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
523
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000524 IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000525 PP, &Context, PCHContainerRdr, Extensions,
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000526 Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation,
527 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
528 HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex));
Richard Smith4eca9b92015-02-04 23:37:59 +0000529
530 // We need the external source to be set up before we read the AST, because
531 // eagerly-deserialized declarations may use it.
532 Context.setExternalSource(Reader.get());
Daniel Dunbar599313e2009-11-13 08:21:10 +0000533
Sebastian Redl07a89a82010-07-30 00:29:29 +0000534 Reader->setDeserializationListener(
Nico Weber824285e2014-05-08 04:26:47 +0000535 static_cast<ASTDeserializationListener *>(DeserializationListener),
536 /*TakeOwnership=*/OwnDeserializationListener);
Graydon Hoarece539b52017-03-29 17:33:09 +0000537
538 if (DependencyFile)
539 DependencyFile->AttachToASTReader(*Reader);
540 for (auto &Listener : DependencyCollectors)
541 Listener->attachToASTReader(*Reader);
542
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000543 switch (Reader->ReadAST(Path,
544 Preamble ? serialization::MK_Preamble
Douglas Gregor4b29c162012-10-22 23:51:00 +0000545 : serialization::MK_PCH,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000546 SourceLocation(),
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000547 ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000548 case ASTReader::Success:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000549 // Set the predefines buffer as suggested by the PCH reader. Typically, the
550 // predefines buffer will be empty.
551 PP.setPredefines(Reader->getSuggestedPredefines());
Richard Smith4eca9b92015-02-04 23:37:59 +0000552 return Reader;
Daniel Dunbar599313e2009-11-13 08:21:10 +0000553
Sebastian Redl2c499f62010-08-18 23:56:43 +0000554 case ASTReader::Failure:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000555 // Unrecoverable failure: don't even try to process the input file.
556 break;
557
Douglas Gregor7029ce12013-03-19 00:28:20 +0000558 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000559 case ASTReader::OutOfDate:
560 case ASTReader::VersionMismatch:
561 case ASTReader::ConfigurationMismatch:
562 case ASTReader::HadErrors:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000563 // No suitable PCH file could be found. Return an error.
564 break;
565 }
566
Richard Smith4eca9b92015-02-04 23:37:59 +0000567 Context.setExternalSource(nullptr);
Craig Topper49a27902014-05-22 04:46:25 +0000568 return nullptr;
Daniel Dunbar599313e2009-11-13 08:21:10 +0000569}
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000570
571// Code Completion
572
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000573static bool EnableCodeCompletion(Preprocessor &PP,
Benjamin Kramer0772c422016-02-13 13:42:54 +0000574 StringRef Filename,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000575 unsigned Line,
576 unsigned Column) {
577 // Tell the source manager to chop off the given file at a specific
578 // line and column.
Chris Lattner5159f612010-11-23 08:35:12 +0000579 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000580 if (!Entry) {
581 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
582 << Filename;
583 return true;
584 }
585
586 // Truncate the named file at the given line/column.
587 PP.SetCodeCompletionPoint(Entry, Line, Column);
588 return false;
589}
590
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000591void CompilerInstance::createCodeCompletionConsumer() {
592 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000593 if (!CompletionConsumer) {
Erik Verbruggen2fca3c22012-04-12 10:31:12 +0000594 setCodeCompletionConsumer(
Douglas Gregor8e984da2010-08-04 16:47:14 +0000595 createCodeCompletionConsumer(getPreprocessor(),
596 Loc.FileName, Loc.Line, Loc.Column,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000597 getFrontendOpts().CodeCompleteOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000598 llvm::outs()));
599 if (!CompletionConsumer)
600 return;
601 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
602 Loc.Line, Loc.Column)) {
Craig Topper49a27902014-05-22 04:46:25 +0000603 setCodeCompletionConsumer(nullptr);
Douglas Gregor00a0cf72010-03-16 06:04:47 +0000604 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000605 }
Douglas Gregorf09935f2009-12-01 05:55:20 +0000606
607 if (CompletionConsumer->isOutputBinary() &&
Rafael Espindolaa3346d82013-06-12 20:44:26 +0000608 llvm::sys::ChangeStdoutToBinary()) {
Douglas Gregorf09935f2009-12-01 05:55:20 +0000609 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
Craig Topper49a27902014-05-22 04:46:25 +0000610 setCodeCompletionConsumer(nullptr);
Douglas Gregorf09935f2009-12-01 05:55:20 +0000611 }
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000612}
613
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000614void CompilerInstance::createFrontendTimer() {
Matthias Braunae032b62016-11-18 19:43:25 +0000615 FrontendTimerGroup.reset(
616 new llvm::TimerGroup("frontend", "Clang front-end time report"));
Richard Smithce18a182015-07-14 00:26:00 +0000617 FrontendTimer.reset(
Matthias Braunae032b62016-11-18 19:43:25 +0000618 new llvm::Timer("frontend", "Clang front-end timer",
619 *FrontendTimerGroup));
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000620}
621
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000622CodeCompleteConsumer *
623CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
Yaron Keren5b816062015-07-06 08:47:15 +0000624 StringRef Filename,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000625 unsigned Line,
626 unsigned Column,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000627 const CodeCompleteOptions &Opts,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000628 raw_ostream &OS) {
Douglas Gregor8e984da2010-08-04 16:47:14 +0000629 if (EnableCodeCompletion(PP, Filename, Line, Column))
Craig Topper49a27902014-05-22 04:46:25 +0000630 return nullptr;
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000631
632 // Set up the creation routine for code-completion.
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000633 return new PrintingCodeCompleteConsumer(Opts, OS);
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000634}
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000635
Douglas Gregor69f74f82011-08-25 22:30:56 +0000636void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregor0e93f012010-08-12 23:31:19 +0000637 CodeCompleteConsumer *CompletionConsumer) {
638 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000639 TUKind, CompletionConsumer));
Benjamin Kramer7de99692016-11-16 18:15:26 +0000640 // Attach the external sema source if there is any.
641 if (ExternalSemaSrc) {
642 TheSema->addExternalSource(ExternalSemaSrc.get());
643 ExternalSemaSrc->InitializeSema(*TheSema);
644 }
Douglas Gregor0e93f012010-08-12 23:31:19 +0000645}
646
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000647// Output Files
648
Rafael Espindola269ec0f2015-04-10 14:11:52 +0000649void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
Rafael Espindola269ec0f2015-04-10 14:11:52 +0000650 OutputFiles.push_back(std::move(OutFile));
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000651}
652
Kovarththanan Rajaratnam1c558cd2010-03-06 12:07:48 +0000653void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Reid Kleckner0aa128e2015-04-10 17:27:58 +0000654 for (OutputFile &OF : OutputFiles) {
Reid Kleckner0aa128e2015-04-10 17:27:58 +0000655 if (!OF.TempFilename.empty()) {
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000656 if (EraseFiles) {
Reid Kleckner0aa128e2015-04-10 17:27:58 +0000657 llvm::sys::fs::remove(OF.TempFilename);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000658 } else {
Reid Kleckner0aa128e2015-04-10 17:27:58 +0000659 SmallString<128> NewOutFile(OF.Filename);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000660
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000661 // If '-working-directory' was passed, the output filename should be
662 // relative to that.
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000663 FileMgr->FixupRelativePath(NewOutFile);
Rafael Espindolac0809172014-06-12 14:02:15 +0000664 if (std::error_code ec =
Reid Kleckner0aa128e2015-04-10 17:27:58 +0000665 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
Manuel Klimek3ef9c442012-05-16 20:55:58 +0000666 getDiagnostics().Report(diag::err_unable_to_rename_temp)
Reid Kleckner0aa128e2015-04-10 17:27:58 +0000667 << OF.TempFilename << OF.Filename << ec.message();
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000668
Reid Kleckner0aa128e2015-04-10 17:27:58 +0000669 llvm::sys::fs::remove(OF.TempFilename);
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000670 }
671 }
Reid Kleckner0aa128e2015-04-10 17:27:58 +0000672 } else if (!OF.Filename.empty() && EraseFiles)
673 llvm::sys::fs::remove(OF.Filename);
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000674 }
675 OutputFiles.clear();
Richard Smith86a3ef52017-06-09 21:24:02 +0000676 if (DeleteBuiltModules) {
677 for (auto &Module : BuiltModules)
678 llvm::sys::fs::remove(Module.second);
679 BuiltModules.clear();
680 }
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000681 NonSeekStream.reset();
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000682}
683
Peter Collingbourne03f89072016-07-15 00:55:40 +0000684std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000685CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000686 StringRef Extension) {
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000687 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarae77b3d2012-03-03 00:36:06 +0000688 /*RemoveFileOnSignal=*/true, InFile, Extension,
689 /*UseTemporary=*/true);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000690}
691
Peter Collingbourne03f89072016-07-15 00:55:40 +0000692std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
693 return llvm::make_unique<llvm::raw_null_ostream>();
Alp Tokerea046722014-06-03 17:23:34 +0000694}
695
Peter Collingbourne03f89072016-07-15 00:55:40 +0000696std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000697CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
698 bool RemoveFileOnSignal, StringRef InFile,
699 StringRef Extension, bool UseTemporary,
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000700 bool CreateMissingDirectories) {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000701 std::string OutputPathName, TempPathName;
702 std::error_code EC;
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000703 std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
Rafael Espindoladae941a2014-08-25 18:17:04 +0000704 OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
Rafael Espindolac80a4062015-04-10 14:30:43 +0000705 UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000706 if (!OS) {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000707 getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
708 << EC.message();
Craig Topper49a27902014-05-22 04:46:25 +0000709 return nullptr;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000710 }
711
712 // Add the output file -- but don't try to remove "-", since this means we are
713 // using stdin.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000714 addOutputFile(
715 OutputFile((OutputPathName != "-") ? OutputPathName : "", TempPathName));
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000716
Peter Collingbourne03f89072016-07-15 00:55:40 +0000717 return OS;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000718}
719
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000720std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
Rafael Espindoladae941a2014-08-25 18:17:04 +0000721 StringRef OutputPath, std::error_code &Error, bool Binary,
722 bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
723 bool UseTemporary, bool CreateMissingDirectories,
724 std::string *ResultPathName, std::string *TempPathName) {
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000725 assert((!CreateMissingDirectories || UseTemporary) &&
726 "CreateMissingDirectories is only allowed when using temporary files");
727
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000728 std::string OutFile, TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000729 if (!OutputPath.empty()) {
730 OutFile = OutputPath;
731 } else if (InFile == "-") {
732 OutFile = "-";
733 } else if (!Extension.empty()) {
Rafael Espindola399ab332013-06-26 04:32:59 +0000734 SmallString<128> Path(InFile);
735 llvm::sys::path::replace_extension(Path, Extension);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000736 OutFile = Path.str();
737 } else {
738 OutFile = "-";
739 }
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000740
Ahmed Charlesb8984322014-03-07 20:03:18 +0000741 std::unique_ptr<llvm::raw_fd_ostream> OS;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000742 std::string OSFile;
743
Rafael Espindola73c23a72013-06-27 18:26:26 +0000744 if (UseTemporary) {
745 if (OutFile == "-")
746 UseTemporary = false;
747 else {
748 llvm::sys::fs::file_status Status;
749 llvm::sys::fs::status(OutputPath, Status);
750 if (llvm::sys::fs::exists(Status)) {
751 // Fail early if we can't write to the final destination.
Douglas Katzman8bfac2c2015-09-17 16:45:12 +0000752 if (!llvm::sys::fs::can_write(OutputPath)) {
Rafael Espindolaee4e08b2015-10-05 11:49:35 +0000753 Error = make_error_code(llvm::errc::operation_not_permitted);
Craig Topper49a27902014-05-22 04:46:25 +0000754 return nullptr;
Douglas Katzman8bfac2c2015-09-17 16:45:12 +0000755 }
Rafael Espindola73c23a72013-06-27 18:26:26 +0000756
757 // Don't use a temporary if the output is a special file. This handles
758 // things like '-o /dev/null'
759 if (!llvm::sys::fs::is_regular_file(Status))
760 UseTemporary = false;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000761 }
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000762 }
763 }
764
Rafael Espindola73c23a72013-06-27 18:26:26 +0000765 if (UseTemporary) {
Rafael Espindola73c23a72013-06-27 18:26:26 +0000766 // Create a temporary file.
Nico Weber2db47192017-08-08 16:21:23 +0000767 // Insert -%%%%%%%% before the extension (if any), and because some tools
768 // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
769 // artifacts, also append .tmp.
770 StringRef OutputExtension = llvm::sys::path::extension(OutFile);
771 SmallString<128> TempPath =
772 StringRef(OutFile).drop_back(OutputExtension.size());
Rafael Espindola73c23a72013-06-27 18:26:26 +0000773 TempPath += "-%%%%%%%%";
Nico Weber2db47192017-08-08 16:21:23 +0000774 TempPath += OutputExtension;
775 TempPath += ".tmp";
Rafael Espindola73c23a72013-06-27 18:26:26 +0000776 int fd;
Rafael Espindolac0809172014-06-12 14:02:15 +0000777 std::error_code EC =
Yaron Keren92e1b622015-03-18 10:17:07 +0000778 llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
Rafael Espindola157f34b2013-06-28 03:49:04 +0000779
780 if (CreateMissingDirectories &&
Rafael Espindola71de0b62014-06-13 17:20:50 +0000781 EC == llvm::errc::no_such_file_or_directory) {
Rafael Espindola157f34b2013-06-28 03:49:04 +0000782 StringRef Parent = llvm::sys::path::parent_path(OutputPath);
783 EC = llvm::sys::fs::create_directories(Parent);
784 if (!EC) {
Yaron Keren92e1b622015-03-18 10:17:07 +0000785 EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
Rafael Espindola157f34b2013-06-28 03:49:04 +0000786 }
787 }
788
789 if (!EC) {
NAKAMURA Takumi69f35282014-08-11 06:53:11 +0000790 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
Rafael Espindola73c23a72013-06-27 18:26:26 +0000791 OSFile = TempFile = TempPath.str();
792 }
793 // If we failed to create the temporary, fallback to writing to the file
794 // directly. This handles the corner case where we cannot write to the
795 // directory, but can write to the file.
796 }
797
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000798 if (!OS) {
799 OSFile = OutFile;
NAKAMURA Takumi69f35282014-08-11 06:53:11 +0000800 OS.reset(new llvm::raw_fd_ostream(
Rafael Espindoladae941a2014-08-25 18:17:04 +0000801 OSFile, Error,
NAKAMURA Takumi69f35282014-08-11 06:53:11 +0000802 (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
Rafael Espindoladae941a2014-08-25 18:17:04 +0000803 if (Error)
Craig Topper49a27902014-05-22 04:46:25 +0000804 return nullptr;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000805 }
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000806
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000807 // Make sure the out stream file gets removed if we crash.
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000808 if (RemoveFileOnSignal)
Rafael Espindola18556de2013-06-13 21:02:40 +0000809 llvm::sys::RemoveFileOnSignal(OSFile);
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000810
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000811 if (ResultPathName)
812 *ResultPathName = OutFile;
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000813 if (TempPathName)
814 *TempPathName = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000815
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000816 if (!Binary || OS->supportsSeeking())
817 return std::move(OS);
818
819 auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
820 assert(!NonSeekStream);
821 NonSeekStream = std::move(OS);
822 return std::move(B);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000823}
Daniel Dunbar409e8902009-11-14 07:53:04 +0000824
825// Initialization Utilities
826
Argyrios Kyrtzidis1b3240b2012-11-09 19:40:33 +0000827bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
Nico Weber2ca4be92016-03-01 23:16:44 +0000828 return InitializeSourceManager(
829 Input, getDiagnostics(), getFileManager(), getSourceManager(),
830 hasPreprocessor() ? &getPreprocessor().getHeaderSearchInfo() : nullptr,
Nico Weber4b5aede2016-03-13 02:44:13 +0000831 getDependencyOutputOpts(), getFrontendOpts());
Daniel Dunbar409e8902009-11-14 07:53:04 +0000832}
833
Nico Weber2ca4be92016-03-01 23:16:44 +0000834// static
Nico Weber4b5aede2016-03-13 02:44:13 +0000835bool CompilerInstance::InitializeSourceManager(
836 const FrontendInputFile &Input, DiagnosticsEngine &Diags,
837 FileManager &FileMgr, SourceManager &SourceMgr, HeaderSearch *HS,
838 DependencyOutputOptions &DepOpts, const FrontendOptions &Opts) {
Richard Smithf3f84612017-06-29 02:19:42 +0000839 SrcMgr::CharacteristicKind Kind =
840 Input.getKind().getFormat() == InputKind::ModuleMap
841 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
842 : SrcMgr::C_User_ModuleMap
843 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
Argyrios Kyrtzidis1b3240b2012-11-09 19:40:33 +0000844
Argyrios Kyrtzidis6566e232012-11-09 19:40:45 +0000845 if (Input.isBuffer()) {
Richard Smith6d9bc272017-09-09 01:14:04 +0000846 SourceMgr.setMainFileID(SourceMgr.createFileID(SourceManager::Unowned,
847 Input.getBuffer(), Kind));
Yaron Keren8b563662015-10-03 10:46:20 +0000848 assert(SourceMgr.getMainFileID().isValid() &&
Argyrios Kyrtzidis6566e232012-11-09 19:40:45 +0000849 "Couldn't establish MainFileID!");
850 return true;
851 }
852
853 StringRef InputFile = Input.getFile();
854
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +0000855 // Figure out where to get and map in the main file.
856 if (InputFile != "-") {
Nico Weber2ca4be92016-03-01 23:16:44 +0000857 const FileEntry *File;
858 if (Opts.FindPchSource.empty()) {
859 File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
860 } else {
861 // When building a pch file in clang-cl mode, the .h file is built as if
862 // it was included by a cc file. Since the driver doesn't know about
863 // all include search directories, the frontend must search the input
864 // file through HeaderSearch here, as if it had been included by the
865 // cc file at Opts.FindPchSource.
866 const FileEntry *FindFile = FileMgr.getFile(Opts.FindPchSource);
867 if (!FindFile) {
868 Diags.Report(diag::err_fe_error_reading) << Opts.FindPchSource;
869 return false;
870 }
871 const DirectoryLookup *UnusedCurDir;
872 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
873 Includers;
874 Includers.push_back(std::make_pair(FindFile, FindFile->getDir()));
875 File = HS->LookupFile(InputFile, SourceLocation(), /*isAngled=*/false,
876 /*FromDir=*/nullptr,
877 /*CurDir=*/UnusedCurDir, Includers,
878 /*SearchPath=*/nullptr,
879 /*RelativePath=*/nullptr,
880 /*RequestingModule=*/nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000881 /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
882 /*SkipCache=*/true);
Nico Weber4b5aede2016-03-13 02:44:13 +0000883 // Also add the header to /showIncludes output.
884 if (File)
Nico Weberf54146c2016-03-23 18:46:57 +0000885 DepOpts.ShowIncludesPretendHeader = File->getName();
Nico Weber2ca4be92016-03-01 23:16:44 +0000886 }
Dan Gohman52765212010-10-26 21:13:51 +0000887 if (!File) {
Daniel Dunbar409e8902009-11-14 07:53:04 +0000888 Diags.Report(diag::err_fe_error_reading) << InputFile;
889 return false;
890 }
Daniel Dunbare2951f42012-11-05 22:53:33 +0000891
892 // The natural SourceManager infrastructure can't currently handle named
893 // pipes, but we would at least like to accept them for the main
Benjamin Kramer3841fa32013-08-12 13:46:52 +0000894 // file. Detect them here, read them with the volatile flag so FileMgr will
895 // pick up the correct size, and simply override their contents as we do for
896 // STDIN.
Daniel Dunbare2951f42012-11-05 22:53:33 +0000897 if (File->isNamedPipe()) {
Benjamin Kramera8857962014-10-26 22:44:13 +0000898 auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
899 if (MB) {
Benjamin Kramer3841fa32013-08-12 13:46:52 +0000900 // Create a new virtual file that will have the correct size.
Benjamin Kramera8857962014-10-26 22:44:13 +0000901 File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
902 SourceMgr.overrideFileContents(File, std::move(*MB));
Benjamin Kramer3841fa32013-08-12 13:46:52 +0000903 } else {
Benjamin Kramera8857962014-10-26 22:44:13 +0000904 Diags.Report(diag::err_cannot_open_file) << InputFile
905 << MB.getError().message();
Daniel Dunbare2951f42012-11-05 22:53:33 +0000906 return false;
907 }
Daniel Dunbare2951f42012-11-05 22:53:33 +0000908 }
Daniel Dunbardb0745a2012-11-27 00:04:16 +0000909
Alp Tokerb671e342014-05-21 01:12:41 +0000910 SourceMgr.setMainFileID(
911 SourceMgr.createFileID(File, SourceLocation(), Kind));
Daniel Dunbar409e8902009-11-14 07:53:04 +0000912 } else {
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000913 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
914 llvm::MemoryBuffer::getSTDIN();
915 if (std::error_code EC = SBOrErr.getError()) {
916 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
Daniel Dunbar409e8902009-11-14 07:53:04 +0000917 return false;
918 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000919 std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
920
Dan Gohman2f76cd72010-10-26 23:21:25 +0000921 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner5159f612010-11-23 08:35:12 +0000922 SB->getBufferSize(), 0);
Alp Tokerb671e342014-05-21 01:12:41 +0000923 SourceMgr.setMainFileID(
924 SourceMgr.createFileID(File, SourceLocation(), Kind));
David Blaikie49cc3182014-08-27 20:54:45 +0000925 SourceMgr.overrideFileContents(File, std::move(SB));
Daniel Dunbar409e8902009-11-14 07:53:04 +0000926 }
927
Yaron Keren8b563662015-10-03 10:46:20 +0000928 assert(SourceMgr.getMainFileID().isValid() &&
Dan Gohman52765212010-10-26 21:13:51 +0000929 "Couldn't establish MainFileID!");
Daniel Dunbar409e8902009-11-14 07:53:04 +0000930 return true;
931}
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000932
933// High-Level Operations
934
935bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
936 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
937 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
938 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
939
940 // FIXME: Take this as an argument, once all the APIs we used have moved to
941 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000942 raw_ostream &OS = llvm::errs();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000943
944 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +0000945 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
Saleem Abdulrasool10a49722016-04-08 16:52:00 +0000946 getInvocation().TargetOpts));
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000947 if (!hasTarget())
948 return false;
949
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000950 // Create TargetInfo for the other side of CUDA and OpenMP compilation.
951 if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) &&
952 !getFrontendOpts().AuxTriple.empty()) {
Justin Lebar76945b22016-04-29 23:05:19 +0000953 auto TO = std::make_shared<TargetOptions>();
Artem Belevichb5bc9232015-09-22 17:23:22 +0000954 TO->Triple = getFrontendOpts().AuxTriple;
Justin Lebar76945b22016-04-29 23:05:19 +0000955 TO->HostTriple = getTarget().getTriple().str();
Saleem Abdulrasool10a49722016-04-08 16:52:00 +0000956 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
Artem Belevichb5bc9232015-09-22 17:23:22 +0000957 }
958
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000959 // Inform the target of the language options.
960 //
961 // FIXME: We shouldn't need to do this, the target should be immutable once
962 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000963 getTarget().adjust(getLangOpts());
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000964
Yaxun Liu2c17e822016-08-09 19:43:38 +0000965 // Adjust target options based on codegen options.
966 getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
967
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000968 // rewriter project will change target built-in bool type from its default.
969 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
970 getTarget().noSignedCharForObjCBool();
971
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000972 // Validate/process some options.
973 if (getHeaderSearchOpts().Verbose)
974 OS << "clang -cc1 version " CLANG_VERSION_STRING
Alp Tokerf988d002014-06-06 10:36:22 +0000975 << " based upon " << BACKEND_PACKAGE_STRING
Sebastian Pop8188c8a2011-11-01 21:33:06 +0000976 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000977
978 if (getFrontendOpts().ShowTimers)
979 createFrontendTimer();
980
Matthias Braunabb6eea2016-09-26 18:53:34 +0000981 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
Matthias Braunec1c5a22016-09-27 19:38:59 +0000982 llvm::EnableStatistics(false);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000983
Vedant Kumar5b60ad62015-11-16 00:59:34 +0000984 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
Ted Kremenekeeccb302014-08-27 15:14:15 +0000985 // Reset the ID tables if we are reusing the SourceManager and parsing
986 // regular files.
987 if (hasSourceManager() && !Act.isModelParsingAction())
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000988 getSourceManager().clearIDTables();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000989
Vedant Kumar5b60ad62015-11-16 00:59:34 +0000990 if (Act.BeginSourceFile(*this, FIF)) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000991 Act.Execute();
992 Act.EndSourceFile();
993 }
994 }
995
Argyrios Kyrtzidis7910d7b2011-12-07 05:52:12 +0000996 // Notify the diagnostic client that all files were processed.
997 getDiagnostics().getClient()->finish();
998
Chris Lattner198cb4d2010-04-07 18:47:42 +0000999 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +00001000 // We can have multiple diagnostics sharing one diagnostic client.
1001 // Get the total number of warnings/errors from the client.
1002 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1003 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001004
Chris Lattner198cb4d2010-04-07 18:47:42 +00001005 if (NumWarnings)
1006 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1007 if (NumWarnings && NumErrors)
1008 OS << " and ";
1009 if (NumErrors)
1010 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
Justin Lebar78137ec2017-09-07 18:37:16 +00001011 if (NumWarnings || NumErrors) {
1012 OS << " generated";
1013 if (getLangOpts().CUDA) {
1014 if (!getLangOpts().CUDAIsDevice) {
1015 OS << " when compiling for host";
1016 } else {
1017 OS << " when compiling for " << getTargetOpts().CPU;
1018 }
1019 }
1020 OS << ".\n";
1021 }
Chris Lattner198cb4d2010-04-07 18:47:42 +00001022 }
Daniel Dunbar4f2bc552010-01-13 00:48:06 +00001023
Matthias Braunabb6eea2016-09-26 18:53:34 +00001024 if (getFrontendOpts().ShowStats) {
1025 if (hasFileManager()) {
1026 getFileManager().PrintStats();
1027 OS << '\n';
1028 }
1029 llvm::PrintStatistics(OS);
1030 }
1031 StringRef StatsFile = getFrontendOpts().StatsFile;
1032 if (!StatsFile.empty()) {
1033 std::error_code EC;
1034 auto StatS = llvm::make_unique<llvm::raw_fd_ostream>(StatsFile, EC,
1035 llvm::sys::fs::F_Text);
1036 if (EC) {
1037 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1038 << StatsFile << EC.message();
1039 } else {
1040 llvm::PrintStatisticsJSON(*StatS);
1041 }
Daniel Dunbar4f2bc552010-01-13 00:48:06 +00001042 }
1043
Argyrios Kyrtzidisbc467932010-11-18 21:13:57 +00001044 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +00001045}
1046
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001047/// \brief Determine the appropriate source input kind based on language
1048/// options.
Richard Smith40c0efa2017-04-26 18:57:40 +00001049static InputKind::Language getLanguageFromOptions(const LangOptions &LangOpts) {
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001050 if (LangOpts.OpenCL)
Richard Smith40c0efa2017-04-26 18:57:40 +00001051 return InputKind::OpenCL;
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001052 if (LangOpts.CUDA)
Richard Smith40c0efa2017-04-26 18:57:40 +00001053 return InputKind::CUDA;
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001054 if (LangOpts.ObjC1)
Richard Smith40c0efa2017-04-26 18:57:40 +00001055 return LangOpts.CPlusPlus ? InputKind::ObjCXX : InputKind::ObjC;
1056 return LangOpts.CPlusPlus ? InputKind::CXX : InputKind::C;
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001057}
1058
Douglas Gregor514b6362011-11-29 19:06:37 +00001059/// \brief Compile a module file for the given module, using the options
Ben Langmuirb797d592014-07-19 16:29:28 +00001060/// provided by the importing compiler instance. Returns true if the module
1061/// was built without errors.
Richard Smith5d2ed482017-06-09 19:22:32 +00001062static bool
1063compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1064 StringRef ModuleName, FrontendInputFile Input,
1065 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1066 llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
1067 [](CompilerInstance &) {},
1068 llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1069 [](CompilerInstance &) {}) {
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001070 // Construct a compiler invocation for creating this module.
David Blaikieea4395e2017-01-06 19:49:01 +00001071 auto Invocation =
1072 std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001073
Douglas Gregorf545f672011-11-29 21:59:16 +00001074 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1075
Douglas Gregor44bf68d2011-09-15 20:53:28 +00001076 // For any options that aren't intended to affect how a module is built,
1077 // reset them to their default values.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001078 Invocation->getLangOpts()->resetNonModularOptions();
Douglas Gregorf545f672011-11-29 21:59:16 +00001079 PPOpts.resetNonModularOptions();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001080
Douglas Gregor5dc38992013-02-07 00:21:12 +00001081 // Remove any macro definitions that are explicitly ignored by the module.
1082 // They aren't supposed to affect how the module is built anyway.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001083 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001084 PPOpts.Macros.erase(
1085 std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
1086 [&HSOpts](const std::pair<std::string, bool> &def) {
1087 StringRef MacroDef = def.first;
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001088 return HSOpts.ModulesIgnoreMacros.count(
1089 llvm::CachedHashString(MacroDef.split('=').first)) > 0;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001090 }),
1091 PPOpts.Macros.end());
Douglas Gregor5dc38992013-02-07 00:21:12 +00001092
Douglas Gregor7d106e42011-11-15 19:35:01 +00001093 // Note the name of the module we're building.
Richard Smith5d2ed482017-06-09 19:22:32 +00001094 Invocation->getLangOpts()->CurrentModule = ModuleName;
Douglas Gregor7d106e42011-11-15 19:35:01 +00001095
Douglas Gregor7a626572012-11-29 23:55:25 +00001096 // Make sure that the failed-module structure has been allocated in
1097 // the importing instance, and propagate the pointer to the newly-created
1098 // instance.
1099 PreprocessorOptions &ImportingPPOpts
1100 = ImportingInstance.getInvocation().getPreprocessorOpts();
1101 if (!ImportingPPOpts.FailedModules)
David Blaikief95113d2017-01-05 19:11:31 +00001102 ImportingPPOpts.FailedModules =
1103 std::make_shared<PreprocessorOptions::FailedModulesSet>();
Douglas Gregor7a626572012-11-29 23:55:25 +00001104 PPOpts.FailedModules = ImportingPPOpts.FailedModules;
1105
Douglas Gregorf545f672011-11-29 21:59:16 +00001106 // If there is a module map file, build the module using the module map.
Douglas Gregor44bf68d2011-09-15 20:53:28 +00001107 // Set up the inputs/outputs so that we build the module from its umbrella
1108 // header.
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001109 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
Douglas Gregor1735f4e2011-09-13 23:15:45 +00001110 FrontendOpts.OutputFile = ModuleFileName.str();
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001111 FrontendOpts.DisableFree = false;
Douglas Gregorc1bbec82013-01-25 00:45:27 +00001112 FrontendOpts.GenerateGlobalModuleIndex = false;
Richard Smithe75ee0f2015-08-17 07:13:32 +00001113 FrontendOpts.BuildingImplicitModule = true;
Richard Smith5d2ed482017-06-09 19:22:32 +00001114 FrontendOpts.OriginalModuleMap = OriginalModuleMapFile;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001115 // Force implicitly-built modules to hash the content of the module file.
1116 HSOpts.ModulesHashContent = true;
Richard Smith5d2ed482017-06-09 19:22:32 +00001117 FrontendOpts.Inputs = {Input};
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001118
Douglas Gregorf545f672011-11-29 21:59:16 +00001119 // Don't free the remapped file buffers; they are owned by our caller.
1120 PPOpts.RetainRemappedFileBuffers = true;
1121
Douglas Gregor2b9b4642011-09-13 01:26:44 +00001122 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
Douglas Gregor3728ea72011-09-13 23:20:27 +00001123 assert(ImportingInstance.getInvocation().getModuleHash() ==
Douglas Gregorf545f672011-11-29 21:59:16 +00001124 Invocation->getModuleHash() && "Module hash mismatch!");
1125
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001126 // Construct a compiler instance that will be used to actually create the
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001127 // module. Since we're sharing a PCMCache,
1128 // CompilerInstance::CompilerInstance is responsible for finalizing the
1129 // buffers to prevent use-after-frees.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001130 CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001131 &ImportingInstance.getPreprocessor().getPCMCache());
David Blaikieea4395e2017-01-06 19:49:01 +00001132 auto &Inv = *Invocation;
1133 Instance.setInvocation(std::move(Invocation));
Douglas Gregor6b930962013-05-03 22:58:43 +00001134
1135 Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
1136 ImportingInstance.getDiagnosticClient()),
Douglas Gregor30071cea2013-05-03 23:07:45 +00001137 /*ShouldOwnClient=*/true);
Douglas Gregoraf8f0262012-11-30 18:38:50 +00001138
Ben Langmuirc8130a72014-02-20 21:59:23 +00001139 Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
1140
Douglas Gregor63365432012-11-30 22:11:57 +00001141 // Note that this module is part of the module build stack, so that we
Douglas Gregoraf8f0262012-11-30 18:38:50 +00001142 // can detect cycles in the module graph.
Ben Langmuird066d4c2014-02-28 21:16:07 +00001143 Instance.setFileManager(&ImportingInstance.getFileManager());
Douglas Gregoraf8f0262012-11-30 18:38:50 +00001144 Instance.createSourceManager(Instance.getFileManager());
1145 SourceManager &SourceMgr = Instance.getSourceManager();
Douglas Gregor63365432012-11-30 22:11:57 +00001146 SourceMgr.setModuleBuildStack(
1147 ImportingInstance.getSourceManager().getModuleBuildStack());
Richard Smith5d2ed482017-06-09 19:22:32 +00001148 SourceMgr.pushModuleBuildStack(ModuleName,
Douglas Gregoraf8f0262012-11-30 18:38:50 +00001149 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
1150
Justin Bogner86d12592014-06-19 19:36:03 +00001151 // If we're collecting module dependencies, we need to share a collector
Richard Smith38c1e6d2015-08-09 06:03:55 +00001152 // between all of the module CompilerInstances. Other than that, we don't
1153 // want to produce any dependency output from the module build.
Justin Bogner86d12592014-06-19 19:36:03 +00001154 Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
David Blaikieea4395e2017-01-06 19:49:01 +00001155 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
Justin Bogner86d12592014-06-19 19:36:03 +00001156
Richard Smith99891da2014-10-14 02:08:30 +00001157 ImportingInstance.getDiagnostics().Report(ImportLoc,
1158 diag::remark_module_build)
Richard Smith5d2ed482017-06-09 19:22:32 +00001159 << ModuleName << ModuleFileName;
1160
1161 PreBuildStep(Instance);
Richard Smith99891da2014-10-14 02:08:30 +00001162
Douglas Gregor51e0b542011-10-04 00:21:21 +00001163 // Execute the action to actually build the module in-place. Use a separate
1164 // thread so that we get a stack large enough.
1165 const unsigned ThreadStackSize = 8 << 20;
1166 llvm::CrashRecoveryContext CRC;
Richard Smithf74d9462017-04-28 01:49:42 +00001167 CRC.RunSafelyOnThread(
1168 [&]() {
1169 GenerateModuleFromModuleMapAction Action;
1170 Instance.ExecuteAction(Action);
1171 },
1172 ThreadStackSize);
Douglas Gregor6b930962013-05-03 22:58:43 +00001173
Richard Smith5d2ed482017-06-09 19:22:32 +00001174 PostBuildStep(Instance);
1175
Richard Smith99891da2014-10-14 02:08:30 +00001176 ImportingInstance.getDiagnostics().Report(ImportLoc,
1177 diag::remark_module_build_done)
Richard Smith5d2ed482017-06-09 19:22:32 +00001178 << ModuleName;
Richard Smith99891da2014-10-14 02:08:30 +00001179
Douglas Gregorf545f672011-11-29 21:59:16 +00001180 // Delete the temporary module map file.
1181 // FIXME: Even though we're executing under crash protection, it would still
1182 // be nice to do this with RemoveFileOnSignal when we can. However, that
1183 // doesn't make sense for all clients, so clean this up manually.
Benjamin Kramer13afbf42012-10-14 19:50:53 +00001184 Instance.clearOutputFiles(/*EraseFiles=*/true);
Douglas Gregor5e306b12013-01-23 22:38:11 +00001185
Richard Smith5d2ed482017-06-09 19:22:32 +00001186 return !Instance.getDiagnostics().hasErrorOccurred();
1187}
1188
1189/// \brief Compile a module file for the given module, using the options
1190/// provided by the importing compiler instance. Returns true if the module
1191/// was built without errors.
1192static bool compileModuleImpl(CompilerInstance &ImportingInstance,
1193 SourceLocation ImportLoc,
1194 Module *Module,
1195 StringRef ModuleFileName) {
1196 InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
1197 InputKind::ModuleMap);
1198
1199 // Get or create the module map that we'll use to build this module.
1200 ModuleMap &ModMap
1201 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1202 bool Result;
1203 if (const FileEntry *ModuleMapFile =
1204 ModMap.getContainingModuleMapFile(Module)) {
1205 // Use the module map where this module resides.
1206 Result = compileModuleImpl(
1207 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1208 FrontendInputFile(ModuleMapFile->getName(), IK, +Module->IsSystem),
1209 ModMap.getModuleMapFileForUniquing(Module)->getName(),
1210 ModuleFileName);
1211 } else {
1212 // FIXME: We only need to fake up an input file here as a way of
1213 // transporting the module's directory to the module map parser. We should
1214 // be able to do that more directly, and parse from a memory buffer without
1215 // inventing this file.
1216 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1217 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1218
1219 std::string InferredModuleMapContent;
1220 llvm::raw_string_ostream OS(InferredModuleMapContent);
1221 Module->print(OS);
1222 OS.flush();
1223
1224 Result = compileModuleImpl(
1225 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1226 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1227 ModMap.getModuleMapFileForUniquing(Module)->getName(),
1228 ModuleFileName,
1229 [&](CompilerInstance &Instance) {
1230 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1231 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1232 ModuleMapFile = Instance.getFileManager().getVirtualFile(
1233 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1234 Instance.getSourceManager().overrideFileContents(
1235 ModuleMapFile, std::move(ModuleMapBuffer));
1236 });
1237 }
1238
Douglas Gregor5e306b12013-01-23 22:38:11 +00001239 // We've rebuilt a module. If we're allowed to generate or update the global
1240 // module index, record that fact in the importing compiler instance.
Douglas Gregorc1bbec82013-01-25 00:45:27 +00001241 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
Douglas Gregor5e306b12013-01-23 22:38:11 +00001242 ImportingInstance.setBuildGlobalModuleIndex(true);
1243 }
Ben Langmuirb797d592014-07-19 16:29:28 +00001244
Richard Smith5d2ed482017-06-09 19:22:32 +00001245 return Result;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001246}
Douglas Gregorfaeb1d42011-09-12 23:31:24 +00001247
Ben Langmuirdbdc0362014-06-17 22:35:27 +00001248static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
1249 SourceLocation ImportLoc,
Ben Langmuirb797d592014-07-19 16:29:28 +00001250 SourceLocation ModuleNameLoc, Module *Module,
Ben Langmuirdbdc0362014-06-17 22:35:27 +00001251 StringRef ModuleFileName) {
Ben Langmuird213aab2014-09-26 22:42:23 +00001252 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1253
Ben Langmuirb797d592014-07-19 16:29:28 +00001254 auto diagnoseBuildFailure = [&] {
Ben Langmuird213aab2014-09-26 22:42:23 +00001255 Diags.Report(ModuleNameLoc, diag::err_module_not_built)
Ben Langmuirb797d592014-07-19 16:29:28 +00001256 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1257 };
1258
Argyrios Kyrtzidis4382fe72014-04-06 03:21:44 +00001259 // FIXME: have LockFileManager return an error_code so that we can
1260 // avoid the mkdir when the directory already exists.
1261 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1262 llvm::sys::fs::create_directories(Dir);
1263
1264 while (1) {
Ben Langmuirdbdc0362014-06-17 22:35:27 +00001265 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
Argyrios Kyrtzidis4382fe72014-04-06 03:21:44 +00001266 llvm::LockFileManager Locked(ModuleFileName);
1267 switch (Locked) {
1268 case llvm::LockFileManager::LFS_Error:
Bruno Cardoso Lopes5a0af1f2017-03-18 00:26:18 +00001269 // PCMCache takes care of correctness and locks are only necessary for
1270 // performance. Fallback to building the module in case of any lock
1271 // related errors.
1272 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
Bruno Cardoso Lopes4a522222016-06-04 01:13:22 +00001273 << Module->Name << Locked.getErrorMessage();
Bruno Cardoso Lopes5a0af1f2017-03-18 00:26:18 +00001274 // Clear out any potential leftover.
1275 Locked.unsafeRemoveLockFile();
1276 // FALLTHROUGH
Argyrios Kyrtzidis4382fe72014-04-06 03:21:44 +00001277 case llvm::LockFileManager::LFS_Owned:
Ben Langmuirdbdc0362014-06-17 22:35:27 +00001278 // We're responsible for building the module ourselves.
Ben Langmuirb797d592014-07-19 16:29:28 +00001279 if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
1280 ModuleFileName)) {
1281 diagnoseBuildFailure();
1282 return false;
1283 }
Argyrios Kyrtzidis4382fe72014-04-06 03:21:44 +00001284 break;
1285
1286 case llvm::LockFileManager::LFS_Shared:
1287 // Someone else is responsible for building the module. Wait for them to
1288 // finish.
Ben Langmuir1daf4802015-02-09 20:35:13 +00001289 switch (Locked.waitForUnlock()) {
1290 case llvm::LockFileManager::Res_Success:
1291 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1292 break;
1293 case llvm::LockFileManager::Res_OwnerDied:
Argyrios Kyrtzidis4382fe72014-04-06 03:21:44 +00001294 continue; // try again to get the lock.
Ben Langmuir1daf4802015-02-09 20:35:13 +00001295 case llvm::LockFileManager::Res_Timeout:
Bruno Cardoso Lopes5a0af1f2017-03-18 00:26:18 +00001296 // Since PCMCache takes care of correctness, we try waiting for another
1297 // process to complete the build so clang does not do it done twice. If
1298 // case of timeout, build it ourselves.
1299 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
Ben Langmuir1daf4802015-02-09 20:35:13 +00001300 << Module->Name;
1301 // Clear the lock file so that future invokations can make progress.
1302 Locked.unsafeRemoveLockFile();
Bruno Cardoso Lopes5a0af1f2017-03-18 00:26:18 +00001303 continue;
Ben Langmuir1daf4802015-02-09 20:35:13 +00001304 }
Ben Langmuirdbdc0362014-06-17 22:35:27 +00001305 break;
Argyrios Kyrtzidis4382fe72014-04-06 03:21:44 +00001306 }
1307
Ben Langmuirdbdc0362014-06-17 22:35:27 +00001308 // Try to read the module file, now that we've compiled it.
1309 ASTReader::ASTReadResult ReadResult =
1310 ImportingInstance.getModuleManager()->ReadAST(
Richard Smithe842a472014-10-22 02:05:46 +00001311 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
Ben Langmuirdbdc0362014-06-17 22:35:27 +00001312 ModuleLoadCapabilities);
1313
1314 if (ReadResult == ASTReader::OutOfDate &&
1315 Locked == llvm::LockFileManager::LFS_Shared) {
1316 // The module may be out of date in the presence of file system races,
1317 // or if one of its imports depends on header search paths that are not
1318 // consistent with this ImportingInstance. Try again...
1319 continue;
1320 } else if (ReadResult == ASTReader::Missing) {
Ben Langmuirb797d592014-07-19 16:29:28 +00001321 diagnoseBuildFailure();
Ben Langmuird213aab2014-09-26 22:42:23 +00001322 } else if (ReadResult != ASTReader::Success &&
1323 !Diags.hasErrorOccurred()) {
1324 // The ASTReader didn't diagnose the error, so conservatively report it.
1325 diagnoseBuildFailure();
Ben Langmuirdbdc0362014-06-17 22:35:27 +00001326 }
1327 return ReadResult == ASTReader::Success;
Argyrios Kyrtzidis4382fe72014-04-06 03:21:44 +00001328 }
1329}
1330
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001331/// \brief Diagnose differences between the current definition of the given
1332/// configuration macro and the definition provided on the command line.
1333static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1334 Module *Mod, SourceLocation ImportLoc) {
1335 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1336 SourceManager &SourceMgr = PP.getSourceManager();
1337
1338 // If this identifier has never had a macro definition, then it could
1339 // not have changed.
1340 if (!Id->hadMacroDefinition())
1341 return;
Richard Smith20e883e2015-04-29 23:20:19 +00001342 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001343
Richard Smith20e883e2015-04-29 23:20:19 +00001344 // Find the macro definition from the command line.
1345 MacroInfo *CmdLineDefinition = nullptr;
1346 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001347 // We only care about the predefines buffer.
Richard Smith20e883e2015-04-29 23:20:19 +00001348 FileID FID = SourceMgr.getFileID(MD->getLocation());
1349 if (FID.isInvalid() || FID != PP.getPredefinesFileID())
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001350 continue;
Richard Smith20e883e2015-04-29 23:20:19 +00001351 if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1352 CmdLineDefinition = DMD->getMacroInfo();
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001353 break;
1354 }
1355
Richard Smith20e883e2015-04-29 23:20:19 +00001356 auto *CurrentDefinition = PP.getMacroInfo(Id);
1357 if (CurrentDefinition == CmdLineDefinition) {
1358 // Macro matches. Nothing to do.
1359 } else if (!CurrentDefinition) {
1360 // This macro was defined on the command line, then #undef'd later.
1361 // Complain.
1362 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1363 << true << ConfigMacro << Mod->getFullModuleName();
1364 auto LatestDef = LatestLocalMD->getDefinition();
1365 assert(LatestDef.isUndefined() &&
1366 "predefined macro went away with no #undef?");
1367 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1368 << true;
1369 return;
1370 } else if (!CmdLineDefinition) {
1371 // There was no definition for this macro in the predefines buffer,
1372 // but there was a local definition. Complain.
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001373 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1374 << false << ConfigMacro << Mod->getFullModuleName();
Richard Smith20e883e2015-04-29 23:20:19 +00001375 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1376 diag::note_module_def_undef_here)
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001377 << false;
Richard Smith20e883e2015-04-29 23:20:19 +00001378 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1379 /*Syntactically=*/true)) {
1380 // The macro definitions differ.
1381 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1382 << false << ConfigMacro << Mod->getFullModuleName();
1383 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1384 diag::note_module_def_undef_here)
1385 << false;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001386 }
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001387}
1388
Douglas Gregor527b1c92013-03-25 21:19:16 +00001389/// \brief Write a new timestamp file with the given path.
1390static void writeTimestampFile(StringRef TimestampFile) {
Rafael Espindoladae941a2014-08-25 18:17:04 +00001391 std::error_code EC;
1392 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
Douglas Gregor527b1c92013-03-25 21:19:16 +00001393}
1394
1395/// \brief Prune the module cache of modules that haven't been accessed in
1396/// a long time.
1397static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1398 struct stat StatBuf;
1399 llvm::SmallString<128> TimestampFile;
1400 TimestampFile = HSOpts.ModuleCachePath;
Richard Smith3938f0c2015-08-15 00:34:15 +00001401 assert(!TimestampFile.empty());
Douglas Gregor527b1c92013-03-25 21:19:16 +00001402 llvm::sys::path::append(TimestampFile, "modules.timestamp");
1403
1404 // Try to stat() the timestamp file.
1405 if (::stat(TimestampFile.c_str(), &StatBuf)) {
1406 // If the timestamp file wasn't there, create one now.
1407 if (errno == ENOENT) {
1408 writeTimestampFile(TimestampFile);
1409 }
1410 return;
1411 }
1412
1413 // Check whether the time stamp is older than our pruning interval.
1414 // If not, do nothing.
1415 time_t TimeStampModTime = StatBuf.st_mtime;
Craig Topper49a27902014-05-22 04:46:25 +00001416 time_t CurrentTime = time(nullptr);
Benjamin Kramerdbcf5032013-03-29 17:39:43 +00001417 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
Douglas Gregor527b1c92013-03-25 21:19:16 +00001418 return;
Douglas Gregor527b1c92013-03-25 21:19:16 +00001419
1420 // Write a new timestamp file so that nobody else attempts to prune.
1421 // There is a benign race condition here, if two Clang instances happen to
1422 // notice at the same time that the timestamp is out-of-date.
1423 writeTimestampFile(TimestampFile);
1424
1425 // Walk the entire module cache, looking for unused module files and module
1426 // indices.
Rafael Espindolac0809172014-06-12 14:02:15 +00001427 std::error_code EC;
Douglas Gregor527b1c92013-03-25 21:19:16 +00001428 SmallString<128> ModuleCachePathNative;
1429 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
Yaron Keren92e1b622015-03-18 10:17:07 +00001430 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
Douglas Gregor527b1c92013-03-25 21:19:16 +00001431 Dir != DirEnd && !EC; Dir.increment(EC)) {
1432 // If we don't have a directory, there's nothing to look into.
Rafael Espindolaa07f7202013-07-17 04:23:07 +00001433 if (!llvm::sys::fs::is_directory(Dir->path()))
Douglas Gregor527b1c92013-03-25 21:19:16 +00001434 continue;
1435
1436 // Walk all of the files within this directory.
Douglas Gregor527b1c92013-03-25 21:19:16 +00001437 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1438 File != FileEnd && !EC; File.increment(EC)) {
1439 // We only care about module and global module index files.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00001440 StringRef Extension = llvm::sys::path::extension(File->path());
1441 if (Extension != ".pcm" && Extension != ".timestamp" &&
1442 llvm::sys::path::filename(File->path()) != "modules.idx")
Douglas Gregor527b1c92013-03-25 21:19:16 +00001443 continue;
Douglas Gregor527b1c92013-03-25 21:19:16 +00001444
1445 // Look at this file. If we can't stat it, there's nothing interesting
1446 // there.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00001447 if (::stat(File->path().c_str(), &StatBuf))
Douglas Gregor527b1c92013-03-25 21:19:16 +00001448 continue;
Douglas Gregor527b1c92013-03-25 21:19:16 +00001449
1450 // If the file has been used recently enough, leave it there.
1451 time_t FileAccessTime = StatBuf.st_atime;
Benjamin Kramerdbcf5032013-03-29 17:39:43 +00001452 if (CurrentTime - FileAccessTime <=
1453 time_t(HSOpts.ModuleCachePruneAfter)) {
Douglas Gregor527b1c92013-03-25 21:19:16 +00001454 continue;
1455 }
1456
1457 // Remove the file.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00001458 llvm::sys::fs::remove(File->path());
1459
1460 // Remove the timestamp file.
1461 std::string TimpestampFilename = File->path() + ".timestamp";
1462 llvm::sys::fs::remove(TimpestampFilename);
Douglas Gregor527b1c92013-03-25 21:19:16 +00001463 }
1464
1465 // If we removed all of the files in the directory, remove the directory
1466 // itself.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00001467 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1468 llvm::sys::fs::directory_iterator() && !EC)
Rafael Espindola2a008782014-01-10 21:32:14 +00001469 llvm::sys::fs::remove(Dir->path());
Douglas Gregor527b1c92013-03-25 21:19:16 +00001470 }
1471}
1472
John Thompson2255f2c2014-04-23 12:57:01 +00001473void CompilerInstance::createModuleManager() {
1474 if (!ModuleManager) {
1475 if (!hasASTContext())
1476 createASTContext();
1477
Chandler Carruth580dd292015-03-24 21:44:25 +00001478 // If we're implicitly building modules but not currently recursively
1479 // building a module, check whether we need to prune the module cache.
Richard Smith3938f0c2015-08-15 00:34:15 +00001480 if (getSourceManager().getModuleBuildStack().empty() &&
1481 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
John Thompson2255f2c2014-04-23 12:57:01 +00001482 getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1483 getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1484 pruneModuleCache(getHeaderSearchOpts());
1485 }
1486
1487 HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1488 std::string Sysroot = HSOpts.Sysroot;
1489 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
Richard Smithce18a182015-07-14 00:26:00 +00001490 std::unique_ptr<llvm::Timer> ReadTimer;
1491 if (FrontendTimerGroup)
Matthias Braunae032b62016-11-18 19:43:25 +00001492 ReadTimer = llvm::make_unique<llvm::Timer>("reading_modules",
1493 "Reading modules",
Richard Smithce18a182015-07-14 00:26:00 +00001494 *FrontendTimerGroup);
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001495 ModuleManager = new ASTReader(
Richard Smithdbafb6c2017-06-29 23:23:46 +00001496 getPreprocessor(), &getASTContext(), getPCHContainerReader(),
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001497 getFrontendOpts().ModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001498 Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation,
1499 /*AllowASTWithCompilerErrors=*/false,
1500 /*AllowConfigurationMismatch=*/false,
1501 HSOpts.ModulesValidateSystemHeaders,
Richard Smithce18a182015-07-14 00:26:00 +00001502 getFrontendOpts().UseGlobalModuleIndex,
1503 std::move(ReadTimer));
John Thompson2255f2c2014-04-23 12:57:01 +00001504 if (hasASTConsumer()) {
1505 ModuleManager->setDeserializationListener(
1506 getASTConsumer().GetASTDeserializationListener());
1507 getASTContext().setASTMutationListener(
1508 getASTConsumer().GetASTMutationListener());
1509 }
1510 getASTContext().setExternalSource(ModuleManager);
1511 if (hasSema())
1512 ModuleManager->InitializeSema(getSema());
Richard Smith293534b2015-08-18 20:39:29 +00001513 if (hasASTConsumer())
John Thompson2255f2c2014-04-23 12:57:01 +00001514 ModuleManager->StartTranslationUnit(&getASTConsumer());
Richard Smith03f7e612015-08-09 02:28:42 +00001515
1516 if (TheDependencyFileGenerator)
1517 TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
Richard Smith03f7e612015-08-09 02:28:42 +00001518 for (auto &Listener : DependencyCollectors)
1519 Listener->attachToASTReader(*ModuleManager);
John Thompson2255f2c2014-04-23 12:57:01 +00001520 }
1521}
1522
Richard Smithd4b230b2014-10-27 23:01:16 +00001523bool CompilerInstance::loadModuleFile(StringRef FileName) {
Richard Smithce18a182015-07-14 00:26:00 +00001524 llvm::Timer Timer;
1525 if (FrontendTimerGroup)
Matthias Braunae032b62016-11-18 19:43:25 +00001526 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1527 *FrontendTimerGroup);
Richard Smithce18a182015-07-14 00:26:00 +00001528 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1529
Richard Smithd4b230b2014-10-27 23:01:16 +00001530 // Helper to recursively read the module names for all modules we're adding.
1531 // We mark these as known and redirect any attempt to load that module to
1532 // the files we were handed.
1533 struct ReadModuleNames : ASTReaderListener {
1534 CompilerInstance &CI;
Richard Smith0f99d6a2015-08-09 08:48:41 +00001535 llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
Richard Smithe842a472014-10-22 02:05:46 +00001536
Richard Smith0f99d6a2015-08-09 08:48:41 +00001537 ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
Richard Smithe842a472014-10-22 02:05:46 +00001538
Richard Smithd4b230b2014-10-27 23:01:16 +00001539 void ReadModuleName(StringRef ModuleName) override {
Richard Smith0f99d6a2015-08-09 08:48:41 +00001540 LoadedModules.push_back(
1541 CI.getPreprocessor().getIdentifierInfo(ModuleName));
Richard Smithd4b230b2014-10-27 23:01:16 +00001542 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00001543
1544 void registerAll() {
1545 for (auto *II : LoadedModules) {
1546 CI.KnownModules[II] = CI.getPreprocessor()
1547 .getHeaderSearchInfo()
1548 .getModuleMap()
1549 .findModule(II->getName());
1550 }
1551 LoadedModules.clear();
1552 }
Richard Smith8a308ec2015-11-05 00:54:55 +00001553
1554 void markAllUnavailable() {
1555 for (auto *II : LoadedModules) {
1556 if (Module *M = CI.getPreprocessor()
1557 .getHeaderSearchInfo()
1558 .getModuleMap()
Richard Smitha114c462016-12-06 00:40:17 +00001559 .findModule(II->getName())) {
Richard Smith8a308ec2015-11-05 00:54:55 +00001560 M->HasIncompatibleModuleFile = true;
Richard Smitha114c462016-12-06 00:40:17 +00001561
1562 // Mark module as available if the only reason it was unavailable
1563 // was missing headers.
1564 SmallVector<Module *, 2> Stack;
1565 Stack.push_back(M);
1566 while (!Stack.empty()) {
1567 Module *Current = Stack.pop_back_val();
1568 if (Current->IsMissingRequirement) continue;
1569 Current->IsAvailable = true;
1570 Stack.insert(Stack.end(),
1571 Current->submodule_begin(), Current->submodule_end());
1572 }
1573 }
Richard Smith8a308ec2015-11-05 00:54:55 +00001574 }
1575 LoadedModules.clear();
1576 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00001577 };
Richard Smithd4b230b2014-10-27 23:01:16 +00001578
Richard Smith7f330cd2015-03-18 01:42:29 +00001579 // If we don't already have an ASTReader, create one now.
1580 if (!ModuleManager)
1581 createModuleManager();
1582
Richard Smith0f99d6a2015-08-09 08:48:41 +00001583 auto Listener = llvm::make_unique<ReadModuleNames>(*this);
1584 auto &ListenerRef = *Listener;
1585 ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager,
1586 std::move(Listener));
Richard Smith7f330cd2015-03-18 01:42:29 +00001587
Richard Smith0f99d6a2015-08-09 08:48:41 +00001588 // Try to load the module file.
Richard Smith95dc57a2015-10-16 23:20:19 +00001589 switch (ModuleManager->ReadAST(FileName, serialization::MK_ExplicitModule,
1590 SourceLocation(),
1591 ASTReader::ARR_ConfigurationMismatch)) {
1592 case ASTReader::Success:
Richard Smith8a308ec2015-11-05 00:54:55 +00001593 // We successfully loaded the module file; remember the set of provided
1594 // modules so that we don't try to load implicit modules for them.
1595 ListenerRef.registerAll();
1596 return true;
Richard Smith95dc57a2015-10-16 23:20:19 +00001597
1598 case ASTReader::ConfigurationMismatch:
1599 // Ignore unusable module files.
1600 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1601 << FileName;
Richard Smith8a308ec2015-11-05 00:54:55 +00001602 // All modules provided by any files we tried and failed to load are now
1603 // unavailable; includes of those modules should now be handled textually.
1604 ListenerRef.markAllUnavailable();
Richard Smith95dc57a2015-10-16 23:20:19 +00001605 return true;
1606
1607 default:
1608 return false;
1609 }
Richard Smithe842a472014-10-22 02:05:46 +00001610}
1611
1612ModuleLoadResult
Douglas Gregor7a626572012-11-29 23:55:25 +00001613CompilerInstance::loadModule(SourceLocation ImportLoc,
1614 ModuleIdPath Path,
1615 Module::NameVisibilityKind Visibility,
1616 bool IsInclusionDirective) {
Richard Smith92304e02013-10-18 22:48:20 +00001617 // Determine what file we're searching from.
Boris Kolpackov734d8542017-08-29 15:30:18 +00001618 // FIXME: Should we be deciding whether this is a submodule (here and
1619 // below) based on -fmodules-ts or should we pass a flag and make the
1620 // caller decide?
1621 std::string ModuleName;
1622 if (getLangOpts().ModulesTS) {
1623 // FIXME: Same code as Sema::ActOnModuleDecl() so there is probably a
1624 // better place/way to do this.
1625 for (auto &Piece : Path) {
1626 if (!ModuleName.empty())
1627 ModuleName += ".";
1628 ModuleName += Piece.first->getName();
1629 }
1630 }
1631 else
1632 ModuleName = Path[0].first->getName();
1633
Richard Smith92304e02013-10-18 22:48:20 +00001634 SourceLocation ModuleNameLoc = Path[0].second;
1635
Douglas Gregor1805b8a2011-11-30 04:26:53 +00001636 // If we've already handled this import, just return the cached result.
1637 // This one-element cache is important to eliminate redundant diagnostics
1638 // when both the preprocessor and parser see the same import declaration.
Yaron Keren8b563662015-10-03 10:46:20 +00001639 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
Douglas Gregorff2be532011-12-01 17:11:21 +00001640 // Make the named module visible.
Richard Smith7e82e012016-02-19 22:25:36 +00001641 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00001642 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00001643 ImportLoc);
Douglas Gregor69021972011-11-30 17:33:56 +00001644 return LastModuleImportResult;
Douglas Gregorff2be532011-12-01 17:11:21 +00001645 }
Douglas Gregor5196bc62011-11-30 04:03:44 +00001646
Craig Topper49a27902014-05-22 04:46:25 +00001647 clang::Module *Module = nullptr;
Richard Smith92304e02013-10-18 22:48:20 +00001648
Douglas Gregor5196bc62011-11-30 04:03:44 +00001649 // If we don't already have information on this module, load the module now.
Douglas Gregorde3ef502011-11-30 23:21:26 +00001650 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
Douglas Gregor69021972011-11-30 17:33:56 +00001651 = KnownModules.find(Path[0].first);
Douglas Gregor2537a362011-12-08 17:01:29 +00001652 if (Known != KnownModules.end()) {
1653 // Retrieve the cached top-level module.
1654 Module = Known->second;
Richard Smith7e82e012016-02-19 22:25:36 +00001655 } else if (ModuleName == getLangOpts().CurrentModule) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001656 // This is the module we're building.
Ben Langmuir527040e2014-05-05 05:31:33 +00001657 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001658 /// FIXME: perhaps we should (a) look for a module using the module name
1659 // to file map (PrebuiltModuleFiles) and (b) diagnose if still not found?
1660 //if (Module == nullptr) {
1661 // getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1662 // << ModuleName;
1663 // ModuleBuildFailed = true;
1664 // return ModuleLoadResult();
1665 //}
Douglas Gregor2537a362011-12-08 17:01:29 +00001666 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1667 } else {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001668 // Search for a module with the given name.
Douglas Gregor279a6c32012-01-29 17:08:11 +00001669 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
Manman Ren11f2a472016-08-18 17:42:15 +00001670 HeaderSearchOptions &HSOpts =
1671 PP->getHeaderSearchInfo().getHeaderSearchOpts();
1672
1673 std::string ModuleFileName;
Richard Smith5d2ed482017-06-09 19:22:32 +00001674 enum ModuleSource {
1675 ModuleNotFound, ModuleCache, PrebuiltModulePath, ModuleBuildPragma
1676 } Source = ModuleNotFound;
1677
1678 // Check to see if the module has been built as part of this compilation
1679 // via a module build pragma.
1680 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1681 if (BuiltModuleIt != BuiltModules.end()) {
1682 ModuleFileName = BuiltModuleIt->second;
1683 Source = ModuleBuildPragma;
1684 }
1685
1686 // Try to load the module from the prebuilt module path.
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001687 if (Source == ModuleNotFound && (!HSOpts.PrebuiltModuleFiles.empty() ||
1688 !HSOpts.PrebuiltModulePaths.empty())) {
1689 ModuleFileName =
1690 PP->getHeaderSearchInfo().getPrebuiltModuleFileName(ModuleName);
Manman Ren11f2a472016-08-18 17:42:15 +00001691 if (!ModuleFileName.empty())
Richard Smith5d2ed482017-06-09 19:22:32 +00001692 Source = PrebuiltModulePath;
Manman Ren11f2a472016-08-18 17:42:15 +00001693 }
Richard Smith5d2ed482017-06-09 19:22:32 +00001694
1695 // Try to load the module from the module cache.
1696 if (Source == ModuleNotFound && Module) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001697 ModuleFileName = PP->getHeaderSearchInfo().getCachedModuleFileName(Module);
Richard Smith5d2ed482017-06-09 19:22:32 +00001698 Source = ModuleCache;
1699 }
1700
1701 if (Source == ModuleNotFound) {
Manman Ren11f2a472016-08-18 17:42:15 +00001702 // We can't find a module, error out here.
Ben Langmuir9eb229b2014-01-22 23:19:39 +00001703 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
Richard Smith5d2ed482017-06-09 19:22:32 +00001704 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
Ben Langmuir9eb229b2014-01-22 23:19:39 +00001705 ModuleBuildFailed = true;
1706 return ModuleLoadResult();
1707 }
1708
Richard Smithd520a252015-07-21 18:07:47 +00001709 if (ModuleFileName.empty()) {
Manman Ren11f2a472016-08-18 17:42:15 +00001710 if (Module && Module->HasIncompatibleModuleFile) {
Richard Smith8a308ec2015-11-05 00:54:55 +00001711 // We tried and failed to load a module file for this module. Fall
1712 // back to textual inclusion for its headers.
Richard Smitha114c462016-12-06 00:40:17 +00001713 return ModuleLoadResult::ConfigMismatch;
Richard Smith8a308ec2015-11-05 00:54:55 +00001714 }
1715
Manuel Klimekd2e8b042015-02-20 11:44:41 +00001716 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1717 << ModuleName;
1718 ModuleBuildFailed = true;
1719 return ModuleLoadResult();
1720 }
Richard Smithd4b230b2014-10-27 23:01:16 +00001721
Douglas Gregor5196bc62011-11-30 04:03:44 +00001722 // If we don't already have an ASTReader, create one now.
John Thompson2255f2c2014-04-23 12:57:01 +00001723 if (!ModuleManager)
1724 createModuleManager();
Douglas Gregor5196bc62011-11-30 04:03:44 +00001725
Richard Smithce18a182015-07-14 00:26:00 +00001726 llvm::Timer Timer;
1727 if (FrontendTimerGroup)
Matthias Braunae032b62016-11-18 19:43:25 +00001728 Timer.init("loading." + ModuleFileName, "Loading " + ModuleFileName,
1729 *FrontendTimerGroup);
Richard Smithce18a182015-07-14 00:26:00 +00001730 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1731
Richard Smith5d2ed482017-06-09 19:22:32 +00001732 // Try to load the module file. If we are not trying to load from the
1733 // module cache, we don't know how to rebuild modules.
1734 unsigned ARRFlags = Source == ModuleCache ?
1735 ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing :
1736 ASTReader::ARR_ConfigurationMismatch;
Richard Smithe842a472014-10-22 02:05:46 +00001737 switch (ModuleManager->ReadAST(ModuleFileName,
Richard Smith5d2ed482017-06-09 19:22:32 +00001738 Source == PrebuiltModulePath
1739 ? serialization::MK_PrebuiltModule
1740 : Source == ModuleBuildPragma
1741 ? serialization::MK_ExplicitModule
1742 : serialization::MK_ImplicitModule,
1743 ImportLoc, ARRFlags)) {
Manman Ren11f2a472016-08-18 17:42:15 +00001744 case ASTReader::Success: {
Richard Smith5d2ed482017-06-09 19:22:32 +00001745 if (Source != ModuleCache && !Module) {
Manman Ren11f2a472016-08-18 17:42:15 +00001746 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1747 if (!Module || !Module->getASTFile() ||
1748 FileMgr->getFile(ModuleFileName) != Module->getASTFile()) {
1749 // Error out if Module does not refer to the file in the prebuilt
1750 // module path.
1751 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1752 << ModuleName;
1753 ModuleBuildFailed = true;
1754 KnownModules[Path[0].first] = nullptr;
1755 return ModuleLoadResult();
1756 }
1757 }
Douglas Gregor5196bc62011-11-30 04:03:44 +00001758 break;
Manman Ren11f2a472016-08-18 17:42:15 +00001759 }
Douglas Gregor5196bc62011-11-30 04:03:44 +00001760
Eli Friedman963ff2c2013-09-17 00:51:29 +00001761 case ASTReader::OutOfDate:
Douglas Gregor7029ce12013-03-19 00:28:20 +00001762 case ASTReader::Missing: {
Richard Smith5d2ed482017-06-09 19:22:32 +00001763 if (Source != ModuleCache) {
1764 // We don't know the desired configuration for this module and don't
1765 // necessarily even have a module map. Since ReadAST already produces
1766 // diagnostics for these two cases, we simply error out here.
Manman Ren11f2a472016-08-18 17:42:15 +00001767 ModuleBuildFailed = true;
1768 KnownModules[Path[0].first] = nullptr;
1769 return ModuleLoadResult();
1770 }
1771
Eli Friedman963ff2c2013-09-17 00:51:29 +00001772 // The module file is missing or out-of-date. Build it.
Ben Langmuir9eb229b2014-01-22 23:19:39 +00001773 assert(Module && "missing module file");
Douglas Gregor7029ce12013-03-19 00:28:20 +00001774 // Check whether there is a cycle in the module graph.
1775 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1776 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1777 for (; Pos != PosEnd; ++Pos) {
1778 if (Pos->first == ModuleName)
1779 break;
1780 }
1781
1782 if (Pos != PosEnd) {
1783 SmallString<256> CyclePath;
1784 for (; Pos != PosEnd; ++Pos) {
1785 CyclePath += Pos->first;
1786 CyclePath += " -> ";
1787 }
1788 CyclePath += ModuleName;
1789
1790 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1791 << ModuleName << CyclePath;
1792 return ModuleLoadResult();
1793 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001794
1795 // Check whether we have already attempted to build this module (but
1796 // failed).
1797 if (getPreprocessorOpts().FailedModules &&
1798 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1799 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1800 << ModuleName
1801 << SourceRange(ImportLoc, ModuleNameLoc);
Douglas Gregorc1bbec82013-01-25 00:45:27 +00001802 ModuleBuildFailed = true;
Douglas Gregor7a626572012-11-29 23:55:25 +00001803 return ModuleLoadResult();
1804 }
1805
Ben Langmuirdbdc0362014-06-17 22:35:27 +00001806 // Try to compile and then load the module.
1807 if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
1808 ModuleFileName)) {
Ben Langmuird213aab2014-09-26 22:42:23 +00001809 assert(getDiagnostics().hasErrorOccurred() &&
1810 "undiagnosed error in compileAndLoadModule");
Douglas Gregor0f2b4632013-01-10 02:04:18 +00001811 if (getPreprocessorOpts().FailedModules)
1812 getPreprocessorOpts().FailedModules->addFailed(ModuleName);
Craig Topper49a27902014-05-22 04:46:25 +00001813 KnownModules[Path[0].first] = nullptr;
Douglas Gregorc1bbec82013-01-25 00:45:27 +00001814 ModuleBuildFailed = true;
Douglas Gregor7a626572012-11-29 23:55:25 +00001815 return ModuleLoadResult();
Douglas Gregor188dbef2012-11-07 17:46:15 +00001816 }
1817
1818 // Okay, we've rebuilt and now loaded the module.
1819 break;
1820 }
1821
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +00001822 case ASTReader::ConfigurationMismatch:
Richard Smith5d2ed482017-06-09 19:22:32 +00001823 if (Source == PrebuiltModulePath)
1824 // FIXME: We shouldn't be setting HadFatalFailure below if we only
1825 // produce a warning here!
Manman Ren11f2a472016-08-18 17:42:15 +00001826 getDiagnostics().Report(SourceLocation(),
1827 diag::warn_module_config_mismatch)
1828 << ModuleFileName;
1829 // Fall through to error out.
Galina Kistanovae37ad5a2017-06-03 06:27:16 +00001830 LLVM_FALLTHROUGH;
Manman Ren11f2a472016-08-18 17:42:15 +00001831 case ASTReader::VersionMismatch:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +00001832 case ASTReader::HadErrors:
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001833 ModuleLoader::HadFatalFailure = true;
Richard Smith0f99d6a2015-08-09 08:48:41 +00001834 // FIXME: The ASTReader will already have complained, but can we shoehorn
Douglas Gregor5196bc62011-11-30 04:03:44 +00001835 // that diagnostic information into a more useful form?
Craig Topper49a27902014-05-22 04:46:25 +00001836 KnownModules[Path[0].first] = nullptr;
Douglas Gregor7a626572012-11-29 23:55:25 +00001837 return ModuleLoadResult();
Douglas Gregor5196bc62011-11-30 04:03:44 +00001838
1839 case ASTReader::Failure:
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001840 ModuleLoader::HadFatalFailure = true;
Douglas Gregor69021972011-11-30 17:33:56 +00001841 // Already complained, but note now that we failed.
Craig Topper49a27902014-05-22 04:46:25 +00001842 KnownModules[Path[0].first] = nullptr;
Douglas Gregorc1bbec82013-01-25 00:45:27 +00001843 ModuleBuildFailed = true;
Douglas Gregor7a626572012-11-29 23:55:25 +00001844 return ModuleLoadResult();
Douglas Gregor5196bc62011-11-30 04:03:44 +00001845 }
Argyrios Kyrtzidis43af5132012-09-29 01:06:04 +00001846
Douglas Gregor69021972011-11-30 17:33:56 +00001847 // Cache the result of this top-level module lookup for later.
1848 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
Douglas Gregor08142532011-08-26 23:56:07 +00001849 }
Douglas Gregor5196bc62011-11-30 04:03:44 +00001850
Douglas Gregor69021972011-11-30 17:33:56 +00001851 // If we never found the module, fail.
1852 if (!Module)
Douglas Gregor7a626572012-11-29 23:55:25 +00001853 return ModuleLoadResult();
Richard Smith5d2ed482017-06-09 19:22:32 +00001854
Douglas Gregor5196bc62011-11-30 04:03:44 +00001855 // Verify that the rest of the module path actually corresponds to
1856 // a submodule.
Bruno Cardoso Lopes84bc0a22017-12-22 05:04:43 +00001857 bool MapPrivateSubModToTopLevel = false;
Boris Kolpackov734d8542017-08-29 15:30:18 +00001858 if (!getLangOpts().ModulesTS && Path.size() > 1) {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001859 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1860 StringRef Name = Path[I].first->getName();
Douglas Gregoreb90e832012-01-04 23:32:19 +00001861 clang::Module *Sub = Module->findSubmodule(Name);
Bruno Cardoso Lopes92849312018-02-12 23:43:21 +00001862
1863 // If the user is requesting Foo.Private and it doesn't exist, try to
1864 // match Foo_Private and emit a warning asking for the user to write
1865 // @import Foo_Private instead. FIXME: remove this when existing clients
1866 // migrate off of Foo.Private syntax.
1867 if (!Sub && PP->getLangOpts().ImplicitModules && Name == "Private" &&
1868 Module == Module->getTopLevelModule()) {
1869 SmallString<128> PrivateModule(Module->Name);
1870 PrivateModule.append("_Private");
1871
1872 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
1873 auto &II = PP->getIdentifierTable().get(
1874 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
1875 PrivPath.push_back(std::make_pair(&II, Path[0].second));
1876
1877 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule))
1878 Sub =
1879 loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
1880 if (Sub) {
1881 MapPrivateSubModToTopLevel = true;
1882 if (!getDiagnostics().isIgnored(
1883 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
1884 getDiagnostics().Report(Path[I].second,
1885 diag::warn_no_priv_submodule_use_toplevel)
1886 << Path[I].first << Module->getFullModuleName() << PrivateModule
1887 << SourceRange(Path[0].second, Path[I].second)
1888 << FixItHint::CreateReplacement(SourceRange(Path[0].second),
1889 PrivateModule);
1890 getDiagnostics().Report(Sub->DefinitionLoc,
1891 diag::note_private_top_level_defined);
1892 }
1893 }
1894 }
Douglas Gregor5196bc62011-11-30 04:03:44 +00001895
Douglas Gregoreb90e832012-01-04 23:32:19 +00001896 if (!Sub) {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001897 // Attempt to perform typo correction to find a module name that works.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001898 SmallVector<StringRef, 2> Best;
Douglas Gregor5196bc62011-11-30 04:03:44 +00001899 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1900
Douglas Gregoreb90e832012-01-04 23:32:19 +00001901 for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1902 JEnd = Module->submodule_end();
Matt Beaumont-Gayeb44eda2011-11-30 19:41:21 +00001903 J != JEnd; ++J) {
Douglas Gregoreb90e832012-01-04 23:32:19 +00001904 unsigned ED = Name.edit_distance((*J)->Name,
Douglas Gregor5196bc62011-11-30 04:03:44 +00001905 /*AllowReplacements=*/true,
1906 BestEditDistance);
1907 if (ED <= BestEditDistance) {
Douglas Gregoreb90e832012-01-04 23:32:19 +00001908 if (ED < BestEditDistance) {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001909 Best.clear();
Douglas Gregoreb90e832012-01-04 23:32:19 +00001910 BestEditDistance = ED;
1911 }
1912
1913 Best.push_back((*J)->Name);
Douglas Gregor5196bc62011-11-30 04:03:44 +00001914 }
1915 }
1916
1917 // If there was a clear winner, user it.
1918 if (Best.size() == 1) {
1919 getDiagnostics().Report(Path[I].second,
1920 diag::err_no_submodule_suggest)
Douglas Gregor69021972011-11-30 17:33:56 +00001921 << Path[I].first << Module->getFullModuleName() << Best[0]
Douglas Gregor5196bc62011-11-30 04:03:44 +00001922 << SourceRange(Path[0].second, Path[I-1].second)
1923 << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1924 Best[0]);
Douglas Gregoreb90e832012-01-04 23:32:19 +00001925
1926 Sub = Module->findSubmodule(Best[0]);
Douglas Gregor5196bc62011-11-30 04:03:44 +00001927 }
1928 }
Bruno Cardoso Lopes84bc0a22017-12-22 05:04:43 +00001929
Douglas Gregoreb90e832012-01-04 23:32:19 +00001930 if (!Sub) {
Douglas Gregor5196bc62011-11-30 04:03:44 +00001931 // No submodule by this name. Complain, and don't look for further
1932 // submodules.
1933 getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
Douglas Gregor69021972011-11-30 17:33:56 +00001934 << Path[I].first << Module->getFullModuleName()
Douglas Gregor5196bc62011-11-30 04:03:44 +00001935 << SourceRange(Path[0].second, Path[I-1].second);
1936 break;
1937 }
1938
Douglas Gregoreb90e832012-01-04 23:32:19 +00001939 Module = Sub;
Douglas Gregor5196bc62011-11-30 04:03:44 +00001940 }
Douglas Gregor08142532011-08-26 23:56:07 +00001941 }
Ben Langmuirb537a3a2014-07-23 15:30:23 +00001942
Douglas Gregor2537a362011-12-08 17:01:29 +00001943 // Make the named module visible, if it's not already part of the module
1944 // we are parsing.
Douglas Gregor98a52db2011-12-20 00:28:52 +00001945 if (ModuleName != getLangOpts().CurrentModule) {
Bruno Cardoso Lopes84bc0a22017-12-22 05:04:43 +00001946 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
Douglas Gregor98a52db2011-12-20 00:28:52 +00001947 // We have an umbrella header or directory that doesn't actually include
1948 // all of the headers within the directory it covers. Complain about
1949 // this missing submodule and recover by forgetting that we ever saw
1950 // this submodule.
1951 // FIXME: Should we detect this at module load time? It seems fairly
1952 // expensive (and rare).
1953 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1954 << Module->getFullModuleName()
1955 << SourceRange(Path.front().second, Path.back().second);
Craig Topper49a27902014-05-22 04:46:25 +00001956
Richard Smitha114c462016-12-06 00:40:17 +00001957 return ModuleLoadResult::MissingExpected;
Douglas Gregor98a52db2011-12-20 00:28:52 +00001958 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00001959
1960 // Check whether this module is available.
Richard Smith27e5aa02017-06-05 18:57:56 +00001961 if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
1962 getDiagnostics(), Module)) {
1963 getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
1964 << SourceRange(Path.front().second, Path.back().second);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00001965 LastModuleImportLoc = ImportLoc;
Douglas Gregor7a626572012-11-29 23:55:25 +00001966 LastModuleImportResult = ModuleLoadResult();
1967 return ModuleLoadResult();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00001968 }
1969
Richard Smitha7e2cc62015-05-01 01:53:09 +00001970 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
Douglas Gregor98a52db2011-12-20 00:28:52 +00001971 }
Douglas Gregor35b13ec2013-03-20 00:22:05 +00001972
1973 // Check for any configuration macros that have changed.
1974 clang::Module *TopModule = Module->getTopLevelModule();
1975 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1976 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
1977 Module, ImportLoc);
1978 }
1979
Douglas Gregor1805b8a2011-11-30 04:26:53 +00001980 LastModuleImportLoc = ImportLoc;
Richard Smitha114c462016-12-06 00:40:17 +00001981 LastModuleImportResult = ModuleLoadResult(Module);
Douglas Gregor7a626572012-11-29 23:55:25 +00001982 return LastModuleImportResult;
Douglas Gregor08142532011-08-26 23:56:07 +00001983}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00001984
Richard Smith5d2ed482017-06-09 19:22:32 +00001985void CompilerInstance::loadModuleFromSource(SourceLocation ImportLoc,
1986 StringRef ModuleName,
1987 StringRef Source) {
Richard Smith9565c75b2017-06-19 23:09:36 +00001988 // Avoid creating filenames with special characters.
1989 SmallString<128> CleanModuleName(ModuleName);
1990 for (auto &C : CleanModuleName)
1991 if (!isAlphanumeric(C))
1992 C = '_';
1993
Richard Smith5d2ed482017-06-09 19:22:32 +00001994 // FIXME: Using a randomized filename here means that our intermediate .pcm
1995 // output is nondeterministic (as .pcm files refer to each other by name).
1996 // Can this affect the output in any way?
1997 SmallString<128> ModuleFileName;
1998 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
Richard Smith9565c75b2017-06-19 23:09:36 +00001999 CleanModuleName, "pcm", ModuleFileName)) {
Richard Smith5d2ed482017-06-09 19:22:32 +00002000 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2001 << ModuleFileName << EC.message();
2002 return;
2003 }
Richard Smith9565c75b2017-06-19 23:09:36 +00002004 std::string ModuleMapFileName = (CleanModuleName + ".map").str();
Richard Smith5d2ed482017-06-09 19:22:32 +00002005
2006 FrontendInputFile Input(
2007 ModuleMapFileName,
2008 InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
2009 InputKind::ModuleMap, /*Preprocessed*/true));
2010
2011 std::string NullTerminatedSource(Source.str());
2012
2013 auto PreBuildStep = [&](CompilerInstance &Other) {
2014 // Create a virtual file containing our desired source.
2015 // FIXME: We shouldn't need to do this.
2016 const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
2017 ModuleMapFileName, NullTerminatedSource.size(), 0);
2018 Other.getSourceManager().overrideFileContents(
2019 ModuleMapFile,
2020 llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
2021
2022 Other.BuiltModules = std::move(BuiltModules);
Richard Smith86a3ef52017-06-09 21:24:02 +00002023 Other.DeleteBuiltModules = false;
Richard Smith5d2ed482017-06-09 19:22:32 +00002024 };
2025
2026 auto PostBuildStep = [this](CompilerInstance &Other) {
2027 BuiltModules = std::move(Other.BuiltModules);
Richard Smith5d2ed482017-06-09 19:22:32 +00002028 };
2029
2030 // Build the module, inheriting any modules that we've built locally.
2031 if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
2032 ModuleFileName, PreBuildStep, PostBuildStep)) {
2033 BuiltModules[ModuleName] = ModuleFileName.str();
2034 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2035 }
2036}
2037
Douglas Gregorc147b0b2013-01-12 01:29:50 +00002038void CompilerInstance::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00002039 Module::NameVisibilityKind Visibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00002040 SourceLocation ImportLoc) {
Richard Smith42413142015-05-15 20:05:43 +00002041 if (!ModuleManager)
2042 createModuleManager();
2043 if (!ModuleManager)
2044 return;
2045
Richard Smitha7e2cc62015-05-01 01:53:09 +00002046 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
Douglas Gregorc147b0b2013-01-12 01:29:50 +00002047}
2048
John Thompson2255f2c2014-04-23 12:57:01 +00002049GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
2050 SourceLocation TriggerLoc) {
Richard Smith3938f0c2015-08-15 00:34:15 +00002051 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2052 return nullptr;
John Thompson2255f2c2014-04-23 12:57:01 +00002053 if (!ModuleManager)
2054 createModuleManager();
2055 // Can't do anything if we don't have the module manager.
2056 if (!ModuleManager)
Craig Topper49a27902014-05-22 04:46:25 +00002057 return nullptr;
John Thompson2255f2c2014-04-23 12:57:01 +00002058 // Get an existing global index. This loads it if not already
2059 // loaded.
2060 ModuleManager->loadGlobalIndex();
2061 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
2062 // If the global index doesn't exist, create it.
2063 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2064 hasPreprocessor()) {
2065 llvm::sys::fs::create_directories(
2066 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2067 GlobalModuleIndex::writeIndex(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00002068 getFileManager(), getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002069 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
John Thompson2255f2c2014-04-23 12:57:01 +00002070 ModuleManager->resetForReload();
2071 ModuleManager->loadGlobalIndex();
2072 GlobalIndex = ModuleManager->getGlobalIndex();
2073 }
2074 // For finding modules needing to be imported for fixit messages,
2075 // we need to make the global index cover all modules, so we do that here.
2076 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2077 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2078 bool RecreateIndex = false;
2079 for (ModuleMap::module_iterator I = MMap.module_begin(),
2080 E = MMap.module_end(); I != E; ++I) {
2081 Module *TheModule = I->second;
2082 const FileEntry *Entry = TheModule->getASTFile();
2083 if (!Entry) {
2084 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2085 Path.push_back(std::make_pair(
Richard Smith629d8e62015-08-11 00:03:28 +00002086 getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
John Thompson2255f2c2014-04-23 12:57:01 +00002087 std::reverse(Path.begin(), Path.end());
Richard Smith629d8e62015-08-11 00:03:28 +00002088 // Load a module as hidden. This also adds it to the global index.
2089 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
John Thompson2255f2c2014-04-23 12:57:01 +00002090 RecreateIndex = true;
2091 }
2092 }
2093 if (RecreateIndex) {
2094 GlobalModuleIndex::writeIndex(
Adrian Prantlfb2398d2015-07-17 01:19:54 +00002095 getFileManager(), getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002096 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
John Thompson2255f2c2014-04-23 12:57:01 +00002097 ModuleManager->resetForReload();
2098 ModuleManager->loadGlobalIndex();
2099 GlobalIndex = ModuleManager->getGlobalIndex();
2100 }
2101 HaveFullGlobalModuleIndex = true;
2102 }
2103 return GlobalIndex;
2104}
John Thompson2d94bbb2014-04-23 19:04:32 +00002105
2106// Check global module index for missing imports.
2107bool
2108CompilerInstance::lookupMissingImports(StringRef Name,
2109 SourceLocation TriggerLoc) {
2110 // Look for the symbol in non-imported modules, but only if an error
2111 // actually occurred.
2112 if (!buildingModule()) {
2113 // Load global module index, or retrieve a previously loaded one.
2114 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
2115 TriggerLoc);
2116
2117 // Only if we have a global index.
2118 if (GlobalIndex) {
2119 GlobalModuleIndex::HitSet FoundModules;
2120
2121 // Find the modules that reference the identifier.
2122 // Note that this only finds top-level modules.
2123 // We'll let diagnoseTypo find the actual declaration module.
2124 if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2125 return true;
2126 }
2127 }
2128
2129 return false;
2130}
David Blaikiea97eaa12014-08-29 16:53:14 +00002131void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); }
Benjamin Kramer7de99692016-11-16 18:15:26 +00002132
2133void CompilerInstance::setExternalSemaSource(
2134 IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
2135 ExternalSemaSrc = std::move(ESS);
2136}