blob: 0089e0c50ab05ab6dd1f14d6d3180e28f4c97b91 [file] [log] [blame]
Ted Kremeneka4b44dd2009-02-13 19:13:46 +00001//===--- CacheTokens.cpp - Caching of lexer tokens for PTH support --------===//
Ted Kremenek85888962008-10-21 00:54:44 +00002//
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//
Ted Kremeneka4b44dd2009-02-13 19:13:46 +000010// This provides a possible implementation of PTH support for Clang that is
Ted Kremenek85888962008-10-21 00:54:44 +000011// 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 {
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000195class VISIBILITY_HIDDEN PTHEntry {
Ted Kremenekbe295332009-01-08 02:44:06 +0000196 Offset TokenData, PPCondData;
Ted Kremenekbe295332009-01-08 02:44:06 +0000197
198public:
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000199 PTHEntry() {}
Ted Kremenekbe295332009-01-08 02:44:06 +0000200
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000201 PTHEntry(Offset td, Offset ppcd)
Ted Kremenek277faca2009-01-27 00:01:05 +0000202 : 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 Kremeneka4b44dd2009-02-13 19:13:46 +0000208
209class VISIBILITY_HIDDEN PTHEntryKeyVariant {
210 union { const FileEntry* FE; const DirectoryEntry* DE; const char* Path; };
211 enum { IsFE = 0x1, IsDE = 0x2, IsNoExist = 0x0 } Kind;
Ted Kremenekd8c02922009-02-10 22:16:22 +0000212public:
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000213 PTHEntryKeyVariant(const FileEntry *fe) : FE(fe), Kind(IsFE) {}
214 PTHEntryKeyVariant(const DirectoryEntry *de) : DE(de), Kind(IsDE) {}
215 PTHEntryKeyVariant(const char* path) : Path(path), Kind(IsNoExist) {}
216
217 const FileEntry *getFile() const { return Kind == IsFE ? FE : 0; }
218 const DirectoryEntry *getDir() const { return Kind == IsDE ? DE : 0; }
219 const char* getNameOfNonExistantFile() const {
220 return Kind == IsNoExist ? Path : 0;
221 }
222
223 const char* getCString() const {
224 switch (Kind) {
225 case IsFE: return FE->getName();
226 case IsDE: return DE->getName();
227 default: return Path;
228 }
229 }
230
231 unsigned getKind() const { return (unsigned) Kind; }
232
233 void EmitData(llvm::raw_ostream& Out) {
234 switch (Kind) {
235 case IsFE:
236 // Emit stat information.
237 ::Emit32(Out, FE->getInode());
238 ::Emit32(Out, FE->getDevice());
239 ::Emit16(Out, FE->getFileMode());
240 ::Emit64(Out, FE->getModificationTime());
241 ::Emit64(Out, FE->getSize());
242 break;
243 case IsDE:
244 // FIXME
245 default: break;
246 // Emit nothing.
247 }
248 }
249
250 unsigned getRepresentationLength() const {
251 switch (Kind) {
252 case IsFE: return 4 + 4 + 2 + 8 + 8;
253 case IsDE: // FIXME
254 default: return 0;
255 }
256 }
257};
258
259class VISIBILITY_HIDDEN FileEntryPTHEntryInfo {
260public:
261 typedef PTHEntryKeyVariant key_type;
Ted Kremenekd8c02922009-02-10 22:16:22 +0000262 typedef key_type key_type_ref;
263
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000264 typedef PTHEntry data_type;
265 typedef const PTHEntry& data_type_ref;
Ted Kremenekd8c02922009-02-10 22:16:22 +0000266
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000267 static unsigned ComputeHash(PTHEntryKeyVariant V) {
268 return BernsteinHash(V.getCString());
Ted Kremenekd8c02922009-02-10 22:16:22 +0000269 }
270
271 static std::pair<unsigned,unsigned>
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000272 EmitKeyDataLength(llvm::raw_ostream& Out, PTHEntryKeyVariant V,
273 const PTHEntry& E) {
Ted Kremenekd8c02922009-02-10 22:16:22 +0000274
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000275 unsigned n = strlen(V.getCString()) + 1 + 1;
Ted Kremenekd8c02922009-02-10 22:16:22 +0000276 ::Emit16(Out, n);
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000277
278 unsigned m = V.getRepresentationLength() + (V.getFile() ? 4 + 4 : 0);
279 ::Emit8(Out, m);
280
281 return std::make_pair(n, m);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000282 }
283
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000284 static void EmitKey(llvm::raw_ostream& Out, PTHEntryKeyVariant V, unsigned n){
285 // Emit the entry kind.
286 ::Emit8(Out, (unsigned) V.getKind());
287 // Emit the string.
288 Out.write(V.getCString(), n - 1);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000289 }
290
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000291 static void EmitData(llvm::raw_ostream& Out, PTHEntryKeyVariant V,
292 const PTHEntry& E, unsigned) {
293
294
295 // For file entries emit the offsets into the PTH file for token data
296 // and the preprocessor blocks table.
297 if (V.getFile()) {
298 ::Emit32(Out, E.getTokenOffset());
299 ::Emit32(Out, E.getPPCondTableOffset());
300 }
301
302 // Emit any other data associated with the key (i.e., stat information).
303 V.EmitData(Out);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000304 }
305};
306
Ted Kremenek277faca2009-01-27 00:01:05 +0000307class OffsetOpt {
308 bool valid;
309 Offset off;
310public:
311 OffsetOpt() : valid(false) {}
312 bool hasOffset() const { return valid; }
313 Offset getOffset() const { assert(valid); return off; }
314 void setOffset(Offset o) { off = o; valid = true; }
Ted Kremenekbe295332009-01-08 02:44:06 +0000315};
316} // end anonymous namespace
317
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000318typedef OnDiskChainedHashTableGenerator<FileEntryPTHEntryInfo> PTHMap;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000319typedef llvm::DenseMap<const IdentifierInfo*,uint32_t> IDMap;
Ted Kremenek277faca2009-01-27 00:01:05 +0000320typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy;
Ted Kremenek85888962008-10-21 00:54:44 +0000321
Ted Kremenekb978c662009-01-08 01:17:37 +0000322namespace {
323class VISIBILITY_HIDDEN PTHWriter {
324 IDMap IM;
325 llvm::raw_fd_ostream& Out;
326 Preprocessor& PP;
327 uint32_t idcount;
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000328 PTHMap PM;
Ted Kremenekbe295332009-01-08 02:44:06 +0000329 CachedStrsTy CachedStrs;
Ted Kremenek277faca2009-01-27 00:01:05 +0000330 Offset CurStrOffset;
331 std::vector<llvm::StringMapEntry<OffsetOpt>*> StrEntries;
Ted Kremenek8f174e12008-12-23 02:52:12 +0000332
Ted Kremenekb978c662009-01-08 01:17:37 +0000333 //// Get the persistent id for the given IdentifierInfo*.
334 uint32_t ResolveID(const IdentifierInfo* II);
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000335
Ted Kremenekb978c662009-01-08 01:17:37 +0000336 /// Emit a token to the PTH file.
337 void EmitToken(const Token& T);
338
339 void Emit8(uint32_t V) {
340 Out << (unsigned char)(V);
341 }
342
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000343 void Emit16(uint32_t V) { ::Emit16(Out, V); }
Ted Kremenekb978c662009-01-08 01:17:37 +0000344
345 void Emit24(uint32_t V) {
346 Out << (unsigned char)(V);
347 Out << (unsigned char)(V >> 8);
348 Out << (unsigned char)(V >> 16);
349 assert((V >> 24) == 0);
350 }
351
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000352 void Emit32(uint32_t V) { ::Emit32(Out, V); }
353
Ted Kremenekb978c662009-01-08 01:17:37 +0000354 void EmitBuf(const char* I, const char* E) {
355 for ( ; I != E ; ++I) Out << *I;
356 }
357
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000358 /// EmitIdentifierTable - Emits two tables to the PTH file. The first is
359 /// a hashtable mapping from identifier strings to persistent IDs.
360 /// The second is a straight table mapping from persistent IDs to string data
361 /// (the keys of the first table).
Ted Kremenekf1de4642009-02-11 16:06:55 +0000362 std::pair<Offset, Offset> EmitIdentifierTable();
363
364 /// EmitFileTable - Emit a table mapping from file name strings to PTH
365 /// token data.
366 Offset EmitFileTable() { return PM.Emit(Out); }
367
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000368 PTHEntry LexTokens(Lexer& L);
Ted Kremenek277faca2009-01-27 00:01:05 +0000369 Offset EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000370
Ted Kremenekb978c662009-01-08 01:17:37 +0000371public:
372 PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp)
Ted Kremenek277faca2009-01-27 00:01:05 +0000373 : Out(out), PP(pp), idcount(0), CurStrOffset(0) {}
Ted Kremenekb978c662009-01-08 01:17:37 +0000374
375 void GeneratePTH();
376};
377} // end anonymous namespace
378
379uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) {
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000380 // Null IdentifierInfo's map to the persistent ID 0.
381 if (!II)
382 return 0;
383
Ted Kremenek85888962008-10-21 00:54:44 +0000384 IDMap::iterator I = IM.find(II);
385
386 if (I == IM.end()) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000387 IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL.
388 return idcount;
Ted Kremenek85888962008-10-21 00:54:44 +0000389 }
390
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000391 return I->second; // We've already added 1.
Ted Kremenek85888962008-10-21 00:54:44 +0000392}
393
Ted Kremenekb978c662009-01-08 01:17:37 +0000394void PTHWriter::EmitToken(const Token& T) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000395 Emit32(((uint32_t) T.getKind()) |
396 (((uint32_t) T.getFlags()) << 8) |
397 (((uint32_t) T.getLength()) << 16));
Ted Kremenek277faca2009-01-27 00:01:05 +0000398
Chris Lattner47246be2009-01-26 19:29:26 +0000399 // Literals (strings, numbers, characters) get cached spellings.
400 if (T.isLiteral()) {
401 // FIXME: This uses the slow getSpelling(). Perhaps we do better
402 // in the future? This only slows down PTH generation.
403 const std::string &spelling = PP.getSpelling(T);
404 const char* s = spelling.c_str();
405
406 // Get the string entry.
Ted Kremenek277faca2009-01-27 00:01:05 +0000407 llvm::StringMapEntry<OffsetOpt> *E =
408 &CachedStrs.GetOrCreateValue(s, s+spelling.size());
409
410 if (!E->getValue().hasOffset()) {
411 E->getValue().setOffset(CurStrOffset);
412 StrEntries.push_back(E);
413 CurStrOffset += spelling.size() + 1;
414 }
415
416 Emit32(E->getValue().getOffset());
Ted Kremenekb978c662009-01-08 01:17:37 +0000417 }
Ted Kremenek277faca2009-01-27 00:01:05 +0000418 else
419 Emit32(ResolveID(T.getIdentifierInfo()));
420
Chris Lattner52c29082009-01-27 06:27:13 +0000421 Emit32(PP.getSourceManager().getFileOffset(T.getLocation()));
Ted Kremenek85888962008-10-21 00:54:44 +0000422}
423
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000424PTHEntry PTHWriter::LexTokens(Lexer& L) {
Ted Kremenek7b78b7c2009-01-19 23:13:15 +0000425 // Pad 0's so that we emit tokens to a 4-byte alignment.
426 // This speed up reading them back in.
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000427 Pad(Out, 4);
428 Offset off = (Offset) Out.tell();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000429
430 // Keep track of matching '#if' ... '#endif'.
431 typedef std::vector<std::pair<Offset, unsigned> > PPCondTable;
432 PPCondTable PPCond;
Ted Kremenekdad7b342008-12-12 18:31:09 +0000433 std::vector<unsigned> PPStartCond;
Ted Kremeneke5680f32008-12-23 01:30:52 +0000434 bool ParsingPreprocessorDirective = false;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000435 Token Tok;
436
437 do {
438 L.LexFromRawLexer(Tok);
Ted Kremenek726080d2009-02-10 22:43:16 +0000439 NextToken:
440
Ted Kremeneke5680f32008-12-23 01:30:52 +0000441 if ((Tok.isAtStartOfLine() || Tok.is(tok::eof)) &&
442 ParsingPreprocessorDirective) {
443 // Insert an eom token into the token cache. It has the same
444 // position as the next token that is not on the same line as the
445 // preprocessor directive. Observe that we continue processing
446 // 'Tok' when we exit this branch.
447 Token Tmp = Tok;
448 Tmp.setKind(tok::eom);
449 Tmp.clearFlag(Token::StartOfLine);
450 Tmp.setIdentifierInfo(0);
Ted Kremenekb978c662009-01-08 01:17:37 +0000451 EmitToken(Tmp);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000452 ParsingPreprocessorDirective = false;
453 }
454
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000455 if (Tok.is(tok::identifier)) {
456 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000457 EmitToken(Tok);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000458 continue;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000459 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000460
461 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000462 // Special processing for #include. Store the '#' token and lex
463 // the next token.
Ted Kremeneke5680f32008-12-23 01:30:52 +0000464 assert(!ParsingPreprocessorDirective);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000465 Offset HashOff = (Offset) Out.tell();
Ted Kremenekb978c662009-01-08 01:17:37 +0000466 EmitToken(Tok);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000467
468 // Get the next token.
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000469 L.LexFromRawLexer(Tok);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000470
471 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000472
473 // Did we see 'include'/'import'/'include_next'?
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000474 if (!Tok.is(tok::identifier)) {
475 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000476 continue;
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000477 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000478
479 IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok);
480 Tok.setIdentifierInfo(II);
481 tok::PPKeywordKind K = II->getPPKeywordID();
482
Ted Kremeneke5680f32008-12-23 01:30:52 +0000483 assert(K != tok::pp_not_keyword);
484 ParsingPreprocessorDirective = true;
485
486 switch (K) {
487 default:
488 break;
489 case tok::pp_include:
490 case tok::pp_import:
491 case tok::pp_include_next: {
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000492 // Save the 'include' token.
Ted Kremenekb978c662009-01-08 01:17:37 +0000493 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000494 // Lex the next token as an include string.
495 L.setParsingPreprocessorDirective(true);
496 L.LexIncludeFilename(Tok);
497 L.setParsingPreprocessorDirective(false);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000498 assert(!Tok.isAtStartOfLine());
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000499 if (Tok.is(tok::identifier))
500 Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000501
502 break;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000503 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000504 case tok::pp_if:
505 case tok::pp_ifdef:
506 case tok::pp_ifndef: {
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000507 // Add an entry for '#if' and friends. We initially set the target
508 // index to 0. This will get backpatched when we hit #endif.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000509 PPStartCond.push_back(PPCond.size());
Ted Kremenekdad7b342008-12-12 18:31:09 +0000510 PPCond.push_back(std::make_pair(HashOff, 0U));
Ted Kremeneke5680f32008-12-23 01:30:52 +0000511 break;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000512 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000513 case tok::pp_endif: {
Ted Kremenekfb645b62008-12-11 23:36:38 +0000514 // Add an entry for '#endif'. We set the target table index to itself.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000515 // This will later be set to zero when emitting to the PTH file. We
516 // use 0 for uninitialized indices because that is easier to debug.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000517 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000518 // Backpatch the opening '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000519 assert(!PPStartCond.empty());
520 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000521 assert(PPCond[PPStartCond.back()].second == 0);
522 PPCond[PPStartCond.back()].second = index;
523 PPStartCond.pop_back();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000524 // Add the new entry to PPCond.
525 PPCond.push_back(std::make_pair(HashOff, index));
Ted Kremenek726080d2009-02-10 22:43:16 +0000526 EmitToken(Tok);
527
528 // Some files have gibberish on the same line as '#endif'.
529 // Discard these tokens.
530 do L.LexFromRawLexer(Tok); while (!Tok.is(tok::eof) &&
531 !Tok.isAtStartOfLine());
532 // We have the next token in hand.
533 // Don't immediately lex the next one.
534 goto NextToken;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000535 }
Ted Kremeneke5680f32008-12-23 01:30:52 +0000536 case tok::pp_elif:
537 case tok::pp_else: {
538 // Add an entry for #elif or #else.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000539 // This serves as both a closing and opening of a conditional block.
540 // This means that its entry will get backpatched later.
Ted Kremenekfb645b62008-12-11 23:36:38 +0000541 unsigned index = PPCond.size();
Ted Kremenekfb645b62008-12-11 23:36:38 +0000542 // Backpatch the previous '#if' entry.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000543 assert(!PPStartCond.empty());
544 assert(PPCond.size() > PPStartCond.back());
Ted Kremenekfb645b62008-12-11 23:36:38 +0000545 assert(PPCond[PPStartCond.back()].second == 0);
546 PPCond[PPStartCond.back()].second = index;
547 PPStartCond.pop_back();
548 // Now add '#elif' as a new block opening.
Ted Kremenekdad7b342008-12-12 18:31:09 +0000549 PPCond.push_back(std::make_pair(HashOff, 0U));
550 PPStartCond.push_back(index);
Ted Kremeneke5680f32008-12-23 01:30:52 +0000551 break;
552 }
Ted Kremenekfb645b62008-12-11 23:36:38 +0000553 }
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000554 }
555
556 EmitToken(Tok);
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000557 }
Ted Kremeneke4f6b1e2009-02-10 22:27:09 +0000558 while (Tok.isNot(tok::eof));
Ted Kremenekb978c662009-01-08 01:17:37 +0000559
Ted Kremenekdad7b342008-12-12 18:31:09 +0000560 assert(PPStartCond.empty() && "Error: imblanced preprocessor conditionals.");
Ted Kremenekb978c662009-01-08 01:17:37 +0000561
Ted Kremenekfb645b62008-12-11 23:36:38 +0000562 // Next write out PPCond.
563 Offset PPCondOff = (Offset) Out.tell();
Ted Kremenekdad7b342008-12-12 18:31:09 +0000564
565 // Write out the size of PPCond so that clients can identifer empty tables.
Ted Kremenekb978c662009-01-08 01:17:37 +0000566 Emit32(PPCond.size());
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000567
Ted Kremenekdad7b342008-12-12 18:31:09 +0000568 for (unsigned i = 0, e = PPCond.size(); i!=e; ++i) {
Ted Kremenekb978c662009-01-08 01:17:37 +0000569 Emit32(PPCond[i].first - off);
Ted Kremenekdad7b342008-12-12 18:31:09 +0000570 uint32_t x = PPCond[i].second;
571 assert(x != 0 && "PPCond entry not backpatched.");
572 // Emit zero for #endifs. This allows us to do checking when
573 // we read the PTH file back in.
Ted Kremenekb978c662009-01-08 01:17:37 +0000574 Emit32(x == i ? 0 : x);
Ted Kremenekfb645b62008-12-11 23:36:38 +0000575 }
576
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000577 return PTHEntry(off, PPCondOff);
Ted Kremenekbe295332009-01-08 02:44:06 +0000578}
579
Ted Kremenek277faca2009-01-27 00:01:05 +0000580Offset PTHWriter::EmitCachedSpellings() {
581 // Write each cached strings to the PTH file.
582 Offset SpellingsOff = Out.tell();
583
584 for (std::vector<llvm::StringMapEntry<OffsetOpt>*>::iterator
585 I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I) {
Ted Kremenekbe295332009-01-08 02:44:06 +0000586
Ted Kremenek277faca2009-01-27 00:01:05 +0000587 const char* data = (*I)->getKeyData();
588 EmitBuf(data, data + (*I)->getKeyLength());
589 Emit8('\0');
Ted Kremenekbe295332009-01-08 02:44:06 +0000590 }
591
Ted Kremenek277faca2009-01-27 00:01:05 +0000592 return SpellingsOff;
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000593}
Ted Kremenek85888962008-10-21 00:54:44 +0000594
Ted Kremenekb978c662009-01-08 01:17:37 +0000595void PTHWriter::GeneratePTH() {
Ted Kremeneke1b64982009-01-26 21:43:14 +0000596 // Generate the prologue.
597 Out << "cfe-pth";
Ted Kremenek67d15052009-01-26 21:50:21 +0000598 Emit32(PTHManager::Version);
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000599
600 // Leave 4 words for the prologue.
601 Offset PrologueOffset = Out.tell();
602 for (unsigned i = 0; i < 4 * sizeof(uint32_t); ++i) Emit8(0);
Ted Kremeneke1b64982009-01-26 21:43:14 +0000603
Ted Kremenek85888962008-10-21 00:54:44 +0000604 // Iterate over all the files in SourceManager. Create a lexer
605 // for each file and cache the tokens.
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000606 SourceManager &SM = PP.getSourceManager();
607 const LangOptions &LOpts = PP.getLangOptions();
Ted Kremenek85888962008-10-21 00:54:44 +0000608
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000609 for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
610 E = SM.fileinfo_end(); I != E; ++I) {
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000611 const SrcMgr::ContentCache &C = *I->second;
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000612 const FileEntry *FE = C.Entry;
Ted Kremenekfc7e2ea2008-12-02 19:44:08 +0000613
614 // FIXME: Handle files with non-absolute paths.
615 llvm::sys::Path P(FE->getName());
616 if (!P.isAbsolute())
617 continue;
Ted Kremenek85888962008-10-21 00:54:44 +0000618
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000619 const llvm::MemoryBuffer *B = C.getBuffer();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000620 if (!B) continue;
Ted Kremenekfb645b62008-12-11 23:36:38 +0000621
Chris Lattner2b2453a2009-01-17 06:22:33 +0000622 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
Chris Lattner025c3a62009-01-17 07:35:14 +0000623 Lexer L(FID, SM, LOpts);
Ted Kremenekd8c02922009-02-10 22:16:22 +0000624 PM.insert(FE, LexTokens(L));
Daniel Dunbar31309ab2008-11-26 02:18:33 +0000625 }
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000626
627 // Write out the identifier table.
Ted Kremenekf1de4642009-02-11 16:06:55 +0000628 const std::pair<Offset,Offset>& IdTableOff = EmitIdentifierTable();
Ted Kremenek85888962008-10-21 00:54:44 +0000629
Ted Kremenekbe295332009-01-08 02:44:06 +0000630 // Write out the cached strings table.
Ted Kremenek277faca2009-01-27 00:01:05 +0000631 Offset SpellingOff = EmitCachedSpellings();
Ted Kremenekbe295332009-01-08 02:44:06 +0000632
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000633 // Write out the file table.
Ted Kremenekb978c662009-01-08 01:17:37 +0000634 Offset FileTableOff = EmitFileTable();
Ted Kremeneka3d764c2008-11-26 03:36:26 +0000635
Ted Kremeneka4bd8eb2009-02-11 23:34:32 +0000636 // Finally, write the prologue.
637 Out.seek(PrologueOffset);
Ted Kremenekb978c662009-01-08 01:17:37 +0000638 Emit32(IdTableOff.first);
Ted Kremenekf1de4642009-02-11 16:06:55 +0000639 Emit32(IdTableOff.second);
Ted Kremenekb978c662009-01-08 01:17:37 +0000640 Emit32(FileTableOff);
Ted Kremenek277faca2009-01-27 00:01:05 +0000641 Emit32(SpellingOff);
Ted Kremenekb978c662009-01-08 01:17:37 +0000642}
643
644void clang::CacheTokens(Preprocessor& PP, const std::string& OutFile) {
645 // Lex through the entire file. This will populate SourceManager with
646 // all of the header information.
647 Token Tok;
648 PP.EnterMainSourceFile();
649 do { PP.Lex(Tok); } while (Tok.isNot(tok::eof));
650
651 // Open up the PTH file.
652 std::string ErrMsg;
653 llvm::raw_fd_ostream Out(OutFile.c_str(), true, ErrMsg);
654
655 if (!ErrMsg.empty()) {
656 llvm::errs() << "PTH error: " << ErrMsg << "\n";
657 return;
658 }
659
660 // Create the PTHWriter and generate the PTH file.
661 PTHWriter PW(Out, PP);
662 PW.GeneratePTH();
Ted Kremenek85888962008-10-21 00:54:44 +0000663}
Ted Kremeneke0ea5dc2009-02-10 01:06:17 +0000664
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000665//===----------------------------------------------------------------------===//
666
667namespace {
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000668class VISIBILITY_HIDDEN PTHIdKey {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000669public:
670 const IdentifierInfo* II;
671 uint32_t FileOffset;
672};
673
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000674class VISIBILITY_HIDDEN PTHIdentifierTableTrait {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000675public:
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000676 typedef PTHIdKey* key_type;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000677 typedef key_type key_type_ref;
678
679 typedef uint32_t data_type;
680 typedef data_type data_type_ref;
681
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000682 static unsigned ComputeHash(PTHIdKey* key) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000683 return BernsteinHash(key->II->getName());
684 }
685
686 static std::pair<unsigned,unsigned>
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000687 EmitKeyDataLength(llvm::raw_ostream& Out, const PTHIdKey* key, uint32_t) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000688 unsigned n = strlen(key->II->getName()) + 1;
689 ::Emit16(Out, n);
690 return std::make_pair(n, sizeof(uint32_t));
691 }
692
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000693 static void EmitKey(llvm::raw_fd_ostream& Out, PTHIdKey* key, unsigned n) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000694 // Record the location of the key data. This is used when generating
695 // the mapping from persistent IDs to strings.
696 key->FileOffset = Out.tell();
697 Out.write(key->II->getName(), n);
698 }
699
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000700 static void EmitData(llvm::raw_ostream& Out, PTHIdKey*, uint32_t pID,
Ted Kremenek337edcd2009-02-12 03:26:59 +0000701 unsigned) {
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000702 ::Emit32(Out, pID);
703 }
704};
705} // end anonymous namespace
706
707/// EmitIdentifierTable - Emits two tables to the PTH file. The first is
708/// a hashtable mapping from identifier strings to persistent IDs. The second
709/// is a straight table mapping from persistent IDs to string data (the
710/// keys of the first table).
711///
712std::pair<Offset,Offset> PTHWriter::EmitIdentifierTable() {
713 // Build two maps:
714 // (1) an inverse map from persistent IDs -> (IdentifierInfo*,Offset)
715 // (2) a map from (IdentifierInfo*, Offset)* -> persistent IDs
716
717 // Note that we use 'calloc', so all the bytes are 0.
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000718 PTHIdKey* IIDMap = (PTHIdKey*) calloc(idcount, sizeof(PTHIdKey));
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000719
720 // Create the hashtable.
Ted Kremeneka4b44dd2009-02-13 19:13:46 +0000721 OnDiskChainedHashTableGenerator<PTHIdentifierTableTrait> IIOffMap;
Ted Kremenek7e3a0042009-02-11 21:29:16 +0000722
723 // Generate mapping from persistent IDs -> IdentifierInfo*.
724 for (IDMap::iterator I=IM.begin(), E=IM.end(); I!=E; ++I) {
725 // Decrement by 1 because we are using a vector for the lookup and
726 // 0 is reserved for NULL.
727 assert(I->second > 0);
728 assert(I->second-1 < idcount);
729 unsigned idx = I->second-1;
730
731 // Store the mapping from persistent ID to IdentifierInfo*
732 IIDMap[idx].II = I->first;
733
734 // Store the reverse mapping in a hashtable.
735 IIOffMap.insert(&IIDMap[idx], I->second);
736 }
737
738 // Write out the inverse map first. This causes the PCIDKey entries to
739 // record PTH file offsets for the string data. This is used to write
740 // the second table.
741 Offset StringTableOffset = IIOffMap.Emit(Out);
742
743 // Now emit the table mapping from persistent IDs to PTH file offsets.
744 Offset IDOff = Out.tell();
745 Emit32(idcount); // Emit the number of identifiers.
746 for (unsigned i = 0 ; i < idcount; ++i) Emit32(IIDMap[i].FileOffset);
747
748 // Finally, release the inverse map.
749 free(IIDMap);
750
751 return std::make_pair(IDOff, StringTableOffset);
752}
753
754