10#include "llvm/Support/MemoryBuffer.h"
11#include "llvm/Support/Threading.h"
15using namespace tooling;
16using namespace dependencies;
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);
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);
120 llvm::ErrorOr<llvm::vfs::Status> Status = UnderlyingFS.status(
Path);
127 InvalidDiagInfo.emplace_back(
Path.data());
129 llvm::vfs::Status CachedStatus = Entry->
getStatus();
130 if (Status->getType() == llvm::sys::fs::file_type::regular_file &&
131 Status->getType() == CachedStatus.getType()) {
139 uint64_t CachedSize = CachedStatus.getSize();
140 uint64_t ActualSize = Status->getSize();
141 if (CachedSize != ActualSize) {
144 InvalidDiagInfo.emplace_back(
Path.data(), CachedSize, ActualSize);
151 return InvalidDiagInfo;
157 assert(llvm::sys::path::is_absolute_gnu(
Filename));
158 std::lock_guard<std::mutex> LockGuard(
CacheLock);
165 llvm::sys::fs::UniqueID UID)
const {
166 std::lock_guard<std::mutex> LockGuard(CacheLock);
167 auto It = EntriesByUID.find(UID);
168 return It == EntriesByUID.end() ? nullptr : It->getSecond();
174 llvm::ErrorOr<llvm::vfs::Status> Stat) {
175 std::lock_guard<std::mutex> LockGuard(CacheLock);
176 auto [It, Inserted] = CacheByFilename.insert({
Filename, {
nullptr,
nullptr}});
181 assert((Inserted ||
CachedRealPath) &&
"existing file with empty pair");
190 llvm::sys::fs::UniqueID UID, llvm::vfs::Status Stat,
191 std::unique_ptr<llvm::MemoryBuffer> Contents) {
192 std::lock_guard<std::mutex> LockGuard(CacheLock);
193 auto [It, Inserted] = EntriesByUID.try_emplace(UID);
194 auto &CachedEntry = It->getSecond();
198 StoredContents =
new (ContentsStorage.Allocate())
200 CachedEntry =
new (EntryStorage.Allocate())
210 std::lock_guard<std::mutex> LockGuard(CacheLock);
211 auto [It, Inserted] = CacheByFilename.insert({
Filename, {&Entry,
nullptr}});
213 if (!Inserted || !CachedEntry)
214 CachedEntry = &Entry;
221 assert(llvm::sys::path::is_absolute_gnu(
Filename));
222 std::lock_guard<std::mutex> LockGuard(CacheLock);
223 auto It = CacheByFilename.find(
Filename);
224 return It == CacheByFilename.end() ? nullptr : It->getValue().second;
229 llvm::ErrorOr<llvm::StringRef> RealPath) {
230 std::lock_guard<std::mutex> LockGuard(CacheLock);
233 if (!StoredRealPath) {
236 return RealPath.getError();
237 return RealPath->str();
240 StoredRealPath =
new (RealPathStorage.Allocate())
244 return *StoredRealPath;
247bool DependencyScanningWorkerFilesystem::shouldBypass(StringRef
Path)
const {
248 return BypassedPathPrefix &&
Path.starts_with(*BypassedPathPrefix);
255 llvm::vfs::ProxyFileSystem>(
std::move(FS)),
256 SharedCache(SharedCache),
257 WorkingDirForCacheLookup(
llvm::errc::invalid_argument) {
258 updateWorkingDirForCacheLookup();
262DependencyScanningWorkerFilesystem::getOrEmplaceSharedEntryForUID(
263 TentativeEntry TEntry) {
264 auto &Shard = SharedCache.
getShardForUID(TEntry.Status.getUniqueID());
266 std::move(TEntry.Status),
267 std::move(TEntry.Contents));
271DependencyScanningWorkerFilesystem::findEntryByFilenameWithWriteThrough(
276 if (
const auto *Entry = Shard.findEntryByFilename(
Filename))
281llvm::ErrorOr<const CachedFileSystemEntry &>
282DependencyScanningWorkerFilesystem::computeAndStoreResult(
283 StringRef OriginalFilename, StringRef FilenameForLookup) {
284 llvm::ErrorOr<llvm::vfs::Status> Stat =
285 getUnderlyingFS().status(OriginalFilename);
288 getOrEmplaceSharedEntryForFilename(FilenameForLookup, Stat.getError());
289 return insertLocalEntryForFilename(FilenameForLookup, Entry);
292 if (
const auto *Entry = findSharedEntryByUID(*Stat))
293 return insertLocalEntryForFilename(FilenameForLookup, *Entry);
296 Stat->isDirectory() ? TentativeEntry(*Stat) : readFile(OriginalFilename);
300 const auto &UIDEntry = getOrEmplaceSharedEntryForUID(std::move(*TEntry));
301 return &getOrInsertSharedEntryForFilename(FilenameForLookup, UIDEntry);
303 return &getOrEmplaceSharedEntryForFilename(FilenameForLookup,
307 return insertLocalEntryForFilename(FilenameForLookup, *SharedEntry);
310llvm::ErrorOr<EntryRef>
312 StringRef OriginalFilename) {
314 auto FilenameForLookup = tryGetFilenameForLookup(OriginalFilename, PathBuf);
315 if (!FilenameForLookup)
316 return FilenameForLookup.getError();
318 if (
const auto *Entry =
319 findEntryByFilenameWithWriteThrough(*FilenameForLookup))
321 auto MaybeEntry = computeAndStoreResult(OriginalFilename, *FilenameForLookup);
323 return MaybeEntry.getError();
327llvm::ErrorOr<llvm::vfs::Status>
333 return getUnderlyingFS().status(
Path);
338 return Result->getStatus();
348 llvm::ErrorOr<llvm::vfs::Status> Status =
status(
Path);
349 return Status && Status->exists();
356class DepScanFile final :
public llvm::vfs::File {
358 DepScanFile(std::unique_ptr<llvm::MemoryBuffer> Buffer,
359 llvm::vfs::Status Stat)
360 : Buffer(
std::move(Buffer)), Stat(
std::move(Stat)) {}
362 static llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> create(
EntryRef Entry);
364 llvm::ErrorOr<llvm::vfs::Status> status()
override {
return Stat; }
366 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
367 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
368 bool IsVolatile)
override {
369 return std::move(Buffer);
372 std::error_code close()
override {
return {}; }
375 std::unique_ptr<llvm::MemoryBuffer> Buffer;
376 llvm::vfs::Status Stat;
381llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
382DepScanFile::create(
EntryRef Entry) {
383 assert(!Entry.
isError() &&
"error");
386 return std::make_error_code(std::errc::is_a_directory);
388 auto Result = std::make_unique<DepScanFile>(
389 llvm::MemoryBuffer::getMemBuffer(Entry.
getContents(),
394 return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
395 std::unique_ptr<llvm::vfs::File>(std::move(
Result)));
398llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
404 return getUnderlyingFS().openFileForRead(
Path);
409 return DepScanFile::create(
Result.get());
416 StringRef OriginalFilename =
Path.toStringRef(OwnedFilename);
418 if (shouldBypass(OriginalFilename))
419 return getUnderlyingFS().getRealPath(
Path, Output);
422 auto FilenameForLookup = tryGetFilenameForLookup(OriginalFilename, PathBuf);
423 if (!FilenameForLookup)
424 return FilenameForLookup.getError();
426 auto HandleCachedRealPath =
429 return RealPath.getError();
430 Output.assign(RealPath->begin(), RealPath->end());
435 if (
const auto *RealPath =
437 return HandleCachedRealPath(*RealPath);
441 if (
const auto *ShardRealPath =
442 Shard.findRealPathByFilename(*FilenameForLookup)) {
444 *FilenameForLookup, *ShardRealPath);
445 return HandleCachedRealPath(RealPath);
449 std::error_code EC = getUnderlyingFS().getRealPath(OriginalFilename, Output);
450 llvm::ErrorOr<llvm::StringRef> ComputedRealPath = EC;
452 ComputedRealPath = StringRef{Output.data(), Output.size()};
457 const auto &RealPath = Shard.getOrEmplaceRealPathForFilename(
458 *FilenameForLookup, ComputedRealPath);
459 return HandleCachedRealPath(
465 std::error_code EC = ProxyFileSystem::setCurrentWorkingDirectory(
Path);
466 updateWorkingDirForCacheLookup();
470void DependencyScanningWorkerFilesystem::updateWorkingDirForCacheLookup() {
471 llvm::ErrorOr<std::string> CWD =
472 getUnderlyingFS().getCurrentWorkingDirectory();
474 WorkingDirForCacheLookup = CWD.getError();
475 }
else if (!llvm::sys::path::is_absolute_gnu(*CWD)) {
476 WorkingDirForCacheLookup = llvm::errc::invalid_argument;
478 WorkingDirForCacheLookup = *CWD;
480 assert(!WorkingDirForCacheLookup ||
481 llvm::sys::path::is_absolute_gnu(*WorkingDirForCacheLookup));
484llvm::ErrorOr<StringRef>
485DependencyScanningWorkerFilesystem::tryGetFilenameForLookup(
487 StringRef FilenameForLookup;
488 if (llvm::sys::path::is_absolute_gnu(OriginalFilename)) {
489 FilenameForLookup = OriginalFilename;
490 }
else if (!WorkingDirForCacheLookup) {
491 return WorkingDirForCacheLookup.getError();
493 StringRef RelFilename = OriginalFilename;
494 RelFilename.consume_front(
"./");
495 PathBuf.assign(WorkingDirForCacheLookup->begin(),
496 WorkingDirForCacheLookup->end());
497 llvm::sys::path::append(PathBuf, RelFilename);
498 FilenameForLookup = StringRef{PathBuf.begin(), PathBuf.size()};
500 assert(llvm::sys::path::is_absolute_gnu(FilenameForLookup));
501 return FilenameForLookup;
An in-memory representation of a file system entity that is of interest to the dependency scanning fi...
std::error_code getError() const
llvm::vfs::Status getStatus() const
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.
The JSON file list parser is used to communicate input to InstallAPI.
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::tooling::dependencies::ModuleID &ID)
Contents and directive tokens of a cached file entry.
std::mutex ValueLock
The mutex that must be locked before mutating directive tokens.
std::atomic< const std::optional< DependencyDirectivesTy > * > DepDirectives
Accessor to the directive tokens that's atomic to avoid data races.
std::unique_ptr< llvm::MemoryBuffer > Original
Owning storage for the original contents.
SmallVector< dependency_directives_scan::Token, 10 > DepDirectiveTokens