ModuleManager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. PCHContainerRdr.ExtractPCH(ModuleEntry->Buffer->getMemBufferRef(),
  123. ModuleEntry->StreamFile);
  124. }
  125. if (ExpectedSignature) {
  126. // If we've not read the control block yet, read the signature eagerly now
  127. // so that we can check it.
  128. if (!ModuleEntry->Signature)
  129. ModuleEntry->Signature = ReadSignature(ModuleEntry->StreamFile);
  130. if (ModuleEntry->Signature != ExpectedSignature) {
  131. ErrorStr = ModuleEntry->Signature ? "signature mismatch"
  132. : "could not read module signature";
  133. if (NewModule)
  134. delete ModuleEntry;
  135. return OutOfDate;
  136. }
  137. }
  138. if (ImportedBy) {
  139. ModuleEntry->ImportedBy.insert(ImportedBy);
  140. ImportedBy->Imports.insert(ModuleEntry);
  141. } else {
  142. if (!ModuleEntry->DirectlyImported)
  143. ModuleEntry->ImportLoc = ImportLoc;
  144. ModuleEntry->DirectlyImported = true;
  145. }
  146. Module = ModuleEntry;
  147. if (!NewModule)
  148. return AlreadyLoaded;
  149. assert(!Modules[Entry] && "module loaded twice");
  150. Modules[Entry] = ModuleEntry;
  151. Chain.push_back(ModuleEntry);
  152. if (!ModuleEntry->isModule())
  153. PCHChain.push_back(ModuleEntry);
  154. if (!ImportedBy)
  155. Roots.push_back(ModuleEntry);
  156. return NewlyLoaded;
  157. }
  158. void ModuleManager::removeModules(
  159. ModuleIterator first, ModuleIterator last,
  160. llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
  161. ModuleMap *modMap) {
  162. if (first == last)
  163. return;
  164. // Explicitly clear VisitOrder since we might not notice it is stale.
  165. VisitOrder.clear();
  166. // Collect the set of module file pointers that we'll be removing.
  167. llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
  168. auto IsVictim = [&](ModuleFile *MF) {
  169. return victimSet.count(MF);
  170. };
  171. // Remove any references to the now-destroyed modules.
  172. for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
  173. Chain[i]->ImportedBy.remove_if(IsVictim);
  174. }
  175. Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
  176. Roots.end());
  177. // Remove the modules from the PCH chain.
  178. for (auto I = first; I != last; ++I) {
  179. if (!(*I)->isModule()) {
  180. PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), *I),
  181. PCHChain.end());
  182. break;
  183. }
  184. }
  185. // Delete the modules and erase them from the various structures.
  186. for (ModuleIterator victim = first; victim != last; ++victim) {
  187. Modules.erase((*victim)->File);
  188. if (modMap) {
  189. StringRef ModuleName = (*victim)->ModuleName;
  190. if (Module *mod = modMap->findModule(ModuleName)) {
  191. mod->setASTFile(nullptr);
  192. }
  193. }
  194. // Files that didn't make it through ReadASTCore successfully will be
  195. // rebuilt (or there was an error). Invalidate them so that we can load the
  196. // new files that will be renamed over the old ones.
  197. if (LoadedSuccessfully.count(*victim) == 0)
  198. FileMgr.invalidateCache((*victim)->File);
  199. delete *victim;
  200. }
  201. // Remove the modules from the chain.
  202. Chain.erase(first, last);
  203. }
  204. void
  205. ModuleManager::addInMemoryBuffer(StringRef FileName,
  206. std::unique_ptr<llvm::MemoryBuffer> Buffer) {
  207. const FileEntry *Entry =
  208. FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
  209. InMemoryBuffers[Entry] = std::move(Buffer);
  210. }
  211. ModuleManager::VisitState *ModuleManager::allocateVisitState() {
  212. // Fast path: if we have a cached state, use it.
  213. if (FirstVisitState) {
  214. VisitState *Result = FirstVisitState;
  215. FirstVisitState = FirstVisitState->NextState;
  216. Result->NextState = nullptr;
  217. return Result;
  218. }
  219. // Allocate and return a new state.
  220. return new VisitState(size());
  221. }
  222. void ModuleManager::returnVisitState(VisitState *State) {
  223. assert(State->NextState == nullptr && "Visited state is in list?");
  224. State->NextState = FirstVisitState;
  225. FirstVisitState = State;
  226. }
  227. void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
  228. GlobalIndex = Index;
  229. if (!GlobalIndex) {
  230. ModulesInCommonWithGlobalIndex.clear();
  231. return;
  232. }
  233. // Notify the global module index about all of the modules we've already
  234. // loaded.
  235. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  236. if (!GlobalIndex->loadedModuleFile(Chain[I])) {
  237. ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
  238. }
  239. }
  240. }
  241. void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
  242. if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
  243. return;
  244. ModulesInCommonWithGlobalIndex.push_back(MF);
  245. }
  246. ModuleManager::ModuleManager(FileManager &FileMgr,
  247. const PCHContainerReader &PCHContainerRdr)
  248. : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr), GlobalIndex(),
  249. FirstVisitState(nullptr) {}
  250. ModuleManager::~ModuleManager() {
  251. for (unsigned i = 0, e = Chain.size(); i != e; ++i)
  252. delete Chain[e - i - 1];
  253. delete FirstVisitState;
  254. }
  255. void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
  256. llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
  257. // If the visitation order vector is the wrong size, recompute the order.
  258. if (VisitOrder.size() != Chain.size()) {
  259. unsigned N = size();
  260. VisitOrder.clear();
  261. VisitOrder.reserve(N);
  262. // Record the number of incoming edges for each module. When we
  263. // encounter a module with no incoming edges, push it into the queue
  264. // to seed the queue.
  265. SmallVector<ModuleFile *, 4> Queue;
  266. Queue.reserve(N);
  267. llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
  268. UnusedIncomingEdges.resize(size());
  269. for (ModuleFile *M : llvm::reverse(*this)) {
  270. unsigned Size = M->ImportedBy.size();
  271. UnusedIncomingEdges[M->Index] = Size;
  272. if (!Size)
  273. Queue.push_back(M);
  274. }
  275. // Traverse the graph, making sure to visit a module before visiting any
  276. // of its dependencies.
  277. while (!Queue.empty()) {
  278. ModuleFile *CurrentModule = Queue.pop_back_val();
  279. VisitOrder.push_back(CurrentModule);
  280. // For any module that this module depends on, push it on the
  281. // stack (if it hasn't already been marked as visited).
  282. for (auto M = CurrentModule->Imports.rbegin(),
  283. MEnd = CurrentModule->Imports.rend();
  284. M != MEnd; ++M) {
  285. // Remove our current module as an impediment to visiting the
  286. // module we depend on. If we were the last unvisited module
  287. // that depends on this particular module, push it into the
  288. // queue to be visited.
  289. unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
  290. if (NumUnusedEdges && (--NumUnusedEdges == 0))
  291. Queue.push_back(*M);
  292. }
  293. }
  294. assert(VisitOrder.size() == N && "Visitation order is wrong?");
  295. delete FirstVisitState;
  296. FirstVisitState = nullptr;
  297. }
  298. VisitState *State = allocateVisitState();
  299. unsigned VisitNumber = State->NextVisitNumber++;
  300. // If the caller has provided us with a hit-set that came from the global
  301. // module index, mark every module file in common with the global module
  302. // index that is *not* in that set as 'visited'.
  303. if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
  304. for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
  305. {
  306. ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
  307. if (!ModuleFilesHit->count(M))
  308. State->VisitNumber[M->Index] = VisitNumber;
  309. }
  310. }
  311. for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
  312. ModuleFile *CurrentModule = VisitOrder[I];
  313. // Should we skip this module file?
  314. if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
  315. continue;
  316. // Visit the module.
  317. assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
  318. State->VisitNumber[CurrentModule->Index] = VisitNumber;
  319. if (!Visitor(*CurrentModule))
  320. continue;
  321. // The visitor has requested that cut off visitation of any
  322. // module that the current module depends on. To indicate this
  323. // behavior, we mark all of the reachable modules as having been visited.
  324. ModuleFile *NextModule = CurrentModule;
  325. do {
  326. // For any module that this module depends on, push it on the
  327. // stack (if it hasn't already been marked as visited).
  328. for (llvm::SetVector<ModuleFile *>::iterator
  329. M = NextModule->Imports.begin(),
  330. MEnd = NextModule->Imports.end();
  331. M != MEnd; ++M) {
  332. if (State->VisitNumber[(*M)->Index] != VisitNumber) {
  333. State->Stack.push_back(*M);
  334. State->VisitNumber[(*M)->Index] = VisitNumber;
  335. }
  336. }
  337. if (State->Stack.empty())
  338. break;
  339. // Pop the next module off the stack.
  340. NextModule = State->Stack.pop_back_val();
  341. } while (true);
  342. }
  343. returnVisitState(State);
  344. }
  345. bool ModuleManager::lookupModuleFile(StringRef FileName,
  346. off_t ExpectedSize,
  347. time_t ExpectedModTime,
  348. const FileEntry *&File) {
  349. if (FileName == "-") {
  350. File = nullptr;
  351. return false;
  352. }
  353. // Open the file immediately to ensure there is no race between stat'ing and
  354. // opening the file.
  355. File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
  356. if (!File)
  357. return false;
  358. if ((ExpectedSize && ExpectedSize != File->getSize()) ||
  359. (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
  360. // Do not destroy File, as it may be referenced. If we need to rebuild it,
  361. // it will be destroyed by removeModules.
  362. return true;
  363. return false;
  364. }
  365. #ifndef NDEBUG
  366. namespace llvm {
  367. template<>
  368. struct GraphTraits<ModuleManager> {
  369. typedef ModuleFile *NodeRef;
  370. typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
  371. typedef ModuleManager::ModuleConstIterator nodes_iterator;
  372. static ChildIteratorType child_begin(NodeRef Node) {
  373. return Node->Imports.begin();
  374. }
  375. static ChildIteratorType child_end(NodeRef Node) {
  376. return Node->Imports.end();
  377. }
  378. static nodes_iterator nodes_begin(const ModuleManager &Manager) {
  379. return Manager.begin();
  380. }
  381. static nodes_iterator nodes_end(const ModuleManager &Manager) {
  382. return Manager.end();
  383. }
  384. };
  385. template<>
  386. struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
  387. explicit DOTGraphTraits(bool IsSimple = false)
  388. : DefaultDOTGraphTraits(IsSimple) { }
  389. static bool renderGraphFromBottomUp() {
  390. return true;
  391. }
  392. std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
  393. return M->ModuleName;
  394. }
  395. };
  396. }
  397. void ModuleManager::viewGraph() {
  398. llvm::ViewGraph(*this, "Modules");
  399. }
  400. #endif