blob: 92c5e8815b3df7066a46e26e6a29e04164b7f544 [file] [log] [blame]
Ted Kremenek274b2082008-11-12 21:37:15 +00001//===--- 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
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000014#include "clang/Basic/TokenKinds.h"
15#include "clang/Basic/FileManager.h"
16#include "clang/Basic/IdentifierTable.h"
Ted Kremenek274b2082008-11-12 21:37:15 +000017#include "clang/Lex/PTHLexer.h"
18#include "clang/Lex/Preprocessor.h"
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000019#include "clang/Lex/PTHManager.h"
20#include "clang/Lex/Token.h"
21#include "clang/Lex/Preprocessor.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/OwningPtr.h"
Ted Kremenek274b2082008-11-12 21:37:15 +000026using namespace clang;
27
Ted Kremenek18d9afb2008-12-23 18:41:34 +000028#define DISK_TOKEN_SIZE (1+1+3+4+2)
Ted Kremenek268ee702008-12-12 18:34:08 +000029
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000030//===----------------------------------------------------------------------===//
31// Utility methods for reading from the mmap'ed PTH file.
32//===----------------------------------------------------------------------===//
33
Chris Lattnerda9d61c2009-01-18 01:57:14 +000034static inline uint8_t Read8(const unsigned char *&Data) {
35 uint8_t V = Data[0];
36 Data += 1;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +000037 return V;
38}
39
Chris Lattnerda9d61c2009-01-18 01:57:14 +000040static inline uint16_t Read16(const unsigned char *&Data) {
Chris Lattnerf15674c2009-01-18 02:19:16 +000041// Targets that directly support unaligned little-endian 16-bit loads can just
42// use them.
43#if defined(__i386__) || defined(__x86_64__)
44 uint16_t V = *((uint16_t*)Data);
45#else
Chris Lattnerda9d61c2009-01-18 01:57:14 +000046 uint16_t V = ((uint16_t)Data[0] << 0) |
47 ((uint16_t)Data[1] << 8);
Chris Lattnerf15674c2009-01-18 02:19:16 +000048#endif
Chris Lattnerda9d61c2009-01-18 01:57:14 +000049 Data += 2;
50 return V;
51}
52
53static inline uint32_t Read24(const unsigned char *&Data) {
Chris Lattnerf15674c2009-01-18 02:19:16 +000054// Targets that directly support unaligned little-endian 16-bit loads can just
55// use them.
56#if defined(__i386__) || defined(__x86_64__)
57 uint32_t V = ((uint16_t*)Data)[0] |
58 ((uint32_t)Data[2] << 16);
59#else
Chris Lattnerda9d61c2009-01-18 01:57:14 +000060 uint32_t V = ((uint32_t)Data[0] << 0) |
61 ((uint32_t)Data[1] << 8) |
62 ((uint32_t)Data[2] << 16);
Chris Lattnerf15674c2009-01-18 02:19:16 +000063#endif
64
Chris Lattnerda9d61c2009-01-18 01:57:14 +000065 Data += 3;
66 return V;
67}
68
69static inline uint32_t Read32(const unsigned char *&Data) {
Chris Lattnerf15674c2009-01-18 02:19:16 +000070// Targets that directly support unaligned little-endian 32-bit loads can just
71// use them.
72#if defined(__i386__) || defined(__x86_64__)
73 uint32_t V = *((uint32_t*)Data);
74#else
Chris Lattnerda9d61c2009-01-18 01:57:14 +000075 uint32_t V = ((uint32_t)Data[0] << 0) |
76 ((uint32_t)Data[1] << 8) |
77 ((uint32_t)Data[2] << 16) |
78 ((uint32_t)Data[3] << 24);
Chris Lattnerf15674c2009-01-18 02:19:16 +000079#endif
Chris Lattnerda9d61c2009-01-18 01:57:14 +000080 Data += 4;
81 return V;
82}
83
84
Ted Kremeneke5680f32008-12-23 01:30:52 +000085//===----------------------------------------------------------------------===//
86// PTHLexer methods.
87//===----------------------------------------------------------------------===//
88
Chris Lattnerda9d61c2009-01-18 01:57:14 +000089PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D,
90 const unsigned char *ppcond,
Chris Lattner2b2453a2009-01-17 06:22:33 +000091 PTHSpellingSearch &mySpellingSrch, PTHManager &PM)
92 : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(0),
Ted Kremenek5f074262009-01-09 22:05:30 +000093 PPCond(ppcond), CurPPCondPtr(ppcond), MySpellingSrch(mySpellingSrch),
Chris Lattner2b2453a2009-01-17 06:22:33 +000094 PTHMgr(PM) {
95
96 FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID);
Ted Kremenek5f074262009-01-09 22:05:30 +000097}
Ted Kremeneke5680f32008-12-23 01:30:52 +000098
99void PTHLexer::Lex(Token& Tok) {
100LexNextToken:
Ted Kremeneke5680f32008-12-23 01:30:52 +0000101
Ted Kremenek866bdf72008-12-23 02:30:15 +0000102 //===--------------------------------------==//
103 // Read the raw token data.
104 //===--------------------------------------==//
105
106 // Shadow CurPtr into an automatic variable.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000107 const unsigned char *CurPtrShadow = CurPtr;
Ted Kremenek866bdf72008-12-23 02:30:15 +0000108
Chris Lattner1b5285e2009-01-18 02:10:31 +0000109 // Read in the data for the token.
110 tok::TokenKind k = (tok::TokenKind) Read8(CurPtrShadow);
111 Token::TokenFlags flags = (Token::TokenFlags) Read8(CurPtrShadow);
112 uint32_t perID = Read24(CurPtrShadow);
113 uint32_t FileOffset = Read32(CurPtrShadow);
114 uint32_t Len = Read16(CurPtrShadow);
115 CurPtr = CurPtrShadow;
Ted Kremenek866bdf72008-12-23 02:30:15 +0000116
117 //===--------------------------------------==//
118 // Construct the token itself.
119 //===--------------------------------------==//
120
121 Tok.startToken();
122 Tok.setKind(k);
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000123 Tok.setFlag(flags);
124 assert(!LexingRawMode);
Ted Kremenek6b1c9702008-12-23 18:27:26 +0000125 Tok.setIdentifierInfo(perID ? PTHMgr.GetIdentifierInfo(perID-1) : 0);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000126 Tok.setLocation(FileStartLoc.getFileLocWithOffset(FileOffset));
Ted Kremenek866bdf72008-12-23 02:30:15 +0000127 Tok.setLength(Len);
128
129 //===--------------------------------------==//
130 // Process the token.
131 //===--------------------------------------==//
Ted Kremenek5f074262009-01-09 22:05:30 +0000132#if 0
133 SourceManager& SM = PP->getSourceManager();
134 llvm::cerr << SM.getFileEntryForID(FileID)->getName()
135 << ':' << SM.getLogicalLineNumber(Tok.getLocation())
136 << ':' << SM.getLogicalColumnNumber(Tok.getLocation())
137 << '\n';
138#endif
Ted Kremeneke5680f32008-12-23 01:30:52 +0000139
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000140 if (k == tok::identifier) {
141 MIOpt.ReadToken();
142 return PP->HandleIdentifier(Tok);
143 }
144
145 if (k == tok::eof) {
Ted Kremeneke5680f32008-12-23 01:30:52 +0000146 // Save the end-of-file token.
147 EofToken = Tok;
148
149 Preprocessor *PPCache = PP;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000150
151 assert(!ParsingPreprocessorDirective);
152 assert(!LexingRawMode);
153
154 // FIXME: Issue diagnostics similar to Lexer.
155 if (PP->HandleEndOfFile(Tok, false))
Ted Kremeneke5680f32008-12-23 01:30:52 +0000156 return;
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000157
Ted Kremeneke5680f32008-12-23 01:30:52 +0000158 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
159 return PPCache->Lex(Tok);
160 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000161
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000162 if (k == tok::hash && Tok.isAtStartOfLine()) {
163 LastHashTokPtr = CurPtr - DISK_TOKEN_SIZE;
164 assert(!LexingRawMode);
165 PP->HandleDirective(Tok);
166
167 if (PP->isCurrentLexer(this))
168 goto LexNextToken;
169
170 return PP->Lex(Tok);
171 }
172
173 if (k == tok::eom) {
174 assert(ParsingPreprocessorDirective);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000175 ParsingPreprocessorDirective = false;
176 return;
177 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000178
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000179 MIOpt.ReadToken();
Ted Kremeneke5680f32008-12-23 01:30:52 +0000180}
181
182// FIXME: We can just grab the last token instead of storing a copy
183// into EofToken.
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000184void PTHLexer::getEOF(Token& Tok) {
Ted Kremenekdefb7092009-01-09 00:36:11 +0000185 assert(EofToken.is(tok::eof));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000186 Tok = EofToken;
187}
188
189void PTHLexer::DiscardToEndOfLine() {
190 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
191 "Must be in a preprocessing directive!");
192
193 // We assume that if the preprocessor wishes to discard to the end of
194 // the line that it also means to end the current preprocessor directive.
195 ParsingPreprocessorDirective = false;
196
197 // Skip tokens by only peeking at their token kind and the flags.
198 // We don't need to actually reconstruct full tokens from the token buffer.
199 // This saves some copies and it also reduces IdentifierInfo* lookup.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000200 const unsigned char* p = CurPtr;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000201 while (1) {
202 // Read the token kind. Are we at the end of the file?
203 tok::TokenKind x = (tok::TokenKind) (uint8_t) *p;
204 if (x == tok::eof) break;
205
206 // Read the token flags. Are we at the start of the next line?
207 Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1];
208 if (y & Token::StartOfLine) break;
209
210 // Skip to the next token.
211 p += DISK_TOKEN_SIZE;
212 }
213
214 CurPtr = p;
215}
216
Ted Kremenek268ee702008-12-12 18:34:08 +0000217/// SkipBlock - Used by Preprocessor to skip the current conditional block.
218bool PTHLexer::SkipBlock() {
219 assert(CurPPCondPtr && "No cached PP conditional information.");
220 assert(LastHashTokPtr && "No known '#' token.");
221
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000222 const unsigned char* HashEntryI = 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000223 uint32_t Offset;
224 uint32_t TableIdx;
225
226 do {
Ted Kremenek41a26602008-12-12 22:05:38 +0000227 // Read the token offset from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000228 Offset = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000229
230 // Read the target table index from the side-table.
Ted Kremenek268ee702008-12-12 18:34:08 +0000231 TableIdx = Read32(CurPPCondPtr);
Ted Kremenek41a26602008-12-12 22:05:38 +0000232
233 // Compute the actual memory address of the '#' token data for this entry.
234 HashEntryI = TokBuf + Offset;
235
236 // Optmization: "Sibling jumping". #if...#else...#endif blocks can
237 // contain nested blocks. In the side-table we can jump over these
238 // nested blocks instead of doing a linear search if the next "sibling"
239 // entry is not at a location greater than LastHashTokPtr.
240 if (HashEntryI < LastHashTokPtr && TableIdx) {
241 // In the side-table we are still at an entry for a '#' token that
242 // is earlier than the last one we saw. Check if the location we would
243 // stride gets us closer.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000244 const unsigned char* NextPPCondPtr =
245 PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenek41a26602008-12-12 22:05:38 +0000246 assert(NextPPCondPtr >= CurPPCondPtr);
247 // Read where we should jump to.
248 uint32_t TmpOffset = Read32(NextPPCondPtr);
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000249 const unsigned char* HashEntryJ = TokBuf + TmpOffset;
Ted Kremenek41a26602008-12-12 22:05:38 +0000250
251 if (HashEntryJ <= LastHashTokPtr) {
252 // Jump directly to the next entry in the side table.
253 HashEntryI = HashEntryJ;
254 Offset = TmpOffset;
255 TableIdx = Read32(NextPPCondPtr);
256 CurPPCondPtr = NextPPCondPtr;
257 }
258 }
Ted Kremenek268ee702008-12-12 18:34:08 +0000259 }
Ted Kremenek41a26602008-12-12 22:05:38 +0000260 while (HashEntryI < LastHashTokPtr);
261 assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'");
Ted Kremenek268ee702008-12-12 18:34:08 +0000262 assert(TableIdx && "No jumping from #endifs.");
263
264 // Update our side-table iterator.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000265 const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2);
Ted Kremenek268ee702008-12-12 18:34:08 +0000266 assert(NextPPCondPtr >= CurPPCondPtr);
267 CurPPCondPtr = NextPPCondPtr;
268
269 // Read where we should jump to.
Ted Kremenek41a26602008-12-12 22:05:38 +0000270 HashEntryI = TokBuf + Read32(NextPPCondPtr);
Ted Kremenek268ee702008-12-12 18:34:08 +0000271 uint32_t NextIdx = Read32(NextPPCondPtr);
272
273 // By construction NextIdx will be zero if this is a #endif. This is useful
274 // to know to obviate lexing another token.
275 bool isEndif = NextIdx == 0;
Ted Kremenek268ee702008-12-12 18:34:08 +0000276
277 // This case can occur when we see something like this:
278 //
279 // #if ...
280 // /* a comment or nothing */
281 // #elif
282 //
283 // If we are skipping the first #if block it will be the case that CurPtr
284 // already points 'elif'. Just return.
285
Ted Kremenek41a26602008-12-12 22:05:38 +0000286 if (CurPtr > HashEntryI) {
287 assert(CurPtr == HashEntryI + DISK_TOKEN_SIZE);
Ted Kremenek268ee702008-12-12 18:34:08 +0000288 // Did we reach a #endif? If so, go ahead and consume that token as well.
289 if (isEndif)
Ted Kremeneke5680f32008-12-23 01:30:52 +0000290 CurPtr += DISK_TOKEN_SIZE*2;
Ted Kremenek268ee702008-12-12 18:34:08 +0000291 else
Ted Kremenek41a26602008-12-12 22:05:38 +0000292 LastHashTokPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000293
294 return isEndif;
295 }
296
297 // Otherwise, we need to advance. Update CurPtr to point to the '#' token.
Ted Kremenek41a26602008-12-12 22:05:38 +0000298 CurPtr = HashEntryI;
Ted Kremenek268ee702008-12-12 18:34:08 +0000299
300 // Update the location of the last observed '#'. This is useful if we
301 // are skipping multiple blocks.
302 LastHashTokPtr = CurPtr;
Ted Kremenek268ee702008-12-12 18:34:08 +0000303
Ted Kremeneke5680f32008-12-23 01:30:52 +0000304 // Skip the '#' token.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000305 assert(((tok::TokenKind)*CurPtr) == tok::hash);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000306 CurPtr += DISK_TOKEN_SIZE;
307
Ted Kremenek268ee702008-12-12 18:34:08 +0000308 // Did we reach a #endif? If so, go ahead and consume that token as well.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000309 if (isEndif) { CurPtr += DISK_TOKEN_SIZE*2; }
Ted Kremenek268ee702008-12-12 18:34:08 +0000310
311 return isEndif;
312}
313
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000314SourceLocation PTHLexer::getSourceLocation() {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000315 // getSourceLocation is not on the hot path. It is used to get the location
316 // of the next token when transitioning back to this lexer when done
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000317 // handling a #included file. Just read the necessary data from the token
318 // data buffer to construct the SourceLocation object.
319 // NOTE: This is a virtual function; hence it is defined out-of-line.
Chris Lattner1b5285e2009-01-18 02:10:31 +0000320 const unsigned char *OffsetPtr = CurPtr + (1 + 1 + 3);
321 uint32_t Offset = Read32(OffsetPtr);
322 return FileStartLoc.getFileLocWithOffset(Offset);
Ted Kremenek30a12ec2008-12-17 23:36:32 +0000323}
324
Ted Kremenek5f074262009-01-09 22:05:30 +0000325//===----------------------------------------------------------------------===//
326// getSpelling() - Use cached data in PTH files for getSpelling().
327//===----------------------------------------------------------------------===//
328
Chris Lattner2b2453a2009-01-17 06:22:33 +0000329unsigned PTHManager::getSpelling(FileID FID, unsigned FPos,
330 const char *&Buffer) {
331 llvm::DenseMap<FileID, PTHSpellingSearch*>::iterator I =SpellingMap.find(FID);
Ted Kremenek5f074262009-01-09 22:05:30 +0000332
333 if (I == SpellingMap.end())
Chris Lattner1b5285e2009-01-18 02:10:31 +0000334 return 0;
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000335
Chris Lattner2b2453a2009-01-17 06:22:33 +0000336 return I->second->getSpellingBinarySearch(FPos, Buffer);
337}
338
339unsigned PTHManager::getSpelling(SourceLocation Loc, const char *&Buffer) {
Chris Lattner6b7b8402009-01-17 06:29:33 +0000340 SourceManager &SM = PP->getSourceManager();
341 Loc = SM.getSpellingLoc(Loc);
342 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedFileLoc(Loc);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000343 return getSpelling(LocInfo.first, LocInfo.second, Buffer);
Ted Kremenek5f074262009-01-09 22:05:30 +0000344}
345
346unsigned PTHManager::getSpellingAtPTHOffset(unsigned PTHOffset,
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000347 const char *&Buffer) {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000348 assert(PTHOffset < Buf->getBufferSize());
349 const unsigned char* Ptr =
350 (const unsigned char*)Buf->getBufferStart() + PTHOffset;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000351
352 // The string is prefixed by 16 bits for its length, followed by the string
353 // itself.
Chris Lattner1b5285e2009-01-18 02:10:31 +0000354 unsigned Len = Read16(Ptr);
355 Buffer = (const char *)Ptr;
356 return Len;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000357}
358
Chris Lattner1b5285e2009-01-18 02:10:31 +0000359unsigned PTHSpellingSearch::getSpellingLinearSearch(unsigned FPos,
Ted Kremenek5f074262009-01-09 22:05:30 +0000360 const char *&Buffer) {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000361 const unsigned char *Ptr = LinearItr;
362 unsigned Len = 0;
Ted Kremenek5f074262009-01-09 22:05:30 +0000363
Chris Lattner1b5285e2009-01-18 02:10:31 +0000364 if (Ptr == TableEnd)
365 return getSpellingBinarySearch(FPos, Buffer);
Ted Kremenek5f074262009-01-09 22:05:30 +0000366
367 do {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000368 uint32_t TokOffset = Read32(Ptr);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000369
Chris Lattner1b5285e2009-01-18 02:10:31 +0000370 if (TokOffset > FPos)
371 return getSpellingBinarySearch(FPos, Buffer);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000372
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000373 // Did we find a matching token offset for this spelling?
Chris Lattner1b5285e2009-01-18 02:10:31 +0000374 if (TokOffset == FPos) {
375 uint32_t SpellingPTHOffset = Read32(Ptr);
376 Len = PTHMgr.getSpellingAtPTHOffset(SpellingPTHOffset, Buffer);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000377 break;
378 }
Chris Lattner1b5285e2009-01-18 02:10:31 +0000379 } while (Ptr != TableEnd);
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000380
Chris Lattner1b5285e2009-01-18 02:10:31 +0000381 LinearItr = Ptr;
382 return Len;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000383}
384
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000385
Chris Lattner1b5285e2009-01-18 02:10:31 +0000386unsigned PTHSpellingSearch::getSpellingBinarySearch(unsigned FPos,
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000387 const char *&Buffer) {
Ted Kremenek5f074262009-01-09 22:05:30 +0000388
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000389 assert((TableEnd - TableBeg) % SpellingEntrySize == 0);
Chris Lattner1b5285e2009-01-18 02:10:31 +0000390 assert(TableEnd >= TableBeg);
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000391
392 if (TableEnd == TableBeg)
393 return 0;
394
Ted Kremenek5f074262009-01-09 22:05:30 +0000395 unsigned min = 0;
Chris Lattner1b5285e2009-01-18 02:10:31 +0000396 const unsigned char *tb = TableBeg;
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000397 unsigned max = NumSpellings;
Ted Kremenek5f074262009-01-09 22:05:30 +0000398
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000399 do {
Ted Kremenek5f074262009-01-09 22:05:30 +0000400 unsigned i = (max - min) / 2 + min;
Chris Lattner1b5285e2009-01-18 02:10:31 +0000401 const unsigned char *Ptr = tb + (i * SpellingEntrySize);
Ted Kremenek5f074262009-01-09 22:05:30 +0000402
Chris Lattner1b5285e2009-01-18 02:10:31 +0000403 uint32_t TokOffset = Read32(Ptr);
404 if (TokOffset > FPos) {
Ted Kremenek5f074262009-01-09 22:05:30 +0000405 max = i;
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000406 assert(!(max == min) || (min == i));
Ted Kremenek5f074262009-01-09 22:05:30 +0000407 continue;
408 }
409
Chris Lattner1b5285e2009-01-18 02:10:31 +0000410 if (TokOffset < FPos) {
Ted Kremenek7bd88aa2009-01-13 22:16:45 +0000411 if (i == min)
412 break;
413
Ted Kremenek5f074262009-01-09 22:05:30 +0000414 min = i;
415 continue;
416 }
417
Chris Lattner1b5285e2009-01-18 02:10:31 +0000418 uint32_t SpellingPTHOffset = Read32(Ptr);
Ted Kremenek5f074262009-01-09 22:05:30 +0000419 return PTHMgr.getSpellingAtPTHOffset(SpellingPTHOffset, Buffer);
420 }
Ted Kremenekf02f6f02009-01-13 22:05:50 +0000421 while (min != max);
Ted Kremenek5f074262009-01-09 22:05:30 +0000422
423 return 0;
424}
425
Chris Lattner2b2453a2009-01-17 06:22:33 +0000426unsigned PTHLexer::getSpelling(SourceLocation Loc, const char *&Buffer) {
427 SourceManager &SM = PP->getSourceManager();
428 Loc = SM.getSpellingLoc(Loc);
429 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedFileLoc(Loc);
430
431 FileID FID = LocInfo.first;
432 unsigned FPos = LocInfo.second;
Ted Kremenek5f074262009-01-09 22:05:30 +0000433
Chris Lattner2b2453a2009-01-17 06:22:33 +0000434 if (FID == getFileID())
435 return MySpellingSrch.getSpellingLinearSearch(FPos, Buffer);
436 return PTHMgr.getSpelling(FID, FPos, Buffer);
Ted Kremenek5f074262009-01-09 22:05:30 +0000437}
438
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000439//===----------------------------------------------------------------------===//
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000440// Internal Data Structures for PTH file lookup and resolving identifiers.
441//===----------------------------------------------------------------------===//
442
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000443
444/// PTHFileLookup - This internal data structure is used by the PTHManager
445/// to map from FileEntry objects managed by FileManager to offsets within
446/// the PTH file.
447namespace {
448class VISIBILITY_HIDDEN PTHFileLookup {
449public:
450 class Val {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000451 uint32_t TokenOff;
452 uint32_t PPCondOff;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000453 uint32_t SpellingOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000454 public:
Ted Kremenekfb645b62008-12-11 23:36:38 +0000455 Val() : TokenOff(~0) {}
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000456 Val(uint32_t toff, uint32_t poff, uint32_t soff)
457 : TokenOff(toff), PPCondOff(poff), SpellingOff(soff) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000458
Chris Lattner1b5285e2009-01-18 02:10:31 +0000459 bool isValid() const { return TokenOff != ~((uint32_t)0); }
460
Ted Kremenekfb645b62008-12-11 23:36:38 +0000461 uint32_t getTokenOffset() const {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000462 assert(isValid() && "PTHFileLookup entry initialized.");
Ted Kremenekfb645b62008-12-11 23:36:38 +0000463 return TokenOff;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000464 }
465
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000466 uint32_t getPPCondOffset() const {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000467 assert(isValid() && "PTHFileLookup entry initialized.");
Ted Kremenekfb645b62008-12-11 23:36:38 +0000468 return PPCondOff;
469 }
470
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000471 uint32_t getSpellingOffset() const {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000472 assert(isValid() && "PTHFileLookup entry initialized.");
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000473 return SpellingOff;
474 }
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000475 };
476
477private:
478 llvm::StringMap<Val> FileMap;
479
480public:
481 PTHFileLookup() {};
482
483 Val Lookup(const FileEntry* FE) {
484 const char* s = FE->getName();
485 unsigned size = strlen(s);
486 return FileMap.GetOrCreateValue(s, s+size).getValue();
487 }
488
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000489 void ReadTable(const unsigned char* D) {
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000490 uint32_t N = Read32(D); // Read the length of the table.
491
492 for ( ; N > 0; --N) { // The rest of the data is the table itself.
Chris Lattner1b5285e2009-01-18 02:10:31 +0000493 uint32_t Len = Read32(D);
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000494 const char* s = (const char *)D;
Chris Lattner1b5285e2009-01-18 02:10:31 +0000495 D += Len;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000496
Ted Kremenekfb645b62008-12-11 23:36:38 +0000497 uint32_t TokenOff = Read32(D);
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000498 uint32_t PPCondOff = Read32(D);
499 uint32_t SpellingOff = Read32(D);
500
Chris Lattner1b5285e2009-01-18 02:10:31 +0000501 FileMap.GetOrCreateValue(s, s+Len).getValue() =
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000502 Val(TokenOff, PPCondOff, SpellingOff);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000503 }
504 }
505};
506} // end anonymous namespace
507
508//===----------------------------------------------------------------------===//
509// PTHManager methods.
510//===----------------------------------------------------------------------===//
511
512PTHManager::PTHManager(const llvm::MemoryBuffer* buf, void* fileLookup,
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000513 const unsigned char* idDataTable,
514 IdentifierInfo** perIDCache,
515 const unsigned char* sortedIdTable, unsigned numIds)
Ted Kremenek6183e482008-12-03 01:16:39 +0000516: Buf(buf), PerIDCache(perIDCache), FileLookup(fileLookup),
Ted Kremenek72b1b152009-01-15 18:47:46 +0000517 IdDataTable(idDataTable), SortedIdTable(sortedIdTable),
518 NumIds(numIds), PP(0) {}
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000519
520PTHManager::~PTHManager() {
521 delete Buf;
522 delete (PTHFileLookup*) FileLookup;
Ted Kremenek0e50b6e2008-12-04 22:47:11 +0000523 free(PerIDCache);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000524}
525
Ted Kremenek72b1b152009-01-15 18:47:46 +0000526PTHManager* PTHManager::Create(const std::string& file) {
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000527 // Memory map the PTH file.
528 llvm::OwningPtr<llvm::MemoryBuffer>
529 File(llvm::MemoryBuffer::getFile(file.c_str()));
530
531 if (!File)
532 return 0;
533
534 // Get the buffer ranges and check if there are at least three 32-bit
535 // words at the end of the file.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000536 const unsigned char* BufBeg = (unsigned char*)File->getBufferStart();
537 const unsigned char* BufEnd = (unsigned char*)File->getBufferEnd();
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000538
539 if(!(BufEnd > BufBeg + sizeof(uint32_t)*3)) {
540 assert(false && "Invalid PTH file.");
541 return 0; // FIXME: Proper error diagnostic?
542 }
543
544 // Compute the address of the index table at the end of the PTH file.
545 // This table contains the offset of the file lookup table, the
546 // persistent ID -> identifer data table.
Ted Kremenek293b4af2009-01-15 01:26:25 +0000547 // FIXME: We should just embed this offset in the PTH file.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000548 const unsigned char* EndTable = BufEnd - sizeof(uint32_t)*4;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000549
550 // Construct the file lookup table. This will be used for mapping from
551 // FileEntry*'s to cached tokens.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000552 const unsigned char* FileTableOffset = EndTable + sizeof(uint32_t)*3;
553 const unsigned char* FileTable = BufBeg + Read32(FileTableOffset);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000554
555 if (!(FileTable > BufBeg && FileTable < BufEnd)) {
556 assert(false && "Invalid PTH file.");
557 return 0; // FIXME: Proper error diagnostic?
558 }
559
560 llvm::OwningPtr<PTHFileLookup> FL(new PTHFileLookup());
561 FL->ReadTable(FileTable);
562
563 // Get the location of the table mapping from persistent ids to the
564 // data needed to reconstruct identifiers.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000565 const unsigned char* IDTableOffset = EndTable + sizeof(uint32_t)*1;
566 const unsigned char* IData = BufBeg + Read32(IDTableOffset);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000567 if (!(IData > BufBeg && IData < BufEnd)) {
568 assert(false && "Invalid PTH file.");
569 return 0; // FIXME: Proper error diagnostic?
570 }
571
Ted Kremenek72b1b152009-01-15 18:47:46 +0000572 // Get the location of the lexigraphically-sorted table of persistent IDs.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000573 const unsigned char* SortedIdTableOffset = EndTable + sizeof(uint32_t)*2;
574 const unsigned char* SortedIdTable = BufBeg + Read32(SortedIdTableOffset);
Ted Kremenek72b1b152009-01-15 18:47:46 +0000575 if (!(SortedIdTable > BufBeg && SortedIdTable < BufEnd)) {
576 assert(false && "Invalid PTH file.");
577 return 0; // FIXME: Proper error diagnostic?
578 }
579
Ted Kremenek6183e482008-12-03 01:16:39 +0000580 // Get the number of IdentifierInfos and pre-allocate the identifier cache.
581 uint32_t NumIds = Read32(IData);
582
583 // Pre-allocate the peristent ID -> IdentifierInfo* cache. We use calloc()
584 // so that we in the best case only zero out memory once when the OS returns
585 // us new pages.
586 IdentifierInfo** PerIDCache =
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000587 (IdentifierInfo**)calloc(NumIds, sizeof(*PerIDCache));
Ted Kremenek6183e482008-12-03 01:16:39 +0000588
589 if (!PerIDCache) {
590 assert(false && "Could not allocate Persistent ID cache.");
591 return 0;
592 }
593
Ted Kremenek72b1b152009-01-15 18:47:46 +0000594 // Create the new PTHManager.
595 return new PTHManager(File.take(), FL.take(), IData, PerIDCache,
596 SortedIdTable, NumIds);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000597}
598
Ted Kremenek866bdf72008-12-23 02:30:15 +0000599IdentifierInfo* PTHManager::GetIdentifierInfo(unsigned persistentID) {
600
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000601 // Check if the IdentifierInfo has already been resolved.
Ted Kremenek72b1b152009-01-15 18:47:46 +0000602 IdentifierInfo* II = PerIDCache[persistentID];
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000603 if (II) return II;
604
605 // Look in the PTH file for the string data for the IdentifierInfo object.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000606 const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*persistentID;
607 const unsigned char* IDData =
608 (const unsigned char*)Buf->getBufferStart() + Read32(TableEntry);
609 assert(IDData < (const unsigned char*)Buf->getBufferEnd());
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000610
Ted Kremenek72b1b152009-01-15 18:47:46 +0000611 // Allocate the object.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000612 std::pair<IdentifierInfo,const unsigned char*> *Mem =
613 Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >();
Ted Kremenek72b1b152009-01-15 18:47:46 +0000614
615 Mem->second = IDData;
616 II = new ((void*) Mem) IdentifierInfo(true);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000617
Ted Kremenek72b1b152009-01-15 18:47:46 +0000618 // Store the new IdentifierInfo in the cache.
619 PerIDCache[persistentID] = II;
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000620 return II;
621}
622
Ted Kremenek72b1b152009-01-15 18:47:46 +0000623IdentifierInfo* PTHManager::get(const char *NameStart, const char *NameEnd) {
624 unsigned min = 0;
625 unsigned max = NumIds;
Chris Lattner1b5285e2009-01-18 02:10:31 +0000626 unsigned Len = NameEnd - NameStart;
Ted Kremenek72b1b152009-01-15 18:47:46 +0000627
628 do {
629 unsigned i = (max - min) / 2 + min;
Chris Lattner1b5285e2009-01-18 02:10:31 +0000630 const unsigned char *Ptr = SortedIdTable + (i * 4);
Ted Kremenek72b1b152009-01-15 18:47:46 +0000631
632 // Read the persistentID.
Chris Lattner1b5285e2009-01-18 02:10:31 +0000633 unsigned perID = Read32(Ptr);
Ted Kremenek72b1b152009-01-15 18:47:46 +0000634
635 // Get the IdentifierInfo.
636 IdentifierInfo* II = GetIdentifierInfo(perID);
637
638 // First compare the lengths.
639 unsigned IILen = II->getLength();
Chris Lattner1b5285e2009-01-18 02:10:31 +0000640 if (Len < IILen) goto IsLess;
641 if (Len > IILen) goto IsGreater;
Ted Kremenek72b1b152009-01-15 18:47:46 +0000642
643 // Now compare the strings!
644 {
Chris Lattner1b5285e2009-01-18 02:10:31 +0000645 signed comp = strncmp(NameStart, II->getName(), Len);
Ted Kremenek72b1b152009-01-15 18:47:46 +0000646 if (comp < 0) goto IsLess;
647 if (comp > 0) goto IsGreater;
648 }
649 // We found a match!
650 return II;
651
652 IsGreater:
653 if (i == min) break;
654 min = i;
655 continue;
656
657 IsLess:
658 max = i;
659 assert(!(max == min) || (min == i));
660 }
Ted Kremeneke1deaac2009-01-15 19:28:38 +0000661 while (min != max);
Ted Kremenek72b1b152009-01-15 18:47:46 +0000662
663 return 0;
664}
665
666
Chris Lattnerf056d922009-01-17 08:06:50 +0000667PTHLexer *PTHManager::CreateLexer(FileID FID) {
668 const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000669 if (!FE)
670 return 0;
671
672 // Lookup the FileEntry object in our file lookup data structure. It will
673 // return a variant that indicates whether or not there is an offset within
674 // the PTH file that contains cached tokens.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000675 PTHFileLookup::Val FileData = ((PTHFileLookup*)FileLookup)->Lookup(FE);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000676
Ted Kremenekfb645b62008-12-11 23:36:38 +0000677 if (!FileData.isValid()) // No tokens available.
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000678 return 0;
679
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000680 const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart();
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000681 // Compute the offset of the token data within the buffer.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000682 const unsigned char* data = BufStart + FileData.getTokenOffset();
Ted Kremenek268ee702008-12-12 18:34:08 +0000683
684 // Get the location of pp-conditional table.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000685 const unsigned char* ppcond = BufStart + FileData.getPPCondOffset();
Chris Lattner1b5285e2009-01-18 02:10:31 +0000686 uint32_t Len = Read32(ppcond);
687 if (Len == 0) ppcond = 0;
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000688
689 // Get the location of the spelling table.
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000690 const unsigned char* spellingTable = BufStart + FileData.getSpellingOffset();
Ted Kremenek32a8ad52009-01-08 04:30:32 +0000691
Chris Lattner1b5285e2009-01-18 02:10:31 +0000692 Len = Read32(spellingTable);
693 if (Len == 0) spellingTable = 0;
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000694
Chris Lattnerda9d61c2009-01-18 01:57:14 +0000695 assert(data < (const unsigned char*)Buf->getBufferEnd());
Ted Kremenek5f074262009-01-09 22:05:30 +0000696
697 // Create the SpellingSearch object for this FileID.
Chris Lattner1b5285e2009-01-18 02:10:31 +0000698 PTHSpellingSearch* ss = new PTHSpellingSearch(*this, Len, spellingTable);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000699 SpellingMap[FID] = ss;
Ted Kremenek5f074262009-01-09 22:05:30 +0000700
Ted Kremenek72b1b152009-01-15 18:47:46 +0000701 assert(PP && "No preprocessor set yet!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000702 return new PTHLexer(*PP, FID, data, ppcond, *ss, *this);
Ted Kremenek0c6a77b2008-12-03 00:38:03 +0000703}