ModuleManager.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 "llvm/Support/MemoryBuffer.h"
  16. #include "llvm/Support/raw_ostream.h"
  17. #include "llvm/Support/system_error.h"
  18. #ifndef NDEBUG
  19. #include "llvm/Support/GraphWriter.h"
  20. #endif
  21. using namespace clang;
  22. using namespace serialization;
  23. ModuleFile *ModuleManager::lookup(StringRef Name) {
  24. const FileEntry *Entry = FileMgr.getFile(Name);
  25. return Modules[Entry];
  26. }
  27. llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
  28. const FileEntry *Entry = FileMgr.getFile(Name);
  29. return InMemoryBuffers[Entry];
  30. }
  31. std::pair<ModuleFile *, bool>
  32. ModuleManager::addModule(StringRef FileName, ModuleKind Type,
  33. SourceLocation ImportLoc, ModuleFile *ImportedBy,
  34. unsigned Generation, std::string &ErrorStr) {
  35. const FileEntry *Entry = FileMgr.getFile(FileName);
  36. if (!Entry && FileName != "-") {
  37. ErrorStr = "file not found";
  38. return std::make_pair(static_cast<ModuleFile*>(0), false);
  39. }
  40. // Check whether we already loaded this module, before
  41. ModuleFile *&ModuleEntry = Modules[Entry];
  42. bool NewModule = false;
  43. if (!ModuleEntry) {
  44. // Allocate a new module.
  45. ModuleFile *New = new ModuleFile(Type, Generation);
  46. New->Index = Chain.size();
  47. New->FileName = FileName.str();
  48. New->File = Entry;
  49. New->ImportLoc = ImportLoc;
  50. Chain.push_back(New);
  51. NewModule = true;
  52. ModuleEntry = New;
  53. // Load the contents of the module
  54. if (llvm::MemoryBuffer *Buffer = lookupBuffer(FileName)) {
  55. // The buffer was already provided for us.
  56. assert(Buffer && "Passed null buffer");
  57. New->Buffer.reset(Buffer);
  58. } else {
  59. // Open the AST file.
  60. llvm::error_code ec;
  61. if (FileName == "-") {
  62. ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
  63. if (ec)
  64. ErrorStr = ec.message();
  65. } else
  66. New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
  67. if (!New->Buffer)
  68. return std::make_pair(static_cast<ModuleFile*>(0), false);
  69. }
  70. // Initialize the stream
  71. New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
  72. (const unsigned char *)New->Buffer->getBufferEnd()); }
  73. if (ImportedBy) {
  74. ModuleEntry->ImportedBy.insert(ImportedBy);
  75. ImportedBy->Imports.insert(ModuleEntry);
  76. } else {
  77. if (!ModuleEntry->DirectlyImported)
  78. ModuleEntry->ImportLoc = ImportLoc;
  79. ModuleEntry->DirectlyImported = true;
  80. }
  81. return std::make_pair(ModuleEntry, NewModule);
  82. }
  83. namespace {
  84. /// \brief Predicate that checks whether a module file occurs within
  85. /// the given set.
  86. class IsInModuleFileSet : public std::unary_function<ModuleFile *, bool> {
  87. llvm::SmallPtrSet<ModuleFile *, 4> &Removed;
  88. public:
  89. IsInModuleFileSet(llvm::SmallPtrSet<ModuleFile *, 4> &Removed)
  90. : Removed(Removed) { }
  91. bool operator()(ModuleFile *MF) const {
  92. return Removed.count(MF);
  93. }
  94. };
  95. }
  96. void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last) {
  97. if (first == last)
  98. return;
  99. // Collect the set of module file pointers that we'll be removing.
  100. llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
  101. // Remove any references to the now-destroyed modules.
  102. IsInModuleFileSet checkInSet(victimSet);
  103. for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
  104. Chain[i]->ImportedBy.remove_if(checkInSet);
  105. }
  106. // Delete the modules and erase them from the various structures.
  107. for (ModuleIterator victim = first; victim != last; ++victim) {
  108. Modules.erase((*victim)->File);
  109. delete *victim;
  110. }
  111. // Remove the modules from the chain.
  112. Chain.erase(first, last);
  113. }
  114. void ModuleManager::addInMemoryBuffer(StringRef FileName,
  115. llvm::MemoryBuffer *Buffer) {
  116. const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
  117. Buffer->getBufferSize(), 0);
  118. InMemoryBuffers[Entry] = Buffer;
  119. }
  120. ModuleManager::ModuleManager(FileManager &FileMgr) : FileMgr(FileMgr) { }
  121. ModuleManager::~ModuleManager() {
  122. for (unsigned i = 0, e = Chain.size(); i != e; ++i)
  123. delete Chain[e - i - 1];
  124. }
  125. void ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
  126. void *UserData) {
  127. // If the visitation number array is the wrong size, resize it and recompute
  128. // an order.
  129. if (VisitOrder.size() != Chain.size()) {
  130. unsigned N = size();
  131. VisitOrder.clear();
  132. VisitOrder.reserve(N);
  133. // Record the number of incoming edges for each module. When we
  134. // encounter a module with no incoming edges, push it into the queue
  135. // to seed the queue.
  136. SmallVector<ModuleFile *, 4> Queue;
  137. Queue.reserve(N);
  138. llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
  139. UnusedIncomingEdges.reserve(size());
  140. for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
  141. if (unsigned Size = (*M)->ImportedBy.size())
  142. UnusedIncomingEdges.push_back(Size);
  143. else {
  144. UnusedIncomingEdges.push_back(0);
  145. Queue.push_back(*M);
  146. }
  147. }
  148. // Traverse the graph, making sure to visit a module before visiting any
  149. // of its dependencies.
  150. unsigned QueueStart = 0;
  151. while (QueueStart < Queue.size()) {
  152. ModuleFile *CurrentModule = Queue[QueueStart++];
  153. VisitOrder.push_back(CurrentModule);
  154. // For any module that this module depends on, push it on the
  155. // stack (if it hasn't already been marked as visited).
  156. for (llvm::SetVector<ModuleFile *>::iterator
  157. M = CurrentModule->Imports.begin(),
  158. MEnd = CurrentModule->Imports.end();
  159. M != MEnd; ++M) {
  160. // Remove our current module as an impediment to visiting the
  161. // module we depend on. If we were the last unvisited module
  162. // that depends on this particular module, push it into the
  163. // queue to be visited.
  164. unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
  165. if (NumUnusedEdges && (--NumUnusedEdges == 0))
  166. Queue.push_back(*M);
  167. }
  168. }
  169. assert(VisitOrder.size() == N && "Visitation order is wrong?");
  170. }
  171. SmallVector<ModuleFile *, 4> Stack;
  172. SmallVector<bool, 4> Visited(size(), false);
  173. for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
  174. ModuleFile *CurrentModule = VisitOrder[I];
  175. // Should we skip this module file?
  176. if (Visited[CurrentModule->Index])
  177. continue;
  178. // Visit the module.
  179. Visited[CurrentModule->Index] = true;
  180. if (!Visitor(*CurrentModule, UserData))
  181. continue;
  182. // The visitor has requested that cut off visitation of any
  183. // module that the current module depends on. To indicate this
  184. // behavior, we mark all of the reachable modules as having been visited.
  185. ModuleFile *NextModule = CurrentModule;
  186. Stack.reserve(size());
  187. do {
  188. // For any module that this module depends on, push it on the
  189. // stack (if it hasn't already been marked as visited).
  190. for (llvm::SetVector<ModuleFile *>::iterator
  191. M = NextModule->Imports.begin(),
  192. MEnd = NextModule->Imports.end();
  193. M != MEnd; ++M) {
  194. if (!Visited[(*M)->Index]) {
  195. Stack.push_back(*M);
  196. Visited[(*M)->Index] = true;
  197. }
  198. }
  199. if (Stack.empty())
  200. break;
  201. // Pop the next module off the stack.
  202. NextModule = Stack.back();
  203. Stack.pop_back();
  204. } while (true);
  205. }
  206. }
  207. /// \brief Perform a depth-first visit of the current module.
  208. static bool visitDepthFirst(ModuleFile &M,
  209. bool (*Visitor)(ModuleFile &M, bool Preorder,
  210. void *UserData),
  211. void *UserData,
  212. SmallVectorImpl<bool> &Visited) {
  213. // Preorder visitation
  214. if (Visitor(M, /*Preorder=*/true, UserData))
  215. return true;
  216. // Visit children
  217. for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
  218. IMEnd = M.Imports.end();
  219. IM != IMEnd; ++IM) {
  220. if (Visited[(*IM)->Index])
  221. continue;
  222. Visited[(*IM)->Index] = true;
  223. if (visitDepthFirst(**IM, Visitor, UserData, Visited))
  224. return true;
  225. }
  226. // Postorder visitation
  227. return Visitor(M, /*Preorder=*/false, UserData);
  228. }
  229. void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
  230. void *UserData),
  231. void *UserData) {
  232. SmallVector<bool, 16> Visited(size(), false);
  233. for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
  234. if (Visited[Chain[I]->Index])
  235. continue;
  236. Visited[Chain[I]->Index] = true;
  237. if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
  238. return;
  239. }
  240. }
  241. #ifndef NDEBUG
  242. namespace llvm {
  243. template<>
  244. struct GraphTraits<ModuleManager> {
  245. typedef ModuleFile NodeType;
  246. typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
  247. typedef ModuleManager::ModuleConstIterator nodes_iterator;
  248. static ChildIteratorType child_begin(NodeType *Node) {
  249. return Node->Imports.begin();
  250. }
  251. static ChildIteratorType child_end(NodeType *Node) {
  252. return Node->Imports.end();
  253. }
  254. static nodes_iterator nodes_begin(const ModuleManager &Manager) {
  255. return Manager.begin();
  256. }
  257. static nodes_iterator nodes_end(const ModuleManager &Manager) {
  258. return Manager.end();
  259. }
  260. };
  261. template<>
  262. struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
  263. explicit DOTGraphTraits(bool IsSimple = false)
  264. : DefaultDOTGraphTraits(IsSimple) { }
  265. static bool renderGraphFromBottomUp() {
  266. return true;
  267. }
  268. std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
  269. return llvm::sys::path::stem(M->FileName);
  270. }
  271. };
  272. }
  273. void ModuleManager::viewGraph() {
  274. llvm::ViewGraph(*this, "Modules");
  275. }
  276. #endif