PTHLexer.cpp 25 KB

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