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