ModuleManager.cpp 15 KB

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