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