clang API Documentation

ModuleManager.cpp
Go to the documentation of this file.
00001 //===--- ModuleManager.cpp - Module Manager ---------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the ModuleManager class, which manages a set of loaded
00011 //  modules for the ASTReader.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 #include "clang/Lex/HeaderSearch.h"
00015 #include "clang/Lex/ModuleMap.h"
00016 #include "clang/Serialization/GlobalModuleIndex.h"
00017 #include "clang/Serialization/ModuleManager.h"
00018 #include "llvm/Support/MemoryBuffer.h"
00019 #include "llvm/Support/Path.h"
00020 #include "llvm/Support/raw_ostream.h"
00021 #include <system_error>
00022 
00023 #ifndef NDEBUG
00024 #include "llvm/Support/GraphWriter.h"
00025 #endif
00026 
00027 using namespace clang;
00028 using namespace serialization;
00029 
00030 ModuleFile *ModuleManager::lookup(StringRef Name) {
00031   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
00032                                            /*cacheFailure=*/false);
00033   if (Entry)
00034     return lookup(Entry);
00035 
00036   return nullptr;
00037 }
00038 
00039 ModuleFile *ModuleManager::lookup(const FileEntry *File) {
00040   llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
00041     = Modules.find(File);
00042   if (Known == Modules.end())
00043     return nullptr;
00044 
00045   return Known->second;
00046 }
00047 
00048 std::unique_ptr<llvm::MemoryBuffer>
00049 ModuleManager::lookupBuffer(StringRef Name) {
00050   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
00051                                            /*cacheFailure=*/false);
00052   return std::move(InMemoryBuffers[Entry]);
00053 }
00054 
00055 ModuleManager::AddModuleResult
00056 ModuleManager::addModule(StringRef FileName, ModuleKind Type,
00057                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
00058                          unsigned Generation,
00059                          off_t ExpectedSize, time_t ExpectedModTime,
00060                          ASTFileSignature ExpectedSignature,
00061                          std::function<ASTFileSignature(llvm::BitstreamReader &)>
00062                              ReadSignature,
00063                          ModuleFile *&Module,
00064                          std::string &ErrorStr) {
00065   Module = nullptr;
00066 
00067   // Look for the file entry. This only fails if the expected size or
00068   // modification time differ.
00069   const FileEntry *Entry;
00070   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
00071     ErrorStr = "module file out of date";
00072     return OutOfDate;
00073   }
00074 
00075   if (!Entry && FileName != "-") {
00076     ErrorStr = "module file not found";
00077     return Missing;
00078   }
00079 
00080   // Check whether we already loaded this module, before
00081   ModuleFile *&ModuleEntry = Modules[Entry];
00082   bool NewModule = false;
00083   if (!ModuleEntry) {
00084     // Allocate a new module.
00085     ModuleFile *New = new ModuleFile(Type, Generation);
00086     New->Index = Chain.size();
00087     New->FileName = FileName.str();
00088     New->File = Entry;
00089     New->ImportLoc = ImportLoc;
00090     Chain.push_back(New);
00091     NewModule = true;
00092     ModuleEntry = New;
00093 
00094     New->InputFilesValidationTimestamp = 0;
00095     if (New->Kind == MK_ImplicitModule) {
00096       std::string TimestampFilename = New->getTimestampFilename();
00097       vfs::Status Status;
00098       // A cached stat value would be fine as well.
00099       if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
00100         New->InputFilesValidationTimestamp =
00101             Status.getLastModificationTime().toEpochTime();
00102     }
00103 
00104     // Load the contents of the module
00105     if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
00106       // The buffer was already provided for us.
00107       New->Buffer = std::move(Buffer);
00108     } else {
00109       // Open the AST file.
00110       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf(
00111           (std::error_code()));
00112       if (FileName == "-") {
00113         Buf = llvm::MemoryBuffer::getSTDIN();
00114       } else {
00115         // Leave the FileEntry open so if it gets read again by another
00116         // ModuleManager it must be the same underlying file.
00117         // FIXME: Because FileManager::getFile() doesn't guarantee that it will
00118         // give us an open file, this may not be 100% reliable.
00119         Buf = FileMgr.getBufferForFile(New->File,
00120                                        /*IsVolatile=*/false,
00121                                        /*ShouldClose=*/false);
00122       }
00123 
00124       if (!Buf) {
00125         ErrorStr = Buf.getError().message();
00126         return Missing;
00127       }
00128 
00129       New->Buffer = std::move(*Buf);
00130     }
00131     
00132     // Initialize the stream
00133     New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
00134                          (const unsigned char *)New->Buffer->getBufferEnd());
00135   }
00136 
00137   if (ExpectedSignature) {
00138     if (NewModule)
00139       ModuleEntry->Signature = ReadSignature(ModuleEntry->StreamFile);
00140     else
00141       assert(ModuleEntry->Signature == ReadSignature(ModuleEntry->StreamFile));
00142 
00143     if (ModuleEntry->Signature != ExpectedSignature) {
00144       ErrorStr = ModuleEntry->Signature ? "signature mismatch"
00145                                         : "could not read module signature";
00146 
00147       if (NewModule) {
00148         // Remove the module file immediately, since removeModules might try to
00149         // invalidate the file cache for Entry, and that is not safe if this
00150         // module is *itself* up to date, but has an out-of-date importer.
00151         Modules.erase(Entry);
00152         Chain.pop_back();
00153         delete ModuleEntry;
00154       }
00155       return OutOfDate;
00156     }
00157   }
00158   
00159   if (ImportedBy) {
00160     ModuleEntry->ImportedBy.insert(ImportedBy);
00161     ImportedBy->Imports.insert(ModuleEntry);
00162   } else {
00163     if (!ModuleEntry->DirectlyImported)
00164       ModuleEntry->ImportLoc = ImportLoc;
00165     
00166     ModuleEntry->DirectlyImported = true;
00167   }
00168 
00169   Module = ModuleEntry;
00170   return NewModule? NewlyLoaded : AlreadyLoaded;
00171 }
00172 
00173 void ModuleManager::removeModules(
00174     ModuleIterator first, ModuleIterator last,
00175     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
00176     ModuleMap *modMap) {
00177   if (first == last)
00178     return;
00179 
00180   // Collect the set of module file pointers that we'll be removing.
00181   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
00182 
00183   // Remove any references to the now-destroyed modules.
00184   for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
00185     Chain[i]->ImportedBy.remove_if([&](ModuleFile *MF) {
00186       return victimSet.count(MF);
00187     });
00188   }
00189 
00190   // Delete the modules and erase them from the various structures.
00191   for (ModuleIterator victim = first; victim != last; ++victim) {
00192     Modules.erase((*victim)->File);
00193 
00194     if (modMap) {
00195       StringRef ModuleName = (*victim)->ModuleName;
00196       if (Module *mod = modMap->findModule(ModuleName)) {
00197         mod->setASTFile(nullptr);
00198       }
00199     }
00200 
00201     // Files that didn't make it through ReadASTCore successfully will be
00202     // rebuilt (or there was an error). Invalidate them so that we can load the
00203     // new files that will be renamed over the old ones.
00204     if (LoadedSuccessfully.count(*victim) == 0)
00205       FileMgr.invalidateCache((*victim)->File);
00206 
00207     delete *victim;
00208   }
00209 
00210   // Remove the modules from the chain.
00211   Chain.erase(first, last);
00212 }
00213 
00214 void
00215 ModuleManager::addInMemoryBuffer(StringRef FileName,
00216                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
00217 
00218   const FileEntry *Entry =
00219       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
00220   InMemoryBuffers[Entry] = std::move(Buffer);
00221 }
00222 
00223 ModuleManager::VisitState *ModuleManager::allocateVisitState() {
00224   // Fast path: if we have a cached state, use it.
00225   if (FirstVisitState) {
00226     VisitState *Result = FirstVisitState;
00227     FirstVisitState = FirstVisitState->NextState;
00228     Result->NextState = nullptr;
00229     return Result;
00230   }
00231 
00232   // Allocate and return a new state.
00233   return new VisitState(size());
00234 }
00235 
00236 void ModuleManager::returnVisitState(VisitState *State) {
00237   assert(State->NextState == nullptr && "Visited state is in list?");
00238   State->NextState = FirstVisitState;
00239   FirstVisitState = State;
00240 }
00241 
00242 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
00243   GlobalIndex = Index;
00244   if (!GlobalIndex) {
00245     ModulesInCommonWithGlobalIndex.clear();
00246     return;
00247   }
00248 
00249   // Notify the global module index about all of the modules we've already
00250   // loaded.
00251   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
00252     if (!GlobalIndex->loadedModuleFile(Chain[I])) {
00253       ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
00254     }
00255   }
00256 }
00257 
00258 void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
00259   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
00260     return;
00261 
00262   ModulesInCommonWithGlobalIndex.push_back(MF);
00263 }
00264 
00265 ModuleManager::ModuleManager(FileManager &FileMgr)
00266   : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(nullptr) {}
00267 
00268 ModuleManager::~ModuleManager() {
00269   for (unsigned i = 0, e = Chain.size(); i != e; ++i)
00270     delete Chain[e - i - 1];
00271   delete FirstVisitState;
00272 }
00273 
00274 void
00275 ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
00276                      void *UserData,
00277                      llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
00278   // If the visitation order vector is the wrong size, recompute the order.
00279   if (VisitOrder.size() != Chain.size()) {
00280     unsigned N = size();
00281     VisitOrder.clear();
00282     VisitOrder.reserve(N);
00283     
00284     // Record the number of incoming edges for each module. When we
00285     // encounter a module with no incoming edges, push it into the queue
00286     // to seed the queue.
00287     SmallVector<ModuleFile *, 4> Queue;
00288     Queue.reserve(N);
00289     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
00290     UnusedIncomingEdges.reserve(size());
00291     for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
00292       if (unsigned Size = (*M)->ImportedBy.size())
00293         UnusedIncomingEdges.push_back(Size);
00294       else {
00295         UnusedIncomingEdges.push_back(0);
00296         Queue.push_back(*M);
00297       }
00298     }
00299 
00300     // Traverse the graph, making sure to visit a module before visiting any
00301     // of its dependencies.
00302     unsigned QueueStart = 0;
00303     while (QueueStart < Queue.size()) {
00304       ModuleFile *CurrentModule = Queue[QueueStart++];
00305       VisitOrder.push_back(CurrentModule);
00306 
00307       // For any module that this module depends on, push it on the
00308       // stack (if it hasn't already been marked as visited).
00309       for (llvm::SetVector<ModuleFile *>::iterator
00310              M = CurrentModule->Imports.begin(),
00311              MEnd = CurrentModule->Imports.end();
00312            M != MEnd; ++M) {
00313         // Remove our current module as an impediment to visiting the
00314         // module we depend on. If we were the last unvisited module
00315         // that depends on this particular module, push it into the
00316         // queue to be visited.
00317         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
00318         if (NumUnusedEdges && (--NumUnusedEdges == 0))
00319           Queue.push_back(*M);
00320       }
00321     }
00322 
00323     assert(VisitOrder.size() == N && "Visitation order is wrong?");
00324 
00325     delete FirstVisitState;
00326     FirstVisitState = nullptr;
00327   }
00328 
00329   VisitState *State = allocateVisitState();
00330   unsigned VisitNumber = State->NextVisitNumber++;
00331 
00332   // If the caller has provided us with a hit-set that came from the global
00333   // module index, mark every module file in common with the global module
00334   // index that is *not* in that set as 'visited'.
00335   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
00336     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
00337     {
00338       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
00339       if (!ModuleFilesHit->count(M))
00340         State->VisitNumber[M->Index] = VisitNumber;
00341     }
00342   }
00343 
00344   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
00345     ModuleFile *CurrentModule = VisitOrder[I];
00346     // Should we skip this module file?
00347     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
00348       continue;
00349 
00350     // Visit the module.
00351     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
00352     State->VisitNumber[CurrentModule->Index] = VisitNumber;
00353     if (!Visitor(*CurrentModule, UserData))
00354       continue;
00355 
00356     // The visitor has requested that cut off visitation of any
00357     // module that the current module depends on. To indicate this
00358     // behavior, we mark all of the reachable modules as having been visited.
00359     ModuleFile *NextModule = CurrentModule;
00360     do {
00361       // For any module that this module depends on, push it on the
00362       // stack (if it hasn't already been marked as visited).
00363       for (llvm::SetVector<ModuleFile *>::iterator
00364              M = NextModule->Imports.begin(),
00365              MEnd = NextModule->Imports.end();
00366            M != MEnd; ++M) {
00367         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
00368           State->Stack.push_back(*M);
00369           State->VisitNumber[(*M)->Index] = VisitNumber;
00370         }
00371       }
00372 
00373       if (State->Stack.empty())
00374         break;
00375 
00376       // Pop the next module off the stack.
00377       NextModule = State->Stack.pop_back_val();
00378     } while (true);
00379   }
00380 
00381   returnVisitState(State);
00382 }
00383 
00384 /// \brief Perform a depth-first visit of the current module.
00385 static bool visitDepthFirst(ModuleFile &M, 
00386                             bool (*Visitor)(ModuleFile &M, bool Preorder, 
00387                                             void *UserData), 
00388                             void *UserData,
00389                             SmallVectorImpl<bool> &Visited) {
00390   // Preorder visitation
00391   if (Visitor(M, /*Preorder=*/true, UserData))
00392     return true;
00393   
00394   // Visit children
00395   for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
00396                                             IMEnd = M.Imports.end();
00397        IM != IMEnd; ++IM) {
00398     if (Visited[(*IM)->Index])
00399       continue;
00400     Visited[(*IM)->Index] = true;
00401 
00402     if (visitDepthFirst(**IM, Visitor, UserData, Visited))
00403       return true;
00404   }  
00405   
00406   // Postorder visitation
00407   return Visitor(M, /*Preorder=*/false, UserData);
00408 }
00409 
00410 void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder, 
00411                                                     void *UserData), 
00412                                     void *UserData) {
00413   SmallVector<bool, 16> Visited(size(), false);
00414   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
00415     if (Visited[Chain[I]->Index])
00416       continue;
00417     Visited[Chain[I]->Index] = true;
00418 
00419     if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
00420       return;
00421   }
00422 }
00423 
00424 bool ModuleManager::lookupModuleFile(StringRef FileName,
00425                                      off_t ExpectedSize,
00426                                      time_t ExpectedModTime,
00427                                      const FileEntry *&File) {
00428   // Open the file immediately to ensure there is no race between stat'ing and
00429   // opening the file.
00430   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
00431 
00432   if (!File && FileName != "-") {
00433     return false;
00434   }
00435 
00436   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
00437       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
00438     // Do not destroy File, as it may be referenced. If we need to rebuild it,
00439     // it will be destroyed by removeModules.
00440     return true;
00441 
00442   return false;
00443 }
00444 
00445 #ifndef NDEBUG
00446 namespace llvm {
00447   template<>
00448   struct GraphTraits<ModuleManager> {
00449     typedef ModuleFile NodeType;
00450     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
00451     typedef ModuleManager::ModuleConstIterator nodes_iterator;
00452     
00453     static ChildIteratorType child_begin(NodeType *Node) {
00454       return Node->Imports.begin();
00455     }
00456 
00457     static ChildIteratorType child_end(NodeType *Node) {
00458       return Node->Imports.end();
00459     }
00460     
00461     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
00462       return Manager.begin();
00463     }
00464     
00465     static nodes_iterator nodes_end(const ModuleManager &Manager) {
00466       return Manager.end();
00467     }
00468   };
00469   
00470   template<>
00471   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
00472     explicit DOTGraphTraits(bool IsSimple = false)
00473       : DefaultDOTGraphTraits(IsSimple) { }
00474     
00475     static bool renderGraphFromBottomUp() {
00476       return true;
00477     }
00478 
00479     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
00480       return M->ModuleName;
00481     }
00482   };
00483 }
00484 
00485 void ModuleManager::viewGraph() {
00486   llvm::ViewGraph(*this, "Modules");
00487 }
00488 #endif