PTHLexer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. //===--- PTHLexer.cpp - Lex from a token stream ---------------------------===//
  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 PTHLexer interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/PTHLexer.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/FileSystemStatCache.h"
  16. #include "clang/Basic/IdentifierTable.h"
  17. #include "clang/Basic/OnDiskHashTable.h"
  18. #include "clang/Basic/TokenKinds.h"
  19. #include "clang/Lex/LexDiagnostic.h"
  20. #include "clang/Lex/PTHManager.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "clang/Lex/Token.h"
  23. #include "llvm/ADT/StringExtras.h"
  24. #include "llvm/ADT/StringMap.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/Support/system_error.h"
  27. #include <memory>
  28. using namespace clang;
  29. using namespace clang::io;
  30. #define DISK_TOKEN_SIZE (1+1+2+4+4)
  31. //===----------------------------------------------------------------------===//
  32. // PTHLexer methods.
  33. //===----------------------------------------------------------------------===//
  34. PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
  35. const unsigned char *ppcond, PTHManager &PM)
  36. : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
  37. PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) {
  38. FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
  39. }
  40. bool PTHLexer::Lex(Token& Tok) {
  41. //===--------------------------------------==//
  42. // Read the raw token data.
  43. //===--------------------------------------==//
  44. using namespace llvm::support;
  45. // Shadow CurPtr into an automatic variable.
  46. const unsigned char *CurPtrShadow = CurPtr;
  47. // Read in the data for the token.
  48. unsigned Word0 = endian::readNext<uint32_t, little, aligned>(CurPtrShadow);
  49. uint32_t IdentifierID =
  50. endian::readNext<uint32_t, little, aligned>(CurPtrShadow);
  51. uint32_t FileOffset =
  52. endian::readNext<uint32_t, little, aligned>(CurPtrShadow);
  53. tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF);
  54. Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF);
  55. uint32_t Len = Word0 >> 16;
  56. CurPtr = CurPtrShadow;
  57. //===--------------------------------------==//
  58. // Construct the token itself.
  59. //===--------------------------------------==//
  60. Tok.startToken();
  61. Tok.setKind(TKind);
  62. Tok.setFlag(TFlags);
  63. assert(!LexingRawMode);
  64. Tok.setLocation(FileStartLoc.getLocWithOffset(FileOffset));
  65. Tok.setLength(Len);
  66. // Handle identifiers.
  67. if (Tok.isLiteral()) {
  68. Tok.setLiteralData((const char*) (PTHMgr.SpellingBase + IdentifierID));
  69. }
  70. else if (IdentifierID) {
  71. MIOpt.ReadToken();
  72. IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1);
  73. Tok.setIdentifierInfo(II);
  74. // Change the kind of this identifier to the appropriate token kind, e.g.
  75. // turning "for" into a keyword.
  76. Tok.setKind(II->getTokenID());
  77. if (II->isHandleIdentifierCase())
  78. return PP->HandleIdentifier(Tok);
  79. return true;
  80. }
  81. //===--------------------------------------==//
  82. // Process the token.
  83. //===--------------------------------------==//
  84. if (TKind == tok::eof) {
  85. // Save the end-of-file token.
  86. EofToken = Tok;
  87. assert(!ParsingPreprocessorDirective);
  88. assert(!LexingRawMode);
  89. return LexEndOfFile(Tok);
  90. }
  91. if (TKind == tok::hash && Tok.isAtStartOfLine()) {
  92. LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
  93. assert(!LexingRawMode);
  94. PP->HandleDirective(Tok);
  95. return false;
  96. }
  97. if (TKind == tok::eod) {
  98. assert(ParsingPreprocessorDirective);
  99. ParsingPreprocessorDirective = false;
  100. return true;
  101. }
  102. MIOpt.ReadToken();
  103. return true;
  104. }
  105. bool PTHLexer::LexEndOfFile(Token &Result) {
  106. // If we hit the end of the file while parsing a preprocessor directive,
  107. // end the preprocessor directive first. The next token returned will
  108. // then be the end of file.
  109. if (ParsingPreprocessorDirective) {
  110. ParsingPreprocessorDirective = false; // Done parsing the "line".
  111. return true; // Have a token.
  112. }
  113. assert(!LexingRawMode);
  114. // If we are in a #if directive, emit an error.
  115. while (!ConditionalStack.empty()) {
  116. if (PP->getCodeCompletionFileLoc() != FileStartLoc)
  117. PP->Diag(ConditionalStack.back().IfLoc,
  118. diag::err_pp_unterminated_conditional);
  119. ConditionalStack.pop_back();
  120. }
  121. // Finally, let the preprocessor handle this.
  122. return PP->HandleEndOfFile(Result);
  123. }
  124. // FIXME: We can just grab the last token instead of storing a copy
  125. // into EofToken.
  126. void PTHLexer::getEOF(Token& Tok) {
  127. assert(EofToken.is(tok::eof));
  128. Tok = EofToken;
  129. }
  130. void PTHLexer::DiscardToEndOfLine() {
  131. assert(ParsingPreprocessorDirective && ParsingFilename == false &&
  132. "Must be in a preprocessing directive!");
  133. // We assume that if the preprocessor wishes to discard to the end of
  134. // the line that it also means to end the current preprocessor directive.
  135. ParsingPreprocessorDirective = false;
  136. // Skip tokens by only peeking at their token kind and the flags.
  137. // We don't need to actually reconstruct full tokens from the token buffer.
  138. // This saves some copies and it also reduces IdentifierInfo* lookup.
  139. const unsigned char* p = CurPtr;
  140. while (1) {
  141. // Read the token kind. Are we at the end of the file?
  142. tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
  143. if (x == tok::eof) break;
  144. // Read the token flags. Are we at the start of the next line?
  145. Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
  146. if (y & Token::StartOfLine) break;
  147. // Skip to the next token.
  148. p += DISK_TOKEN_SIZE;
  149. }
  150. CurPtr = p;
  151. }
  152. /// SkipBlock - Used by Preprocessor to skip the current conditional block.
  153. bool PTHLexer::SkipBlock() {
  154. using namespace llvm::support;
  155. assert(CurPPCondPtr && "No cached PP conditional information.");
  156. assert(LastHashTokPtr && "No known '#' token.");
  157. const unsigned char* HashEntryI = 0;
  158. uint32_t TableIdx;
  159. do {
  160. // Read the token offset from the side-table.
  161. uint32_t Offset = endian::readNext<uint32_t, little, aligned>(CurPPCondPtr);
  162. // Read the target table index from the side-table.
  163. TableIdx = endian::readNext<uint32_t, little, aligned>(CurPPCondPtr);
  164. // Compute the actual memory address of the '#' token data for this entry.
  165. HashEntryI = TokBuf + Offset;
  166. // Optmization: "Sibling jumping". #if...#else...#endif blocks can
  167. // contain nested blocks. In the side-table we can jump over these
  168. // nested blocks instead of doing a linear search if the next "sibling"
  169. // entry is not at a location greater than LastHashTokPtr.
  170. if (HashEntryI < LastHashTokPtr && TableIdx) {
  171. // In the side-table we are still at an entry for a '#' token that
  172. // is earlier than the last one we saw. Check if the location we would
  173. // stride gets us closer.
  174. const unsigned char* NextPPCondPtr =
  175. PPCond + TableIdx*(sizeof(uint32_t)*2);
  176. assert(NextPPCondPtr >= CurPPCondPtr);
  177. // Read where we should jump to.
  178. const unsigned char *HashEntryJ =
  179. TokBuf + endian::readNext<uint32_t, little, aligned>(NextPPCondPtr);
  180. if (HashEntryJ <= LastHashTokPtr) {
  181. // Jump directly to the next entry in the side table.
  182. HashEntryI = HashEntryJ;
  183. TableIdx = endian::readNext<uint32_t, little, aligned>(NextPPCondPtr);
  184. CurPPCondPtr = NextPPCondPtr;
  185. }
  186. }
  187. }
  188. while (HashEntryI < LastHashTokPtr);
  189. assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
  190. assert(TableIdx && "No jumping from #endifs.");
  191. // Update our side-table iterator.
  192. const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
  193. assert(NextPPCondPtr >= CurPPCondPtr);
  194. CurPPCondPtr = NextPPCondPtr;
  195. // Read where we should jump to.
  196. HashEntryI =
  197. TokBuf + endian::readNext<uint32_t, little, aligned>(NextPPCondPtr);
  198. uint32_t NextIdx = endian::readNext<uint32_t, little, aligned>(NextPPCondPtr);
  199. // By construction NextIdx will be zero if this is a #endif. This is useful
  200. // to know to obviate lexing another token.
  201. bool isEndif = NextIdx == 0;
  202. // This case can occur when we see something like this:
  203. //
  204. // #if ...
  205. // /* a comment or nothing */
  206. // #elif
  207. //
  208. // If we are skipping the first #if block it will be the case that CurPtr
  209. // already points 'elif'. Just return.
  210. if (CurPtr > HashEntryI) {
  211. assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
  212. // Did we reach a #endif? If so, go ahead and consume that token as well.
  213. if (isEndif)
  214. CurPtr += DISK_TOKEN_SIZE*2;
  215. else
  216. LastHashTokPtr = HashEntryI;
  217. return isEndif;
  218. }
  219. // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
  220. CurPtr = HashEntryI;
  221. // Update the location of the last observed '#'. This is useful if we
  222. // are skipping multiple blocks.
  223. LastHashTokPtr = CurPtr;
  224. // Skip the '#' token.
  225. assert(((tok::TokenKind)*CurPtr) == tok::hash);
  226. CurPtr += DISK_TOKEN_SIZE;
  227. // Did we reach a #endif? If so, go ahead and consume that token as well.
  228. if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
  229. return isEndif;
  230. }
  231. SourceLocation PTHLexer::getSourceLocation() {
  232. // getSourceLocation is not on the hot path. It is used to get the location
  233. // of the next token when transitioning back to this lexer when done
  234. // handling a #included file. Just read the necessary data from the token
  235. // data buffer to construct the SourceLocation object.
  236. // NOTE: This is a virtual function; hence it is defined out-of-line.
  237. using namespace llvm::support;
  238. const unsigned char *OffsetPtr = CurPtr + (DISK_TOKEN_SIZE - 4);
  239. uint32_t Offset = endian::readNext<uint32_t, little, aligned>(OffsetPtr);
  240. return FileStartLoc.getLocWithOffset(Offset);
  241. }
  242. //===----------------------------------------------------------------------===//
  243. // PTH file lookup: map from strings to file data.
  244. //===----------------------------------------------------------------------===//
  245. /// PTHFileLookup - This internal data structure is used by the PTHManager
  246. /// to map from FileEntry objects managed by FileManager to offsets within
  247. /// the PTH file.
  248. namespace {
  249. class PTHFileData {
  250. const uint32_t TokenOff;
  251. const uint32_t PPCondOff;
  252. public:
  253. PTHFileData(uint32_t tokenOff, uint32_t ppCondOff)
  254. : TokenOff(tokenOff), PPCondOff(ppCondOff) {}
  255. uint32_t getTokenOffset() const { return TokenOff; }
  256. uint32_t getPPCondOffset() const { return PPCondOff; }
  257. };
  258. class PTHFileLookupCommonTrait {
  259. public:
  260. typedef std::pair<unsigned char, const char*> internal_key_type;
  261. static unsigned ComputeHash(internal_key_type x) {
  262. return llvm::HashString(x.second);
  263. }
  264. static std::pair<unsigned, unsigned>
  265. ReadKeyDataLength(const unsigned char*& d) {
  266. using namespace llvm::support;
  267. unsigned keyLen =
  268. (unsigned)endian::readNext<uint16_t, little, unaligned>(d);
  269. unsigned dataLen = (unsigned) *(d++);
  270. return std::make_pair(keyLen, dataLen);
  271. }
  272. static internal_key_type ReadKey(const unsigned char* d, unsigned) {
  273. unsigned char k = *(d++); // Read the entry kind.
  274. return std::make_pair(k, (const char*) d);
  275. }
  276. };
  277. class PTHFileLookupTrait : public PTHFileLookupCommonTrait {
  278. public:
  279. typedef const FileEntry* external_key_type;
  280. typedef PTHFileData data_type;
  281. static internal_key_type GetInternalKey(const FileEntry* FE) {
  282. return std::make_pair((unsigned char) 0x1, FE->getName());
  283. }
  284. static bool EqualKey(internal_key_type a, internal_key_type b) {
  285. return a.first == b.first && strcmp(a.second, b.second) == 0;
  286. }
  287. static PTHFileData ReadData(const internal_key_type& k,
  288. const unsigned char* d, unsigned) {
  289. assert(k.first == 0x1 && "Only file lookups can match!");
  290. using namespace llvm::support;
  291. uint32_t x = endian::readNext<uint32_t, little, unaligned>(d);
  292. uint32_t y = endian::readNext<uint32_t, little, unaligned>(d);
  293. return PTHFileData(x, y);
  294. }
  295. };
  296. class PTHStringLookupTrait {
  297. public:
  298. typedef uint32_t
  299. data_type;
  300. typedef const std::pair<const char*, unsigned>
  301. external_key_type;
  302. typedef external_key_type internal_key_type;
  303. static bool EqualKey(const internal_key_type& a,
  304. const internal_key_type& b) {
  305. return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
  306. : false;
  307. }
  308. static unsigned ComputeHash(const internal_key_type& a) {
  309. return llvm::HashString(StringRef(a.first, a.second));
  310. }
  311. // This hopefully will just get inlined and removed by the optimizer.
  312. static const internal_key_type&
  313. GetInternalKey(const external_key_type& x) { return x; }
  314. static std::pair<unsigned, unsigned>
  315. ReadKeyDataLength(const unsigned char*& d) {
  316. using namespace llvm::support;
  317. return std::make_pair(
  318. (unsigned)endian::readNext<uint16_t, little, unaligned>(d),
  319. sizeof(uint32_t));
  320. }
  321. static std::pair<const char*, unsigned>
  322. ReadKey(const unsigned char* d, unsigned n) {
  323. assert(n >= 2 && d[n-1] == '\0');
  324. return std::make_pair((const char*) d, n-1);
  325. }
  326. static uint32_t ReadData(const internal_key_type& k, const unsigned char* d,
  327. unsigned) {
  328. using namespace llvm::support;
  329. return endian::readNext<uint32_t, little, unaligned>(d);
  330. }
  331. };
  332. } // end anonymous namespace
  333. typedef OnDiskChainedHashTable<PTHFileLookupTrait> PTHFileLookup;
  334. typedef OnDiskChainedHashTable<PTHStringLookupTrait> PTHStringIdLookup;
  335. //===----------------------------------------------------------------------===//
  336. // PTHManager methods.
  337. //===----------------------------------------------------------------------===//
  338. PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
  339. const unsigned char* idDataTable,
  340. IdentifierInfo** perIDCache,
  341. void* stringIdLookup, unsigned numIds,
  342. const unsigned char* spellingBase,
  343. const char* originalSourceFile)
  344. : Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
  345. IdDataTable(idDataTable), StringIdLookup(stringIdLookup),
  346. NumIds(numIds), PP(0), SpellingBase(spellingBase),
  347. OriginalSourceFile(originalSourceFile) {}
  348. PTHManager::~PTHManager() {
  349. delete Buf;
  350. delete (PTHFileLookup*) FileLookup;
  351. delete (PTHStringIdLookup*) StringIdLookup;
  352. free(PerIDCache);
  353. }
  354. static void InvalidPTH(DiagnosticsEngine &Diags, const char *Msg) {
  355. Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0")) << Msg;
  356. }
  357. PTHManager *PTHManager::Create(const std::string &file,
  358. DiagnosticsEngine &Diags) {
  359. // Memory map the PTH file.
  360. std::unique_ptr<llvm::MemoryBuffer> File;
  361. if (llvm::MemoryBuffer::getFile(file, File)) {
  362. // FIXME: Add ec.message() to this diag.
  363. Diags.Report(diag::err_invalid_pth_file) << file;
  364. return 0;
  365. }
  366. using namespace llvm::support;
  367. // Get the buffer ranges and check if there are at least three 32-bit
  368. // words at the end of the file.
  369. const unsigned char *BufBeg = (const unsigned char*)File->getBufferStart();
  370. const unsigned char *BufEnd = (const unsigned char*)File->getBufferEnd();
  371. // Check the prologue of the file.
  372. if ((BufEnd - BufBeg) < (signed)(sizeof("cfe-pth") + 4 + 4) ||
  373. memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth")) != 0) {
  374. Diags.Report(diag::err_invalid_pth_file) << file;
  375. return 0;
  376. }
  377. // Read the PTH version.
  378. const unsigned char *p = BufBeg + (sizeof("cfe-pth"));
  379. unsigned Version = endian::readNext<uint32_t, little, aligned>(p);
  380. if (Version < PTHManager::Version) {
  381. InvalidPTH(Diags,
  382. Version < PTHManager::Version
  383. ? "PTH file uses an older PTH format that is no longer supported"
  384. : "PTH file uses a newer PTH format that cannot be read");
  385. return 0;
  386. }
  387. // Compute the address of the index table at the end of the PTH file.
  388. const unsigned char *PrologueOffset = p;
  389. if (PrologueOffset >= BufEnd) {
  390. Diags.Report(diag::err_invalid_pth_file) << file;
  391. return 0;
  392. }
  393. // Construct the file lookup table. This will be used for mapping from
  394. // FileEntry*'s to cached tokens.
  395. const unsigned char* FileTableOffset = PrologueOffset + sizeof(uint32_t)*2;
  396. const unsigned char *FileTable =
  397. BufBeg + endian::readNext<uint32_t, little, aligned>(FileTableOffset);
  398. if (!(FileTable > BufBeg && FileTable < BufEnd)) {
  399. Diags.Report(diag::err_invalid_pth_file) << file;
  400. return 0; // FIXME: Proper error diagnostic?
  401. }
  402. std::unique_ptr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg));
  403. // Warn if the PTH file is empty. We still want to create a PTHManager
  404. // as the PTH could be used with -include-pth.
  405. if (FL->isEmpty())
  406. InvalidPTH(Diags, "PTH file contains no cached source data");
  407. // Get the location of the table mapping from persistent ids to the
  408. // data needed to reconstruct identifiers.
  409. const unsigned char* IDTableOffset = PrologueOffset + sizeof(uint32_t)*0;
  410. const unsigned char *IData =
  411. BufBeg + endian::readNext<uint32_t, little, aligned>(IDTableOffset);
  412. if (!(IData >= BufBeg && IData < BufEnd)) {
  413. Diags.Report(diag::err_invalid_pth_file) << file;
  414. return 0;
  415. }
  416. // Get the location of the hashtable mapping between strings and
  417. // persistent IDs.
  418. const unsigned char* StringIdTableOffset = PrologueOffset + sizeof(uint32_t)*1;
  419. const unsigned char *StringIdTable =
  420. BufBeg + endian::readNext<uint32_t, little, aligned>(StringIdTableOffset);
  421. if (!(StringIdTable >= BufBeg && StringIdTable < BufEnd)) {
  422. Diags.Report(diag::err_invalid_pth_file) << file;
  423. return 0;
  424. }
  425. std::unique_ptr<PTHStringIdLookup> SL(
  426. PTHStringIdLookup::Create(StringIdTable, BufBeg));
  427. // Get the location of the spelling cache.
  428. const unsigned char* spellingBaseOffset = PrologueOffset + sizeof(uint32_t)*3;
  429. const unsigned char *spellingBase =
  430. BufBeg + endian::readNext<uint32_t, little, aligned>(spellingBaseOffset);
  431. if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) {
  432. Diags.Report(diag::err_invalid_pth_file) << file;
  433. return 0;
  434. }
  435. // Get the number of IdentifierInfos and pre-allocate the identifier cache.
  436. uint32_t NumIds = endian::readNext<uint32_t, little, aligned>(IData);
  437. // Pre-allocate the persistent ID -> IdentifierInfo* cache. We use calloc()
  438. // so that we in the best case only zero out memory once when the OS returns
  439. // us new pages.
  440. IdentifierInfo** PerIDCache = 0;
  441. if (NumIds) {
  442. PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache));
  443. if (!PerIDCache) {
  444. InvalidPTH(Diags, "Could not allocate memory for processing PTH file");
  445. return 0;
  446. }
  447. }
  448. // Compute the address of the original source file.
  449. const unsigned char* originalSourceBase = PrologueOffset + sizeof(uint32_t)*4;
  450. unsigned len =
  451. endian::readNext<uint16_t, little, unaligned>(originalSourceBase);
  452. if (!len) originalSourceBase = 0;
  453. // Create the new PTHManager.
  454. return new PTHManager(File.release(), FL.release(), IData, PerIDCache,
  455. SL.release(), NumIds, spellingBase,
  456. (const char *)originalSourceBase);
  457. }
  458. IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
  459. using namespace llvm::support;
  460. // Look in the PTH file for the string data for the IdentifierInfo object.
  461. const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID;
  462. const unsigned char *IDData =
  463. (const unsigned char *)Buf->getBufferStart() +
  464. endian::readNext<uint32_t, little, aligned>(TableEntry);
  465. assert(IDData < (const unsigned char*)Buf->getBufferEnd());
  466. // Allocate the object.
  467. std::pair<IdentifierInfo,const unsigned char*> *Mem =
  468. Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >();
  469. Mem->second = IDData;
  470. assert(IDData[0] != '\0');
  471. IdentifierInfo *II = new ((void*) Mem) IdentifierInfo();
  472. // Store the new IdentifierInfo in the cache.
  473. PerIDCache[PersistentID] = II;
  474. assert(II->getNameStart() && II->getNameStart()[0] != '\0');
  475. return II;
  476. }
  477. IdentifierInfo* PTHManager::get(StringRef Name) {
  478. PTHStringIdLookup& SL = *((PTHStringIdLookup*)StringIdLookup);
  479. // Double check our assumption that the last character isn't '\0'.
  480. assert(Name.empty() || Name.back() != '\0');
  481. PTHStringIdLookup::iterator I = SL.find(std::make_pair(Name.data(),
  482. Name.size()));
  483. if (I == SL.end()) // No identifier found?
  484. return 0;
  485. // Match found. Return the identifier!
  486. assert(*I > 0);
  487. return GetIdentifierInfo(*I-1);
  488. }
  489. PTHLexer *PTHManager::CreateLexer(FileID FID) {
  490. const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID);
  491. if (!FE)
  492. return 0;
  493. using namespace llvm::support;
  494. // Lookup the FileEntry object in our file lookup data structure. It will
  495. // return a variant that indicates whether or not there is an offset within
  496. // the PTH file that contains cached tokens.
  497. PTHFileLookup& PFL = *((PTHFileLookup*)FileLookup);
  498. PTHFileLookup::iterator I = PFL.find(FE);
  499. if (I == PFL.end()) // No tokens available?
  500. return 0;
  501. const PTHFileData& FileData = *I;
  502. const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
  503. // Compute the offset of the token data within the buffer.
  504. const unsigned char* data = BufStart + FileData.getTokenOffset();
  505. // Get the location of pp-conditional table.
  506. const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
  507. uint32_t Len = endian::readNext<uint32_t, little, aligned>(ppcond);
  508. if (Len == 0) ppcond = 0;
  509. assert(PP && "No preprocessor set yet!");
  510. return new PTHLexer(*PP, FID, data, ppcond, *this);
  511. }
  512. //===----------------------------------------------------------------------===//
  513. // 'stat' caching.
  514. //===----------------------------------------------------------------------===//
  515. namespace {
  516. class PTHStatData {
  517. public:
  518. const bool HasData;
  519. uint64_t Size;
  520. time_t ModTime;
  521. llvm::sys::fs::UniqueID UniqueID;
  522. bool IsDirectory;
  523. PTHStatData(uint64_t Size, time_t ModTime, llvm::sys::fs::UniqueID UniqueID,
  524. bool IsDirectory)
  525. : HasData(true), Size(Size), ModTime(ModTime), UniqueID(UniqueID),
  526. IsDirectory(IsDirectory) {}
  527. PTHStatData() : HasData(false) {}
  528. };
  529. class PTHStatLookupTrait : public PTHFileLookupCommonTrait {
  530. public:
  531. typedef const char* external_key_type; // const char*
  532. typedef PTHStatData data_type;
  533. static internal_key_type GetInternalKey(const char *path) {
  534. // The key 'kind' doesn't matter here because it is ignored in EqualKey.
  535. return std::make_pair((unsigned char) 0x0, path);
  536. }
  537. static bool EqualKey(internal_key_type a, internal_key_type b) {
  538. // When doing 'stat' lookups we don't care about the kind of 'a' and 'b',
  539. // just the paths.
  540. return strcmp(a.second, b.second) == 0;
  541. }
  542. static data_type ReadData(const internal_key_type& k, const unsigned char* d,
  543. unsigned) {
  544. if (k.first /* File or Directory */) {
  545. bool IsDirectory = true;
  546. if (k.first == 0x1 /* File */) {
  547. IsDirectory = false;
  548. d += 4 * 2; // Skip the first 2 words.
  549. }
  550. using namespace llvm::support;
  551. uint64_t File = endian::readNext<uint64_t, little, unaligned>(d);
  552. uint64_t Device = endian::readNext<uint64_t, little, unaligned>(d);
  553. llvm::sys::fs::UniqueID UniqueID(File, Device);
  554. time_t ModTime = endian::readNext<uint64_t, little, unaligned>(d);
  555. uint64_t Size = endian::readNext<uint64_t, little, unaligned>(d);
  556. return data_type(Size, ModTime, UniqueID, IsDirectory);
  557. }
  558. // Negative stat. Don't read anything.
  559. return data_type();
  560. }
  561. };
  562. class PTHStatCache : public FileSystemStatCache {
  563. typedef OnDiskChainedHashTable<PTHStatLookupTrait> CacheTy;
  564. CacheTy Cache;
  565. public:
  566. PTHStatCache(PTHFileLookup &FL) :
  567. Cache(FL.getNumBuckets(), FL.getNumEntries(), FL.getBuckets(),
  568. FL.getBase()) {}
  569. ~PTHStatCache() {}
  570. LookupResult getStat(const char *Path, FileData &Data, bool isFile,
  571. vfs::File **F, vfs::FileSystem &FS) override {
  572. // Do the lookup for the file's data in the PTH file.
  573. CacheTy::iterator I = Cache.find(Path);
  574. // If we don't get a hit in the PTH file just forward to 'stat'.
  575. if (I == Cache.end())
  576. return statChained(Path, Data, isFile, F, FS);
  577. const PTHStatData &D = *I;
  578. if (!D.HasData)
  579. return CacheMissing;
  580. Data.Name = Path;
  581. Data.Size = D.Size;
  582. Data.ModTime = D.ModTime;
  583. Data.UniqueID = D.UniqueID;
  584. Data.IsDirectory = D.IsDirectory;
  585. Data.IsNamedPipe = false;
  586. Data.InPCH = true;
  587. return CacheExists;
  588. }
  589. };
  590. } // end anonymous namespace
  591. FileSystemStatCache *PTHManager::createStatCache() {
  592. return new PTHStatCache(*((PTHFileLookup*) FileLookup));
  593. }