ModuleManager.cpp 15 KB

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