CacheTokens.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. //===--- CacheTokens.cpp - Caching of lexer tokens for PTH support --------===//
  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 provides a possible implementation of PTH support for Clang that is
  11. // based on caching lexed tokens and identifiers.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Frontend/Utils.h"
  15. #include "clang/Basic/Diagnostic.h"
  16. #include "clang/Basic/FileManager.h"
  17. #include "clang/Basic/FileSystemStatCache.h"
  18. #include "clang/Basic/IdentifierTable.h"
  19. #include "clang/Basic/OnDiskHashTable.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "clang/Lex/Lexer.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "llvm/ADT/StringExtras.h"
  24. #include "llvm/ADT/StringMap.h"
  25. #include "llvm/Support/FileSystem.h"
  26. #include "llvm/Support/MemoryBuffer.h"
  27. #include "llvm/Support/Path.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. // FIXME: put this somewhere else?
  30. #ifndef S_ISDIR
  31. #define S_ISDIR(x) (((x)&_S_IFDIR)!=0)
  32. #endif
  33. using namespace clang;
  34. using namespace clang::io;
  35. //===----------------------------------------------------------------------===//
  36. // PTH-specific stuff.
  37. //===----------------------------------------------------------------------===//
  38. namespace {
  39. class PTHEntry {
  40. Offset TokenData, PPCondData;
  41. public:
  42. PTHEntry() {}
  43. PTHEntry(Offset td, Offset ppcd)
  44. : TokenData(td), PPCondData(ppcd) {}
  45. Offset getTokenOffset() const { return TokenData; }
  46. Offset getPPCondTableOffset() const { return PPCondData; }
  47. };
  48. class PTHEntryKeyVariant {
  49. union { const FileEntry* FE; const char* Path; };
  50. enum { IsFE = 0x1, IsDE = 0x2, IsNoExist = 0x0 } Kind;
  51. FileData *Data;
  52. public:
  53. PTHEntryKeyVariant(const FileEntry *fe) : FE(fe), Kind(IsFE), Data(0) {}
  54. PTHEntryKeyVariant(FileData *Data, const char *path)
  55. : Path(path), Kind(IsDE), Data(new FileData(*Data)) {}
  56. explicit PTHEntryKeyVariant(const char *path)
  57. : Path(path), Kind(IsNoExist), Data(0) {}
  58. bool isFile() const { return Kind == IsFE; }
  59. StringRef getString() const {
  60. return Kind == IsFE ? FE->getName() : Path;
  61. }
  62. unsigned getKind() const { return (unsigned) Kind; }
  63. void EmitData(raw_ostream& Out) {
  64. switch (Kind) {
  65. case IsFE: {
  66. // Emit stat information.
  67. llvm::sys::fs::UniqueID UID = FE->getUniqueID();
  68. ::Emit64(Out, UID.getFile());
  69. ::Emit64(Out, UID.getDevice());
  70. ::Emit64(Out, FE->getModificationTime());
  71. ::Emit64(Out, FE->getSize());
  72. } break;
  73. case IsDE:
  74. // Emit stat information.
  75. ::Emit64(Out, Data->UniqueID.getFile());
  76. ::Emit64(Out, Data->UniqueID.getDevice());
  77. ::Emit64(Out, Data->ModTime);
  78. ::Emit64(Out, Data->Size);
  79. delete Data;
  80. break;
  81. default:
  82. break;
  83. }
  84. }
  85. unsigned getRepresentationLength() const {
  86. return Kind == IsNoExist ? 0 : 4 + 4 + 2 + 8 + 8;
  87. }
  88. };
  89. class FileEntryPTHEntryInfo {
  90. public:
  91. typedef PTHEntryKeyVariant key_type;
  92. typedef key_type key_type_ref;
  93. typedef PTHEntry data_type;
  94. typedef const PTHEntry& data_type_ref;
  95. static unsigned ComputeHash(PTHEntryKeyVariant V) {
  96. return llvm::HashString(V.getString());
  97. }
  98. static std::pair<unsigned,unsigned>
  99. EmitKeyDataLength(raw_ostream& Out, PTHEntryKeyVariant V,
  100. const PTHEntry& E) {
  101. unsigned n = V.getString().size() + 1 + 1;
  102. ::Emit16(Out, n);
  103. unsigned m = V.getRepresentationLength() + (V.isFile() ? 4 + 4 : 0);
  104. ::Emit8(Out, m);
  105. return std::make_pair(n, m);
  106. }
  107. static void EmitKey(raw_ostream& Out, PTHEntryKeyVariant V, unsigned n){
  108. // Emit the entry kind.
  109. ::Emit8(Out, (unsigned) V.getKind());
  110. // Emit the string.
  111. Out.write(V.getString().data(), n - 1);
  112. }
  113. static void EmitData(raw_ostream& Out, PTHEntryKeyVariant V,
  114. const PTHEntry& E, unsigned) {
  115. // For file entries emit the offsets into the PTH file for token data
  116. // and the preprocessor blocks table.
  117. if (V.isFile()) {
  118. ::Emit32(Out, E.getTokenOffset());
  119. ::Emit32(Out, E.getPPCondTableOffset());
  120. }
  121. // Emit any other data associated with the key (i.e., stat information).
  122. V.EmitData(Out);
  123. }
  124. };
  125. class OffsetOpt {
  126. bool valid;
  127. Offset off;
  128. public:
  129. OffsetOpt() : valid(false) {}
  130. bool hasOffset() const { return valid; }
  131. Offset getOffset() const { assert(valid); return off; }
  132. void setOffset(Offset o) { off = o; valid = true; }
  133. };
  134. } // end anonymous namespace
  135. typedef OnDiskChainedHashTableGenerator<FileEntryPTHEntryInfo> PTHMap;
  136. namespace {
  137. class PTHWriter {
  138. typedef llvm::DenseMap<const IdentifierInfo*,uint32_t> IDMap;
  139. typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy;
  140. IDMap IM;
  141. llvm::raw_fd_ostream& Out;
  142. Preprocessor& PP;
  143. uint32_t idcount;
  144. PTHMap PM;
  145. CachedStrsTy CachedStrs;
  146. Offset CurStrOffset;
  147. std::vector<llvm::StringMapEntry<OffsetOpt>*> StrEntries;
  148. //// Get the persistent id for the given IdentifierInfo*.
  149. uint32_t ResolveID(const IdentifierInfo* II);
  150. /// Emit a token to the PTH file.
  151. void EmitToken(const Token& T);
  152. void Emit8(uint32_t V) { ::Emit8(Out, V); }
  153. void Emit16(uint32_t V) { ::Emit16(Out, V); }
  154. void Emit32(uint32_t V) { ::Emit32(Out, V); }
  155. void EmitBuf(const char *Ptr, unsigned NumBytes) {
  156. Out.write(Ptr, NumBytes);
  157. }
  158. void EmitString(StringRef V) {
  159. ::Emit16(Out, V.size());
  160. EmitBuf(V.data(), V.size());
  161. }
  162. /// EmitIdentifierTable - Emits two tables to the PTH file. The first is
  163. /// a hashtable mapping from identifier strings to persistent IDs.
  164. /// The second is a straight table mapping from persistent IDs to string data
  165. /// (the keys of the first table).
  166. std::pair<Offset, Offset> EmitIdentifierTable();
  167. /// EmitFileTable - Emit a table mapping from file name strings to PTH
  168. /// token data.
  169. Offset EmitFileTable() { return PM.Emit(Out); }
  170. PTHEntry LexTokens(Lexer& L);
  171. Offset EmitCachedSpellings();
  172. public:
  173. PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp)
  174. : Out(out), PP(pp), idcount(0), CurStrOffset(0) {}
  175. PTHMap &getPM() { return PM; }
  176. void GeneratePTH(const std::string &MainFile);
  177. };
  178. } // end anonymous namespace
  179. uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) {
  180. // Null IdentifierInfo's map to the persistent ID 0.
  181. if (!II)
  182. return 0;
  183. IDMap::iterator I = IM.find(II);
  184. if (I != IM.end())
  185. return I->second; // We've already added 1.
  186. IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL.
  187. return idcount;
  188. }
  189. void PTHWriter::EmitToken(const Token& T) {
  190. // Emit the token kind, flags, and length.
  191. Emit32(((uint32_t) T.getKind()) | ((((uint32_t) T.getFlags())) << 8)|
  192. (((uint32_t) T.getLength()) << 16));
  193. if (!T.isLiteral()) {
  194. Emit32(ResolveID(T.getIdentifierInfo()));
  195. } else {
  196. // We cache *un-cleaned* spellings. This gives us 100% fidelity with the
  197. // source code.
  198. StringRef s(T.getLiteralData(), T.getLength());
  199. // Get the string entry.
  200. llvm::StringMapEntry<OffsetOpt> *E = &CachedStrs.GetOrCreateValue(s);
  201. // If this is a new string entry, bump the PTH offset.
  202. if (!E->getValue().hasOffset()) {
  203. E->getValue().setOffset(CurStrOffset);
  204. StrEntries.push_back(E);
  205. CurStrOffset += s.size() + 1;
  206. }
  207. // Emit the relative offset into the PTH file for the spelling string.
  208. Emit32(E->getValue().getOffset());
  209. }
  210. // Emit the offset into the original source file of this token so that we
  211. // can reconstruct its SourceLocation.
  212. Emit32(PP.getSourceManager().getFileOffset(T.getLocation()));
  213. }
  214. PTHEntry PTHWriter::LexTokens(Lexer& L) {
  215. // Pad 0's so that we emit tokens to a 4-byte alignment.
  216. // This speed up reading them back in.
  217. Pad(Out, 4);
  218. Offset TokenOff = (Offset) Out.tell();
  219. // Keep track of matching '#if' ... '#endif'.
  220. typedef std::vector<std::pair<Offset, unsigned> > PPCondTable;
  221. PPCondTable PPCond;
  222. std::vector<unsigned> PPStartCond;
  223. bool ParsingPreprocessorDirective = false;
  224. Token Tok;
  225. do {
  226. L.LexFromRawLexer(Tok);
  227. NextToken:
  228. if ((Tok.isAtStartOfLine() || Tok.is(tok::eof)) &&
  229. ParsingPreprocessorDirective) {
  230. // Insert an eod token into the token cache. It has the same
  231. // position as the next token that is not on the same line as the
  232. // preprocessor directive. Observe that we continue processing
  233. // 'Tok' when we exit this branch.
  234. Token Tmp = Tok;
  235. Tmp.setKind(tok::eod);
  236. Tmp.clearFlag(Token::StartOfLine);
  237. Tmp.setIdentifierInfo(0);
  238. EmitToken(Tmp);
  239. ParsingPreprocessorDirective = false;
  240. }
  241. if (Tok.is(tok::raw_identifier)) {
  242. PP.LookUpIdentifierInfo(Tok);
  243. EmitToken(Tok);
  244. continue;
  245. }
  246. if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
  247. // Special processing for #include. Store the '#' token and lex
  248. // the next token.
  249. assert(!ParsingPreprocessorDirective);
  250. Offset HashOff = (Offset) Out.tell();
  251. // Get the next token.
  252. Token NextTok;
  253. L.LexFromRawLexer(NextTok);
  254. // If we see the start of line, then we had a null directive "#". In
  255. // this case, discard both tokens.
  256. if (NextTok.isAtStartOfLine())
  257. goto NextToken;
  258. // The token is the start of a directive. Emit it.
  259. EmitToken(Tok);
  260. Tok = NextTok;
  261. // Did we see 'include'/'import'/'include_next'?
  262. if (Tok.isNot(tok::raw_identifier)) {
  263. EmitToken(Tok);
  264. continue;
  265. }
  266. IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok);
  267. tok::PPKeywordKind K = II->getPPKeywordID();
  268. ParsingPreprocessorDirective = true;
  269. switch (K) {
  270. case tok::pp_not_keyword:
  271. // Invalid directives "#foo" can occur in #if 0 blocks etc, just pass
  272. // them through.
  273. default:
  274. break;
  275. case tok::pp_include:
  276. case tok::pp_import:
  277. case tok::pp_include_next: {
  278. // Save the 'include' token.
  279. EmitToken(Tok);
  280. // Lex the next token as an include string.
  281. L.setParsingPreprocessorDirective(true);
  282. L.LexIncludeFilename(Tok);
  283. L.setParsingPreprocessorDirective(false);
  284. assert(!Tok.isAtStartOfLine());
  285. if (Tok.is(tok::raw_identifier))
  286. PP.LookUpIdentifierInfo(Tok);
  287. break;
  288. }
  289. case tok::pp_if:
  290. case tok::pp_ifdef:
  291. case tok::pp_ifndef: {
  292. // Add an entry for '#if' and friends. We initially set the target
  293. // index to 0. This will get backpatched when we hit #endif.
  294. PPStartCond.push_back(PPCond.size());
  295. PPCond.push_back(std::make_pair(HashOff, 0U));
  296. break;
  297. }
  298. case tok::pp_endif: {
  299. // Add an entry for '#endif'. We set the target table index to itself.
  300. // This will later be set to zero when emitting to the PTH file. We
  301. // use 0 for uninitialized indices because that is easier to debug.
  302. unsigned index = PPCond.size();
  303. // Backpatch the opening '#if' entry.
  304. assert(!PPStartCond.empty());
  305. assert(PPCond.size() > PPStartCond.back());
  306. assert(PPCond[PPStartCond.back()].second == 0);
  307. PPCond[PPStartCond.back()].second = index;
  308. PPStartCond.pop_back();
  309. // Add the new entry to PPCond.
  310. PPCond.push_back(std::make_pair(HashOff, index));
  311. EmitToken(Tok);
  312. // Some files have gibberish on the same line as '#endif'.
  313. // Discard these tokens.
  314. do
  315. L.LexFromRawLexer(Tok);
  316. while (Tok.isNot(tok::eof) && !Tok.isAtStartOfLine());
  317. // We have the next token in hand.
  318. // Don't immediately lex the next one.
  319. goto NextToken;
  320. }
  321. case tok::pp_elif:
  322. case tok::pp_else: {
  323. // Add an entry for #elif or #else.
  324. // This serves as both a closing and opening of a conditional block.
  325. // This means that its entry will get backpatched later.
  326. unsigned index = PPCond.size();
  327. // Backpatch the previous '#if' entry.
  328. assert(!PPStartCond.empty());
  329. assert(PPCond.size() > PPStartCond.back());
  330. assert(PPCond[PPStartCond.back()].second == 0);
  331. PPCond[PPStartCond.back()].second = index;
  332. PPStartCond.pop_back();
  333. // Now add '#elif' as a new block opening.
  334. PPCond.push_back(std::make_pair(HashOff, 0U));
  335. PPStartCond.push_back(index);
  336. break;
  337. }
  338. }
  339. }
  340. EmitToken(Tok);
  341. }
  342. while (Tok.isNot(tok::eof));
  343. assert(PPStartCond.empty() && "Error: imblanced preprocessor conditionals.");
  344. // Next write out PPCond.
  345. Offset PPCondOff = (Offset) Out.tell();
  346. // Write out the size of PPCond so that clients can identifer empty tables.
  347. Emit32(PPCond.size());
  348. for (unsigned i = 0, e = PPCond.size(); i!=e; ++i) {
  349. Emit32(PPCond[i].first - TokenOff);
  350. uint32_t x = PPCond[i].second;
  351. assert(x != 0 && "PPCond entry not backpatched.");
  352. // Emit zero for #endifs. This allows us to do checking when
  353. // we read the PTH file back in.
  354. Emit32(x == i ? 0 : x);
  355. }
  356. return PTHEntry(TokenOff, PPCondOff);
  357. }
  358. Offset PTHWriter::EmitCachedSpellings() {
  359. // Write each cached strings to the PTH file.
  360. Offset SpellingsOff = Out.tell();
  361. for (std::vector<llvm::StringMapEntry<OffsetOpt>*>::iterator
  362. I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I)
  363. EmitBuf((*I)->getKeyData(), (*I)->getKeyLength()+1 /*nul included*/);
  364. return SpellingsOff;
  365. }
  366. void PTHWriter::GeneratePTH(const std::string &MainFile) {
  367. // Generate the prologue.
  368. Out << "cfe-pth" << '\0';
  369. Emit32(PTHManager::Version);
  370. // Leave 4 words for the prologue.
  371. Offset PrologueOffset = Out.tell();
  372. for (unsigned i = 0; i < 4; ++i)
  373. Emit32(0);
  374. // Write the name of the MainFile.
  375. if (!MainFile.empty()) {
  376. EmitString(MainFile);
  377. } else {
  378. // String with 0 bytes.
  379. Emit16(0);
  380. }
  381. Emit8(0);
  382. // Iterate over all the files in SourceManager. Create a lexer
  383. // for each file and cache the tokens.
  384. SourceManager &SM = PP.getSourceManager();
  385. const LangOptions &LOpts = PP.getLangOpts();
  386. for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
  387. E = SM.fileinfo_end(); I != E; ++I) {
  388. const SrcMgr::ContentCache &C = *I->second;
  389. const FileEntry *FE = C.OrigEntry;
  390. // FIXME: Handle files with non-absolute paths.
  391. if (llvm::sys::path::is_relative(FE->getName()))
  392. continue;
  393. const llvm::MemoryBuffer *B = C.getBuffer(PP.getDiagnostics(), SM);
  394. if (!B) continue;
  395. FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
  396. const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
  397. Lexer L(FID, FromFile, SM, LOpts);
  398. PM.insert(FE, LexTokens(L));
  399. }
  400. // Write out the identifier table.
  401. const std::pair<Offset,Offset> &IdTableOff = EmitIdentifierTable();
  402. // Write out the cached strings table.
  403. Offset SpellingOff = EmitCachedSpellings();
  404. // Write out the file table.
  405. Offset FileTableOff = EmitFileTable();
  406. // Finally, write the prologue.
  407. Out.seek(PrologueOffset);
  408. Emit32(IdTableOff.first);
  409. Emit32(IdTableOff.second);
  410. Emit32(FileTableOff);
  411. Emit32(SpellingOff);
  412. }
  413. namespace {
  414. /// StatListener - A simple "interpose" object used to monitor stat calls
  415. /// invoked by FileManager while processing the original sources used
  416. /// as input to PTH generation. StatListener populates the PTHWriter's
  417. /// file map with stat information for directories as well as negative stats.
  418. /// Stat information for files are populated elsewhere.
  419. class StatListener : public FileSystemStatCache {
  420. PTHMap &PM;
  421. public:
  422. StatListener(PTHMap &pm) : PM(pm) {}
  423. ~StatListener() {}
  424. LookupResult getStat(const char *Path, FileData &Data, bool isFile,
  425. vfs::File **F, vfs::FileSystem &FS) override {
  426. LookupResult Result = statChained(Path, Data, isFile, F, FS);
  427. if (Result == CacheMissing) // Failed 'stat'.
  428. PM.insert(PTHEntryKeyVariant(Path), PTHEntry());
  429. else if (Data.IsDirectory) {
  430. // Only cache directories with absolute paths.
  431. if (llvm::sys::path::is_relative(Path))
  432. return Result;
  433. PM.insert(PTHEntryKeyVariant(&Data, Path), PTHEntry());
  434. }
  435. return Result;
  436. }
  437. };
  438. } // end anonymous namespace
  439. void clang::CacheTokens(Preprocessor &PP, llvm::raw_fd_ostream* OS) {
  440. // Get the name of the main file.
  441. const SourceManager &SrcMgr = PP.getSourceManager();
  442. const FileEntry *MainFile = SrcMgr.getFileEntryForID(SrcMgr.getMainFileID());
  443. SmallString<128> MainFilePath(MainFile->getName());
  444. llvm::sys::fs::make_absolute(MainFilePath);
  445. // Create the PTHWriter.
  446. PTHWriter PW(*OS, PP);
  447. // Install the 'stat' system call listener in the FileManager.
  448. StatListener *StatCache = new StatListener(PW.getPM());
  449. PP.getFileManager().addStatCache(StatCache, /*AtBeginning=*/true);
  450. // Lex through the entire file. This will populate SourceManager with
  451. // all of the header information.
  452. Token Tok;
  453. PP.EnterMainSourceFile();
  454. do { PP.Lex(Tok); } while (Tok.isNot(tok::eof));
  455. // Generate the PTH file.
  456. PP.getFileManager().removeStatCache(StatCache);
  457. PW.GeneratePTH(MainFilePath.str());
  458. }
  459. //===----------------------------------------------------------------------===//
  460. namespace {
  461. class PTHIdKey {
  462. public:
  463. const IdentifierInfo* II;
  464. uint32_t FileOffset;
  465. };
  466. class PTHIdentifierTableTrait {
  467. public:
  468. typedef PTHIdKey* key_type;
  469. typedef key_type key_type_ref;
  470. typedef uint32_t data_type;
  471. typedef data_type data_type_ref;
  472. static unsigned ComputeHash(PTHIdKey* key) {
  473. return llvm::HashString(key->II->getName());
  474. }
  475. static std::pair<unsigned,unsigned>
  476. EmitKeyDataLength(raw_ostream& Out, const PTHIdKey* key, uint32_t) {
  477. unsigned n = key->II->getLength() + 1;
  478. ::Emit16(Out, n);
  479. return std::make_pair(n, sizeof(uint32_t));
  480. }
  481. static void EmitKey(raw_ostream& Out, PTHIdKey* key, unsigned n) {
  482. // Record the location of the key data. This is used when generating
  483. // the mapping from persistent IDs to strings.
  484. key->FileOffset = Out.tell();
  485. Out.write(key->II->getNameStart(), n);
  486. }
  487. static void EmitData(raw_ostream& Out, PTHIdKey*, uint32_t pID,
  488. unsigned) {
  489. ::Emit32(Out, pID);
  490. }
  491. };
  492. } // end anonymous namespace
  493. /// EmitIdentifierTable - Emits two tables to the PTH file. The first is
  494. /// a hashtable mapping from identifier strings to persistent IDs. The second
  495. /// is a straight table mapping from persistent IDs to string data (the
  496. /// keys of the first table).
  497. ///
  498. std::pair<Offset,Offset> PTHWriter::EmitIdentifierTable() {
  499. // Build two maps:
  500. // (1) an inverse map from persistent IDs -> (IdentifierInfo*,Offset)
  501. // (2) a map from (IdentifierInfo*, Offset)* -> persistent IDs
  502. // Note that we use 'calloc', so all the bytes are 0.
  503. PTHIdKey *IIDMap = (PTHIdKey*)calloc(idcount, sizeof(PTHIdKey));
  504. // Create the hashtable.
  505. OnDiskChainedHashTableGenerator<PTHIdentifierTableTrait> IIOffMap;
  506. // Generate mapping from persistent IDs -> IdentifierInfo*.
  507. for (IDMap::iterator I = IM.begin(), E = IM.end(); I != E; ++I) {
  508. // Decrement by 1 because we are using a vector for the lookup and
  509. // 0 is reserved for NULL.
  510. assert(I->second > 0);
  511. assert(I->second-1 < idcount);
  512. unsigned idx = I->second-1;
  513. // Store the mapping from persistent ID to IdentifierInfo*
  514. IIDMap[idx].II = I->first;
  515. // Store the reverse mapping in a hashtable.
  516. IIOffMap.insert(&IIDMap[idx], I->second);
  517. }
  518. // Write out the inverse map first. This causes the PCIDKey entries to
  519. // record PTH file offsets for the string data. This is used to write
  520. // the second table.
  521. Offset StringTableOffset = IIOffMap.Emit(Out);
  522. // Now emit the table mapping from persistent IDs to PTH file offsets.
  523. Offset IDOff = Out.tell();
  524. Emit32(idcount); // Emit the number of identifiers.
  525. for (unsigned i = 0 ; i < idcount; ++i)
  526. Emit32(IIDMap[i].FileOffset);
  527. // Finally, release the inverse map.
  528. free(IIDMap);
  529. return std::make_pair(IDOff, StringTableOffset);
  530. }