ModuleManager.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. //===- ModuleManager.cpp - Module Manager ---------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the ModuleManager class, which manages a set of loaded
  10. // modules for the ASTReader.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Serialization/ModuleManager.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/LLVM.h"
  16. #include "clang/Lex/HeaderSearch.h"
  17. #include "clang/Lex/ModuleMap.h"
  18. #include "clang/Serialization/GlobalModuleIndex.h"
  19. #include "clang/Serialization/InMemoryModuleCache.h"
  20. #include "clang/Serialization/Module.h"
  21. #include "clang/Serialization/PCHContainerOperations.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SetVector.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/iterator.h"
  28. #include "llvm/Support/Chrono.h"
  29. #include "llvm/Support/DOTGraphTraits.h"
  30. #include "llvm/Support/ErrorOr.h"
  31. #include "llvm/Support/GraphWriter.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/VirtualFileSystem.h"
  34. #include <algorithm>
  35. #include <cassert>
  36. #include <memory>
  37. #include <string>
  38. #include <system_error>
  39. using namespace clang;
  40. using namespace serialization;
  41. ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
  42. const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
  43. /*cacheFailure=*/false);
  44. if (Entry)
  45. return lookup(Entry);
  46. return nullptr;
  47. }
  48. ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
  49. if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
  50. if (const FileEntry *File = Mod->getASTFile())
  51. return lookup(File);
  52. return nullptr;
  53. }
  54. ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
  55. auto Known = Modules.find(File);
  56. if (Known == Modules.end())
  57. return nullptr;
  58. return Known->second;
  59. }
  60. std::unique_ptr<llvm::MemoryBuffer>
  61. ModuleManager::lookupBuffer(StringRef Name) {
  62. const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
  63. /*cacheFailure=*/false);
  64. return std::move(InMemoryBuffers[Entry]);
  65. }
  66. static bool checkSignature(ASTFileSignature Signature,
  67. ASTFileSignature ExpectedSignature,
  68. std::string &ErrorStr) {
  69. if (!ExpectedSignature || Signature == ExpectedSignature)
  70. return false;
  71. ErrorStr =
  72. Signature ? "signature mismatch" : "could not read module signature";
  73. return true;
  74. }
  75. static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
  76. SourceLocation ImportLoc) {
  77. if (ImportedBy) {
  78. MF.ImportedBy.insert(ImportedBy);
  79. ImportedBy->Imports.insert(&MF);
  80. } else {
  81. if (!MF.DirectlyImported)
  82. MF.ImportLoc = ImportLoc;
  83. MF.DirectlyImported = true;
  84. }
  85. }
  86. ModuleManager::AddModuleResult
  87. ModuleManager::addModule(StringRef FileName, ModuleKind Type,
  88. SourceLocation ImportLoc, ModuleFile *ImportedBy,
  89. unsigned Generation,
  90. off_t ExpectedSize, time_t ExpectedModTime,
  91. ASTFileSignature ExpectedSignature,
  92. ASTFileSignatureReader ReadSignature,
  93. ModuleFile *&Module,
  94. std::string &ErrorStr) {
  95. Module = nullptr;
  96. // Look for the file entry. This only fails if the expected size or
  97. // modification time differ.
  98. const FileEntry *Entry;
  99. if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
  100. // If we're not expecting to pull this file out of the module cache, it
  101. // might have a different mtime due to being moved across filesystems in
  102. // a distributed build. The size must still match, though. (As must the
  103. // contents, but we can't check that.)
  104. ExpectedModTime = 0;
  105. }
  106. if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
  107. ErrorStr = "module file out of date";
  108. return OutOfDate;
  109. }
  110. if (!Entry && FileName != "-") {
  111. ErrorStr = "module file not found";
  112. return Missing;
  113. }
  114. // Check whether we already loaded this module, before
  115. if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
  116. // Check the stored signature.
  117. if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
  118. return OutOfDate;
  119. Module = ModuleEntry;
  120. updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
  121. return AlreadyLoaded;
  122. }
  123. // Allocate a new module.
  124. auto NewModule = llvm::make_unique<ModuleFile>(Type, Generation);
  125. NewModule->Index = Chain.size();
  126. NewModule->FileName = FileName.str();
  127. NewModule->File = Entry;
  128. NewModule->ImportLoc = ImportLoc;
  129. NewModule->InputFilesValidationTimestamp = 0;
  130. if (NewModule->Kind == MK_ImplicitModule) {
  131. std::string TimestampFilename = NewModule->getTimestampFilename();
  132. llvm::vfs::Status Status;
  133. // A cached stat value would be fine as well.
  134. if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
  135. NewModule->InputFilesValidationTimestamp =
  136. llvm::sys::toTimeT(Status.getLastModificationTime());
  137. }
  138. // Load the contents of the module
  139. if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
  140. // The buffer was already provided for us.
  141. NewModule->Buffer = &ModuleCache->addBuffer(FileName, std::move(Buffer));
  142. // Since the cached buffer is reused, it is safe to close the file
  143. // descriptor that was opened while stat()ing the PCM in
  144. // lookupModuleFile() above, it won't be needed any longer.
  145. Entry->closeFile();
  146. } else if (llvm::MemoryBuffer *Buffer =
  147. getModuleCache().lookupBuffer(FileName)) {
  148. NewModule->Buffer = Buffer;
  149. // As above, the file descriptor is no longer needed.
  150. Entry->closeFile();
  151. } else {
  152. // Open the AST file.
  153. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
  154. if (FileName == "-") {
  155. Buf = llvm::MemoryBuffer::getSTDIN();
  156. } else {
  157. // Get a buffer of the file and close the file descriptor when done.
  158. Buf = FileMgr.getBufferForFile(NewModule->File,
  159. /*IsVolatile=*/false,
  160. /*ShouldClose=*/true);
  161. }
  162. if (!Buf) {
  163. ErrorStr = Buf.getError().message();
  164. return Missing;
  165. }
  166. NewModule->Buffer = &getModuleCache().addBuffer(FileName, std::move(*Buf));
  167. }
  168. // Initialize the stream.
  169. NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
  170. // Read the signature eagerly now so that we can check it. Avoid calling
  171. // ReadSignature unless there's something to check though.
  172. if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
  173. ExpectedSignature, ErrorStr)) {
  174. // Try to remove the buffer. If it can't be removed, then it was already
  175. // validated by this process.
  176. if (!getModuleCache().tryToRemoveBuffer(NewModule->FileName))
  177. FileMgr.invalidateCache(NewModule->File);
  178. return OutOfDate;
  179. }
  180. // We're keeping this module. Store it everywhere.
  181. Module = Modules[Entry] = NewModule.get();
  182. updateModuleImports(*NewModule, ImportedBy, ImportLoc);
  183. if (!NewModule->isModule())
  184. PCHChain.push_back(NewModule.get());
  185. if (!ImportedBy)
  186. Roots.push_back(NewModule.get());
  187. Chain.push_back(std::move(NewModule));
  188. return NewlyLoaded;
  189. }
  190. void ModuleManager::removeModules(
  191. ModuleIterator First,
  192. llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
  193. ModuleMap *modMap) {
  194. auto Last = end();
  195. if (First == Last)
  196. return;
  197. // Explicitly clear VisitOrder since we might not notice it is stale.
  198. VisitOrder.clear();
  199. // Collect the set of module file pointers that we'll be removing.
  200. llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
  201. (llvm::pointer_iterator<ModuleIterator>(First)),
  202. (llvm::pointer_iterator<ModuleIterator>(Last)));
  203. auto IsVictim = [&](ModuleFile *MF) {
  204. return victimSet.count(MF);
  205. };
  206. // Remove any references to the now-destroyed modules.
  207. for (auto I = begin(); I != First; ++I) {
  208. I->Imports.remove_if(IsVictim);
  209. I->ImportedBy.remove_if(IsVictim);
  210. }
  211. Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
  212. Roots.end());
  213. // Remove the modules from the PCH chain.
  214. for (auto I = First; I != Last; ++I) {
  215. if (!I->isModule()) {
  216. PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), &*I),
  217. PCHChain.end());
  218. break;
  219. }
  220. }
  221. // Delete the modules and erase them from the various structures.
  222. for (ModuleIterator victim = First; victim != Last; ++victim) {
  223. Modules.erase(victim->File);
  224. if (modMap) {
  225. StringRef ModuleName = victim->ModuleName;
  226. if (Module *mod = modMap->findModule(ModuleName)) {
  227. mod->setASTFile(nullptr);
  228. }
  229. }
  230. // Files that didn't make it through ReadASTCore successfully will be
  231. // rebuilt (or there was an error). Invalidate them so that we can load the
  232. // new files that will be renamed over the old ones.
  233. //
  234. // The ModuleCache tracks whether the module was successfully loaded in
  235. // another thread/context; in that case, it won't need to be rebuilt (and
  236. // we can't safely invalidate it anyway).
  237. if (LoadedSuccessfully.count(&*victim) == 0 &&
  238. !getModuleCache().tryToRemoveBuffer(victim->FileName))
  239. FileMgr.invalidateCache(victim->File);
  240. }
  241. // Delete the modules.
  242. Chain.erase(Chain.begin() + (First - begin()), Chain.end());
  243. }
  244. void
  245. ModuleManager::addInMemoryBuffer(StringRef FileName,
  246. std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  247. const FileEntry *Entry =
  248. FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
  249. InMemoryBuffers[Entry] = std::move(Buffer);
  250. }
  251. ModuleManager::VisitState *ModuleManager::allocateVisitState() {
  252. // Fast path: if we have a cached state, use it.
  253. if (FirstVisitState) {
  254. VisitState *Result = FirstVisitState;
  255. FirstVisitState = FirstVisitState->NextState;
  256. Result->NextState = nullptr;
  257. return Result;
  258. }
  259. // Allocate and return a new state.
  260. return new VisitState(size());
  261. }
  262. void ModuleManager::returnVisitState(VisitState *State) {
  263. assert(State->NextState == nullptr && "Visited state is in list?");
  264. State->NextState = FirstVisitState;
  265. FirstVisitState = State;
  266. }
  267. void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
  268. GlobalIndex = Index;
  269. if (!GlobalIndex) {
  270. ModulesInCommonWithGlobalIndex.clear();
  271. return;
  272. }
  273. // Notify the global module index about all of the modules we've already
  274. // loaded.
  275. for (ModuleFile &M : *this)
  276. if (!GlobalIndex->loadedModuleFile(&M))
  277. ModulesInCommonWithGlobalIndex.push_back(&M);
  278. }
  279. void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
  280. if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
  281. return;
  282. ModulesInCommonWithGlobalIndex.push_back(MF);
  283. }
  284. ModuleManager::ModuleManager(FileManager &FileMgr,
  285. InMemoryModuleCache &ModuleCache,
  286. const PCHContainerReader &PCHContainerRdr,
  287. const HeaderSearch &HeaderSearchInfo)
  288. : FileMgr(FileMgr), ModuleCache(&ModuleCache),
  289. PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
  290. ModuleManager::~ModuleManager() { delete FirstVisitState; }
  291. void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
  292. llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
  293. // If the visitation order vector is the wrong size, recompute the order.
  294. if (VisitOrder.size() != Chain.size()) {
  295. unsigned N = size();
  296. VisitOrder.clear();
  297. VisitOrder.reserve(N);
  298. // Record the number of incoming edges for each module. When we
  299. // encounter a module with no incoming edges, push it into the queue
  300. // to seed the queue.
  301. SmallVector<ModuleFile *, 4> Queue;
  302. Queue.reserve(N);
  303. llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
  304. UnusedIncomingEdges.resize(size());
  305. for (ModuleFile &M : llvm::reverse(*this)) {
  306. unsigned Size = M.ImportedBy.size();
  307. UnusedIncomingEdges[M.Index] = Size;
  308. if (!Size)
  309. Queue.push_back(&M);
  310. }
  311. // Traverse the graph, making sure to visit a module before visiting any
  312. // of its dependencies.
  313. while (!Queue.empty()) {
  314. ModuleFile *CurrentModule = Queue.pop_back_val();
  315. VisitOrder.push_back(CurrentModule);
  316. // For any module that this module depends on, push it on the
  317. // stack (if it hasn't already been marked as visited).
  318. for (auto M = CurrentModule->Imports.rbegin(),
  319. MEnd = CurrentModule->Imports.rend();
  320. M != MEnd; ++M) {
  321. // Remove our current module as an impediment to visiting the
  322. // module we depend on. If we were the last unvisited module
  323. // that depends on this particular module, push it into the
  324. // queue to be visited.
  325. unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
  326. if (NumUnusedEdges && (--NumUnusedEdges == 0))
  327. Queue.push_back(*M);
  328. }
  329. }
  330. assert(VisitOrder.size() == N && "Visitation order is wrong?");
  331. delete FirstVisitState;
  332. FirstVisitState = nullptr;
  333. }
  334. VisitState *State = allocateVisitState();
  335. unsigned VisitNumber = State->NextVisitNumber++;
  336. // If the caller has provided us with a hit-set that came from the global
  337. // module index, mark every module file in common with the global module
  338. // index that is *not* in that set as 'visited'.
  339. if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
  340. for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
  341. {
  342. ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
  343. if (!ModuleFilesHit->count(M))
  344. State->VisitNumber[M->Index] = VisitNumber;
  345. }
  346. }
  347. for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
  348. ModuleFile *CurrentModule = VisitOrder[I];
  349. // Should we skip this module file?
  350. if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
  351. continue;
  352. // Visit the module.
  353. assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
  354. State->VisitNumber[CurrentModule->Index] = VisitNumber;
  355. if (!Visitor(*CurrentModule))
  356. continue;
  357. // The visitor has requested that cut off visitation of any
  358. // module that the current module depends on. To indicate this
  359. // behavior, we mark all of the reachable modules as having been visited.
  360. ModuleFile *NextModule = CurrentModule;
  361. do {
  362. // For any module that this module depends on, push it on the
  363. // stack (if it hasn't already been marked as visited).
  364. for (llvm::SetVector<ModuleFile *>::iterator
  365. M = NextModule->Imports.begin(),
  366. MEnd = NextModule->Imports.end();
  367. M != MEnd; ++M) {
  368. if (State->VisitNumber[(*M)->Index] != VisitNumber) {
  369. State->Stack.push_back(*M);
  370. State->VisitNumber[(*M)->Index] = VisitNumber;
  371. }
  372. }
  373. if (State->Stack.empty())
  374. break;
  375. // Pop the next module off the stack.
  376. NextModule = State->Stack.pop_back_val();
  377. } while (true);
  378. }
  379. returnVisitState(State);
  380. }
  381. bool ModuleManager::lookupModuleFile(StringRef FileName,
  382. off_t ExpectedSize,
  383. time_t ExpectedModTime,
  384. const FileEntry *&File) {
  385. if (FileName == "-") {
  386. File = nullptr;
  387. return false;
  388. }
  389. // Open the file immediately to ensure there is no race between stat'ing and
  390. // opening the file.
  391. File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
  392. if (!File)
  393. return false;
  394. if ((ExpectedSize && ExpectedSize != File->getSize()) ||
  395. (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
  396. // Do not destroy File, as it may be referenced. If we need to rebuild it,
  397. // it will be destroyed by removeModules.
  398. return true;
  399. return false;
  400. }
  401. #ifndef NDEBUG
  402. namespace llvm {
  403. template<>
  404. struct GraphTraits<ModuleManager> {
  405. using NodeRef = ModuleFile *;
  406. using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
  407. using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
  408. static ChildIteratorType child_begin(NodeRef Node) {
  409. return Node->Imports.begin();
  410. }
  411. static ChildIteratorType child_end(NodeRef Node) {
  412. return Node->Imports.end();
  413. }
  414. static nodes_iterator nodes_begin(const ModuleManager &Manager) {
  415. return nodes_iterator(Manager.begin());
  416. }
  417. static nodes_iterator nodes_end(const ModuleManager &Manager) {
  418. return nodes_iterator(Manager.end());
  419. }
  420. };
  421. template<>
  422. struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
  423. explicit DOTGraphTraits(bool IsSimple = false)
  424. : DefaultDOTGraphTraits(IsSimple) {}
  425. static bool renderGraphFromBottomUp() { return true; }
  426. std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
  427. return M->ModuleName;
  428. }
  429. };
  430. } // namespace llvm
  431. void ModuleManager::viewGraph() {
  432. llvm::ViewGraph(*this, "Modules");
  433. }
  434. #endif