ModuleManager.cpp 15 KB

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