blob: 21a714999b0c89cac5c860918e26b639203d4a0b [file] [log] [blame]
Douglas Gregor5e306b12013-01-23 22:38:11 +00001//===--- GlobalModuleIndex.cpp - Global Module Index ------------*- C++ -*-===//
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 GlobalModuleIndex class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTReaderInternals.h"
15#include "clang/Basic/FileManager.h"
Ben Langmuirbeee15e2014-04-14 18:00:01 +000016#include "clang/Lex/HeaderSearch.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000017#include "clang/Serialization/ASTBitCodes.h"
18#include "clang/Serialization/GlobalModuleIndex.h"
Douglas Gregor603cd862013-03-22 18:50:14 +000019#include "clang/Serialization/Module.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000020#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/MapVector.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/Bitcode/BitstreamReader.h"
25#include "llvm/Bitcode/BitstreamWriter.h"
Douglas Gregor8ec343c2013-01-23 22:45:24 +000026#include "llvm/Support/FileSystem.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000027#include "llvm/Support/LockFileManager.h"
28#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000029#include "llvm/Support/OnDiskHashTable.h"
Rafael Espindola552c1692013-06-11 22:15:02 +000030#include "llvm/Support/Path.h"
NAKAMURA Takumif0add232013-01-25 01:47:07 +000031#include <cstdio>
Douglas Gregor5e306b12013-01-23 22:38:11 +000032using namespace clang;
33using namespace serialization;
34
35//----------------------------------------------------------------------------//
36// Shared constants
37//----------------------------------------------------------------------------//
38namespace {
39 enum {
40 /// \brief The block containing the index.
41 GLOBAL_INDEX_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID
42 };
43
44 /// \brief Describes the record types in the index.
45 enum IndexRecordTypes {
46 /// \brief Contains version information and potentially other metadata,
47 /// used to determine if we can read this global index file.
Douglas Gregore060e572013-01-25 01:03:03 +000048 INDEX_METADATA,
Douglas Gregor5e306b12013-01-23 22:38:11 +000049 /// \brief Describes a module, including its file name and dependencies.
50 MODULE,
51 /// \brief The index for identifiers.
52 IDENTIFIER_INDEX
53 };
54}
55
56/// \brief The name of the global index file.
57static const char * const IndexFileName = "modules.idx";
58
59/// \brief The global index file version.
60static const unsigned CurrentVersion = 1;
61
62//----------------------------------------------------------------------------//
Douglas Gregore060e572013-01-25 01:03:03 +000063// Global module index reader.
64//----------------------------------------------------------------------------//
65
66namespace {
67
68/// \brief Trait used to read the identifier index from the on-disk hash
69/// table.
70class IdentifierIndexReaderTrait {
71public:
72 typedef StringRef external_key_type;
73 typedef StringRef internal_key_type;
74 typedef SmallVector<unsigned, 2> data_type;
Justin Bogner25463f12014-04-18 20:27:24 +000075 typedef unsigned hash_value_type;
76 typedef unsigned offset_type;
Douglas Gregore060e572013-01-25 01:03:03 +000077
78 static bool EqualKey(const internal_key_type& a, const internal_key_type& b) {
79 return a == b;
80 }
81
Justin Bogner25463f12014-04-18 20:27:24 +000082 static hash_value_type ComputeHash(const internal_key_type& a) {
Douglas Gregore060e572013-01-25 01:03:03 +000083 return llvm::HashString(a);
84 }
85
86 static std::pair<unsigned, unsigned>
87 ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +000088 using namespace llvm::support;
89 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
90 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Douglas Gregore060e572013-01-25 01:03:03 +000091 return std::make_pair(KeyLen, DataLen);
92 }
93
94 static const internal_key_type&
95 GetInternalKey(const external_key_type& x) { return x; }
96
97 static const external_key_type&
98 GetExternalKey(const internal_key_type& x) { return x; }
99
100 static internal_key_type ReadKey(const unsigned char* d, unsigned n) {
101 return StringRef((const char *)d, n);
102 }
103
104 static data_type ReadData(const internal_key_type& k,
105 const unsigned char* d,
106 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000107 using namespace llvm::support;
Douglas Gregore060e572013-01-25 01:03:03 +0000108
109 data_type Result;
110 while (DataLen > 0) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000111 unsigned ID = endian::readNext<uint32_t, little, unaligned>(d);
Douglas Gregore060e572013-01-25 01:03:03 +0000112 Result.push_back(ID);
113 DataLen -= 4;
114 }
115
116 return Result;
117 }
118};
119
Justin Bognerbb094f02014-04-18 19:57:06 +0000120typedef llvm::OnDiskIterableChainedHashTable<IdentifierIndexReaderTrait>
Justin Bognerda4e6502014-04-14 16:34:29 +0000121 IdentifierIndexTable;
Douglas Gregore060e572013-01-25 01:03:03 +0000122
Douglas Gregore060e572013-01-25 01:03:03 +0000123}
124
Douglas Gregor7029ce12013-03-19 00:28:20 +0000125GlobalModuleIndex::GlobalModuleIndex(llvm::MemoryBuffer *Buffer,
Douglas Gregore060e572013-01-25 01:03:03 +0000126 llvm::BitstreamCursor Cursor)
Douglas Gregor603cd862013-03-22 18:50:14 +0000127 : Buffer(Buffer), IdentifierIndex(),
Douglas Gregor7211ac12013-01-25 23:32:03 +0000128 NumIdentifierLookups(), NumIdentifierLookupHits()
Douglas Gregore060e572013-01-25 01:03:03 +0000129{
Douglas Gregore060e572013-01-25 01:03:03 +0000130 // Read the global index.
Douglas Gregore060e572013-01-25 01:03:03 +0000131 bool InGlobalIndexBlock = false;
132 bool Done = false;
Douglas Gregore060e572013-01-25 01:03:03 +0000133 while (!Done) {
134 llvm::BitstreamEntry Entry = Cursor.advance();
135
136 switch (Entry.Kind) {
137 case llvm::BitstreamEntry::Error:
138 return;
139
140 case llvm::BitstreamEntry::EndBlock:
141 if (InGlobalIndexBlock) {
142 InGlobalIndexBlock = false;
143 Done = true;
144 continue;
145 }
146 return;
147
148
149 case llvm::BitstreamEntry::Record:
150 // Entries in the global index block are handled below.
151 if (InGlobalIndexBlock)
152 break;
153
154 return;
155
156 case llvm::BitstreamEntry::SubBlock:
157 if (!InGlobalIndexBlock && Entry.ID == GLOBAL_INDEX_BLOCK_ID) {
158 if (Cursor.EnterSubBlock(GLOBAL_INDEX_BLOCK_ID))
159 return;
160
161 InGlobalIndexBlock = true;
162 } else if (Cursor.SkipBlock()) {
163 return;
164 }
165 continue;
166 }
167
168 SmallVector<uint64_t, 64> Record;
169 StringRef Blob;
170 switch ((IndexRecordTypes)Cursor.readRecord(Entry.ID, Record, &Blob)) {
171 case INDEX_METADATA:
172 // Make sure that the version matches.
173 if (Record.size() < 1 || Record[0] != CurrentVersion)
174 return;
175 break;
176
177 case MODULE: {
178 unsigned Idx = 0;
179 unsigned ID = Record[Idx++];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000180
181 // Make room for this module's information.
182 if (ID == Modules.size())
183 Modules.push_back(ModuleInfo());
184 else
185 Modules.resize(ID + 1);
186
187 // Size/modification time for this module file at the time the
188 // global index was built.
189 Modules[ID].Size = Record[Idx++];
190 Modules[ID].ModTime = Record[Idx++];
Douglas Gregore060e572013-01-25 01:03:03 +0000191
192 // File name.
193 unsigned NameLen = Record[Idx++];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000194 Modules[ID].FileName.assign(Record.begin() + Idx,
195 Record.begin() + Idx + NameLen);
Douglas Gregore060e572013-01-25 01:03:03 +0000196 Idx += NameLen;
197
198 // Dependencies
199 unsigned NumDeps = Record[Idx++];
Douglas Gregor7029ce12013-03-19 00:28:20 +0000200 Modules[ID].Dependencies.insert(Modules[ID].Dependencies.end(),
201 Record.begin() + Idx,
202 Record.begin() + Idx + NumDeps);
203 Idx += NumDeps;
Douglas Gregore060e572013-01-25 01:03:03 +0000204
Douglas Gregor7029ce12013-03-19 00:28:20 +0000205 // Make sure we're at the end of the record.
206 assert(Idx == Record.size() && "More module info?");
Douglas Gregor603cd862013-03-22 18:50:14 +0000207
208 // Record this module as an unresolved module.
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000209 // FIXME: this doesn't work correctly for module names containing path
210 // separators.
211 StringRef ModuleName = llvm::sys::path::stem(Modules[ID].FileName);
212 // Remove the -<hash of ModuleMapPath>
213 ModuleName = ModuleName.rsplit('-').first;
214 UnresolvedModules[ModuleName] = ID;
Douglas Gregore060e572013-01-25 01:03:03 +0000215 break;
216 }
217
218 case IDENTIFIER_INDEX:
219 // Wire up the identifier index.
220 if (Record[0]) {
221 IdentifierIndex = IdentifierIndexTable::Create(
Justin Bognerda4e6502014-04-14 16:34:29 +0000222 (const unsigned char *)Blob.data() + Record[0],
223 (const unsigned char *)Blob.data() + sizeof(uint32_t),
224 (const unsigned char *)Blob.data(), IdentifierIndexReaderTrait());
Douglas Gregore060e572013-01-25 01:03:03 +0000225 }
226 break;
227 }
228 }
Douglas Gregore060e572013-01-25 01:03:03 +0000229}
230
231GlobalModuleIndex::~GlobalModuleIndex() { }
232
233std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode>
Douglas Gregor7029ce12013-03-19 00:28:20 +0000234GlobalModuleIndex::readIndex(StringRef Path) {
Douglas Gregore060e572013-01-25 01:03:03 +0000235 // Load the index file, if it's there.
236 llvm::SmallString<128> IndexPath;
237 IndexPath += Path;
238 llvm::sys::path::append(IndexPath, IndexFileName);
239
Ahmed Charlesb8984322014-03-07 20:03:18 +0000240 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Rafael Espindola1a3605c2013-10-25 19:00:49 +0000241 if (llvm::MemoryBuffer::getFile(IndexPath.c_str(), Buffer) !=
242 llvm::errc::success)
Douglas Gregore060e572013-01-25 01:03:03 +0000243 return std::make_pair((GlobalModuleIndex *)0, EC_NotFound);
244
245 /// \brief The bitstream reader from which we'll read the AST file.
246 llvm::BitstreamReader Reader((const unsigned char *)Buffer->getBufferStart(),
247 (const unsigned char *)Buffer->getBufferEnd());
248
249 /// \brief The main bitstream cursor for the main block.
250 llvm::BitstreamCursor Cursor(Reader);
251
252 // Sniff for the signature.
253 if (Cursor.Read(8) != 'B' ||
254 Cursor.Read(8) != 'C' ||
255 Cursor.Read(8) != 'G' ||
256 Cursor.Read(8) != 'I') {
257 return std::make_pair((GlobalModuleIndex *)0, EC_IOError);
258 }
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000259
260 return std::make_pair(new GlobalModuleIndex(Buffer.release(), Cursor),
261 EC_None);
Douglas Gregore060e572013-01-25 01:03:03 +0000262}
263
Douglas Gregor7029ce12013-03-19 00:28:20 +0000264void
265GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
Douglas Gregore060e572013-01-25 01:03:03 +0000266 ModuleFiles.clear();
267 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000268 if (ModuleFile *MF = Modules[I].File)
269 ModuleFiles.push_back(MF);
Douglas Gregore060e572013-01-25 01:03:03 +0000270 }
271}
272
273void GlobalModuleIndex::getModuleDependencies(
Douglas Gregor7029ce12013-03-19 00:28:20 +0000274 ModuleFile *File,
275 SmallVectorImpl<ModuleFile *> &Dependencies) {
Douglas Gregore060e572013-01-25 01:03:03 +0000276 // Look for information about this module file.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000277 llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
278 = ModulesByFile.find(File);
Douglas Gregore060e572013-01-25 01:03:03 +0000279 if (Known == ModulesByFile.end())
280 return;
281
282 // Record dependencies.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000283 Dependencies.clear();
284 ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
285 for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000286 if (ModuleFile *MF = Modules[I].File)
Douglas Gregor7029ce12013-03-19 00:28:20 +0000287 Dependencies.push_back(MF);
288 }
Douglas Gregore060e572013-01-25 01:03:03 +0000289}
290
Douglas Gregor7211ac12013-01-25 23:32:03 +0000291bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
292 Hits.clear();
Douglas Gregore060e572013-01-25 01:03:03 +0000293
294 // If there's no identifier index, there is nothing we can do.
295 if (!IdentifierIndex)
296 return false;
297
298 // Look into the identifier index.
299 ++NumIdentifierLookups;
300 IdentifierIndexTable &Table
301 = *static_cast<IdentifierIndexTable *>(IdentifierIndex);
302 IdentifierIndexTable::iterator Known = Table.find(Name);
303 if (Known == Table.end()) {
304 return true;
305 }
306
307 SmallVector<unsigned, 2> ModuleIDs = *Known;
308 for (unsigned I = 0, N = ModuleIDs.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000309 if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
310 Hits.insert(MF);
Douglas Gregore060e572013-01-25 01:03:03 +0000311 }
312
313 ++NumIdentifierLookupHits;
314 return true;
315}
316
Douglas Gregor603cd862013-03-22 18:50:14 +0000317bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
318 // Look for the module in the global module index based on the module name.
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000319 StringRef Name = File->ModuleName;
Douglas Gregor603cd862013-03-22 18:50:14 +0000320 llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
321 if (Known == UnresolvedModules.end()) {
322 return true;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000323 }
324
Douglas Gregor603cd862013-03-22 18:50:14 +0000325 // Rectify this module with the global module index.
326 ModuleInfo &Info = Modules[Known->second];
327
328 // If the size and modification time match what we expected, record this
329 // module file.
330 bool Failed = true;
331 if (File->File->getSize() == Info.Size &&
332 File->File->getModificationTime() == Info.ModTime) {
333 Info.File = File;
334 ModulesByFile[File] = Known->second;
335
336 Failed = false;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000337 }
338
Douglas Gregor603cd862013-03-22 18:50:14 +0000339 // One way or another, we have resolved this module file.
340 UnresolvedModules.erase(Known);
341 return Failed;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000342}
343
Douglas Gregore060e572013-01-25 01:03:03 +0000344void GlobalModuleIndex::printStats() {
345 std::fprintf(stderr, "*** Global Module Index Statistics:\n");
346 if (NumIdentifierLookups) {
347 fprintf(stderr, " %u / %u identifier lookups succeeded (%f%%)\n",
348 NumIdentifierLookupHits, NumIdentifierLookups,
349 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
350 }
Douglas Gregore060e572013-01-25 01:03:03 +0000351 std::fprintf(stderr, "\n");
352}
353
John Thompsonbcdcc922014-04-16 21:03:41 +0000354void GlobalModuleIndex::dump() {
John Thompsona39baf12014-04-17 17:06:13 +0000355 llvm::errs() << "*** Global Module Index Dump:\n";
356 llvm::errs() << "Module files:\n";
John Thompson4f52d442014-04-17 18:17:36 +0000357 for (auto &MI : Modules) {
John Thompsona39baf12014-04-17 17:06:13 +0000358 llvm::errs() << "** " << MI.FileName << "\n";
359 if (MI.File)
360 MI.File->dump();
John Thompsonbcdcc922014-04-16 21:03:41 +0000361 else
John Thompsona39baf12014-04-17 17:06:13 +0000362 llvm::errs() << "\n";
John Thompsonbcdcc922014-04-16 21:03:41 +0000363 }
John Thompsona39baf12014-04-17 17:06:13 +0000364 llvm::errs() << "\n";
John Thompsonbcdcc922014-04-16 21:03:41 +0000365}
366
Douglas Gregore060e572013-01-25 01:03:03 +0000367//----------------------------------------------------------------------------//
Douglas Gregor5e306b12013-01-23 22:38:11 +0000368// Global module index writer.
369//----------------------------------------------------------------------------//
370
371namespace {
372 /// \brief Provides information about a specific module file.
373 struct ModuleFileInfo {
374 /// \brief The numberic ID for this module file.
375 unsigned ID;
376
377 /// \brief The set of modules on which this module depends. Each entry is
378 /// a module ID.
379 SmallVector<unsigned, 4> Dependencies;
380 };
381
382 /// \brief Builder that generates the global module index file.
383 class GlobalModuleIndexBuilder {
384 FileManager &FileMgr;
385
386 /// \brief Mapping from files to module file information.
387 typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
388
389 /// \brief Information about each of the known module files.
390 ModuleFilesMap ModuleFiles;
391
392 /// \brief Mapping from identifiers to the list of module file IDs that
393 /// consider this identifier to be interesting.
394 typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
395
396 /// \brief A mapping from all interesting identifiers to the set of module
397 /// files in which those identifiers are considered interesting.
398 InterestingIdentifierMap InterestingIdentifiers;
399
400 /// \brief Write the block-info block for the global module index file.
401 void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
402
403 /// \brief Retrieve the module file information for the given file.
404 ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
405 llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
406 = ModuleFiles.find(File);
407 if (Known != ModuleFiles.end())
408 return Known->second;
409
410 unsigned NewID = ModuleFiles.size();
411 ModuleFileInfo &Info = ModuleFiles[File];
412 Info.ID = NewID;
413 return Info;
414 }
415
416 public:
417 explicit GlobalModuleIndexBuilder(FileManager &FileMgr) : FileMgr(FileMgr){}
418
419 /// \brief Load the contents of the given module file into the builder.
420 ///
421 /// \returns true if an error occurred, false otherwise.
422 bool loadModuleFile(const FileEntry *File);
423
424 /// \brief Write the index to the given bitstream.
425 void writeIndex(llvm::BitstreamWriter &Stream);
426 };
427}
428
429static void emitBlockID(unsigned ID, const char *Name,
430 llvm::BitstreamWriter &Stream,
431 SmallVectorImpl<uint64_t> &Record) {
432 Record.clear();
433 Record.push_back(ID);
434 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
435
436 // Emit the block name if present.
437 if (Name == 0 || Name[0] == 0) return;
438 Record.clear();
439 while (*Name)
440 Record.push_back(*Name++);
441 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
442}
443
444static void emitRecordID(unsigned ID, const char *Name,
445 llvm::BitstreamWriter &Stream,
446 SmallVectorImpl<uint64_t> &Record) {
447 Record.clear();
448 Record.push_back(ID);
449 while (*Name)
450 Record.push_back(*Name++);
451 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
452}
453
454void
455GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
456 SmallVector<uint64_t, 64> Record;
457 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
458
459#define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
460#define RECORD(X) emitRecordID(X, #X, Stream, Record)
461 BLOCK(GLOBAL_INDEX_BLOCK);
Douglas Gregore060e572013-01-25 01:03:03 +0000462 RECORD(INDEX_METADATA);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000463 RECORD(MODULE);
464 RECORD(IDENTIFIER_INDEX);
465#undef RECORD
466#undef BLOCK
467
468 Stream.ExitBlock();
469}
470
Douglas Gregore060e572013-01-25 01:03:03 +0000471namespace {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000472 class InterestingASTIdentifierLookupTrait
473 : public serialization::reader::ASTIdentifierLookupTraitBase {
474
475 public:
476 /// \brief The identifier and whether it is "interesting".
477 typedef std::pair<StringRef, bool> data_type;
478
479 data_type ReadData(const internal_key_type& k,
480 const unsigned char* d,
481 unsigned DataLen) {
482 // The first bit indicates whether this identifier is interesting.
483 // That's all we care about.
Justin Bogner57ba0b22014-03-28 22:03:24 +0000484 using namespace llvm::support;
485 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000486 bool IsInteresting = RawID & 0x01;
487 return std::make_pair(k, IsInteresting);
488 }
489 };
490}
491
492bool GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
493 // Open the module file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000494 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Douglas Gregorcb680662013-02-06 18:08:37 +0000495 std::string ErrorStr;
496 Buffer.reset(FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000497 if (!Buffer) {
498 return true;
499 }
500
501 // Initialize the input stream
502 llvm::BitstreamReader InStreamFile;
503 llvm::BitstreamCursor InStream;
504 InStreamFile.init((const unsigned char *)Buffer->getBufferStart(),
505 (const unsigned char *)Buffer->getBufferEnd());
506 InStream.init(InStreamFile);
507
508 // Sniff for the signature.
509 if (InStream.Read(8) != 'C' ||
510 InStream.Read(8) != 'P' ||
511 InStream.Read(8) != 'C' ||
512 InStream.Read(8) != 'H') {
513 return true;
514 }
515
516 // Record this module file and assign it a unique ID (if it doesn't have
517 // one already).
518 unsigned ID = getModuleFileInfo(File).ID;
519
520 // Search for the blocks and records we care about.
Douglas Gregore060e572013-01-25 01:03:03 +0000521 enum { Other, ControlBlock, ASTBlock } State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000522 bool Done = false;
523 while (!Done) {
Douglas Gregore060e572013-01-25 01:03:03 +0000524 llvm::BitstreamEntry Entry = InStream.advance();
Douglas Gregor5e306b12013-01-23 22:38:11 +0000525 switch (Entry.Kind) {
526 case llvm::BitstreamEntry::Error:
Douglas Gregore060e572013-01-25 01:03:03 +0000527 Done = true;
528 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000529
530 case llvm::BitstreamEntry::Record:
Douglas Gregore060e572013-01-25 01:03:03 +0000531 // In the 'other' state, just skip the record. We don't care.
532 if (State == Other) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000533 InStream.skipRecord(Entry.ID);
534 continue;
535 }
536
537 // Handle potentially-interesting records below.
538 break;
539
540 case llvm::BitstreamEntry::SubBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000541 if (Entry.ID == CONTROL_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000542 if (InStream.EnterSubBlock(CONTROL_BLOCK_ID))
543 return true;
544
545 // Found the control block.
546 State = ControlBlock;
547 continue;
548 }
549
Douglas Gregore060e572013-01-25 01:03:03 +0000550 if (Entry.ID == AST_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000551 if (InStream.EnterSubBlock(AST_BLOCK_ID))
552 return true;
553
554 // Found the AST block.
555 State = ASTBlock;
556 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000557 }
558
559 if (InStream.SkipBlock())
560 return true;
561
562 continue;
563
564 case llvm::BitstreamEntry::EndBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000565 State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000566 continue;
567 }
568
569 // Read the given record.
570 SmallVector<uint64_t, 64> Record;
571 StringRef Blob;
572 unsigned Code = InStream.readRecord(Entry.ID, Record, &Blob);
573
574 // Handle module dependencies.
575 if (State == ControlBlock && Code == IMPORTS) {
576 // Load each of the imported PCH files.
577 unsigned Idx = 0, N = Record.size();
578 while (Idx < N) {
579 // Read information about the AST file.
580
581 // Skip the imported kind
582 ++Idx;
583
584 // Skip the import location
585 ++Idx;
586
Douglas Gregor7029ce12013-03-19 00:28:20 +0000587 // Load stored size/modification time.
588 off_t StoredSize = (off_t)Record[Idx++];
589 time_t StoredModTime = (time_t)Record[Idx++];
590
Douglas Gregor5e306b12013-01-23 22:38:11 +0000591 // Retrieve the imported file name.
592 unsigned Length = Record[Idx++];
593 SmallString<128> ImportedFile(Record.begin() + Idx,
594 Record.begin() + Idx + Length);
595 Idx += Length;
596
597 // Find the imported module file.
Douglas Gregordadd85d2013-02-08 21:27:45 +0000598 const FileEntry *DependsOnFile
599 = FileMgr.getFile(ImportedFile, /*openFile=*/false,
600 /*cacheFailure=*/false);
Douglas Gregor7029ce12013-03-19 00:28:20 +0000601 if (!DependsOnFile ||
602 (StoredSize != DependsOnFile->getSize()) ||
603 (StoredModTime != DependsOnFile->getModificationTime()))
Douglas Gregor5e306b12013-01-23 22:38:11 +0000604 return true;
605
606 // Record the dependency.
607 unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
608 getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
609 }
610
611 continue;
612 }
613
614 // Handle the identifier table
615 if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
Justin Bognerbb094f02014-04-18 19:57:06 +0000616 typedef llvm::OnDiskIterableChainedHashTable<
617 InterestingASTIdentifierLookupTrait> InterestingIdentifierTable;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000618 std::unique_ptr<InterestingIdentifierTable> Table(
619 InterestingIdentifierTable::Create(
620 (const unsigned char *)Blob.data() + Record[0],
Justin Bognerda4e6502014-04-14 16:34:29 +0000621 (const unsigned char *)Blob.data() + sizeof(uint32_t),
Ahmed Charlesb8984322014-03-07 20:03:18 +0000622 (const unsigned char *)Blob.data()));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000623 for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
624 DEnd = Table->data_end();
625 D != DEnd; ++D) {
626 std::pair<StringRef, bool> Ident = *D;
627 if (Ident.second)
628 InterestingIdentifiers[Ident.first].push_back(ID);
Douglas Gregore060e572013-01-25 01:03:03 +0000629 else
630 (void)InterestingIdentifiers[Ident.first];
Douglas Gregor5e306b12013-01-23 22:38:11 +0000631 }
632 }
633
Douglas Gregor5e306b12013-01-23 22:38:11 +0000634 // We don't care about this record.
635 }
636
637 return false;
638}
639
640namespace {
641
642/// \brief Trait used to generate the identifier index as an on-disk hash
643/// table.
644class IdentifierIndexWriterTrait {
645public:
646 typedef StringRef key_type;
647 typedef StringRef key_type_ref;
648 typedef SmallVector<unsigned, 2> data_type;
649 typedef const SmallVector<unsigned, 2> &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +0000650 typedef unsigned hash_value_type;
651 typedef unsigned offset_type;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000652
Justin Bogner25463f12014-04-18 20:27:24 +0000653 static hash_value_type ComputeHash(key_type_ref Key) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000654 return llvm::HashString(Key);
655 }
656
657 std::pair<unsigned,unsigned>
658 EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000659 using namespace llvm::support;
660 endian::Writer<little> LE(Out);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000661 unsigned KeyLen = Key.size();
662 unsigned DataLen = Data.size() * 4;
Justin Bognere1c147c2014-03-28 22:03:19 +0000663 LE.write<uint16_t>(KeyLen);
664 LE.write<uint16_t>(DataLen);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000665 return std::make_pair(KeyLen, DataLen);
666 }
667
668 void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
669 Out.write(Key.data(), KeyLen);
670 }
671
672 void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
673 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000674 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000675 for (unsigned I = 0, N = Data.size(); I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +0000676 endian::Writer<little>(Out).write<uint32_t>(Data[I]);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000677 }
678};
679
680}
681
682void GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
683 using namespace llvm;
684
685 // Emit the file header.
686 Stream.Emit((unsigned)'B', 8);
687 Stream.Emit((unsigned)'C', 8);
688 Stream.Emit((unsigned)'G', 8);
689 Stream.Emit((unsigned)'I', 8);
690
691 // Write the block-info block, which describes the records in this bitcode
692 // file.
693 emitBlockInfoBlock(Stream);
694
695 Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
696
697 // Write the metadata.
698 SmallVector<uint64_t, 2> Record;
699 Record.push_back(CurrentVersion);
Douglas Gregore060e572013-01-25 01:03:03 +0000700 Stream.EmitRecord(INDEX_METADATA, Record);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000701
702 // Write the set of known module files.
703 for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
704 MEnd = ModuleFiles.end();
705 M != MEnd; ++M) {
706 Record.clear();
707 Record.push_back(M->second.ID);
708 Record.push_back(M->first->getSize());
709 Record.push_back(M->first->getModificationTime());
710
711 // File name
712 StringRef Name(M->first->getName());
713 Record.push_back(Name.size());
714 Record.append(Name.begin(), Name.end());
715
716 // Dependencies
717 Record.push_back(M->second.Dependencies.size());
718 Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
719 Stream.EmitRecord(MODULE, Record);
720 }
721
722 // Write the identifier -> module file mapping.
723 {
Justin Bognerbb094f02014-04-18 19:57:06 +0000724 llvm::OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000725 IdentifierIndexWriterTrait Trait;
726
727 // Populate the hash table.
728 for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
729 IEnd = InterestingIdentifiers.end();
730 I != IEnd; ++I) {
731 Generator.insert(I->first(), I->second, Trait);
732 }
733
734 // Create the on-disk hash table in a buffer.
735 SmallString<4096> IdentifierTable;
736 uint32_t BucketOffset;
737 {
Justin Bognere1c147c2014-03-28 22:03:19 +0000738 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000739 llvm::raw_svector_ostream Out(IdentifierTable);
740 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +0000741 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000742 BucketOffset = Generator.Emit(Out, Trait);
743 }
744
745 // Create a blob abbreviation
746 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
747 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
750 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
751
752 // Write the identifier table
753 Record.clear();
754 Record.push_back(IDENTIFIER_INDEX);
755 Record.push_back(BucketOffset);
756 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
757 }
758
Douglas Gregor5e306b12013-01-23 22:38:11 +0000759 Stream.ExitBlock();
760}
761
762GlobalModuleIndex::ErrorCode
763GlobalModuleIndex::writeIndex(FileManager &FileMgr, StringRef Path) {
764 llvm::SmallString<128> IndexPath;
765 IndexPath += Path;
766 llvm::sys::path::append(IndexPath, IndexFileName);
767
768 // Coordinate building the global index file with other processes that might
769 // try to do the same.
770 llvm::LockFileManager Locked(IndexPath);
771 switch (Locked) {
772 case llvm::LockFileManager::LFS_Error:
773 return EC_IOError;
774
775 case llvm::LockFileManager::LFS_Owned:
776 // We're responsible for building the index ourselves. Do so below.
777 break;
778
779 case llvm::LockFileManager::LFS_Shared:
780 // Someone else is responsible for building the index. We don't care
781 // when they finish, so we're done.
782 return EC_Building;
783 }
784
785 // The module index builder.
786 GlobalModuleIndexBuilder Builder(FileMgr);
787
788 // Load each of the module files.
789 llvm::error_code EC;
790 for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
791 D != DEnd && !EC;
792 D.increment(EC)) {
793 // If this isn't a module file, we don't care.
794 if (llvm::sys::path::extension(D->path()) != ".pcm") {
795 // ... unless it's a .pcm.lock file, which indicates that someone is
796 // in the process of rebuilding a module. They'll rebuild the index
797 // at the end of that translation unit, so we don't have to.
798 if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
799 return EC_Building;
800
801 continue;
802 }
803
804 // If we can't find the module file, skip it.
805 const FileEntry *ModuleFile = FileMgr.getFile(D->path());
806 if (!ModuleFile)
807 continue;
808
809 // Load this module file.
810 if (Builder.loadModuleFile(ModuleFile))
811 return EC_IOError;
812 }
813
814 // The output buffer, into which the global index will be written.
815 SmallVector<char, 16> OutputBuffer;
816 {
817 llvm::BitstreamWriter OutputStream(OutputBuffer);
818 Builder.writeIndex(OutputStream);
819 }
820
821 // Write the global index file to a temporary file.
822 llvm::SmallString<128> IndexTmpPath;
823 int TmpFD;
Rafael Espindola18627112013-07-05 21:13:58 +0000824 if (llvm::sys::fs::createUniqueFile(IndexPath + "-%%%%%%%%", TmpFD,
825 IndexTmpPath))
Douglas Gregor5e306b12013-01-23 22:38:11 +0000826 return EC_IOError;
827
828 // Open the temporary global index file for output.
NAKAMURA Takumie00c9862013-01-24 08:20:11 +0000829 llvm::raw_fd_ostream Out(TmpFD, true);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000830 if (Out.has_error())
831 return EC_IOError;
832
833 // Write the index.
834 Out.write(OutputBuffer.data(), OutputBuffer.size());
835 Out.close();
836 if (Out.has_error())
837 return EC_IOError;
838
839 // Remove the old index file. It isn't relevant any more.
Rafael Espindola2a008782014-01-10 21:32:14 +0000840 llvm::sys::fs::remove(IndexPath.str());
Douglas Gregor5e306b12013-01-23 22:38:11 +0000841
842 // Rename the newly-written index file to the proper name.
843 if (llvm::sys::fs::rename(IndexTmpPath.str(), IndexPath.str())) {
844 // Rename failed; just remove the
Rafael Espindola2a008782014-01-10 21:32:14 +0000845 llvm::sys::fs::remove(IndexTmpPath.str());
Douglas Gregor5e306b12013-01-23 22:38:11 +0000846 return EC_IOError;
847 }
848
849 // We're done.
850 return EC_None;
851}
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000852
853namespace {
854 class GlobalIndexIdentifierIterator : public IdentifierIterator {
855 /// \brief The current position within the identifier lookup table.
856 IdentifierIndexTable::key_iterator Current;
857
858 /// \brief The end position within the identifier lookup table.
859 IdentifierIndexTable::key_iterator End;
860
861 public:
862 explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
863 Current = Idx.key_begin();
864 End = Idx.key_end();
865 }
866
Craig Topper3e89dfe2014-03-13 02:13:41 +0000867 StringRef Next() override {
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000868 if (Current == End)
869 return StringRef();
870
871 StringRef Result = *Current;
872 ++Current;
873 return Result;
874 }
875 };
876}
877
878IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
879 IdentifierIndexTable &Table =
880 *static_cast<IdentifierIndexTable *>(IdentifierIndex);
881 return new GlobalIndexIdentifierIterator(Table);
882}