CacheTokens.cpp 20 KB

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