blob: 68a23ea870db6504d065a5f8a1b23b898510cdbc [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"
Adrian Prantlc4091aa2015-02-20 19:44:52 +000018#include "clang/Serialization/ASTReader.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000019#include "clang/Serialization/GlobalModuleIndex.h"
Douglas Gregor603cd862013-03-22 18:50:14 +000020#include "clang/Serialization/Module.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000021#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Bitcode/BitstreamReader.h"
26#include "llvm/Bitcode/BitstreamWriter.h"
Douglas Gregor8ec343c2013-01-23 22:45:24 +000027#include "llvm/Support/FileSystem.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000028#include "llvm/Support/LockFileManager.h"
29#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000030#include "llvm/Support/OnDiskHashTable.h"
Rafael Espindola552c1692013-06-11 22:15:02 +000031#include "llvm/Support/Path.h"
NAKAMURA Takumif0add232013-01-25 01:47:07 +000032#include <cstdio>
Douglas Gregor5e306b12013-01-23 22:38:11 +000033using namespace clang;
34using namespace serialization;
35
36//----------------------------------------------------------------------------//
37// Shared constants
38//----------------------------------------------------------------------------//
39namespace {
40 enum {
41 /// \brief The block containing the index.
42 GLOBAL_INDEX_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID
43 };
44
45 /// \brief Describes the record types in the index.
46 enum IndexRecordTypes {
47 /// \brief Contains version information and potentially other metadata,
48 /// used to determine if we can read this global index file.
Douglas Gregore060e572013-01-25 01:03:03 +000049 INDEX_METADATA,
Douglas Gregor5e306b12013-01-23 22:38:11 +000050 /// \brief Describes a module, including its file name and dependencies.
51 MODULE,
52 /// \brief The index for identifiers.
53 IDENTIFIER_INDEX
54 };
55}
56
57/// \brief The name of the global index file.
58static const char * const IndexFileName = "modules.idx";
59
60/// \brief The global index file version.
61static const unsigned CurrentVersion = 1;
62
63//----------------------------------------------------------------------------//
Douglas Gregore060e572013-01-25 01:03:03 +000064// Global module index reader.
65//----------------------------------------------------------------------------//
66
67namespace {
68
69/// \brief Trait used to read the identifier index from the on-disk hash
70/// table.
71class IdentifierIndexReaderTrait {
72public:
73 typedef StringRef external_key_type;
74 typedef StringRef internal_key_type;
75 typedef SmallVector<unsigned, 2> data_type;
Justin Bogner25463f12014-04-18 20:27:24 +000076 typedef unsigned hash_value_type;
77 typedef unsigned offset_type;
Douglas Gregore060e572013-01-25 01:03:03 +000078
79 static bool EqualKey(const internal_key_type& a, const internal_key_type& b) {
80 return a == b;
81 }
82
Justin Bogner25463f12014-04-18 20:27:24 +000083 static hash_value_type ComputeHash(const internal_key_type& a) {
Douglas Gregore060e572013-01-25 01:03:03 +000084 return llvm::HashString(a);
85 }
86
87 static std::pair<unsigned, unsigned>
88 ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +000089 using namespace llvm::support;
90 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
91 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Douglas Gregore060e572013-01-25 01:03:03 +000092 return std::make_pair(KeyLen, DataLen);
93 }
94
95 static const internal_key_type&
96 GetInternalKey(const external_key_type& x) { return x; }
97
98 static const external_key_type&
99 GetExternalKey(const internal_key_type& x) { return x; }
100
101 static internal_key_type ReadKey(const unsigned char* d, unsigned n) {
102 return StringRef((const char *)d, n);
103 }
104
105 static data_type ReadData(const internal_key_type& k,
106 const unsigned char* d,
107 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000108 using namespace llvm::support;
Douglas Gregore060e572013-01-25 01:03:03 +0000109
110 data_type Result;
111 while (DataLen > 0) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000112 unsigned ID = endian::readNext<uint32_t, little, unaligned>(d);
Douglas Gregore060e572013-01-25 01:03:03 +0000113 Result.push_back(ID);
114 DataLen -= 4;
115 }
116
117 return Result;
118 }
119};
120
Justin Bognerbb094f02014-04-18 19:57:06 +0000121typedef llvm::OnDiskIterableChainedHashTable<IdentifierIndexReaderTrait>
Justin Bognerda4e6502014-04-14 16:34:29 +0000122 IdentifierIndexTable;
Douglas Gregore060e572013-01-25 01:03:03 +0000123
Douglas Gregore060e572013-01-25 01:03:03 +0000124}
125
David Blaikieafa10d32014-08-11 18:47:26 +0000126GlobalModuleIndex::GlobalModuleIndex(std::unique_ptr<llvm::MemoryBuffer> Buffer,
Douglas Gregore060e572013-01-25 01:03:03 +0000127 llvm::BitstreamCursor Cursor)
David Blaikieafa10d32014-08-11 18:47:26 +0000128 : Buffer(std::move(Buffer)), IdentifierIndex(), NumIdentifierLookups(),
129 NumIdentifierLookupHits() {
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
Nico Webere68b8472014-04-25 19:45:23 +0000231GlobalModuleIndex::~GlobalModuleIndex() {
232 delete static_cast<IdentifierIndexTable *>(IdentifierIndex);
233}
Douglas Gregore060e572013-01-25 01:03:03 +0000234
235std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode>
Douglas Gregor7029ce12013-03-19 00:28:20 +0000236GlobalModuleIndex::readIndex(StringRef Path) {
Douglas Gregore060e572013-01-25 01:03:03 +0000237 // Load the index file, if it's there.
238 llvm::SmallString<128> IndexPath;
239 IndexPath += Path;
240 llvm::sys::path::append(IndexPath, IndexFileName);
241
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000242 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferOrErr =
243 llvm::MemoryBuffer::getFile(IndexPath.c_str());
244 if (!BufferOrErr)
Craig Toppera13603a2014-05-22 05:54:18 +0000245 return std::make_pair(nullptr, EC_NotFound);
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000246 std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(BufferOrErr.get());
Douglas Gregore060e572013-01-25 01:03:03 +0000247
248 /// \brief The bitstream reader from which we'll read the AST file.
249 llvm::BitstreamReader Reader((const unsigned char *)Buffer->getBufferStart(),
250 (const unsigned char *)Buffer->getBufferEnd());
251
252 /// \brief The main bitstream cursor for the main block.
253 llvm::BitstreamCursor Cursor(Reader);
254
255 // Sniff for the signature.
256 if (Cursor.Read(8) != 'B' ||
257 Cursor.Read(8) != 'C' ||
258 Cursor.Read(8) != 'G' ||
259 Cursor.Read(8) != 'I') {
Craig Toppera13603a2014-05-22 05:54:18 +0000260 return std::make_pair(nullptr, EC_IOError);
Douglas Gregore060e572013-01-25 01:03:03 +0000261 }
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000262
David Blaikieafa10d32014-08-11 18:47:26 +0000263 return std::make_pair(new GlobalModuleIndex(std::move(Buffer), Cursor),
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000264 EC_None);
Douglas Gregore060e572013-01-25 01:03:03 +0000265}
266
Douglas Gregor7029ce12013-03-19 00:28:20 +0000267void
268GlobalModuleIndex::getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles) {
Douglas Gregore060e572013-01-25 01:03:03 +0000269 ModuleFiles.clear();
270 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000271 if (ModuleFile *MF = Modules[I].File)
272 ModuleFiles.push_back(MF);
Douglas Gregore060e572013-01-25 01:03:03 +0000273 }
274}
275
276void GlobalModuleIndex::getModuleDependencies(
Douglas Gregor7029ce12013-03-19 00:28:20 +0000277 ModuleFile *File,
278 SmallVectorImpl<ModuleFile *> &Dependencies) {
Douglas Gregore060e572013-01-25 01:03:03 +0000279 // Look for information about this module file.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000280 llvm::DenseMap<ModuleFile *, unsigned>::iterator Known
281 = ModulesByFile.find(File);
Douglas Gregore060e572013-01-25 01:03:03 +0000282 if (Known == ModulesByFile.end())
283 return;
284
285 // Record dependencies.
Douglas Gregor7029ce12013-03-19 00:28:20 +0000286 Dependencies.clear();
287 ArrayRef<unsigned> StoredDependencies = Modules[Known->second].Dependencies;
288 for (unsigned I = 0, N = StoredDependencies.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000289 if (ModuleFile *MF = Modules[I].File)
Douglas Gregor7029ce12013-03-19 00:28:20 +0000290 Dependencies.push_back(MF);
291 }
Douglas Gregore060e572013-01-25 01:03:03 +0000292}
293
Douglas Gregor7211ac12013-01-25 23:32:03 +0000294bool GlobalModuleIndex::lookupIdentifier(StringRef Name, HitSet &Hits) {
295 Hits.clear();
Douglas Gregore060e572013-01-25 01:03:03 +0000296
297 // If there's no identifier index, there is nothing we can do.
298 if (!IdentifierIndex)
299 return false;
300
301 // Look into the identifier index.
302 ++NumIdentifierLookups;
303 IdentifierIndexTable &Table
304 = *static_cast<IdentifierIndexTable *>(IdentifierIndex);
305 IdentifierIndexTable::iterator Known = Table.find(Name);
306 if (Known == Table.end()) {
307 return true;
308 }
309
310 SmallVector<unsigned, 2> ModuleIDs = *Known;
311 for (unsigned I = 0, N = ModuleIDs.size(); I != N; ++I) {
Douglas Gregor603cd862013-03-22 18:50:14 +0000312 if (ModuleFile *MF = Modules[ModuleIDs[I]].File)
313 Hits.insert(MF);
Douglas Gregore060e572013-01-25 01:03:03 +0000314 }
315
316 ++NumIdentifierLookupHits;
317 return true;
318}
319
Douglas Gregor603cd862013-03-22 18:50:14 +0000320bool GlobalModuleIndex::loadedModuleFile(ModuleFile *File) {
321 // Look for the module in the global module index based on the module name.
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000322 StringRef Name = File->ModuleName;
Douglas Gregor603cd862013-03-22 18:50:14 +0000323 llvm::StringMap<unsigned>::iterator Known = UnresolvedModules.find(Name);
324 if (Known == UnresolvedModules.end()) {
325 return true;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000326 }
327
Douglas Gregor603cd862013-03-22 18:50:14 +0000328 // Rectify this module with the global module index.
329 ModuleInfo &Info = Modules[Known->second];
330
331 // If the size and modification time match what we expected, record this
332 // module file.
333 bool Failed = true;
334 if (File->File->getSize() == Info.Size &&
335 File->File->getModificationTime() == Info.ModTime) {
336 Info.File = File;
337 ModulesByFile[File] = Known->second;
338
339 Failed = false;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000340 }
341
Douglas Gregor603cd862013-03-22 18:50:14 +0000342 // One way or another, we have resolved this module file.
343 UnresolvedModules.erase(Known);
344 return Failed;
Douglas Gregor7029ce12013-03-19 00:28:20 +0000345}
346
Douglas Gregore060e572013-01-25 01:03:03 +0000347void GlobalModuleIndex::printStats() {
348 std::fprintf(stderr, "*** Global Module Index Statistics:\n");
349 if (NumIdentifierLookups) {
350 fprintf(stderr, " %u / %u identifier lookups succeeded (%f%%)\n",
351 NumIdentifierLookupHits, NumIdentifierLookups,
352 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
353 }
Douglas Gregore060e572013-01-25 01:03:03 +0000354 std::fprintf(stderr, "\n");
355}
356
John Thompsonbcdcc922014-04-16 21:03:41 +0000357void GlobalModuleIndex::dump() {
John Thompsona39baf12014-04-17 17:06:13 +0000358 llvm::errs() << "*** Global Module Index Dump:\n";
359 llvm::errs() << "Module files:\n";
John Thompson4f52d442014-04-17 18:17:36 +0000360 for (auto &MI : Modules) {
John Thompsona39baf12014-04-17 17:06:13 +0000361 llvm::errs() << "** " << MI.FileName << "\n";
362 if (MI.File)
363 MI.File->dump();
John Thompsonbcdcc922014-04-16 21:03:41 +0000364 else
John Thompsona39baf12014-04-17 17:06:13 +0000365 llvm::errs() << "\n";
John Thompsonbcdcc922014-04-16 21:03:41 +0000366 }
John Thompsona39baf12014-04-17 17:06:13 +0000367 llvm::errs() << "\n";
John Thompsonbcdcc922014-04-16 21:03:41 +0000368}
369
Douglas Gregore060e572013-01-25 01:03:03 +0000370//----------------------------------------------------------------------------//
Douglas Gregor5e306b12013-01-23 22:38:11 +0000371// Global module index writer.
372//----------------------------------------------------------------------------//
373
374namespace {
375 /// \brief Provides information about a specific module file.
376 struct ModuleFileInfo {
377 /// \brief The numberic ID for this module file.
378 unsigned ID;
379
380 /// \brief The set of modules on which this module depends. Each entry is
381 /// a module ID.
382 SmallVector<unsigned, 4> Dependencies;
383 };
384
385 /// \brief Builder that generates the global module index file.
386 class GlobalModuleIndexBuilder {
387 FileManager &FileMgr;
388
389 /// \brief Mapping from files to module file information.
390 typedef llvm::MapVector<const FileEntry *, ModuleFileInfo> ModuleFilesMap;
391
392 /// \brief Information about each of the known module files.
393 ModuleFilesMap ModuleFiles;
394
395 /// \brief Mapping from identifiers to the list of module file IDs that
396 /// consider this identifier to be interesting.
397 typedef llvm::StringMap<SmallVector<unsigned, 2> > InterestingIdentifierMap;
398
399 /// \brief A mapping from all interesting identifiers to the set of module
400 /// files in which those identifiers are considered interesting.
401 InterestingIdentifierMap InterestingIdentifiers;
402
403 /// \brief Write the block-info block for the global module index file.
404 void emitBlockInfoBlock(llvm::BitstreamWriter &Stream);
405
406 /// \brief Retrieve the module file information for the given file.
407 ModuleFileInfo &getModuleFileInfo(const FileEntry *File) {
408 llvm::MapVector<const FileEntry *, ModuleFileInfo>::iterator Known
409 = ModuleFiles.find(File);
410 if (Known != ModuleFiles.end())
411 return Known->second;
412
413 unsigned NewID = ModuleFiles.size();
414 ModuleFileInfo &Info = ModuleFiles[File];
415 Info.ID = NewID;
416 return Info;
417 }
418
419 public:
420 explicit GlobalModuleIndexBuilder(FileManager &FileMgr) : FileMgr(FileMgr){}
421
422 /// \brief Load the contents of the given module file into the builder.
423 ///
424 /// \returns true if an error occurred, false otherwise.
425 bool loadModuleFile(const FileEntry *File);
426
427 /// \brief Write the index to the given bitstream.
428 void writeIndex(llvm::BitstreamWriter &Stream);
429 };
430}
431
432static void emitBlockID(unsigned ID, const char *Name,
433 llvm::BitstreamWriter &Stream,
434 SmallVectorImpl<uint64_t> &Record) {
435 Record.clear();
436 Record.push_back(ID);
437 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
438
439 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000440 if (!Name || Name[0] == 0) return;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000441 Record.clear();
442 while (*Name)
443 Record.push_back(*Name++);
444 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
445}
446
447static void emitRecordID(unsigned ID, const char *Name,
448 llvm::BitstreamWriter &Stream,
449 SmallVectorImpl<uint64_t> &Record) {
450 Record.clear();
451 Record.push_back(ID);
452 while (*Name)
453 Record.push_back(*Name++);
454 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
455}
456
457void
458GlobalModuleIndexBuilder::emitBlockInfoBlock(llvm::BitstreamWriter &Stream) {
459 SmallVector<uint64_t, 64> Record;
460 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
461
462#define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record)
463#define RECORD(X) emitRecordID(X, #X, Stream, Record)
464 BLOCK(GLOBAL_INDEX_BLOCK);
Douglas Gregore060e572013-01-25 01:03:03 +0000465 RECORD(INDEX_METADATA);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000466 RECORD(MODULE);
467 RECORD(IDENTIFIER_INDEX);
468#undef RECORD
469#undef BLOCK
470
471 Stream.ExitBlock();
472}
473
Douglas Gregore060e572013-01-25 01:03:03 +0000474namespace {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000475 class InterestingASTIdentifierLookupTrait
476 : public serialization::reader::ASTIdentifierLookupTraitBase {
477
478 public:
479 /// \brief The identifier and whether it is "interesting".
480 typedef std::pair<StringRef, bool> data_type;
481
482 data_type ReadData(const internal_key_type& k,
483 const unsigned char* d,
484 unsigned DataLen) {
485 // The first bit indicates whether this identifier is interesting.
486 // That's all we care about.
Justin Bogner57ba0b22014-03-28 22:03:24 +0000487 using namespace llvm::support;
488 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000489 bool IsInteresting = RawID & 0x01;
490 return std::make_pair(k, IsInteresting);
491 }
492 };
493}
494
495bool GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
496 // Open the module file.
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000497
Benjamin Kramera8857962014-10-26 22:44:13 +0000498 auto Buffer = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000499 if (!Buffer) {
500 return true;
501 }
502
503 // Initialize the input stream
504 llvm::BitstreamReader InStreamFile;
Adrian Prantlc4091aa2015-02-20 19:44:52 +0000505 ASTReader::InitStreamFileWithModule((*Buffer)->getMemBufferRef(),
506 InStreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +0000507 llvm::BitstreamCursor InStream(InStreamFile);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000508
509 // Sniff for the signature.
510 if (InStream.Read(8) != 'C' ||
511 InStream.Read(8) != 'P' ||
512 InStream.Read(8) != 'C' ||
513 InStream.Read(8) != 'H') {
514 return true;
515 }
516
517 // Record this module file and assign it a unique ID (if it doesn't have
518 // one already).
519 unsigned ID = getModuleFileInfo(File).ID;
520
521 // Search for the blocks and records we care about.
Douglas Gregore060e572013-01-25 01:03:03 +0000522 enum { Other, ControlBlock, ASTBlock } State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000523 bool Done = false;
524 while (!Done) {
Douglas Gregore060e572013-01-25 01:03:03 +0000525 llvm::BitstreamEntry Entry = InStream.advance();
Douglas Gregor5e306b12013-01-23 22:38:11 +0000526 switch (Entry.Kind) {
527 case llvm::BitstreamEntry::Error:
Douglas Gregore060e572013-01-25 01:03:03 +0000528 Done = true;
529 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000530
531 case llvm::BitstreamEntry::Record:
Douglas Gregore060e572013-01-25 01:03:03 +0000532 // In the 'other' state, just skip the record. We don't care.
533 if (State == Other) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000534 InStream.skipRecord(Entry.ID);
535 continue;
536 }
537
538 // Handle potentially-interesting records below.
539 break;
540
541 case llvm::BitstreamEntry::SubBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000542 if (Entry.ID == CONTROL_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000543 if (InStream.EnterSubBlock(CONTROL_BLOCK_ID))
544 return true;
545
546 // Found the control block.
547 State = ControlBlock;
548 continue;
549 }
550
Douglas Gregore060e572013-01-25 01:03:03 +0000551 if (Entry.ID == AST_BLOCK_ID) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000552 if (InStream.EnterSubBlock(AST_BLOCK_ID))
553 return true;
554
555 // Found the AST block.
556 State = ASTBlock;
557 continue;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000558 }
559
560 if (InStream.SkipBlock())
561 return true;
562
563 continue;
564
565 case llvm::BitstreamEntry::EndBlock:
Douglas Gregore060e572013-01-25 01:03:03 +0000566 State = Other;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000567 continue;
568 }
569
570 // Read the given record.
571 SmallVector<uint64_t, 64> Record;
572 StringRef Blob;
573 unsigned Code = InStream.readRecord(Entry.ID, Record, &Blob);
574
575 // Handle module dependencies.
576 if (State == ControlBlock && Code == IMPORTS) {
577 // Load each of the imported PCH files.
578 unsigned Idx = 0, N = Record.size();
579 while (Idx < N) {
580 // Read information about the AST file.
581
582 // Skip the imported kind
583 ++Idx;
584
585 // Skip the import location
586 ++Idx;
587
Douglas Gregor7029ce12013-03-19 00:28:20 +0000588 // Load stored size/modification time.
589 off_t StoredSize = (off_t)Record[Idx++];
590 time_t StoredModTime = (time_t)Record[Idx++];
591
Ben Langmuir487ea142014-10-23 18:05:36 +0000592 // Skip the stored signature.
593 // FIXME: we could read the signature out of the import and validate it.
594 Idx++;
595
Douglas Gregor5e306b12013-01-23 22:38:11 +0000596 // Retrieve the imported file name.
597 unsigned Length = Record[Idx++];
598 SmallString<128> ImportedFile(Record.begin() + Idx,
599 Record.begin() + Idx + Length);
600 Idx += Length;
601
602 // Find the imported module file.
Douglas Gregordadd85d2013-02-08 21:27:45 +0000603 const FileEntry *DependsOnFile
604 = FileMgr.getFile(ImportedFile, /*openFile=*/false,
605 /*cacheFailure=*/false);
Douglas Gregor7029ce12013-03-19 00:28:20 +0000606 if (!DependsOnFile ||
607 (StoredSize != DependsOnFile->getSize()) ||
608 (StoredModTime != DependsOnFile->getModificationTime()))
Douglas Gregor5e306b12013-01-23 22:38:11 +0000609 return true;
610
611 // Record the dependency.
612 unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
613 getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
614 }
615
616 continue;
617 }
618
619 // Handle the identifier table
620 if (State == ASTBlock && Code == IDENTIFIER_TABLE && Record[0] > 0) {
Justin Bognerbb094f02014-04-18 19:57:06 +0000621 typedef llvm::OnDiskIterableChainedHashTable<
622 InterestingASTIdentifierLookupTrait> InterestingIdentifierTable;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000623 std::unique_ptr<InterestingIdentifierTable> Table(
624 InterestingIdentifierTable::Create(
625 (const unsigned char *)Blob.data() + Record[0],
Justin Bognerda4e6502014-04-14 16:34:29 +0000626 (const unsigned char *)Blob.data() + sizeof(uint32_t),
Ahmed Charlesb8984322014-03-07 20:03:18 +0000627 (const unsigned char *)Blob.data()));
Douglas Gregor5e306b12013-01-23 22:38:11 +0000628 for (InterestingIdentifierTable::data_iterator D = Table->data_begin(),
629 DEnd = Table->data_end();
630 D != DEnd; ++D) {
631 std::pair<StringRef, bool> Ident = *D;
632 if (Ident.second)
633 InterestingIdentifiers[Ident.first].push_back(ID);
Douglas Gregore060e572013-01-25 01:03:03 +0000634 else
635 (void)InterestingIdentifiers[Ident.first];
Douglas Gregor5e306b12013-01-23 22:38:11 +0000636 }
637 }
638
Douglas Gregor5e306b12013-01-23 22:38:11 +0000639 // We don't care about this record.
640 }
641
642 return false;
643}
644
645namespace {
646
647/// \brief Trait used to generate the identifier index as an on-disk hash
648/// table.
649class IdentifierIndexWriterTrait {
650public:
651 typedef StringRef key_type;
652 typedef StringRef key_type_ref;
653 typedef SmallVector<unsigned, 2> data_type;
654 typedef const SmallVector<unsigned, 2> &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +0000655 typedef unsigned hash_value_type;
656 typedef unsigned offset_type;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000657
Justin Bogner25463f12014-04-18 20:27:24 +0000658 static hash_value_type ComputeHash(key_type_ref Key) {
Douglas Gregor5e306b12013-01-23 22:38:11 +0000659 return llvm::HashString(Key);
660 }
661
662 std::pair<unsigned,unsigned>
663 EmitKeyDataLength(raw_ostream& Out, key_type_ref Key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000664 using namespace llvm::support;
665 endian::Writer<little> LE(Out);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000666 unsigned KeyLen = Key.size();
667 unsigned DataLen = Data.size() * 4;
Justin Bognere1c147c2014-03-28 22:03:19 +0000668 LE.write<uint16_t>(KeyLen);
669 LE.write<uint16_t>(DataLen);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000670 return std::make_pair(KeyLen, DataLen);
671 }
672
673 void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
674 Out.write(Key.data(), KeyLen);
675 }
676
677 void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
678 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +0000679 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000680 for (unsigned I = 0, N = Data.size(); I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +0000681 endian::Writer<little>(Out).write<uint32_t>(Data[I]);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000682 }
683};
684
685}
686
687void GlobalModuleIndexBuilder::writeIndex(llvm::BitstreamWriter &Stream) {
688 using namespace llvm;
689
690 // Emit the file header.
691 Stream.Emit((unsigned)'B', 8);
692 Stream.Emit((unsigned)'C', 8);
693 Stream.Emit((unsigned)'G', 8);
694 Stream.Emit((unsigned)'I', 8);
695
696 // Write the block-info block, which describes the records in this bitcode
697 // file.
698 emitBlockInfoBlock(Stream);
699
700 Stream.EnterSubblock(GLOBAL_INDEX_BLOCK_ID, 3);
701
702 // Write the metadata.
703 SmallVector<uint64_t, 2> Record;
704 Record.push_back(CurrentVersion);
Douglas Gregore060e572013-01-25 01:03:03 +0000705 Stream.EmitRecord(INDEX_METADATA, Record);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000706
707 // Write the set of known module files.
708 for (ModuleFilesMap::iterator M = ModuleFiles.begin(),
709 MEnd = ModuleFiles.end();
710 M != MEnd; ++M) {
711 Record.clear();
712 Record.push_back(M->second.ID);
713 Record.push_back(M->first->getSize());
714 Record.push_back(M->first->getModificationTime());
715
716 // File name
717 StringRef Name(M->first->getName());
718 Record.push_back(Name.size());
719 Record.append(Name.begin(), Name.end());
720
721 // Dependencies
722 Record.push_back(M->second.Dependencies.size());
723 Record.append(M->second.Dependencies.begin(), M->second.Dependencies.end());
724 Stream.EmitRecord(MODULE, Record);
725 }
726
727 // Write the identifier -> module file mapping.
728 {
Justin Bognerbb094f02014-04-18 19:57:06 +0000729 llvm::OnDiskChainedHashTableGenerator<IdentifierIndexWriterTrait> Generator;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000730 IdentifierIndexWriterTrait Trait;
731
732 // Populate the hash table.
733 for (InterestingIdentifierMap::iterator I = InterestingIdentifiers.begin(),
734 IEnd = InterestingIdentifiers.end();
735 I != IEnd; ++I) {
736 Generator.insert(I->first(), I->second, Trait);
737 }
738
739 // Create the on-disk hash table in a buffer.
740 SmallString<4096> IdentifierTable;
741 uint32_t BucketOffset;
742 {
Justin Bognere1c147c2014-03-28 22:03:19 +0000743 using namespace llvm::support;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000744 llvm::raw_svector_ostream Out(IdentifierTable);
745 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +0000746 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000747 BucketOffset = Generator.Emit(Out, Trait);
748 }
749
750 // Create a blob abbreviation
751 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
752 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_INDEX));
753 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
754 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
755 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
756
757 // Write the identifier table
758 Record.clear();
759 Record.push_back(IDENTIFIER_INDEX);
760 Record.push_back(BucketOffset);
761 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
762 }
763
Douglas Gregor5e306b12013-01-23 22:38:11 +0000764 Stream.ExitBlock();
765}
766
767GlobalModuleIndex::ErrorCode
768GlobalModuleIndex::writeIndex(FileManager &FileMgr, StringRef Path) {
769 llvm::SmallString<128> IndexPath;
770 IndexPath += Path;
771 llvm::sys::path::append(IndexPath, IndexFileName);
772
773 // Coordinate building the global index file with other processes that might
774 // try to do the same.
775 llvm::LockFileManager Locked(IndexPath);
776 switch (Locked) {
777 case llvm::LockFileManager::LFS_Error:
778 return EC_IOError;
779
780 case llvm::LockFileManager::LFS_Owned:
781 // We're responsible for building the index ourselves. Do so below.
782 break;
783
784 case llvm::LockFileManager::LFS_Shared:
785 // Someone else is responsible for building the index. We don't care
786 // when they finish, so we're done.
787 return EC_Building;
788 }
789
790 // The module index builder.
791 GlobalModuleIndexBuilder Builder(FileMgr);
792
793 // Load each of the module files.
Rafael Espindolac0809172014-06-12 14:02:15 +0000794 std::error_code EC;
Douglas Gregor5e306b12013-01-23 22:38:11 +0000795 for (llvm::sys::fs::directory_iterator D(Path, EC), DEnd;
796 D != DEnd && !EC;
797 D.increment(EC)) {
798 // If this isn't a module file, we don't care.
799 if (llvm::sys::path::extension(D->path()) != ".pcm") {
800 // ... unless it's a .pcm.lock file, which indicates that someone is
801 // in the process of rebuilding a module. They'll rebuild the index
802 // at the end of that translation unit, so we don't have to.
803 if (llvm::sys::path::extension(D->path()) == ".pcm.lock")
804 return EC_Building;
805
806 continue;
807 }
808
809 // If we can't find the module file, skip it.
810 const FileEntry *ModuleFile = FileMgr.getFile(D->path());
811 if (!ModuleFile)
812 continue;
813
814 // Load this module file.
815 if (Builder.loadModuleFile(ModuleFile))
816 return EC_IOError;
817 }
818
819 // The output buffer, into which the global index will be written.
820 SmallVector<char, 16> OutputBuffer;
821 {
822 llvm::BitstreamWriter OutputStream(OutputBuffer);
823 Builder.writeIndex(OutputStream);
824 }
825
826 // Write the global index file to a temporary file.
827 llvm::SmallString<128> IndexTmpPath;
828 int TmpFD;
Rafael Espindola18627112013-07-05 21:13:58 +0000829 if (llvm::sys::fs::createUniqueFile(IndexPath + "-%%%%%%%%", TmpFD,
830 IndexTmpPath))
Douglas Gregor5e306b12013-01-23 22:38:11 +0000831 return EC_IOError;
832
833 // Open the temporary global index file for output.
NAKAMURA Takumie00c9862013-01-24 08:20:11 +0000834 llvm::raw_fd_ostream Out(TmpFD, true);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000835 if (Out.has_error())
836 return EC_IOError;
837
838 // Write the index.
839 Out.write(OutputBuffer.data(), OutputBuffer.size());
840 Out.close();
841 if (Out.has_error())
842 return EC_IOError;
843
844 // Remove the old index file. It isn't relevant any more.
Rafael Espindola2a008782014-01-10 21:32:14 +0000845 llvm::sys::fs::remove(IndexPath.str());
Douglas Gregor5e306b12013-01-23 22:38:11 +0000846
847 // Rename the newly-written index file to the proper name.
848 if (llvm::sys::fs::rename(IndexTmpPath.str(), IndexPath.str())) {
849 // Rename failed; just remove the
Rafael Espindola2a008782014-01-10 21:32:14 +0000850 llvm::sys::fs::remove(IndexTmpPath.str());
Douglas Gregor5e306b12013-01-23 22:38:11 +0000851 return EC_IOError;
852 }
853
854 // We're done.
855 return EC_None;
856}
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000857
858namespace {
859 class GlobalIndexIdentifierIterator : public IdentifierIterator {
860 /// \brief The current position within the identifier lookup table.
861 IdentifierIndexTable::key_iterator Current;
862
863 /// \brief The end position within the identifier lookup table.
864 IdentifierIndexTable::key_iterator End;
865
866 public:
867 explicit GlobalIndexIdentifierIterator(IdentifierIndexTable &Idx) {
868 Current = Idx.key_begin();
869 End = Idx.key_end();
870 }
871
Craig Topper3e89dfe2014-03-13 02:13:41 +0000872 StringRef Next() override {
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +0000873 if (Current == End)
874 return StringRef();
875
876 StringRef Result = *Current;
877 ++Current;
878 return Result;
879 }
880 };
881}
882
883IdentifierIterator *GlobalModuleIndex::createIdentifierIterator() const {
884 IdentifierIndexTable &Table =
885 *static_cast<IdentifierIndexTable *>(IdentifierIndex);
886 return new GlobalIndexIdentifierIterator(Table);
887}