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