ModuleManager.cpp 15 KB

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