1 //===--- GlobalModuleIndex.cpp - Global Module Index ------------*- 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 implements the GlobalModuleIndex class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ASTReaderInternals.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Lex/HeaderSearch.h"
17 #include "clang/Serialization/ASTBitCodes.h"
18 #include "clang/Serialization/GlobalModuleIndex.h"
19 #include "clang/Serialization/Module.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/MapVector.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Bitcode/BitstreamReader.h"
25 #include "llvm/Bitcode/BitstreamWriter.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/LockFileManager.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/OnDiskHashTable.h"
30 #include "llvm/Support/Path.h"
31 #include <cstdio>
32 using namespace clang;
33 using namespace serialization;
34 
35 //----------------------------------------------------------------------------//
36 // Shared constants
37 //----------------------------------------------------------------------------//
38 namespace {
39   enum {
40     /// \brief The block containing the index.
41     GLOBAL_INDEX_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID
42   };
43 
44   /// \brief Describes the record types in the index.
45   enum IndexRecordTypes {
46     /// \brief Contains version information and potentially other metadata,
47     /// used to determine if we can read this global index file.
48     INDEX_METADATA,
49     /// \brief Describes a module, including its file name and dependencies.
50     MODULE,
51     /// \brief The index for identifiers.
52     IDENTIFIER_INDEX
53   };
54 }
55 
56 /// \brief The name of the global index file.
57 static const char * const IndexFileName = "modules.idx";
58 
59 /// \brief The global index file version.
60 static const unsigned CurrentVersion = 1;
61 
62 //----------------------------------------------------------------------------//
63 // Global module index reader.
64 //----------------------------------------------------------------------------//
65 
66 namespace {
67 
68 /// \brief Trait used to read the identifier index from the on-disk hash
69 /// table.
70 class IdentifierIndexReaderTrait {
71 public:
72   typedef StringRef external_key_type;
73   typedef StringRef internal_key_type;
74   typedef SmallVector<unsigned, 2> data_type;
75   typedef unsigned hash_value_type;
76   typedef unsigned offset_type;
77 
78   static bool EqualKey(const internal_key_type& a, const internal_key_type& b) {
79     return a == b;
80   }
81 
82   static hash_value_type ComputeHash(const internal_key_type& a) {
83     return llvm::HashString(a);
84   }
85 
86   static std::pair<unsigned, unsigned>
87   ReadKeyDataLength(const unsigned char*& d) {
88     using namespace llvm::support;
89     unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
90     unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
91     return std::make_pair(KeyLen, DataLen);
92   }
93 
94   static const internal_key_type&
95   GetInternalKey(const external_key_type& x) { return x; }
96 
97   static const external_key_type&
98   GetExternalKey(const internal_key_type& x) { return x; }
99 
100   static internal_key_type ReadKey(const unsigned char* d, unsigned n) {
101     return StringRef((const char *)d, n);
102   }
103 
104   static data_type ReadData(const internal_key_type& k,
105                             const unsigned char* d,
106                             unsigned DataLen) {
107     using namespace llvm::support;
108 
109     data_type Result;
110     while (DataLen > 0) {
111       unsigned ID = endian::readNext<uint32_t, little, unaligned>(d);
112       Result.push_back(ID);
113       DataLen -= 4;
114     }
115 
116     return Result;
117   }
118 };
119 
120 typedef llvm::OnDiskIterableChainedHashTable<IdentifierIndexReaderTrait>
121     IdentifierIndexTable;
122 
123 }
124 
125 GlobalModuleIndex::GlobalModuleIndex(llvm::MemoryBuffer *Buffer,
126                                      llvm::BitstreamCursor Cursor)
127   : Buffer(Buffer), IdentifierIndex(),
128     NumIdentifierLookups(), NumIdentifierLookupHits()
129 {
130   // Read the global index.
131   bool InGlobalIndexBlock = false;
132   bool Done = false;
133   while (!Done) {
134     llvm::BitstreamEntry Entry = Cursor.advance();
135 
136     switch (Entry.Kind) {
137     case llvm::BitstreamEntry::Error:
138       return;
139 
140     case llvm::BitstreamEntry::EndBlock:
141       if (InGlobalIndexBlock) {
142         InGlobalIndexBlock = false;
143         Done = true;
144         continue;
145       }
146       return;
147 
148 
149     case llvm::BitstreamEntry::Record:
150       // Entries in the global index block are handled below.
151       if (InGlobalIndexBlock)
152         break;
153 
154       return;
155 
156     case llvm::BitstreamEntry::SubBlock:
157       if (!InGlobalIndexBlock && Entry.ID == GLOBAL_INDEX_BLOCK_ID) {
158         if (Cursor.EnterSubBlock(GLOBAL_INDEX_BLOCK_ID))
159           return;
160 
161         InGlobalIndexBlock = true;
162       } else if (Cursor.SkipBlock()) {
163         return;
164       }
165       continue;
166     }
167 
168     SmallVector<uint64_t, 64> Record;
169     StringRef Blob;
170     switch ((IndexRecordTypes)Cursor.readRecord(Entry.ID, Record, &Blob)) {
171     case INDEX_METADATA:
172       // Make sure that the version matches.
173       if (Record.size() < 1 || Record[0] != CurrentVersion)
174         return;
175       break;
176 
177     case MODULE: {
178       unsigned Idx = 0;
179       unsigned ID = Record[Idx++];
180 
181       // Make room for this module's information.
182       if (ID == Modules.size())
183         Modules.push_back(ModuleInfo());
184       else
185         Modules.resize(ID + 1);
186 
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++];
191 
192       // File name.
193       unsigned NameLen = Record[Idx++];
194       Modules[ID].FileName.assign(Record.begin() + Idx,
195                                   Record.begin() + Idx + NameLen);
196       Idx += NameLen;
197 
198       // Dependencies
199       unsigned NumDeps = Record[Idx++];
200       Modules[ID].Dependencies.insert(Modules[ID].Dependencies.end(),
201                                       Record.begin() + Idx,
202                                       Record.begin() + Idx + NumDeps);
203       Idx += NumDeps;
204 
205       // Make sure we're at the end of the record.
206       assert(Idx == Record.size() && "More module info?");
207 
208       // Record this module as an unresolved module.
209       // FIXME: this doesn't work correctly for module names containing path
210       // separators.
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;
215       break;
216     }
217 
218     case IDENTIFIER_INDEX:
219       // Wire up the identifier index.
220       if (Record[0]) {
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());
225       }
226       break;
227     }
228   }
229 }
230 
231 GlobalModuleIndex::~GlobalModuleIndex() { }
232 
233 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode>
234 GlobalModuleIndex::readIndex(StringRef Path) {
235   // Load the index file, if it's there.
236   llvm::SmallString<128> IndexPath;
237   IndexPath += Path;
238   llvm::sys::path::append(IndexPath, IndexFileName);
239 
240   std::unique_ptr<llvm::MemoryBuffer> Buffer;
241   if (llvm::MemoryBuffer::getFile(IndexPath.c_str(), Buffer) !=
242       llvm::errc::success)
243     return std::make_pair((GlobalModuleIndex *)0, EC_NotFound);
244 
245   /// \brief The bitstream reader from which we'll read the AST file.
246   llvm::BitstreamReader Reader((const unsigned char *)Buffer->getBufferStart(),
247                                (const unsigned char *)Buffer->getBufferEnd());
248 
249   /// \brief The main bitstream cursor for the main block.
250   llvm::BitstreamCursor Cursor(Reader);
251 
252   // Sniff for the signature.
253   if (Cursor.Read(8) != 'B' ||
254       Cursor.Read(8) != 'C' ||
255       Cursor.Read(8) != 'G' ||
256       Cursor.Read(8) != 'I') {
257     return std::make_pair((GlobalModuleIndex *)0, EC_IOError);
258   }
259 
260   return std::make_pair(new GlobalModuleIndex(Buffer.release(), Cursor),
261                         EC_None);
262 }
263 
264 void
265 GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
266   ModuleFiles.clear();
267   for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
268     if (ModuleFile *MF = Modules[I].File)
269       ModuleFiles.push_back(MF);
270   }
271 }
272 
273 void GlobalModuleIndex::getModuleDependencies(
274        ModuleFile *File,
275        SmallVectorImpl<ModuleFile *> &Dependencies) {
276   // Look for information about this module file.
277   llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
278     = ModulesByFile.find(File);
279   if (Known == ModulesByFile.end())
280     return;
281 
282   // Record dependencies.
283   Dependencies.clear();
284   ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
285   for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
286     if (ModuleFile *MF = Modules[I].File)
287       Dependencies.push_back(MF);
288   }
289 }
290 
291 bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
292   Hits.clear();
293 
294   // If there's no identifier index, there is nothing we can do.
295   if (!IdentifierIndex)
296     return false;
297 
298   // Look into the identifier index.
299   ++NumIdentifierLookups;
300   IdentifierIndexTable &Table
301     = *static_cast<IdentifierIndexTable *>(IdentifierIndex);
302   IdentifierIndexTable::iterator Known = Table.find(Name);
303   if (Known == Table.end()) {
304     return true;
305   }
306 
307   SmallVector<unsigned, 2> ModuleIDs = *Known;
308   for (unsigned I = 0, N = ModuleIDs.size(); I != N; ++I) {
309     if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
310       Hits.insert(MF);
311   }
312 
313   ++NumIdentifierLookupHits;
314   return true;
315 }
316 
317 bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
318   // Look for the module in the global module index based on the module name.
319   StringRef Name = File->ModuleName;
320   llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
321   if (Known == UnresolvedModules.end()) {
322     return true;
323   }
324 
325   // Rectify this module with the global module index.
326   ModuleInfo &Info = Modules[Known->second];
327 
328   //  If the size and modification time match what we expected, record this
329   // module file.
330   bool Failed = true;
331   if (File->File->getSize() == Info.Size &&
332       File->File->getModificationTime() == Info.ModTime) {
333     Info.File = File;
334     ModulesByFile[File] = Known->second;
335 
336     Failed = false;
337   }
338 
339   // One way or another, we have resolved this module file.
340   UnresolvedModules.erase(Known);
341   return Failed;
342 }
343 
344 void GlobalModuleIndex::printStats() {
345   std::fprintf(stderr, "*** Global Module Index Statistics:\n");
346   if (NumIdentifierLookups) {
347     fprintf(stderr, "  %u / %u identifier lookups succeeded (%f%%)\n",
348             NumIdentifierLookupHits, NumIdentifierLookups,
349             (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
350   }
351   std::fprintf(stderr, "\n");
352 }
353 
354 void GlobalModuleIndex::dump() {
355   llvm::errs() << "*** Global Module Index Dump:\n";
356   llvm::errs() << "Module files:\n";
357   for (auto &MI : Modules) {
358     llvm::errs() << "** " << MI.FileName << "\n";
359     if (MI.File)
360       MI.File->dump();
361     else
362       llvm::errs() << "\n";
363   }
364   llvm::errs() << "\n";
365 }
366 
367 //----------------------------------------------------------------------------//
368 // Global module index writer.
369 //----------------------------------------------------------------------------//
370 
371 namespace {
372   /// \brief Provides information about a specific module file.
373   struct ModuleFileInfo {
374     /// \brief The numberic ID for this module file.
375     unsigned ID;
376 
377     /// \brief The set of modules on which this module depends. Each entry is
378     /// a module ID.
379     SmallVector<unsigned, 4> Dependencies;
380   };
381 
382   /// \brief Builder that generates the global module index file.
383   class GlobalModuleIndexBuilder {
384     FileManager &FileMgr;
385 
386     /// \brief Mapping from files to module file information.
387     typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
388 
389     /// \brief Information about each of the known module files.
390     ModuleFilesMap ModuleFiles;
391 
392     /// \brief Mapping from identifiers to the list of module file IDs that
393     /// consider this identifier to be interesting.
394     typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
395 
396     /// \brief A mapping from all interesting identifiers to the set of module
397     /// files in which those identifiers are considered interesting.
398     InterestingIdentifierMap InterestingIdentifiers;
399 
400     /// \brief Write the block-info block for the global module index file.
401     void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
402 
403     /// \brief Retrieve the module file information for the given file.
404     ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
405       llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
406         = ModuleFiles.find(File);
407       if (Known != ModuleFiles.end())
408         return Known->second;
409 
410       unsigned NewID = ModuleFiles.size();
411       ModuleFileInfo &Info = ModuleFiles[File];
412       Info.ID = NewID;
413       return Info;
414     }
415 
416   public:
417     explicit GlobalModuleIndexBuilder(FileManager &FileMgr) : FileMgr(FileMgr){}
418 
419     /// \brief Load the contents of the given module file into the builder.
420     ///
421     /// \returns true if an error occurred, false otherwise.
422     bool loadModuleFile(const FileEntry *File);
423 
424     /// \brief Write the index to the given bitstream.
425     void writeIndex(llvm::BitstreamWriter &Stream);
426   };
427 }
428 
429 static void emitBlockID(unsigned ID, const char *Name,
430                         llvm::BitstreamWriter &Stream,
431                         SmallVectorImpl<uint64_t> &Record) {
432   Record.clear();
433   Record.push_back(ID);
434   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
435 
436   // Emit the block name if present.
437   if (Name == 0 || Name[0] == 0) return;
438   Record.clear();
439   while (*Name)
440     Record.push_back(*Name++);
441   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
442 }
443 
444 static void emitRecordID(unsigned ID, const char *Name,
445                          llvm::BitstreamWriter &Stream,
446                          SmallVectorImpl<uint64_t> &Record) {
447   Record.clear();
448   Record.push_back(ID);
449   while (*Name)
450     Record.push_back(*Name++);
451   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
452 }
453 
454 void
455 GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
456   SmallVector<uint64_t, 64> Record;
457   Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
458 
459 #define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
460 #define RECORD(X) emitRecordID(X, #X, Stream, Record)
461   BLOCK(GLOBAL_INDEX_BLOCK);
462   RECORD(INDEX_METADATA);
463   RECORD(MODULE);
464   RECORD(IDENTIFIER_INDEX);
465 #undef RECORD
466 #undef BLOCK
467 
468   Stream.ExitBlock();
469 }
470 
471 namespace {
472   class InterestingASTIdentifierLookupTrait
473     : public serialization::reader::ASTIdentifierLookupTraitBase {
474 
475   public:
476     /// \brief The identifier and whether it is "interesting".
477     typedef std::pair<StringRef, bool> data_type;
478 
479     data_type ReadData(const internal_key_type& k,
480                        const unsigned char* d,
481                        unsigned DataLen) {
482       // The first bit indicates whether this identifier is interesting.
483       // That's all we care about.
484       using namespace llvm::support;
485       unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
486       bool IsInteresting = RawID & 0x01;
487       return std::make_pair(k, IsInteresting);
488     }
489   };
490 }
491 
492 bool GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
493   // Open the module file.
494   std::unique_ptr<llvm::MemoryBuffer> Buffer;
495   std::string ErrorStr;
496   Buffer.reset(FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true));
497   if (!Buffer) {
498     return true;
499   }
500 
501   // Initialize the input stream
502   llvm::BitstreamReader InStreamFile;
503   llvm::BitstreamCursor InStream;
504   InStreamFile.init((const unsigned char *)Buffer->getBufferStart(),
505                   (const unsigned char *)Buffer->getBufferEnd());
506   InStream.init(InStreamFile);
507 
508   // Sniff for the signature.
509   if (InStream.Read(8) != 'C' ||
510       InStream.Read(8) != 'P' ||
511       InStream.Read(8) != 'C' ||
512       InStream.Read(8) != 'H') {
513     return true;
514   }
515 
516   // Record this module file and assign it a unique ID (if it doesn't have
517   // one already).
518   unsigned ID = getModuleFileInfo(File).ID;
519 
520   // Search for the blocks and records we care about.
521   enum { Other, ControlBlock, ASTBlock } State = Other;
522   bool Done = false;
523   while (!Done) {
524     llvm::BitstreamEntry Entry = InStream.advance();
525     switch (Entry.Kind) {
526     case llvm::BitstreamEntry::Error:
527       Done = true;
528       continue;
529 
530     case llvm::BitstreamEntry::Record:
531       // In the 'other' state, just skip the record. We don't care.
532       if (State == Other) {
533         InStream.skipRecord(Entry.ID);
534         continue;
535       }
536 
537       // Handle potentially-interesting records below.
538       break;
539 
540     case llvm::BitstreamEntry::SubBlock:
541       if (Entry.ID == CONTROL_BLOCK_ID) {
542         if (InStream.EnterSubBlock(CONTROL_BLOCK_ID))
543           return true;
544 
545         // Found the control block.
546         State = ControlBlock;
547         continue;
548       }
549 
550       if (Entry.ID == AST_BLOCK_ID) {
551         if (InStream.EnterSubBlock(AST_BLOCK_ID))
552           return true;
553 
554         // Found the AST block.
555         State = ASTBlock;
556         continue;
557       }
558 
559       if (InStream.SkipBlock())
560         return true;
561 
562       continue;
563 
564     case llvm::BitstreamEntry::EndBlock:
565       State = Other;
566       continue;
567     }
568 
569     // Read the given record.
570     SmallVector<uint64_t, 64> Record;
571     StringRef Blob;
572     unsigned Code = InStream.readRecord(Entry.ID, Record, &Blob);
573 
574     // Handle module dependencies.
575     if (State == ControlBlock && Code == IMPORTS) {
576       // Load each of the imported PCH files.
577       unsigned Idx = 0, N = Record.size();
578       while (Idx < N) {
579         // Read information about the AST file.
580 
581         // Skip the imported kind
582         ++Idx;
583 
584         // Skip the import location
585         ++Idx;
586 
587         // Load stored size/modification time.
588         off_t StoredSize = (off_t)Record[Idx++];
589         time_t StoredModTime = (time_t)Record[Idx++];
590 
591         // Retrieve the imported file name.
592         unsigned Length = Record[Idx++];
593         SmallString<128> ImportedFile(Record.begin() + Idx,
594                                       Record.begin() + Idx + Length);
595         Idx += Length;
596 
597         // Find the imported module file.
598         const FileEntry *DependsOnFile
599           = FileMgr.getFile(ImportedFile, /*openFile=*/false,
600                             /*cacheFailure=*/false);
601         if (!DependsOnFile ||
602             (StoredSize != DependsOnFile->getSize()) ||
603             (StoredModTime != DependsOnFile->getModificationTime()))
604           return true;
605 
606         // Record the dependency.
607         unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
608         getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
609       }
610 
611       continue;
612     }
613 
614     // Handle the identifier table
615     if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
616       typedef llvm::OnDiskIterableChainedHashTable<
617           InterestingASTIdentifierLookupTrait> InterestingIdentifierTable;
618       std::unique_ptr<InterestingIdentifierTable> Table(
619           InterestingIdentifierTable::Create(
620               (const unsigned char *)Blob.data() + Record[0],
621               (const unsigned char *)Blob.data() + sizeof(uint32_t),
622               (const unsigned char *)Blob.data()));
623       for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
624                                                      DEnd = Table->data_end();
625            D != DEnd; ++D) {
626         std::pair<StringRef, bool> Ident = *D;
627         if (Ident.second)
628           InterestingIdentifiers[Ident.first].push_back(ID);
629         else
630           (void)InterestingIdentifiers[Ident.first];
631       }
632     }
633 
634     // We don't care about this record.
635   }
636 
637   return false;
638 }
639 
640 namespace {
641 
642 /// \brief Trait used to generate the identifier index as an on-disk hash
643 /// table.
644 class IdentifierIndexWriterTrait {
645 public:
646   typedef StringRef key_type;
647   typedef StringRef key_type_ref;
648   typedef SmallVector<unsigned, 2> data_type;
649   typedef const SmallVector<unsigned, 2> &data_type_ref;
650   typedef unsigned hash_value_type;
651   typedef unsigned offset_type;
652 
653   static hash_value_type ComputeHash(key_type_ref Key) {
654     return llvm::HashString(Key);
655   }
656 
657   std::pair<unsigned,unsigned>
658   EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
659     using namespace llvm::support;
660     endian::Writer<little> LE(Out);
661     unsigned KeyLen = Key.size();
662     unsigned DataLen = Data.size() * 4;
663     LE.write<uint16_t>(KeyLen);
664     LE.write<uint16_t>(DataLen);
665     return std::make_pair(KeyLen, DataLen);
666   }
667 
668   void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
669     Out.write(Key.data(), KeyLen);
670   }
671 
672   void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
673                 unsigned DataLen) {
674     using namespace llvm::support;
675     for (unsigned I = 0, N = Data.size(); I != N; ++I)
676       endian::Writer<little>(Out).write<uint32_t>(Data[I]);
677   }
678 };
679 
680 }
681 
682 void GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
683   using namespace llvm;
684 
685   // Emit the file header.
686   Stream.Emit((unsigned)'B', 8);
687   Stream.Emit((unsigned)'C', 8);
688   Stream.Emit((unsigned)'G', 8);
689   Stream.Emit((unsigned)'I', 8);
690 
691   // Write the block-info block, which describes the records in this bitcode
692   // file.
693   emitBlockInfoBlock(Stream);
694 
695   Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
696 
697   // Write the metadata.
698   SmallVector<uint64_t, 2> Record;
699   Record.push_back(CurrentVersion);
700   Stream.EmitRecord(INDEX_METADATA, Record);
701 
702   // Write the set of known module files.
703   for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
704                                 MEnd = ModuleFiles.end();
705        M != MEnd; ++M) {
706     Record.clear();
707     Record.push_back(M->second.ID);
708     Record.push_back(M->first->getSize());
709     Record.push_back(M->first->getModificationTime());
710 
711     // File name
712     StringRef Name(M->first->getName());
713     Record.push_back(Name.size());
714     Record.append(Name.begin(), Name.end());
715 
716     // Dependencies
717     Record.push_back(M->second.Dependencies.size());
718     Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
719     Stream.EmitRecord(MODULE, Record);
720   }
721 
722   // Write the identifier -> module file mapping.
723   {
724     llvm::OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
725     IdentifierIndexWriterTrait Trait;
726 
727     // Populate the hash table.
728     for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
729                                             IEnd = InterestingIdentifiers.end();
730          I != IEnd; ++I) {
731       Generator.insert(I->first(), I->second, Trait);
732     }
733 
734     // Create the on-disk hash table in a buffer.
735     SmallString<4096> IdentifierTable;
736     uint32_t BucketOffset;
737     {
738       using namespace llvm::support;
739       llvm::raw_svector_ostream Out(IdentifierTable);
740       // Make sure that no bucket is at offset 0
741       endian::Writer<little>(Out).write<uint32_t>(0);
742       BucketOffset = Generator.Emit(Out, Trait);
743     }
744 
745     // Create a blob abbreviation
746     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
747     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
748     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
749     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
750     unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
751 
752     // Write the identifier table
753     Record.clear();
754     Record.push_back(IDENTIFIER_INDEX);
755     Record.push_back(BucketOffset);
756     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
757   }
758 
759   Stream.ExitBlock();
760 }
761 
762 GlobalModuleIndex::ErrorCode
763 GlobalModuleIndex::writeIndex(FileManager &FileMgr, StringRef Path) {
764   llvm::SmallString<128> IndexPath;
765   IndexPath += Path;
766   llvm::sys::path::append(IndexPath, IndexFileName);
767 
768   // Coordinate building the global index file with other processes that might
769   // try to do the same.
770   llvm::LockFileManager Locked(IndexPath);
771   switch (Locked) {
772   case llvm::LockFileManager::LFS_Error:
773     return EC_IOError;
774 
775   case llvm::LockFileManager::LFS_Owned:
776     // We're responsible for building the index ourselves. Do so below.
777     break;
778 
779   case llvm::LockFileManager::LFS_Shared:
780     // Someone else is responsible for building the index. We don't care
781     // when they finish, so we're done.
782     return EC_Building;
783   }
784 
785   // The module index builder.
786   GlobalModuleIndexBuilder Builder(FileMgr);
787 
788   // Load each of the module files.
789   llvm::error_code EC;
790   for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
791        D != DEnd && !EC;
792        D.increment(EC)) {
793     // If this isn't a module file, we don't care.
794     if (llvm::sys::path::extension(D->path()) != ".pcm") {
795       // ... unless it's a .pcm.lock file, which indicates that someone is
796       // in the process of rebuilding a module. They'll rebuild the index
797       // at the end of that translation unit, so we don't have to.
798       if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
799         return EC_Building;
800 
801       continue;
802     }
803 
804     // If we can't find the module file, skip it.
805     const FileEntry *ModuleFile = FileMgr.getFile(D->path());
806     if (!ModuleFile)
807       continue;
808 
809     // Load this module file.
810     if (Builder.loadModuleFile(ModuleFile))
811       return EC_IOError;
812   }
813 
814   // The output buffer, into which the global index will be written.
815   SmallVector<char, 16> OutputBuffer;
816   {
817     llvm::BitstreamWriter OutputStream(OutputBuffer);
818     Builder.writeIndex(OutputStream);
819   }
820 
821   // Write the global index file to a temporary file.
822   llvm::SmallString<128> IndexTmpPath;
823   int TmpFD;
824   if (llvm::sys::fs::createUniqueFile(IndexPath + "-%%%%%%%%", TmpFD,
825                                       IndexTmpPath))
826     return EC_IOError;
827 
828   // Open the temporary global index file for output.
829   llvm::raw_fd_ostream Out(TmpFD, true);
830   if (Out.has_error())
831     return EC_IOError;
832 
833   // Write the index.
834   Out.write(OutputBuffer.data(), OutputBuffer.size());
835   Out.close();
836   if (Out.has_error())
837     return EC_IOError;
838 
839   // Remove the old index file. It isn't relevant any more.
840   llvm::sys::fs::remove(IndexPath.str());
841 
842   // Rename the newly-written index file to the proper name.
843   if (llvm::sys::fs::rename(IndexTmpPath.str(), IndexPath.str())) {
844     // Rename failed; just remove the
845     llvm::sys::fs::remove(IndexTmpPath.str());
846     return EC_IOError;
847   }
848 
849   // We're done.
850   return EC_None;
851 }
852 
853 namespace {
854   class GlobalIndexIdentifierIterator : public IdentifierIterator {
855     /// \brief The current position within the identifier lookup table.
856     IdentifierIndexTable::key_iterator Current;
857 
858     /// \brief The end position within the identifier lookup table.
859     IdentifierIndexTable::key_iterator End;
860 
861   public:
862     explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
863       Current = Idx.key_begin();
864       End = Idx.key_end();
865     }
866 
867     StringRef Next() override {
868       if (Current == End)
869         return StringRef();
870 
871       StringRef Result = *Current;
872       ++Current;
873       return Result;
874     }
875   };
876 }
877 
878 IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
879   IdentifierIndexTable &Table =
880     *static_cast<IdentifierIndexTable *>(IdentifierIndex);
881   return new GlobalIndexIdentifierIterator(Table);
882 }
883