11#include "llvm/Support/MemoryBuffer.h"
12#include "llvm/Support/Threading.h"
18llvm::ErrorOr<DependencyScanningWorkerFilesystem::TentativeEntry>
19DependencyScanningWorkerFilesystem::readFile(StringRef Filename) {
21 auto MaybeFile = getUnderlyingFS().openFileForRead(Filename);
23 return MaybeFile.getError();
24 auto File = std::move(*MaybeFile);
26 auto MaybeStat =
File->status();
28 return MaybeStat.getError();
29 auto Stat = std::move(*MaybeStat);
31 auto MaybeBuffer =
File->getBuffer(Stat.getName());
33 return MaybeBuffer.getError();
34 auto Buffer = std::move(*MaybeBuffer);
37 if (Stat.getSize() != Buffer->getBufferSize())
38 Stat = llvm::vfs::Status::copyWithNewSize(Stat, Buffer->getBufferSize());
40 return TentativeEntry(Stat, std::move(Buffer));
45 auto &Entry = Ref.Entry;
47 if (Entry.isError() || Entry.isDirectory())
51 assert(Contents &&
"contents not initialized");
57 std::lock_guard<std::mutex> GuardLock(Contents->
ValueLock);
71 Contents->
DepDirectives.store(
new std::optional<DependencyDirectivesTy>());
80 new std::optional<DependencyDirectivesTy>(std::move(Directives)));
92 std::max(2u, llvm::hardware_concurrency().compute_thread_count() / 4);
93 CacheShards = std::make_unique<CacheShard[]>(NumShards);
98 StringRef Filename)
const {
99 assert(llvm::sys::path::is_absolute_gnu(Filename));
105 llvm::sys::fs::UniqueID UID)
const {
106 auto Hash = llvm::hash_combine(UID.getDevice(), UID.getFile());
107 return CacheShards[Hash % NumShards];
110std::vector<DependencyScanningFilesystemSharedCache::OutOfDateEntry>
112 llvm::vfs::FileSystem &UnderlyingFS)
const {
114 std::vector<OutOfDateEntry> InvalidDiagInfo;
115 for (
unsigned i = 0; i < NumShards; i++) {
117 std::lock_guard<std::mutex> LockGuard(Shard.
CacheLock);
125 llvm::ErrorOr<llvm::vfs::Status> Status = UnderlyingFS.status(Path);
132 InvalidDiagInfo.emplace_back(Path.data());
134 llvm::vfs::Status CachedStatus = Entry->
getStatus();
135 if (Status->getType() == llvm::sys::fs::file_type::regular_file &&
136 Status->getType() == CachedStatus.getType()) {
144 uint64_t CachedSize = CachedStatus.getSize();
145 uint64_t ActualSize = Status->getSize();
146 if (CachedSize != ActualSize) {
149 InvalidDiagInfo.emplace_back(Path.data(), CachedSize, ActualSize);
156 return InvalidDiagInfo;
160using InProgressEntry =
162using SlotResolved = llvm::ErrorOr<const CachedFileSystemEntry *>;
163using SlotProducer = std::shared_ptr<InProgressEntry>;
164using SlotAcquisitionResult = std::variant<SlotResolved, SlotProducer>;
169template <
typename Map,
typename Key>
170SlotAcquisitionResult acquireSlot(std::mutex &CacheLock, Map &M,
const Key &K) {
171 std::shared_ptr<InProgressEntry> Pending;
173 std::lock_guard<std::mutex> ShardLock(CacheLock);
178 return SlotResolved{State.Entry};
180 if (!State.InProgress) {
181 State.InProgress = std::make_shared<InProgressEntry>();
182 return SlotProducer{State.InProgress};
187 Pending = State.InProgress;
191 std::unique_lock<std::mutex> EntryLock(Pending->Mutex);
192 Pending->CondVar.wait(EntryLock, [&] {
return Pending->Done; });
193 return SlotResolved{Pending->Result};
199 StringRef Filename)
const {
200 assert(llvm::sys::path::is_absolute_gnu(Filename));
201 std::lock_guard<std::mutex> LockGuard(
CacheLock);
208 llvm::ErrorOr<llvm::StringRef> RealPath) {
209 std::lock_guard<std::mutex> LockGuard(
CacheLock);
212 if (!StoredRealPath) {
215 return RealPath.getError();
216 return RealPath->str();
223 return *StoredRealPath;
231 Service(Service), WorkingDirForCacheLookup(
llvm::errc::invalid_argument) {
232 updateWorkingDirForCacheLookup();
236DependencyScanningWorkerFilesystem::resolveUIDThroughSharedCache(
237 StringRef OriginalFilename,
const llvm::vfs::Status &Stat) {
239 auto UIDSlot = acquireSlot(UIDShard.CacheLock, UIDShard.EntriesByUID,
241 if (
auto *Resolved = std::get_if<SlotResolved>(&UIDSlot)) {
242 assert(*Resolved && **Resolved &&
243 "in-progress UID slot fulfilled without an entry");
246 auto UIDProducer = std::move(std::get<SlotProducer>(UIDSlot));
249 Stat.isDirectory() ? TentativeEntry(Stat) : readFile(OriginalFilename);
257 std::lock_guard<std::mutex> ShardLock(UIDShard.CacheLock);
258 auto &State = UIDShard.EntriesByUID[Stat.getUniqueID()];
259 assert(!State.Entry &&
"UID slot already published an entry");
262 if (TEntry->Contents)
263 StoredContents =
new (UIDShard.ContentsStorage.Allocate())
265 SharedEntry =
new (UIDShard.EntryStorage.Allocate())
268 SharedEntry =
new (UIDShard.EntryStorage.Allocate())
271 State.Entry = SharedEntry;
272 State.InProgress.reset();
274 UIDProducer->publish(SharedEntry);
278llvm::ErrorOr<const CachedFileSystemEntry *>
279DependencyScanningWorkerFilesystem::resolveFilenameThroughSharedCache(
280 StringRef OriginalFilename, StringRef FilenameForLookup) {
281 assert(llvm::sys::path::is_absolute_gnu(FilenameForLookup));
282 auto &FilenameShard =
283 Service.getSharedCache().getShardForFilename(FilenameForLookup);
285 acquireSlot(FilenameShard.CacheLock, FilenameShard.CacheByFilename,
287 if (
auto *Resolved = std::get_if<SlotResolved>(&FilenameSlot))
289 auto FilenameProducer = std::move(std::get<SlotProducer>(FilenameSlot));
298 auto Stat = getUnderlyingFS().status(OriginalFilename);
299 const bool ShouldCacheNegativeStat =
300 !Stat && Service.getOpts().CacheNegativeStats &&
302 llvm::ErrorOr<const CachedFileSystemEntry *>
Result = std::error_code{};
304 Result = resolveUIDThroughSharedCache(OriginalFilename, *Stat);
305 else if (!ShouldCacheNegativeStat)
312 std::lock_guard<std::mutex> ShardLock(FilenameShard.CacheLock);
313 auto &State = FilenameShard.CacheByFilename[FilenameForLookup];
314 assert(!State.Entry &&
"filename slot already published an entry");
315 if (ShouldCacheNegativeStat) {
316 auto *Entry =
new (FilenameShard.EntryStorage.Allocate())
317 CachedFileSystemEntry(Stat.getError());
323 State.InProgress.reset();
325 FilenameProducer->publish(
Result);
329llvm::ErrorOr<EntryRef>
331 StringRef OriginalFilename) {
333 auto FilenameForLookup = tryGetFilenameForLookup(OriginalFilename, PathBuf);
334 if (!FilenameForLookup)
335 return FilenameForLookup.getError();
337 auto &Local = LocalCache[*FilenameForLookup];
342 resolveFilenameThroughSharedCache(OriginalFilename, *FilenameForLookup);
344 return MaybeEntry.getError();
345 Local.File = *MaybeEntry;
349llvm::ErrorOr<llvm::vfs::Status>
352 StringRef Filename = Path.toStringRef(OwnedFilename);
357 return Result->getStatus();
367 llvm::ErrorOr<llvm::vfs::Status> Status =
status(Path);
368 return Status && Status->exists();
375class DepScanFile final :
public llvm::vfs::File {
377 DepScanFile(std::unique_ptr<llvm::MemoryBuffer> Buffer,
378 llvm::vfs::Status Stat)
379 : Buffer(
std::move(Buffer)), Stat(
std::move(Stat)) {}
381 static llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> create(
EntryRef Entry);
383 llvm::ErrorOr<llvm::vfs::Status> status()
override {
return Stat; }
385 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
386 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
387 bool IsVolatile)
override {
388 return llvm::MemoryBuffer::getMemBuffer(Buffer->getMemBufferRef(),
389 RequiresNullTerminator);
392 std::error_code close()
override {
return {}; }
395 std::unique_ptr<llvm::MemoryBuffer> Buffer;
396 llvm::vfs::Status Stat;
401llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
402DepScanFile::create(
EntryRef Entry) {
403 assert(!Entry.
isError() &&
"error");
406 return std::make_error_code(std::errc::is_a_directory);
408 auto Result = std::make_unique<DepScanFile>(
409 llvm::MemoryBuffer::getMemBuffer(Entry.
getContents(),
414 return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
415 std::unique_ptr<llvm::vfs::File>(std::move(
Result)));
418llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
421 StringRef Filename = Path.toStringRef(OwnedFilename);
426 return DepScanFile::create(
Result.get());
433 StringRef OriginalFilename = Path.toStringRef(OwnedFilename);
436 auto FilenameForLookup = tryGetFilenameForLookup(OriginalFilename, PathBuf);
437 if (!FilenameForLookup)
438 return FilenameForLookup.getError();
440 auto HandleCachedRealPath =
443 return RealPath.getError();
444 Output.assign(RealPath->begin(), RealPath->end());
449 auto &Local = LocalCache[*FilenameForLookup];
451 return HandleCachedRealPath(*Local.RealPath);
455 Service.getSharedCache().getShardForFilename(*FilenameForLookup);
456 if (
const auto *ShardRealPath =
457 Shard.findRealPathByFilename(*FilenameForLookup)) {
458 Local.RealPath = ShardRealPath;
459 return HandleCachedRealPath(*Local.RealPath);
463 std::error_code EC = getUnderlyingFS().getRealPath(OriginalFilename, Output);
464 llvm::ErrorOr<llvm::StringRef> ComputedRealPath = EC;
466 ComputedRealPath = StringRef{Output.data(), Output.size()};
471 const auto &RealPath = Shard.getOrEmplaceRealPathForFilename(
472 *FilenameForLookup, ComputedRealPath);
473 Local.RealPath = &RealPath;
474 return HandleCachedRealPath(*Local.RealPath);
479 std::error_code EC = ProxyFileSystem::setCurrentWorkingDirectory(Path);
480 updateWorkingDirForCacheLookup();
484void DependencyScanningWorkerFilesystem::updateWorkingDirForCacheLookup() {
485 llvm::ErrorOr<std::string> CWD =
486 getUnderlyingFS().getCurrentWorkingDirectory();
488 WorkingDirForCacheLookup = CWD.getError();
489 }
else if (!llvm::sys::path::is_absolute_gnu(*CWD)) {
490 WorkingDirForCacheLookup = llvm::errc::invalid_argument;
492 WorkingDirForCacheLookup = *CWD;
494 assert(!WorkingDirForCacheLookup ||
495 llvm::sys::path::is_absolute_gnu(*WorkingDirForCacheLookup));
498llvm::ErrorOr<StringRef>
499DependencyScanningWorkerFilesystem::tryGetFilenameForLookup(
500 StringRef OriginalFilename, llvm::SmallVectorImpl<char> &PathBuf)
const {
501 StringRef FilenameForLookup;
502 if (llvm::sys::path::is_absolute_gnu(OriginalFilename)) {
503 FilenameForLookup = OriginalFilename;
504 }
else if (!WorkingDirForCacheLookup) {
505 return WorkingDirForCacheLookup.getError();
507 StringRef RelFilename = OriginalFilename;
508 RelFilename.consume_front(
"./");
509 PathBuf.assign(WorkingDirForCacheLookup->begin(),
510 WorkingDirForCacheLookup->end());
511 llvm::sys::path::append(PathBuf, RelFilename);
512 FilenameForLookup = StringRef{PathBuf.begin(), PathBuf.size()};
514 assert(llvm::sys::path::is_absolute_gnu(FilenameForLookup));
515 return FilenameForLookup;
An in-memory representation of a file system entity that is of interest to the dependency scanning fi...
llvm::vfs::Status getStatus() const
std::error_code getError() const
CacheShard & getShardForUID(llvm::sys::fs::UniqueID UID) const
CacheShard & getShardForFilename(StringRef Filename) const
Returns shard for the given key.
std::vector< OutOfDateEntry > getOutOfDateEntries(llvm::vfs::FileSystem &UnderlyingFS) const
Visits all cached entries and re-stat an entry using UnderlyingFS to check if the cache contains out-...
DependencyScanningFilesystemSharedCache()
The dependency scanning service contains shared configuration and state that is used by the individua...
DependencyScanningFilesystemSharedCache & getSharedCache()
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) override
bool ensureDirectiveTokensArePopulated(EntryRef Entry)
Ensure the directive tokens are populated for this file entry.
bool exists(const Twine &Path) override
Check whether Path exists.
DependencyScanningWorkerFilesystem(DependencyScanningService &Service, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
llvm::ErrorOr< EntryRef > getOrCreateFileSystemEntry(StringRef Filename)
Returns entry for the given filename.
llvm::ErrorOr< std::unique_ptr< llvm::vfs::File > > openFileForRead(const Twine &Path) override
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
llvm::ErrorOr< llvm::vfs::Status > status(const Twine &Path) override
Reference to a CachedFileSystemEntry.
llvm::vfs::Status getStatus() const
StringRef getContents() const
llvm::ErrorOr< EntryRef > unwrapError() const
If the cached entry represents an error, promotes it into ErrorOr.
llvm::ErrorOr< std::string > CachedRealPath
bool shouldCacheNegativeStatsForPath(StringRef Path)
The JSON file list parser is used to communicate input to InstallAPI.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool scanSourceForDependencyDirectives(StringRef Input, SmallVectorImpl< dependency_directives_scan::Token > &Tokens, SmallVectorImpl< dependency_directives_scan::Directive > &Directives, DiagnosticsEngine *Diags=nullptr, SourceLocation InputSourceLoc=SourceLocation())
Scan the input for the preprocessor directives that might have an effect on the dependencies for a co...
@ Result
The result type of a method or function.
Diagnostic wrappers for TextAPI types for error reporting.
hash_code hash_value(const clang::dependencies::ModuleID &ID)
Contents and directive tokens of a cached file entry.
std::unique_ptr< llvm::MemoryBuffer > Original
Owning storage for the original contents.
SmallVector< dependency_directives_scan::Token, 10 > DepDirectiveTokens
std::atomic< const std::optional< DependencyDirectivesTy > * > DepDirectives
Accessor to the directive tokens that's atomic to avoid data races.
std::mutex ValueLock
The mutex that must be locked before mutating directive tokens.
llvm::StringMap< FilenameCacheState, llvm::BumpPtrAllocator > CacheByFilename
Map from filenames to their cached state.
llvm::SpecificBumpPtrAllocator< CachedRealPath > RealPathStorage
The backing storage for cached real paths.
const CachedRealPath * findRealPathByFilename(StringRef Filename) const
Returns the real path associated with the filename or nullptr if none is found.
std::mutex CacheLock
The mutex that needs to be locked before mutation of any member.
const CachedRealPath & getOrEmplaceRealPathForFilename(StringRef Filename, llvm::ErrorOr< StringRef > RealPath)
Returns the real path associated with the filename if there is some.
In-flight slot used to dedup concurrent producers for the same key.