blob: 52ce082d135a903e58682eba14eb3e5fe2d81f44 [file] [log] [blame]
Ted Kremenek85888962008-10-21 00:54:44 +00001//===--- CacheTokens.cpp - Caching of lexer tokens for PCH support --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a possible implementation of PCH support for Clang that is
11// based on caching lexed tokens and identifiers.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang.h"
16#include "clang/Basic/FileManager.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Lex/Lexer.h"
21#include "clang/Lex/Preprocessor.h"
Ted Kremenekbe295332009-01-08 02:44:06 +000022#include "llvm/ADT/StringMap.h"
Ted Kremenek85888962008-10-21 00:54:44 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +000025#include "llvm/System/Path.h"
Ted Kremenekb978c662009-01-08 01:17:37 +000026#include "llvm/Support/Compiler.h"
Ted Kremenek72b1b152009-01-15 18:47:46 +000027#include "llvm/Support/Streams.h"
Ted Kremenek85888962008-10-21 00:54:44 +000028
29using namespace clang;
30
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +000031typedef uint32_t Offset;
32
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +000033static void Emit8(llvm::raw_ostream& Out, uint32_t V) {
34 Out << (unsigned char)(V);
35}
36
37static void Emit16(llvm::raw_ostream& Out, uint32_t V) {
38 Out << (unsigned char)(V);
39 Out << (unsigned char)(V >> 8);
40 assert((V >> 16) == 0);
41}
42
43static void Emit32(llvm::raw_ostream& Out, uint32_t V) {
44 Out << (unsigned char)(V);
45 Out << (unsigned char)(V >> 8);
46 Out << (unsigned char)(V >> 16);
47 Out << (unsigned char)(V >> 24);
48}
49
Ted Kremenek337edcd2009-02-12 03:26:59 +000050static void Emit64(llvm::raw_ostream& Out, uint64_t V) {
51 Out << (unsigned char)(V);
52 Out << (unsigned char)(V >> 8);
53 Out << (unsigned char)(V >> 16);
54 Out << (unsigned char)(V >> 24);
55 Out << (unsigned char)(V >> 32);
56 Out << (unsigned char)(V >> 40);
57 Out << (unsigned char)(V >> 48);
58 Out << (unsigned char)(V >> 56);
59}
60
Ted Kremenekd8c02922009-02-10 22:16:22 +000061static void Pad(llvm::raw_fd_ostream& Out, unsigned A) {
62 Offset off = (Offset) Out.tell();
63 uint32_t n = ((uintptr_t)(off+A-1) & ~(uintptr_t)(A-1)) - off;
64 for ( ; n ; --n ) Emit8(Out, 0);
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +000065}
66
Ted Kremenek7e3a0042009-02-11 21:29:16 +000067// Bernstein hash function:
68// This is basically copy-and-paste from StringMap. This likely won't
69// stay here, which is why I didn't both to expose this function from
70// String Map.
71static unsigned BernsteinHash(const char* x) {
72 unsigned int R = 0;
73 for ( ; *x != '\0' ; ++x) R = R * 33 + *x;
74 return R + (R >> 5);
75}
76
Ted Kremenekf0e1f792009-02-10 01:14:45 +000077//===----------------------------------------------------------------------===//
78// On Disk Hashtable Logic. This will eventually get refactored and put
79// elsewhere.
80//===----------------------------------------------------------------------===//
81
82template<typename Info>
83class OnDiskChainedHashTableGenerator {
84 unsigned NumBuckets;
85 unsigned NumEntries;
86 llvm::BumpPtrAllocator BA;
87
88 class Item {
89 public:
Ted Kremenekd8c02922009-02-10 22:16:22 +000090 typename Info::key_type key;
91 typename Info::data_type data;
Ted Kremenekf0e1f792009-02-10 01:14:45 +000092 Item *next;
93 const uint32_t hash;
94
Ted Kremenekd8c02922009-02-10 22:16:22 +000095 Item(typename Info::key_type_ref k, typename Info::data_type_ref d)
96 : key(k), data(d), next(0), hash(Info::ComputeHash(k)) {}
Ted Kremenekf0e1f792009-02-10 01:14:45 +000097 };
98
99 class Bucket {
100 public:
101 Offset off;
102 Item* head;
103 unsigned length;
104
105 Bucket() {}
106 };
107
108 Bucket* Buckets;
109
110private:
Ted Kremenekd8c02922009-02-10 22:16:22 +0000111 void insert(Bucket* b, size_t size, Item* E) {
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000112 unsigned idx = E->hash & (size - 1);
113 Bucket& B = b[idx];
114 E->next = B.head;
115 ++B.length;
116 B.head = E;
117 }
118
119 void resize(size_t newsize) {
Ted Kremenekd8c02922009-02-10 22:16:22 +0000120 Bucket* newBuckets = (Bucket*) calloc(newsize, sizeof(Bucket));
121 // Populate newBuckets with the old entries.
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000122 for (unsigned i = 0; i < NumBuckets; ++i)
Ted Kremenekd8c02922009-02-10 22:16:22 +0000123 for (Item* E = Buckets[i].head; E ; ) {
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000124 Item* N = E->next;
Ted Kremenekd8c02922009-02-10 22:16:22 +0000125 E->next = 0;
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000126 insert(newBuckets, newsize, E);
127 E = N;
128 }
129
130 free(Buckets);
131 NumBuckets = newsize;
132 Buckets = newBuckets;
133 }
134
135public:
136
Ted Kremenekd8c02922009-02-10 22:16:22 +0000137 void insert(typename Info::key_type_ref key,
138 typename Info::data_type_ref data) {
139
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000140 ++NumEntries;
141 if (4*NumEntries >= 3*NumBuckets) resize(NumBuckets*2);
142 insert(Buckets, NumBuckets, new (BA.Allocate<Item>()) Item(key, data));
143 }
144
145 Offset Emit(llvm::raw_fd_ostream& out) {
146 // Emit the payload of the table.
147 for (unsigned i = 0; i < NumBuckets; ++i) {
148 Bucket& B = Buckets[i];
149 if (!B.head) continue;
150
151 // Store the offset for the data of this bucket.
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000152 B.off = out.tell();
153
Ted Kremenekd8c02922009-02-10 22:16:22 +0000154 // Write out the number of items in the bucket.
155 Emit16(out, B.length);
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000156
157 // Write out the entries in the bucket.
158 for (Item *I = B.head; I ; I = I->next) {
159 Emit32(out, I->hash);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000160 const std::pair<unsigned, unsigned>& Len =
161 Info::EmitKeyDataLength(out, I->key, I->data);
162 Info::EmitKey(out, I->key, Len.first);
Ted Kremenek337edcd2009-02-12 03:26:59 +0000163 Info::EmitData(out, I->key, I->data, Len.second);
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000164 }
165 }
166
167 // Emit the hashtable itself.
168 Pad(out, 4);
169 Offset TableOff = out.tell();
Ted Kremenekd8c02922009-02-10 22:16:22 +0000170 Emit32(out, NumBuckets);
171 Emit32(out, NumEntries);
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000172 for (unsigned i = 0; i < NumBuckets; ++i) Emit32(out, Buckets[i].off);
173
174 return TableOff;
175 }
176
177 OnDiskChainedHashTableGenerator() {
178 NumEntries = 0;
Ted Kremenekd8c02922009-02-10 22:16:22 +0000179 NumBuckets = 64;
180 // Note that we do not need to run the constructors of the individual
181 // Bucket objects since 'calloc' returns bytes that are all 0.
182 Buckets = (Bucket*) calloc(NumBuckets, sizeof(Bucket));
Ted Kremenekf0e1f792009-02-10 01:14:45 +0000183 }
184
185 ~OnDiskChainedHashTableGenerator() {
186 free(Buckets);
187 }
188};
189
190//===----------------------------------------------------------------------===//
191// PTH-specific stuff.
192//===----------------------------------------------------------------------===//
193
Ted Kremenekbe295332009-01-08 02:44:06 +0000194namespace {
195class VISIBILITY_HIDDEN PCHEntry {
196 Offset TokenData, PPCondData;
Ted Kremenekbe295332009-01-08 02:44:06 +0000197
198public:
199 PCHEntry() {}
200
Ted Kremenek277faca2009-01-27 00:01:05 +0000201 PCHEntry(Offset td, Offset ppcd)
202 : TokenData(td), PPCondData(ppcd) {}
Ted Kremenekbe295332009-01-08 02:44:06 +0000203
Ted Kremenek277faca2009-01-27 00:01:05 +0000204 Offset getTokenOffset() const { return TokenData; }
Ted Kremenekbe295332009-01-08 02:44:06 +0000205 Offset getPPCondTableOffset() const { return PPCondData; }
Ted Kremenek277faca2009-01-27 00:01:05 +0000206};
Ted Kremenekbe295332009-01-08 02:44:06 +0000207
Ted Kremenekd8c02922009-02-10 22:16:22 +0000208class VISIBILITY_HIDDEN FileEntryPCHEntryInfo {
209public:
210 typedef const FileEntry* key_type;
211 typedef key_type key_type_ref;
212
213 typedef PCHEntry data_type;
214 typedef const PCHEntry& data_type_ref;
215
216 static unsigned ComputeHash(const FileEntry* FE) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000217 return BernsteinHash(FE->getName());
Ted Kremenekd8c02922009-02-10 22:16:22 +0000218 }
219
220 static std::pair<unsigned,unsigned>
221 EmitKeyDataLength(llvm::raw_ostream& Out, const FileEntry* FE,
222 const PCHEntry& E) {
223
224 unsigned n = strlen(FE->getName()) + 1;
225 ::Emit16(Out, n);
Ted Kremenek337edcd2009-02-12 03:26:59 +0000226 return std::make_pair(n,(4*2)+(4+4+2+8+8));
Ted Kremenekd8c02922009-02-10 22:16:22 +0000227 }
228
229 static void EmitKey(llvm::raw_ostream& Out, const FileEntry* FE, unsigned n) {
230 Out.write(FE->getName(), n);
231 }
232
Ted Kremenek337edcd2009-02-12 03:26:59 +0000233 static void EmitData(llvm::raw_ostream& Out, const FileEntry* FE,
234 const PCHEntry& E, unsigned) {
Ted Kremenekd8c02922009-02-10 22:16:22 +0000235 ::Emit32(Out, E.getTokenOffset());
236 ::Emit32(Out, E.getPPCondTableOffset());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000237 // Emit stat information.
238 ::Emit32(Out, FE->getInode());
239 ::Emit32(Out, FE->getDevice());
240 ::Emit16(Out, FE->getFileMode());
241 ::Emit64(Out, FE->getModificationTime());
242 ::Emit64(Out, FE->getSize());
Ted Kremenekd8c02922009-02-10 22:16:22 +0000243 }
244};
245
Ted Kremenek277faca2009-01-27 00:01:05 +0000246class OffsetOpt {
247 bool valid;
248 Offset off;
249public:
250 OffsetOpt() : valid(false) {}
251 bool hasOffset() const { return valid; }
252 Offset getOffset() const { assert(valid); return off; }
253 void setOffset(Offset o) { off = o; valid = true; }
Ted Kremenekbe295332009-01-08 02:44:06 +0000254};
255} // end anonymous namespace
256
Ted Kremenekd8c02922009-02-10 22:16:22 +0000257typedef OnDiskChainedHashTableGenerator<FileEntryPCHEntryInfo> PCHMap;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000258typedef llvm::DenseMap<const IdentifierInfo*,uint32_t> IDMap;
Ted Kremenek277faca2009-01-27 00:01:05 +0000259typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy;
Ted Kremenek85888962008-10-21 00:54:44 +0000260
Ted Kremenekb978c662009-01-08 01:17:37 +0000261namespace {
262class VISIBILITY_HIDDEN PTHWriter {
263 IDMap IM;
264 llvm::raw_fd_ostream& Out;
265 Preprocessor& PP;
266 uint32_t idcount;
267 PCHMap PM;
Ted Kremenekbe295332009-01-08 02:44:06 +0000268 CachedStrsTy CachedStrs;
Ted Kremenek277faca2009-01-27 00:01:05 +0000269 Offset CurStrOffset;
270 std::vector<llvm::StringMapEntry<OffsetOpt>*> StrEntries;
Ted Kremenek8f174e12008-12-23 02:52:12 +0000271
Ted Kremenekb978c662009-01-08 01:17:37 +0000272 //// Get the persistent id for the given IdentifierInfo*.
273 uint32_t ResolveID(const IdentifierInfo* II);
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000274
Ted Kremenekb978c662009-01-08 01:17:37 +0000275 /// Emit a token to the PTH file.
276 void EmitToken(const Token& T);
277
278 void Emit8(uint32_t V) {
279 Out << (unsigned char)(V);
280 }
281
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000282 void Emit16(uint32_t V) { ::Emit16(Out, V); }
Ted Kremenekb978c662009-01-08 01:17:37 +0000283
284 void Emit24(uint32_t V) {
285 Out << (unsigned char)(V);
286 Out << (unsigned char)(V >> 8);
287 Out << (unsigned char)(V >> 16);
288 assert((V >> 24) == 0);
289 }
290
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000291 void Emit32(uint32_t V) { ::Emit32(Out, V); }
292
Ted Kremenekb978c662009-01-08 01:17:37 +0000293 void EmitBuf(const char* I, const char* E) {
294 for ( ; I != E ; ++I) Out << *I;
295 }
296
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000297 /// EmitIdentifierTable - Emits two tables to the PTH file. The first is
298 /// a hashtable mapping from identifier strings to persistent IDs.
299 /// The second is a straight table mapping from persistent IDs to string data
300 /// (the keys of the first table).
Ted Kremenekf1de4642009-02-11 16:06:55 +0000301 std::pair<Offset, Offset> EmitIdentifierTable();
302
303 /// EmitFileTable - Emit a table mapping from file name strings to PTH
304 /// token data.
305 Offset EmitFileTable() { return PM.Emit(Out); }
306
Ted Kremenekbe295332009-01-08 02:44:06 +0000307 PCHEntry LexTokens(Lexer& L);
Ted Kremenek277faca2009-01-27 00:01:05 +0000308 Offset EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000309
Ted Kremenekb978c662009-01-08 01:17:37 +0000310public:
311 PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp)
Ted Kremenek277faca2009-01-27 00:01:05 +0000312 : Out(out), PP(pp), idcount(0), CurStrOffset(0) {}
Ted Kremenekb978c662009-01-08 01:17:37 +0000313
314 void GeneratePTH();
315};
316} // end anonymous namespace
317
318uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) {
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000319 // Null IdentifierInfo's map to the persistent ID 0.
320 if (!II)
321 return 0;
322
Ted Kremenek85888962008-10-21 00:54:44 +0000323 IDMap::iterator I = IM.find(II);
324
325 if (I == IM.end()) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000326 IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL.
327 return idcount;
Ted Kremenek85888962008-10-21 00:54:44 +0000328 }
329
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000330 return I->second; // We've already added 1.
Ted Kremenek85888962008-10-21 00:54:44 +0000331}
332
Ted Kremenekb978c662009-01-08 01:17:37 +0000333void PTHWriter::EmitToken(const Token& T) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000334 Emit32(((uint32_t) T.getKind()) |
335 (((uint32_t) T.getFlags()) << 8) |
336 (((uint32_t) T.getLength()) << 16));
Ted Kremenek277faca2009-01-27 00:01:05 +0000337
Chris Lattner47246be2009-01-26 19:29:26 +0000338 // Literals (strings, numbers, characters) get cached spellings.
339 if (T.isLiteral()) {
340 // FIXME: This uses the slow getSpelling(). Perhaps we do better
341 // in the future? This only slows down PTH generation.
342 const std::string &spelling = PP.getSpelling(T);
343 const char* s = spelling.c_str();
344
345 // Get the string entry.
Ted Kremenek277faca2009-01-27 00:01:05 +0000346 llvm::StringMapEntry<OffsetOpt> *E =
347 &CachedStrs.GetOrCreateValue(s, s+spelling.size());
348
349 if (!E->getValue().hasOffset()) {
350 E->getValue().setOffset(CurStrOffset);
351 StrEntries.push_back(E);
352 CurStrOffset += spelling.size() + 1;
353 }
354
355 Emit32(E->getValue().getOffset());
Ted Kremenekb978c662009-01-08 01:17:37 +0000356 }
Ted Kremenek277faca2009-01-27 00:01:05 +0000357 else
358 Emit32(ResolveID(T.getIdentifierInfo()));
359
Chris Lattner52c29082009-01-27 06:27:13 +0000360 Emit32(PP.getSourceManager().getFileOffset(T.getLocation()));
Ted Kremenek85888962008-10-21 00:54:44 +0000361}
362
Ted Kremenekbe295332009-01-08 02:44:06 +0000363PCHEntry PTHWriter::LexTokens(Lexer& L) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000364 // Pad 0's so that we emit tokens to a 4-byte alignment.
365 // This speed up reading them back in.
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000366 Pad(Out, 4);
367 Offset off = (Offset) Out.tell();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000368
369 // Keep track of matching '#if' ... '#endif'.
370 typedef std::vector<std::pair<Offset, unsigned> > PPCondTable;
371 PPCondTable PPCond;
Ted Kremenekdad7b342008-12-12 18:31:09 +0000372 std::vector<unsigned> PPStartCond;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000373 bool ParsingPreprocessorDirective = false;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000374 Token Tok;
375
376 do {
377 L.LexFromRawLexer(Tok);
Ted Kremenek726080d2009-02-10 22:43:16 +0000378 NextToken:
379
Ted Kremeneke5680f32008-12-23 01:30:52 +0000380 if ((Tok.isAtStartOfLine() || Tok.is(tok::eof)) &&
381 ParsingPreprocessorDirective) {
382 // Insert an eom token into the token cache. It has the same
383 // position as the next token that is not on the same line as the
384 // preprocessor directive. Observe that we continue processing
385 // 'Tok' when we exit this branch.
386 Token Tmp = Tok;
387 Tmp.setKind(tok::eom);
388 Tmp.clearFlag(Token::StartOfLine);
389 Tmp.setIdentifierInfo(0);
Ted Kremenekb978c662009-01-08 01:17:37 +0000390 EmitToken(Tmp);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000391 ParsingPreprocessorDirective = false;
392 }
393
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000394 if (Tok.is(tok::identifier)) {
395 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000396 EmitToken(Tok);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000397 continue;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000398 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000399
400 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000401 // Special processing for #include. Store the '#' token and lex
402 // the next token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000403 assert(!ParsingPreprocessorDirective);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000404 Offset HashOff = (Offset) Out.tell();
Ted Kremenekb978c662009-01-08 01:17:37 +0000405 EmitToken(Tok);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000406
407 // Get the next token.
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000408 L.LexFromRawLexer(Tok);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000409
410 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000411
412 // Did we see 'include'/'import'/'include_next'?
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000413 if (!Tok.is(tok::identifier)) {
414 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000415 continue;
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000416 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000417
418 IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok);
419 Tok.setIdentifierInfo(II);
420 tok::PPKeywordKind K = II->getPPKeywordID();
421
Ted Kremeneke5680f32008-12-23 01:30:52 +0000422 assert(K != tok::pp_not_keyword);
423 ParsingPreprocessorDirective = true;
424
425 switch (K) {
426 default:
427 break;
428 case tok::pp_include:
429 case tok::pp_import:
430 case tok::pp_include_next: {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000431 // Save the 'include' token.
Ted Kremenekb978c662009-01-08 01:17:37 +0000432 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000433 // Lex the next token as an include string.
434 L.setParsingPreprocessorDirective(true);
435 L.LexIncludeFilename(Tok);
436 L.setParsingPreprocessorDirective(false);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000437 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000438 if (Tok.is(tok::identifier))
439 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000440
441 break;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000442 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000443 case tok::pp_if:
444 case tok::pp_ifdef:
445 case tok::pp_ifndef: {
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000446 // Add an entry for '#if' and friends. We initially set the target
447 // index to 0. This will get backpatched when we hit #endif.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000448 PPStartCond.push_back(PPCond.size());
Ted Kremenekdad7b342008-12-12 18:31:09 +0000449 PPCond.push_back(std::make_pair(HashOff, 0U));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000450 break;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000451 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000452 case tok::pp_endif: {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000453 // Add an entry for '#endif'. We set the target table index to itself.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000454 // This will later be set to zero when emitting to the PTH file. We
455 // use 0 for uninitialized indices because that is easier to debug.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000456 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000457 // Backpatch the opening '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000458 assert(!PPStartCond.empty());
459 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000460 assert(PPCond[PPStartCond.back()].second == 0);
461 PPCond[PPStartCond.back()].second = index;
462 PPStartCond.pop_back();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000463 // Add the new entry to PPCond.
464 PPCond.push_back(std::make_pair(HashOff, index));
Ted Kremenek726080d2009-02-10 22:43:16 +0000465 EmitToken(Tok);
466
467 // Some files have gibberish on the same line as '#endif'.
468 // Discard these tokens.
469 do L.LexFromRawLexer(Tok); while (!Tok.is(tok::eof) &&
470 !Tok.isAtStartOfLine());
471 // We have the next token in hand.
472 // Don't immediately lex the next one.
473 goto NextToken;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000474 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000475 case tok::pp_elif:
476 case tok::pp_else: {
477 // Add an entry for #elif or #else.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000478 // This serves as both a closing and opening of a conditional block.
479 // This means that its entry will get backpatched later.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000480 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000481 // Backpatch the previous '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000482 assert(!PPStartCond.empty());
483 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000484 assert(PPCond[PPStartCond.back()].second == 0);
485 PPCond[PPStartCond.back()].second = index;
486 PPStartCond.pop_back();
487 // Now add '#elif' as a new block opening.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000488 PPCond.push_back(std::make_pair(HashOff, 0U));
489 PPStartCond.push_back(index);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000490 break;
491 }
Ted Kremenekfb645b62008-12-11 23:36:38 +0000492 }
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000493 }
494
495 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000496 }
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000497 while (Tok.isNot(tok::eof));
Ted Kremenekb978c662009-01-08 01:17:37 +0000498
Ted Kremenekdad7b342008-12-12 18:31:09 +0000499 assert(PPStartCond.empty() && "Error: imblanced preprocessor conditionals.");
Ted Kremenekb978c662009-01-08 01:17:37 +0000500
Ted Kremenekfb645b62008-12-11 23:36:38 +0000501 // Next write out PPCond.
502 Offset PPCondOff = (Offset) Out.tell();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000503
504 // Write out the size of PPCond so that clients can identifer empty tables.
Ted Kremenekb978c662009-01-08 01:17:37 +0000505 Emit32(PPCond.size());
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000506
Ted Kremenekdad7b342008-12-12 18:31:09 +0000507 for (unsigned i = 0, e = PPCond.size(); i!=e; ++i) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000508 Emit32(PPCond[i].first - off);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000509 uint32_t x = PPCond[i].second;
510 assert(x != 0 && "PPCond entry not backpatched.");
511 // Emit zero for #endifs. This allows us to do checking when
512 // we read the PTH file back in.
Ted Kremenekb978c662009-01-08 01:17:37 +0000513 Emit32(x == i ? 0 : x);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000514 }
515
Ted Kremenek277faca2009-01-27 00:01:05 +0000516 return PCHEntry(off, PPCondOff);
Ted Kremenekbe295332009-01-08 02:44:06 +0000517}
518
Ted Kremenek277faca2009-01-27 00:01:05 +0000519Offset PTHWriter::EmitCachedSpellings() {
520 // Write each cached strings to the PTH file.
521 Offset SpellingsOff = Out.tell();
522
523 for (std::vector<llvm::StringMapEntry<OffsetOpt>*>::iterator
524 I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I) {
Ted Kremenekbe295332009-01-08 02:44:06 +0000525
Ted Kremenek277faca2009-01-27 00:01:05 +0000526 const char* data = (*I)->getKeyData();
527 EmitBuf(data, data + (*I)->getKeyLength());
528 Emit8('\0');
Ted Kremenekbe295332009-01-08 02:44:06 +0000529 }
530
Ted Kremenek277faca2009-01-27 00:01:05 +0000531 return SpellingsOff;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000532}
Ted Kremenek85888962008-10-21 00:54:44 +0000533
Ted Kremenekb978c662009-01-08 01:17:37 +0000534void PTHWriter::GeneratePTH() {
Ted Kremeneke1b64982009-01-26 21:43:14 +0000535 // Generate the prologue.
536 Out << "cfe-pth";
Ted Kremenek67d15052009-01-26 21:50:21 +0000537 Emit32(PTHManager::Version);
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000538
539 // Leave 4 words for the prologue.
540 Offset PrologueOffset = Out.tell();
541 for (unsigned i = 0; i < 4 * sizeof(uint32_t); ++i) Emit8(0);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000542
Ted Kremenek85888962008-10-21 00:54:44 +0000543 // Iterate over all the files in SourceManager. Create a lexer
544 // for each file and cache the tokens.
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000545 SourceManager &SM = PP.getSourceManager();
546 const LangOptions &LOpts = PP.getLangOptions();
Ted Kremenek85888962008-10-21 00:54:44 +0000547
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000548 for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
549 E = SM.fileinfo_end(); I != E; ++I) {
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000550 const SrcMgr::ContentCache &C = *I->second;
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000551 const FileEntry *FE = C.Entry;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000552
553 // FIXME: Handle files with non-absolute paths.
554 llvm::sys::Path P(FE->getName());
555 if (!P.isAbsolute())
556 continue;
Ted Kremenek85888962008-10-21 00:54:44 +0000557
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000558 const llvm::MemoryBuffer *B = C.getBuffer();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000559 if (!B) continue;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000560
Chris Lattner2b2453a2009-01-17 06:22:33 +0000561 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
Chris Lattner025c3a62009-01-17 07:35:14 +0000562 Lexer L(FID, SM, LOpts);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000563 PM.insert(FE, LexTokens(L));
Daniel Dunbar31309ab2008-11-26 02:18:33 +0000564 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000565
566 // Write out the identifier table.
Ted Kremenekf1de4642009-02-11 16:06:55 +0000567 const std::pair<Offset,Offset>& IdTableOff = EmitIdentifierTable();
Ted Kremenek85888962008-10-21 00:54:44 +0000568
Ted Kremenekbe295332009-01-08 02:44:06 +0000569 // Write out the cached strings table.
Ted Kremenek277faca2009-01-27 00:01:05 +0000570 Offset SpellingOff = EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000571
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000572 // Write out the file table.
Ted Kremenekb978c662009-01-08 01:17:37 +0000573 Offset FileTableOff = EmitFileTable();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000574
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000575 // Finally, write the prologue.
576 Out.seek(PrologueOffset);
Ted Kremenekb978c662009-01-08 01:17:37 +0000577 Emit32(IdTableOff.first);
Ted Kremenekf1de4642009-02-11 16:06:55 +0000578 Emit32(IdTableOff.second);
Ted Kremenekb978c662009-01-08 01:17:37 +0000579 Emit32(FileTableOff);
Ted Kremenek277faca2009-01-27 00:01:05 +0000580 Emit32(SpellingOff);
Ted Kremenekb978c662009-01-08 01:17:37 +0000581}
582
583void clang::CacheTokens(Preprocessor& PP, const std::string& OutFile) {
584 // Lex through the entire file. This will populate SourceManager with
585 // all of the header information.
586 Token Tok;
587 PP.EnterMainSourceFile();
588 do { PP.Lex(Tok); } while (Tok.isNot(tok::eof));
589
590 // Open up the PTH file.
591 std::string ErrMsg;
592 llvm::raw_fd_ostream Out(OutFile.c_str(), true, ErrMsg);
593
594 if (!ErrMsg.empty()) {
595 llvm::errs() << "PTH error: " << ErrMsg << "\n";
596 return;
597 }
598
599 // Create the PTHWriter and generate the PTH file.
600 PTHWriter PW(Out, PP);
601 PW.GeneratePTH();
Ted Kremenek85888962008-10-21 00:54:44 +0000602}
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000603
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000604//===----------------------------------------------------------------------===//
605
606namespace {
607class VISIBILITY_HIDDEN PCHIdKey {
608public:
609 const IdentifierInfo* II;
610 uint32_t FileOffset;
611};
612
613class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
614public:
615 typedef PCHIdKey* key_type;
616 typedef key_type key_type_ref;
617
618 typedef uint32_t data_type;
619 typedef data_type data_type_ref;
620
621 static unsigned ComputeHash(PCHIdKey* key) {
622 return BernsteinHash(key->II->getName());
623 }
624
625 static std::pair<unsigned,unsigned>
626 EmitKeyDataLength(llvm::raw_ostream& Out, const PCHIdKey* key, uint32_t) {
627 unsigned n = strlen(key->II->getName()) + 1;
628 ::Emit16(Out, n);
629 return std::make_pair(n, sizeof(uint32_t));
630 }
631
632 static void EmitKey(llvm::raw_fd_ostream& Out, PCHIdKey* key, unsigned n) {
633 // Record the location of the key data. This is used when generating
634 // the mapping from persistent IDs to strings.
635 key->FileOffset = Out.tell();
636 Out.write(key->II->getName(), n);
637 }
638
Ted Kremenek337edcd2009-02-12 03:26:59 +0000639 static void EmitData(llvm::raw_ostream& Out, PCHIdKey*, uint32_t pID,
640 unsigned) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000641 ::Emit32(Out, pID);
642 }
643};
644} // end anonymous namespace
645
646/// EmitIdentifierTable - Emits two tables to the PTH file. The first is
647/// a hashtable mapping from identifier strings to persistent IDs. The second
648/// is a straight table mapping from persistent IDs to string data (the
649/// keys of the first table).
650///
651std::pair<Offset,Offset> PTHWriter::EmitIdentifierTable() {
652 // Build two maps:
653 // (1) an inverse map from persistent IDs -> (IdentifierInfo*,Offset)
654 // (2) a map from (IdentifierInfo*, Offset)* -> persistent IDs
655
656 // Note that we use 'calloc', so all the bytes are 0.
657 PCHIdKey* IIDMap = (PCHIdKey*) calloc(idcount, sizeof(PCHIdKey));
658
659 // Create the hashtable.
660 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> IIOffMap;
661
662 // Generate mapping from persistent IDs -> IdentifierInfo*.
663 for (IDMap::iterator I=IM.begin(), E=IM.end(); I!=E; ++I) {
664 // Decrement by 1 because we are using a vector for the lookup and
665 // 0 is reserved for NULL.
666 assert(I->second > 0);
667 assert(I->second-1 < idcount);
668 unsigned idx = I->second-1;
669
670 // Store the mapping from persistent ID to IdentifierInfo*
671 IIDMap[idx].II = I->first;
672
673 // Store the reverse mapping in a hashtable.
674 IIOffMap.insert(&IIDMap[idx], I->second);
675 }
676
677 // Write out the inverse map first. This causes the PCIDKey entries to
678 // record PTH file offsets for the string data. This is used to write
679 // the second table.
680 Offset StringTableOffset = IIOffMap.Emit(Out);
681
682 // Now emit the table mapping from persistent IDs to PTH file offsets.
683 Offset IDOff = Out.tell();
684 Emit32(idcount); // Emit the number of identifiers.
685 for (unsigned i = 0 ; i < idcount; ++i) Emit32(IIDMap[i].FileOffset);
686
687 // Finally, release the inverse map.
688 free(IIDMap);
689
690 return std::make_pair(IDOff, StringTableOffset);
691}
692
693