1 //===--- GlobalModuleIndex.cpp - Global Module Index ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the GlobalModuleIndex class.
12 //===----------------------------------------------------------------------===//
14 #include "ASTReaderInternals.h"
15 #include "clang/Frontend/PCHContainerOperations.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Lex/HeaderSearch.h"
18 #include "clang/Serialization/ASTBitCodes.h"
19 #include "clang/Serialization/GlobalModuleIndex.h"
20 #include "clang/Serialization/Module.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Bitcode/BitstreamReader.h"
26 #include "llvm/Bitcode/BitstreamWriter.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/LockFileManager.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/OnDiskHashTable.h"
31 #include "llvm/Support/Path.h"
33 using namespace clang;
34 using namespace serialization;
36 //----------------------------------------------------------------------------//
38 //----------------------------------------------------------------------------//
41 /// \brief The block containing the index.
42 GLOBAL_INDEX_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID
45 /// \brief Describes the record types in the index.
46 enum IndexRecordTypes {
47 /// \brief Contains version information and potentially other metadata,
48 /// used to determine if we can read this global index file.
50 /// \brief Describes a module, including its file name and dependencies.
52 /// \brief The index for identifiers.
57 /// \brief The name of the global index file.
58 static const char * const IndexFileName = "modules.idx";
60 /// \brief The global index file version.
61 static const unsigned CurrentVersion = 1;
63 //----------------------------------------------------------------------------//
64 // Global module index reader.
65 //----------------------------------------------------------------------------//
69 /// \brief Trait used to read the identifier index from the on-disk hash
71 class IdentifierIndexReaderTrait {
73 typedef StringRef external_key_type;
74 typedef StringRef internal_key_type;
75 typedef SmallVector<unsigned, 2> data_type;
76 typedef unsigned hash_value_type;
77 typedef unsigned offset_type;
79 static bool EqualKey(const internal_key_type& a, const internal_key_type& b) {
83 static hash_value_type ComputeHash(const internal_key_type& a) {
84 return llvm::HashString(a);
87 static std::pair<unsigned, unsigned>
88 ReadKeyDataLength(const unsigned char*& d) {
89 using namespace llvm::support;
90 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
91 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
92 return std::make_pair(KeyLen, DataLen);
95 static const internal_key_type&
96 GetInternalKey(const external_key_type& x) { return x; }
98 static const external_key_type&
99 GetExternalKey(const internal_key_type& x) { return x; }
101 static internal_key_type ReadKey(const unsigned char* d, unsigned n) {
102 return StringRef((const char *)d, n);
105 static data_type ReadData(const internal_key_type& k,
106 const unsigned char* d,
108 using namespace llvm::support;
111 while (DataLen > 0) {
112 unsigned ID = endian::readNext<uint32_t, little, unaligned>(d);
113 Result.push_back(ID);
121 typedef llvm::OnDiskIterableChainedHashTable<IdentifierIndexReaderTrait>
122 IdentifierIndexTable;
126 GlobalModuleIndex::GlobalModuleIndex(std::unique_ptr<llvm::MemoryBuffer> Buffer,
127 llvm::BitstreamCursor Cursor)
128 : Buffer(std::move(Buffer)), IdentifierIndex(), NumIdentifierLookups(),
129 NumIdentifierLookupHits() {
130 // Read the global index.
131 bool InGlobalIndexBlock = false;
134 llvm::BitstreamEntry Entry = Cursor.advance();
136 switch (Entry.Kind) {
137 case llvm::BitstreamEntry::Error:
140 case llvm::BitstreamEntry::EndBlock:
141 if (InGlobalIndexBlock) {
142 InGlobalIndexBlock = false;
149 case llvm::BitstreamEntry::Record:
150 // Entries in the global index block are handled below.
151 if (InGlobalIndexBlock)
156 case llvm::BitstreamEntry::SubBlock:
157 if (!InGlobalIndexBlock && Entry.ID == GLOBAL_INDEX_BLOCK_ID) {
158 if (Cursor.EnterSubBlock(GLOBAL_INDEX_BLOCK_ID))
161 InGlobalIndexBlock = true;
162 } else if (Cursor.SkipBlock()) {
168 SmallVector<uint64_t, 64> Record;
170 switch ((IndexRecordTypes)Cursor.readRecord(Entry.ID, Record, &Blob)) {
172 // Make sure that the version matches.
173 if (Record.size() < 1 || Record[0] != CurrentVersion)
179 unsigned ID = Record[Idx++];
181 // Make room for this module's information.
182 if (ID == Modules.size())
183 Modules.push_back(ModuleInfo());
185 Modules.resize(ID + 1);
187 // Size/modification time for this module file at the time the
188 // global index was built.
189 Modules[ID].Size = Record[Idx++];
190 Modules[ID].ModTime = Record[Idx++];
193 unsigned NameLen = Record[Idx++];
194 Modules[ID].FileName.assign(Record.begin() + Idx,
195 Record.begin() + Idx + NameLen);
199 unsigned NumDeps = Record[Idx++];
200 Modules[ID].Dependencies.insert(Modules[ID].Dependencies.end(),
201 Record.begin() + Idx,
202 Record.begin() + Idx + NumDeps);
205 // Make sure we're at the end of the record.
206 assert(Idx == Record.size() && "More module info?");
208 // Record this module as an unresolved module.
209 // FIXME: this doesn't work correctly for module names containing path
211 StringRef ModuleName = llvm::sys::path::stem(Modules[ID].FileName);
212 // Remove the -<hash of ModuleMapPath>
213 ModuleName = ModuleName.rsplit('-').first;
214 UnresolvedModules[ModuleName] = ID;
218 case IDENTIFIER_INDEX:
219 // Wire up the identifier index.
221 IdentifierIndex = IdentifierIndexTable::Create(
222 (const unsigned char *)Blob.data() + Record[0],
223 (const unsigned char *)Blob.data() + sizeof(uint32_t),
224 (const unsigned char *)Blob.data(), IdentifierIndexReaderTrait());
231 GlobalModuleIndex::~GlobalModuleIndex() {
232 delete static_cast<IdentifierIndexTable *>(IdentifierIndex);
235 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode>
236 GlobalModuleIndex::readIndex(StringRef Path) {
237 // Load the index file, if it's there.
238 llvm::SmallString<128> IndexPath;
240 llvm::sys::path::append(IndexPath, IndexFileName);
242 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferOrErr =
243 llvm::MemoryBuffer::getFile(IndexPath.c_str());
245 return std::make_pair(nullptr, EC_NotFound);
246 std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(BufferOrErr.get());
248 /// \brief The bitstream reader from which we'll read the AST file.
249 llvm::BitstreamReader Reader((const unsigned char *)Buffer->getBufferStart(),
250 (const unsigned char *)Buffer->getBufferEnd());
252 /// \brief The main bitstream cursor for the main block.
253 llvm::BitstreamCursor Cursor(Reader);
255 // Sniff for the signature.
256 if (Cursor.Read(8) != 'B' ||
257 Cursor.Read(8) != 'C' ||
258 Cursor.Read(8) != 'G' ||
259 Cursor.Read(8) != 'I') {
260 return std::make_pair(nullptr, EC_IOError);
263 return std::make_pair(new GlobalModuleIndex(std::move(Buffer), Cursor),
268 GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
270 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
271 if (ModuleFile *MF = Modules[I].File)
272 ModuleFiles.push_back(MF);
276 void GlobalModuleIndex::getModuleDependencies(
278 SmallVectorImpl<ModuleFile *> &Dependencies) {
279 // Look for information about this module file.
280 llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
281 = ModulesByFile.find(File);
282 if (Known == ModulesByFile.end())
285 // Record dependencies.
286 Dependencies.clear();
287 ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
288 for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
289 if (ModuleFile *MF = Modules[I].File)
290 Dependencies.push_back(MF);
294 bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
297 // If there's no identifier index, there is nothing we can do.
298 if (!IdentifierIndex)
301 // Look into the identifier index.
302 ++NumIdentifierLookups;
303 IdentifierIndexTable &Table
304 = *static_cast<IdentifierIndexTable *>(IdentifierIndex);
305 IdentifierIndexTable::iterator Known = Table.find(Name);
306 if (Known == Table.end()) {
310 SmallVector<unsigned, 2> ModuleIDs = *Known;
311 for (unsigned I = 0, N = ModuleIDs.size(); I != N; ++I) {
312 if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
316 ++NumIdentifierLookupHits;
320 bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
321 // Look for the module in the global module index based on the module name.
322 StringRef Name = File->ModuleName;
323 llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
324 if (Known == UnresolvedModules.end()) {
328 // Rectify this module with the global module index.
329 ModuleInfo &Info = Modules[Known->second];
331 // If the size and modification time match what we expected, record this
334 if (File->File->getSize() == Info.Size &&
335 File->File->getModificationTime() == Info.ModTime) {
337 ModulesByFile[File] = Known->second;
342 // One way or another, we have resolved this module file.
343 UnresolvedModules.erase(Known);
347 void GlobalModuleIndex::printStats() {
348 std::fprintf(stderr, "*** Global Module Index Statistics:\n");
349 if (NumIdentifierLookups) {
350 fprintf(stderr, " %u / %u identifier lookups succeeded (%f%%)\n",
351 NumIdentifierLookupHits, NumIdentifierLookups,
352 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
354 std::fprintf(stderr, "\n");
357 void GlobalModuleIndex::dump() {
358 llvm::errs() << "*** Global Module Index Dump:\n";
359 llvm::errs() << "Module files:\n";
360 for (auto &MI : Modules) {
361 llvm::errs() << "** " << MI.FileName << "\n";
365 llvm::errs() << "\n";
367 llvm::errs() << "\n";
370 //----------------------------------------------------------------------------//
371 // Global module index writer.
372 //----------------------------------------------------------------------------//
375 /// \brief Provides information about a specific module file.
376 struct ModuleFileInfo {
377 /// \brief The numberic ID for this module file.
380 /// \brief The set of modules on which this module depends. Each entry is
382 SmallVector<unsigned, 4> Dependencies;
385 /// \brief Builder that generates the global module index file.
386 class GlobalModuleIndexBuilder {
387 FileManager &FileMgr;
388 const PCHContainerReader &PCHContainerRdr;
390 /// \brief Mapping from files to module file information.
391 typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
393 /// \brief Information about each of the known module files.
394 ModuleFilesMap ModuleFiles;
396 /// \brief Mapping from identifiers to the list of module file IDs that
397 /// consider this identifier to be interesting.
398 typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
400 /// \brief A mapping from all interesting identifiers to the set of module
401 /// files in which those identifiers are considered interesting.
402 InterestingIdentifierMap InterestingIdentifiers;
404 /// \brief Write the block-info block for the global module index file.
405 void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
407 /// \brief Retrieve the module file information for the given file.
408 ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
409 llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
410 = ModuleFiles.find(File);
411 if (Known != ModuleFiles.end())
412 return Known->second;
414 unsigned NewID = ModuleFiles.size();
415 ModuleFileInfo &Info = ModuleFiles[File];
421 explicit GlobalModuleIndexBuilder(
422 FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr)
423 : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr) {}
425 /// \brief Load the contents of the given module file into the builder.
427 /// \returns true if an error occurred, false otherwise.
428 bool loadModuleFile(const FileEntry *File);
430 /// \brief Write the index to the given bitstream.
431 void writeIndex(llvm::BitstreamWriter &Stream);
435 static void emitBlockID(unsigned ID, const char *Name,
436 llvm::BitstreamWriter &Stream,
437 SmallVectorImpl<uint64_t> &Record) {
439 Record.push_back(ID);
440 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
442 // Emit the block name if present.
443 if (!Name || Name[0] == 0) return;
446 Record.push_back(*Name++);
447 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
450 static void emitRecordID(unsigned ID, const char *Name,
451 llvm::BitstreamWriter &Stream,
452 SmallVectorImpl<uint64_t> &Record) {
454 Record.push_back(ID);
456 Record.push_back(*Name++);
457 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
461 GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
462 SmallVector<uint64_t, 64> Record;
463 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
465 #define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
466 #define RECORD(X) emitRecordID(X, #X, Stream, Record)
467 BLOCK(GLOBAL_INDEX_BLOCK);
468 RECORD(INDEX_METADATA);
470 RECORD(IDENTIFIER_INDEX);
478 class InterestingASTIdentifierLookupTrait
479 : public serialization::reader::ASTIdentifierLookupTraitBase {
482 /// \brief The identifier and whether it is "interesting".
483 typedef std::pair<StringRef, bool> data_type;
485 data_type ReadData(const internal_key_type& k,
486 const unsigned char* d,
488 // The first bit indicates whether this identifier is interesting.
489 // That's all we care about.
490 using namespace llvm::support;
491 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
492 bool IsInteresting = RawID & 0x01;
493 return std::make_pair(k, IsInteresting);
498 bool GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
499 // Open the module file.
501 auto Buffer = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
506 // Initialize the input stream
507 llvm::BitstreamReader InStreamFile;
508 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), InStreamFile);
509 llvm::BitstreamCursor InStream(InStreamFile);
511 // Sniff for the signature.
512 if (InStream.Read(8) != 'C' ||
513 InStream.Read(8) != 'P' ||
514 InStream.Read(8) != 'C' ||
515 InStream.Read(8) != 'H') {
519 // Record this module file and assign it a unique ID (if it doesn't have
521 unsigned ID = getModuleFileInfo(File).ID;
523 // Search for the blocks and records we care about.
524 enum { Other, ControlBlock, ASTBlock } State = Other;
527 llvm::BitstreamEntry Entry = InStream.advance();
528 switch (Entry.Kind) {
529 case llvm::BitstreamEntry::Error:
533 case llvm::BitstreamEntry::Record:
534 // In the 'other' state, just skip the record. We don't care.
535 if (State == Other) {
536 InStream.skipRecord(Entry.ID);
540 // Handle potentially-interesting records below.
543 case llvm::BitstreamEntry::SubBlock:
544 if (Entry.ID == CONTROL_BLOCK_ID) {
545 if (InStream.EnterSubBlock(CONTROL_BLOCK_ID))
548 // Found the control block.
549 State = ControlBlock;
553 if (Entry.ID == AST_BLOCK_ID) {
554 if (InStream.EnterSubBlock(AST_BLOCK_ID))
557 // Found the AST block.
562 if (InStream.SkipBlock())
567 case llvm::BitstreamEntry::EndBlock:
572 // Read the given record.
573 SmallVector<uint64_t, 64> Record;
575 unsigned Code = InStream.readRecord(Entry.ID, Record, &Blob);
577 // Handle module dependencies.
578 if (State == ControlBlock && Code == IMPORTS) {
579 // Load each of the imported PCH files.
580 unsigned Idx = 0, N = Record.size();
582 // Read information about the AST file.
584 // Skip the imported kind
587 // Skip the import location
590 // Load stored size/modification time.
591 off_t StoredSize = (off_t)Record[Idx++];
592 time_t StoredModTime = (time_t)Record[Idx++];
594 // Skip the stored signature.
595 // FIXME: we could read the signature out of the import and validate it.
598 // Retrieve the imported file name.
599 unsigned Length = Record[Idx++];
600 SmallString<128> ImportedFile(Record.begin() + Idx,
601 Record.begin() + Idx + Length);
604 // Find the imported module file.
605 const FileEntry *DependsOnFile
606 = FileMgr.getFile(ImportedFile, /*openFile=*/false,
607 /*cacheFailure=*/false);
608 if (!DependsOnFile ||
609 (StoredSize != DependsOnFile->getSize()) ||
610 (StoredModTime != DependsOnFile->getModificationTime()))
613 // Record the dependency.
614 unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
615 getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
621 // Handle the identifier table
622 if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
623 typedef llvm::OnDiskIterableChainedHashTable<
624 InterestingASTIdentifierLookupTrait> InterestingIdentifierTable;
625 std::unique_ptr<InterestingIdentifierTable> Table(
626 InterestingIdentifierTable::Create(
627 (const unsigned char *)Blob.data() + Record[0],
628 (const unsigned char *)Blob.data() + sizeof(uint32_t),
629 (const unsigned char *)Blob.data()));
630 for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
631 DEnd = Table->data_end();
633 std::pair<StringRef, bool> Ident = *D;
635 InterestingIdentifiers[Ident.first].push_back(ID);
637 (void)InterestingIdentifiers[Ident.first];
641 // We don't care about this record.
649 /// \brief Trait used to generate the identifier index as an on-disk hash
651 class IdentifierIndexWriterTrait {
653 typedef StringRef key_type;
654 typedef StringRef key_type_ref;
655 typedef SmallVector<unsigned, 2> data_type;
656 typedef const SmallVector<unsigned, 2> &data_type_ref;
657 typedef unsigned hash_value_type;
658 typedef unsigned offset_type;
660 static hash_value_type ComputeHash(key_type_ref Key) {
661 return llvm::HashString(Key);
664 std::pair<unsigned,unsigned>
665 EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
666 using namespace llvm::support;
667 endian::Writer<little> LE(Out);
668 unsigned KeyLen = Key.size();
669 unsigned DataLen = Data.size() * 4;
670 LE.write<uint16_t>(KeyLen);
671 LE.write<uint16_t>(DataLen);
672 return std::make_pair(KeyLen, DataLen);
675 void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
676 Out.write(Key.data(), KeyLen);
679 void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
681 using namespace llvm::support;
682 for (unsigned I = 0, N = Data.size(); I != N; ++I)
683 endian::Writer<little>(Out).write<uint32_t>(Data[I]);
689 void GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
690 using namespace llvm;
692 // Emit the file header.
693 Stream.Emit((unsigned)'B', 8);
694 Stream.Emit((unsigned)'C', 8);
695 Stream.Emit((unsigned)'G', 8);
696 Stream.Emit((unsigned)'I', 8);
698 // Write the block-info block, which describes the records in this bitcode
700 emitBlockInfoBlock(Stream);
702 Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
704 // Write the metadata.
705 SmallVector<uint64_t, 2> Record;
706 Record.push_back(CurrentVersion);
707 Stream.EmitRecord(INDEX_METADATA, Record);
709 // Write the set of known module files.
710 for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
711 MEnd = ModuleFiles.end();
714 Record.push_back(M->second.ID);
715 Record.push_back(M->first->getSize());
716 Record.push_back(M->first->getModificationTime());
719 StringRef Name(M->first->getName());
720 Record.push_back(Name.size());
721 Record.append(Name.begin(), Name.end());
724 Record.push_back(M->second.Dependencies.size());
725 Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
726 Stream.EmitRecord(MODULE, Record);
729 // Write the identifier -> module file mapping.
731 llvm::OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
732 IdentifierIndexWriterTrait Trait;
734 // Populate the hash table.
735 for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
736 IEnd = InterestingIdentifiers.end();
738 Generator.insert(I->first(), I->second, Trait);
741 // Create the on-disk hash table in a buffer.
742 SmallString<4096> IdentifierTable;
743 uint32_t BucketOffset;
745 using namespace llvm::support;
746 llvm::raw_svector_ostream Out(IdentifierTable);
747 // Make sure that no bucket is at offset 0
748 endian::Writer<little>(Out).write<uint32_t>(0);
749 BucketOffset = Generator.Emit(Out, Trait);
752 // Create a blob abbreviation
753 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
754 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
755 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
756 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
757 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
759 // Write the identifier table
761 Record.push_back(IDENTIFIER_INDEX);
762 Record.push_back(BucketOffset);
763 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
769 GlobalModuleIndex::ErrorCode
770 GlobalModuleIndex::writeIndex(FileManager &FileMgr,
771 const PCHContainerReader &PCHContainerRdr,
773 llvm::SmallString<128> IndexPath;
775 llvm::sys::path::append(IndexPath, IndexFileName);
777 // Coordinate building the global index file with other processes that might
778 // try to do the same.
779 llvm::LockFileManager Locked(IndexPath);
781 case llvm::LockFileManager::LFS_Error:
784 case llvm::LockFileManager::LFS_Owned:
785 // We're responsible for building the index ourselves. Do so below.
788 case llvm::LockFileManager::LFS_Shared:
789 // Someone else is responsible for building the index. We don't care
790 // when they finish, so we're done.
794 // The module index builder.
795 GlobalModuleIndexBuilder Builder(FileMgr, PCHContainerRdr);
797 // Load each of the module files.
799 for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
802 // If this isn't a module file, we don't care.
803 if (llvm::sys::path::extension(D->path()) != ".pcm") {
804 // ... unless it's a .pcm.lock file, which indicates that someone is
805 // in the process of rebuilding a module. They'll rebuild the index
806 // at the end of that translation unit, so we don't have to.
807 if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
813 // If we can't find the module file, skip it.
814 const FileEntry *ModuleFile = FileMgr.getFile(D->path());
818 // Load this module file.
819 if (Builder.loadModuleFile(ModuleFile))
823 // The output buffer, into which the global index will be written.
824 SmallVector<char, 16> OutputBuffer;
826 llvm::BitstreamWriter OutputStream(OutputBuffer);
827 Builder.writeIndex(OutputStream);
830 // Write the global index file to a temporary file.
831 llvm::SmallString<128> IndexTmpPath;
833 if (llvm::sys::fs::createUniqueFile(IndexPath + "-%%%%%%%%", TmpFD,
837 // Open the temporary global index file for output.
838 llvm::raw_fd_ostream Out(TmpFD, true);
843 Out.write(OutputBuffer.data(), OutputBuffer.size());
848 // Remove the old index file. It isn't relevant any more.
849 llvm::sys::fs::remove(IndexPath);
851 // Rename the newly-written index file to the proper name.
852 if (llvm::sys::fs::rename(IndexTmpPath, IndexPath)) {
853 // Rename failed; just remove the
854 llvm::sys::fs::remove(IndexTmpPath);
863 class GlobalIndexIdentifierIterator : public IdentifierIterator {
864 /// \brief The current position within the identifier lookup table.
865 IdentifierIndexTable::key_iterator Current;
867 /// \brief The end position within the identifier lookup table.
868 IdentifierIndexTable::key_iterator End;
871 explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
872 Current = Idx.key_begin();
876 StringRef Next() override {
880 StringRef Result = *Current;
887 IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
888 IdentifierIndexTable &Table =
889 *static_cast<IdentifierIndexTable *>(IdentifierIndex);
890 return new GlobalIndexIdentifierIterator(Table);