GlobalModuleIndex.cpp 27 KB

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