CacheTokens.cpp 21 KB

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