1 //===--- PTHLexer.cpp - Lex from a token stream ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PTHLexer interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/TokenKinds.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/FileSystemStatCache.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/OnDiskHashTable.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/PTHLexer.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Lex/PTHManager.h"
23 #include "clang/Lex/Token.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "llvm/ADT/OwningPtr.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/system_error.h"
30 using namespace clang;
31 using namespace clang::io;
33 #define DISK_TOKEN_SIZE (1+1+2+4+4)
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
40 const unsigned char *ppcond, PTHManager &PM)
41 : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
42 PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) {
44 FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
47 void PTHLexer::Lex(Token& Tok) {
50 //===--------------------------------------==//
51 // Read the raw token data.
52 //===--------------------------------------==//
54 // Shadow CurPtr into an automatic variable.
55 const unsigned char *CurPtrShadow = CurPtr;
57 // Read in the data for the token.
58 unsigned Word0 = ReadLE32(CurPtrShadow);
59 uint32_t IdentifierID = ReadLE32(CurPtrShadow);
60 uint32_t FileOffset = ReadLE32(CurPtrShadow);
62 tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF);
63 Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF);
64 uint32_t Len = Word0 >> 16;
66 CurPtr = CurPtrShadow;
68 //===--------------------------------------==//
69 // Construct the token itself.
70 //===--------------------------------------==//
75 assert(!LexingRawMode);
76 Tok.setLocation(FileStartLoc.getLocWithOffset(FileOffset));
79 // Handle identifiers.
80 if (Tok.isLiteral()) {
81 Tok.setLiteralData((const char*) (PTHMgr.SpellingBase + IdentifierID));
83 else if (IdentifierID) {
85 IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1);
87 Tok.setIdentifierInfo(II);
89 // Change the kind of this identifier to the appropriate token kind, e.g.
90 // turning "for" into a keyword.
91 Tok.setKind(II->getTokenID());
93 if (II->isHandleIdentifierCase())
94 PP->HandleIdentifier(Tok);
98 //===--------------------------------------==//
100 //===--------------------------------------==//
101 if (TKind == tok::eof) {
102 // Save the end-of-file token.
105 // Save 'PP' to 'PPCache' as LexEndOfFile can delete 'this'.
106 Preprocessor *PPCache = PP;
108 assert(!ParsingPreprocessorDirective);
109 assert(!LexingRawMode);
111 if (LexEndOfFile(Tok))
114 return PPCache->Lex(Tok);
117 if (TKind == tok::hash && Tok.isAtStartOfLine()) {
118 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
119 assert(!LexingRawMode);
120 PP->HandleDirective(Tok);
122 if (PP->isCurrentLexer(this))
128 if (TKind == tok::eod) {
129 assert(ParsingPreprocessorDirective);
130 ParsingPreprocessorDirective = false;
137 bool PTHLexer::LexEndOfFile(Token &Result) {
138 // If we hit the end of the file while parsing a preprocessor directive,
139 // end the preprocessor directive first. The next token returned will
140 // then be the end of file.
141 if (ParsingPreprocessorDirective) {
142 ParsingPreprocessorDirective = false; // Done parsing the "line".
143 return true; // Have a token.
146 assert(!LexingRawMode);
148 // If we are in a #if directive, emit an error.
149 while (!ConditionalStack.empty()) {
150 if (PP->getCodeCompletionFileLoc() != FileStartLoc)
151 PP->Diag(ConditionalStack.back().IfLoc,
152 diag::err_pp_unterminated_conditional);
153 ConditionalStack.pop_back();
156 // Finally, let the preprocessor handle this.
157 return PP->HandleEndOfFile(Result);
160 // FIXME: We can just grab the last token instead of storing a copy
162 void PTHLexer::getEOF(Token& Tok) {
163 assert(EofToken.is(tok::eof));
167 void PTHLexer::DiscardToEndOfLine() {
168 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
169 "Must be in a preprocessing directive!");
171 // We assume that if the preprocessor wishes to discard to the end of
172 // the line that it also means to end the current preprocessor directive.
173 ParsingPreprocessorDirective = false;
175 // Skip tokens by only peeking at their token kind and the flags.
176 // We don't need to actually reconstruct full tokens from the token buffer.
177 // This saves some copies and it also reduces IdentifierInfo* lookup.
178 const unsigned char* p = CurPtr;
180 // Read the token kind. Are we at the end of the file?
181 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
182 if (x == tok::eof) break;
184 // Read the token flags. Are we at the start of the next line?
185 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
186 if (y & Token::StartOfLine) break;
188 // Skip to the next token.
189 p += DISK_TOKEN_SIZE;
195 /// SkipBlock - Used by Preprocessor to skip the current conditional block.
196 bool PTHLexer::SkipBlock() {
197 assert(CurPPCondPtr && "No cached PP conditional information.");
198 assert(LastHashTokPtr && "No known '#' token.");
200 const unsigned char* HashEntryI = 0;
204 // Read the token offset from the side-table.
205 uint32_t Offset = ReadLE32(CurPPCondPtr);
207 // Read the target table index from the side-table.
208 TableIdx = ReadLE32(CurPPCondPtr);
210 // Compute the actual memory address of the '#' token data for this entry.
211 HashEntryI = TokBuf + Offset;
213 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
214 // contain nested blocks. In the side-table we can jump over these
215 // nested blocks instead of doing a linear search if the next "sibling"
216 // entry is not at a location greater than LastHashTokPtr.
217 if (HashEntryI < LastHashTokPtr && TableIdx) {
218 // In the side-table we are still at an entry for a '#' token that
219 // is earlier than the last one we saw. Check if the location we would
220 // stride gets us closer.
221 const unsigned char* NextPPCondPtr =
222 PPCond + TableIdx*(sizeof(uint32_t)*2);
223 assert(NextPPCondPtr >= CurPPCondPtr);
224 // Read where we should jump to.
225 const unsigned char* HashEntryJ = TokBuf + ReadLE32(NextPPCondPtr);
227 if (HashEntryJ <= LastHashTokPtr) {
228 // Jump directly to the next entry in the side table.
229 HashEntryI = HashEntryJ;
230 TableIdx = ReadLE32(NextPPCondPtr);
231 CurPPCondPtr = NextPPCondPtr;
235 while (HashEntryI < LastHashTokPtr);
236 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
237 assert(TableIdx && "No jumping from #endifs.");
239 // Update our side-table iterator.
240 const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
241 assert(NextPPCondPtr >= CurPPCondPtr);
242 CurPPCondPtr = NextPPCondPtr;
244 // Read where we should jump to.
245 HashEntryI = TokBuf + ReadLE32(NextPPCondPtr);
246 uint32_t NextIdx = ReadLE32(NextPPCondPtr);
248 // By construction NextIdx will be zero if this is a #endif. This is useful
249 // to know to obviate lexing another token.
250 bool isEndif = NextIdx == 0;
252 // This case can occur when we see something like this:
255 // /* a comment or nothing */
258 // If we are skipping the first #if block it will be the case that CurPtr
259 // already points 'elif'. Just return.
261 if (CurPtr > HashEntryI) {
262 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
263 // Did we reach a #endif? If so, go ahead and consume that token as well.
265 CurPtr += DISK_TOKEN_SIZE*2;
267 LastHashTokPtr = HashEntryI;
272 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
275 // Update the location of the last observed '#'. This is useful if we
276 // are skipping multiple blocks.
277 LastHashTokPtr = CurPtr;
279 // Skip the '#' token.
280 assert(((tok::TokenKind)*CurPtr) == tok::hash);
281 CurPtr += DISK_TOKEN_SIZE;
283 // Did we reach a #endif? If so, go ahead and consume that token as well.
284 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
289 SourceLocation PTHLexer::getSourceLocation() {
290 // getSourceLocation is not on the hot path. It is used to get the location
291 // of the next token when transitioning back to this lexer when done
292 // handling a #included file. Just read the necessary data from the token
293 // data buffer to construct the SourceLocation object.
294 // NOTE: This is a virtual function; hence it is defined out-of-line.
295 const unsigned char *OffsetPtr = CurPtr + (DISK_TOKEN_SIZE - 4);
296 uint32_t Offset = ReadLE32(OffsetPtr);
297 return FileStartLoc.getLocWithOffset(Offset);
300 //===----------------------------------------------------------------------===//
301 // PTH file lookup: map from strings to file data.
302 //===----------------------------------------------------------------------===//
304 /// PTHFileLookup - This internal data structure is used by the PTHManager
305 /// to map from FileEntry objects managed by FileManager to offsets within
309 const uint32_t TokenOff;
310 const uint32_t PPCondOff;
312 PTHFileData(uint32_t tokenOff, uint32_t ppCondOff)
313 : TokenOff(tokenOff), PPCondOff(ppCondOff) {}
315 uint32_t getTokenOffset() const { return TokenOff; }
316 uint32_t getPPCondOffset() const { return PPCondOff; }
320 class PTHFileLookupCommonTrait {
322 typedef std::pair<unsigned char, const char*> internal_key_type;
324 static unsigned ComputeHash(internal_key_type x) {
325 return llvm::HashString(x.second);
328 static std::pair<unsigned, unsigned>
329 ReadKeyDataLength(const unsigned char*& d) {
330 unsigned keyLen = (unsigned) ReadUnalignedLE16(d);
331 unsigned dataLen = (unsigned) *(d++);
332 return std::make_pair(keyLen, dataLen);
335 static internal_key_type ReadKey(const unsigned char* d, unsigned) {
336 unsigned char k = *(d++); // Read the entry kind.
337 return std::make_pair(k, (const char*) d);
341 class PTHFileLookupTrait : public PTHFileLookupCommonTrait {
343 typedef const FileEntry* external_key_type;
344 typedef PTHFileData data_type;
346 static internal_key_type GetInternalKey(const FileEntry* FE) {
347 return std::make_pair((unsigned char) 0x1, FE->getName());
350 static bool EqualKey(internal_key_type a, internal_key_type b) {
351 return a.first == b.first && strcmp(a.second, b.second) == 0;
354 static PTHFileData ReadData(const internal_key_type& k,
355 const unsigned char* d, unsigned) {
356 assert(k.first == 0x1 && "Only file lookups can match!");
357 uint32_t x = ::ReadUnalignedLE32(d);
358 uint32_t y = ::ReadUnalignedLE32(d);
359 return PTHFileData(x, y);
363 class PTHStringLookupTrait {
368 typedef const std::pair<const char*, unsigned>
371 typedef external_key_type internal_key_type;
373 static bool EqualKey(const internal_key_type& a,
374 const internal_key_type& b) {
375 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
379 static unsigned ComputeHash(const internal_key_type& a) {
380 return llvm::HashString(StringRef(a.first, a.second));
383 // This hopefully will just get inlined and removed by the optimizer.
384 static const internal_key_type&
385 GetInternalKey(const external_key_type& x) { return x; }
387 static std::pair<unsigned, unsigned>
388 ReadKeyDataLength(const unsigned char*& d) {
389 return std::make_pair((unsigned) ReadUnalignedLE16(d), sizeof(uint32_t));
392 static std::pair<const char*, unsigned>
393 ReadKey(const unsigned char* d, unsigned n) {
394 assert(n >= 2 && d[n-1] == '\0');
395 return std::make_pair((const char*) d, n-1);
398 static uint32_t ReadData(const internal_key_type& k, const unsigned char* d,
400 return ::ReadUnalignedLE32(d);
404 } // end anonymous namespace
406 typedef OnDiskChainedHashTable<PTHFileLookupTrait> PTHFileLookup;
407 typedef OnDiskChainedHashTable<PTHStringLookupTrait> PTHStringIdLookup;
409 //===----------------------------------------------------------------------===//
410 // PTHManager methods.
411 //===----------------------------------------------------------------------===//
413 PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
414 const unsigned char* idDataTable,
415 IdentifierInfo** perIDCache,
416 void* stringIdLookup, unsigned numIds,
417 const unsigned char* spellingBase,
418 const char* originalSourceFile)
419 : Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
420 IdDataTable(idDataTable), StringIdLookup(stringIdLookup),
421 NumIds(numIds), PP(0), SpellingBase(spellingBase),
422 OriginalSourceFile(originalSourceFile) {}
424 PTHManager::~PTHManager() {
426 delete (PTHFileLookup*) FileLookup;
427 delete (PTHStringIdLookup*) StringIdLookup;
431 static void InvalidPTH(DiagnosticsEngine &Diags, const char *Msg) {
432 Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, Msg));
435 PTHManager *PTHManager::Create(const std::string &file,
436 DiagnosticsEngine &Diags) {
437 // Memory map the PTH file.
438 OwningPtr<llvm::MemoryBuffer> File;
440 if (llvm::MemoryBuffer::getFile(file, File)) {
441 // FIXME: Add ec.message() to this diag.
442 Diags.Report(diag::err_invalid_pth_file) << file;
446 // Get the buffer ranges and check if there are at least three 32-bit
447 // words at the end of the file.
448 const unsigned char *BufBeg = (const unsigned char*)File->getBufferStart();
449 const unsigned char *BufEnd = (const unsigned char*)File->getBufferEnd();
451 // Check the prologue of the file.
452 if ((BufEnd - BufBeg) < (signed)(sizeof("cfe-pth") + 4 + 4) ||
453 memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth")) != 0) {
454 Diags.Report(diag::err_invalid_pth_file) << file;
458 // Read the PTH version.
459 const unsigned char *p = BufBeg + (sizeof("cfe-pth"));
460 unsigned Version = ReadLE32(p);
462 if (Version < PTHManager::Version) {
464 Version < PTHManager::Version
465 ? "PTH file uses an older PTH format that is no longer supported"
466 : "PTH file uses a newer PTH format that cannot be read");
470 // Compute the address of the index table at the end of the PTH file.
471 const unsigned char *PrologueOffset = p;
473 if (PrologueOffset >= BufEnd) {
474 Diags.Report(diag::err_invalid_pth_file) << file;
478 // Construct the file lookup table. This will be used for mapping from
479 // FileEntry*'s to cached tokens.
480 const unsigned char* FileTableOffset = PrologueOffset + sizeof(uint32_t)*2;
481 const unsigned char* FileTable = BufBeg + ReadLE32(FileTableOffset);
483 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
484 Diags.Report(diag::err_invalid_pth_file) << file;
485 return 0; // FIXME: Proper error diagnostic?
488 OwningPtr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg));
490 // Warn if the PTH file is empty. We still want to create a PTHManager
491 // as the PTH could be used with -include-pth.
493 InvalidPTH(Diags, "PTH file contains no cached source data");
495 // Get the location of the table mapping from persistent ids to the
496 // data needed to reconstruct identifiers.
497 const unsigned char* IDTableOffset = PrologueOffset + sizeof(uint32_t)*0;
498 const unsigned char* IData = BufBeg + ReadLE32(IDTableOffset);
500 if (!(IData >= BufBeg && IData < BufEnd)) {
501 Diags.Report(diag::err_invalid_pth_file) << file;
505 // Get the location of the hashtable mapping between strings and
507 const unsigned char* StringIdTableOffset = PrologueOffset + sizeof(uint32_t)*1;
508 const unsigned char* StringIdTable = BufBeg + ReadLE32(StringIdTableOffset);
509 if (!(StringIdTable >= BufBeg && StringIdTable < BufEnd)) {
510 Diags.Report(diag::err_invalid_pth_file) << file;
514 OwningPtr<PTHStringIdLookup> SL(PTHStringIdLookup::Create(StringIdTable,
517 // Get the location of the spelling cache.
518 const unsigned char* spellingBaseOffset = PrologueOffset + sizeof(uint32_t)*3;
519 const unsigned char* spellingBase = BufBeg + ReadLE32(spellingBaseOffset);
520 if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) {
521 Diags.Report(diag::err_invalid_pth_file) << file;
525 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
526 uint32_t NumIds = ReadLE32(IData);
528 // Pre-allocate the persistent ID -> IdentifierInfo* cache. We use calloc()
529 // so that we in the best case only zero out memory once when the OS returns
531 IdentifierInfo** PerIDCache = 0;
534 PerIDCache = (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache));
536 InvalidPTH(Diags, "Could not allocate memory for processing PTH file");
541 // Compute the address of the original source file.
542 const unsigned char* originalSourceBase = PrologueOffset + sizeof(uint32_t)*4;
543 unsigned len = ReadUnalignedLE16(originalSourceBase);
544 if (!len) originalSourceBase = 0;
546 // Create the new PTHManager.
547 return new PTHManager(File.take(), FL.take(), IData, PerIDCache,
548 SL.take(), NumIds, spellingBase,
549 (const char*) originalSourceBase);
552 IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) {
553 // Look in the PTH file for the string data for the IdentifierInfo object.
554 const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID;
555 const unsigned char* IDData =
556 (const unsigned char*)Buf->getBufferStart() + ReadLE32(TableEntry);
557 assert(IDData < (const unsigned char*)Buf->getBufferEnd());
559 // Allocate the object.
560 std::pair<IdentifierInfo,const unsigned char*> *Mem =
561 Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >();
563 Mem->second = IDData;
564 assert(IDData[0] != '\0');
565 IdentifierInfo *II = new ((void*) Mem) IdentifierInfo();
567 // Store the new IdentifierInfo in the cache.
568 PerIDCache[PersistentID] = II;
569 assert(II->getNameStart() && II->getNameStart()[0] != '\0');
573 IdentifierInfo* PTHManager::get(StringRef Name) {
574 PTHStringIdLookup& SL = *((PTHStringIdLookup*)StringIdLookup);
575 // Double check our assumption that the last character isn't '\0'.
576 assert(Name.empty() || Name.back() != '\0');
577 PTHStringIdLookup::iterator I = SL.find(std::make_pair(Name.data(),
579 if (I == SL.end()) // No identifier found?
582 // Match found. Return the identifier!
584 return GetIdentifierInfo(*I-1);
587 PTHLexer *PTHManager::CreateLexer(FileID FID) {
588 const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID);
592 // Lookup the FileEntry object in our file lookup data structure. It will
593 // return a variant that indicates whether or not there is an offset within
594 // the PTH file that contains cached tokens.
595 PTHFileLookup& PFL = *((PTHFileLookup*)FileLookup);
596 PTHFileLookup::iterator I = PFL.find(FE);
598 if (I == PFL.end()) // No tokens available?
601 const PTHFileData& FileData = *I;
603 const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
604 // Compute the offset of the token data within the buffer.
605 const unsigned char* data = BufStart + FileData.getTokenOffset();
607 // Get the location of pp-conditional table.
608 const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
609 uint32_t Len = ReadLE32(ppcond);
610 if (Len == 0) ppcond = 0;
612 assert(PP && "No preprocessor set yet!");
613 return new PTHLexer(*PP, FID, data, ppcond, *this);
616 //===----------------------------------------------------------------------===//
618 //===----------------------------------------------------------------------===//
630 PTHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
631 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
634 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
637 class PTHStatLookupTrait : public PTHFileLookupCommonTrait {
639 typedef const char* external_key_type; // const char*
640 typedef PTHStatData data_type;
642 static internal_key_type GetInternalKey(const char *path) {
643 // The key 'kind' doesn't matter here because it is ignored in EqualKey.
644 return std::make_pair((unsigned char) 0x0, path);
647 static bool EqualKey(internal_key_type a, internal_key_type b) {
648 // When doing 'stat' lookups we don't care about the kind of 'a' and 'b',
650 return strcmp(a.second, b.second) == 0;
653 static data_type ReadData(const internal_key_type& k, const unsigned char* d,
656 if (k.first /* File or Directory */) {
657 if (k.first == 0x1 /* File */) d += 4 * 2; // Skip the first 2 words.
658 ino_t ino = (ino_t) ReadUnalignedLE32(d);
659 dev_t dev = (dev_t) ReadUnalignedLE32(d);
660 mode_t mode = (mode_t) ReadUnalignedLE16(d);
661 time_t mtime = (time_t) ReadUnalignedLE64(d);
662 return data_type(ino, dev, mode, mtime, (off_t) ReadUnalignedLE64(d));
665 // Negative stat. Don't read anything.
670 class PTHStatCache : public FileSystemStatCache {
671 typedef OnDiskChainedHashTable<PTHStatLookupTrait> CacheTy;
675 PTHStatCache(PTHFileLookup &FL) :
676 Cache(FL.getNumBuckets(), FL.getNumEntries(), FL.getBuckets(),
681 LookupResult getStat(const char *Path, struct stat &StatBuf,
682 int *FileDescriptor) {
683 // Do the lookup for the file's data in the PTH file.
684 CacheTy::iterator I = Cache.find(Path);
686 // If we don't get a hit in the PTH file just forward to 'stat'.
687 if (I == Cache.end())
688 return statChained(Path, StatBuf, FileDescriptor);
690 const PTHStatData &Data = *I;
695 StatBuf.st_ino = Data.ino;
696 StatBuf.st_dev = Data.dev;
697 StatBuf.st_mtime = Data.mtime;
698 StatBuf.st_mode = Data.mode;
699 StatBuf.st_size = Data.size;
703 } // end anonymous namespace
705 FileSystemStatCache *PTHManager::createStatCache() {
706 return new PTHStatCache(*((PTHFileLookup*) FileLookup));