17330f729Sjoerg //===- DependencyScanningFilesystem.cpp - clang-scan-deps fs --------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg 
97330f729Sjoerg #include "clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h"
107330f729Sjoerg #include "clang/Lex/DependencyDirectivesSourceMinimizer.h"
117330f729Sjoerg #include "llvm/Support/MemoryBuffer.h"
127330f729Sjoerg #include "llvm/Support/Threading.h"
137330f729Sjoerg 
147330f729Sjoerg using namespace clang;
157330f729Sjoerg using namespace tooling;
167330f729Sjoerg using namespace dependencies;
177330f729Sjoerg 
createFileEntry(StringRef Filename,llvm::vfs::FileSystem & FS,bool Minimize)187330f729Sjoerg CachedFileSystemEntry CachedFileSystemEntry::createFileEntry(
197330f729Sjoerg     StringRef Filename, llvm::vfs::FileSystem &FS, bool Minimize) {
207330f729Sjoerg   // Load the file and its content from the file system.
217330f729Sjoerg   llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> MaybeFile =
227330f729Sjoerg       FS.openFileForRead(Filename);
237330f729Sjoerg   if (!MaybeFile)
247330f729Sjoerg     return MaybeFile.getError();
257330f729Sjoerg   llvm::ErrorOr<llvm::vfs::Status> Stat = (*MaybeFile)->status();
267330f729Sjoerg   if (!Stat)
277330f729Sjoerg     return Stat.getError();
287330f729Sjoerg 
297330f729Sjoerg   llvm::vfs::File &F = **MaybeFile;
307330f729Sjoerg   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MaybeBuffer =
317330f729Sjoerg       F.getBuffer(Stat->getName());
327330f729Sjoerg   if (!MaybeBuffer)
337330f729Sjoerg     return MaybeBuffer.getError();
347330f729Sjoerg 
357330f729Sjoerg   llvm::SmallString<1024> MinimizedFileContents;
367330f729Sjoerg   // Minimize the file down to directives that might affect the dependencies.
377330f729Sjoerg   const auto &Buffer = *MaybeBuffer;
387330f729Sjoerg   SmallVector<minimize_source_to_dependency_directives::Token, 64> Tokens;
397330f729Sjoerg   if (!Minimize || minimizeSourceToDependencyDirectives(
407330f729Sjoerg                        Buffer->getBuffer(), MinimizedFileContents, Tokens)) {
417330f729Sjoerg     // Use the original file unless requested otherwise, or
427330f729Sjoerg     // if the minimization failed.
437330f729Sjoerg     // FIXME: Propage the diagnostic if desired by the client.
447330f729Sjoerg     CachedFileSystemEntry Result;
457330f729Sjoerg     Result.MaybeStat = std::move(*Stat);
467330f729Sjoerg     Result.Contents.reserve(Buffer->getBufferSize() + 1);
477330f729Sjoerg     Result.Contents.append(Buffer->getBufferStart(), Buffer->getBufferEnd());
487330f729Sjoerg     // Implicitly null terminate the contents for Clang's lexer.
497330f729Sjoerg     Result.Contents.push_back('\0');
507330f729Sjoerg     Result.Contents.pop_back();
517330f729Sjoerg     return Result;
527330f729Sjoerg   }
537330f729Sjoerg 
547330f729Sjoerg   CachedFileSystemEntry Result;
557330f729Sjoerg   size_t Size = MinimizedFileContents.size();
567330f729Sjoerg   Result.MaybeStat = llvm::vfs::Status(Stat->getName(), Stat->getUniqueID(),
577330f729Sjoerg                                        Stat->getLastModificationTime(),
587330f729Sjoerg                                        Stat->getUser(), Stat->getGroup(), Size,
597330f729Sjoerg                                        Stat->getType(), Stat->getPermissions());
607330f729Sjoerg   // The contents produced by the minimizer must be null terminated.
617330f729Sjoerg   assert(MinimizedFileContents.data()[MinimizedFileContents.size()] == '\0' &&
627330f729Sjoerg          "not null terminated contents");
637330f729Sjoerg   // Even though there's an implicit null terminator in the minimized contents,
647330f729Sjoerg   // we want to temporarily make it explicit. This will ensure that the
657330f729Sjoerg   // std::move will preserve it even if it needs to do a copy if the
667330f729Sjoerg   // SmallString still has the small capacity.
677330f729Sjoerg   MinimizedFileContents.push_back('\0');
687330f729Sjoerg   Result.Contents = std::move(MinimizedFileContents);
697330f729Sjoerg   // Now make the null terminator implicit again, so that Clang's lexer can find
707330f729Sjoerg   // it right where the buffer ends.
717330f729Sjoerg   Result.Contents.pop_back();
727330f729Sjoerg 
737330f729Sjoerg   // Compute the skipped PP ranges that speedup skipping over inactive
747330f729Sjoerg   // preprocessor blocks.
757330f729Sjoerg   llvm::SmallVector<minimize_source_to_dependency_directives::SkippedRange, 32>
767330f729Sjoerg       SkippedRanges;
777330f729Sjoerg   minimize_source_to_dependency_directives::computeSkippedRanges(Tokens,
787330f729Sjoerg                                                                  SkippedRanges);
797330f729Sjoerg   PreprocessorSkippedRangeMapping Mapping;
807330f729Sjoerg   for (const auto &Range : SkippedRanges) {
817330f729Sjoerg     if (Range.Length < 16) {
827330f729Sjoerg       // Ignore small ranges as non-profitable.
837330f729Sjoerg       // FIXME: This is a heuristic, its worth investigating the tradeoffs
847330f729Sjoerg       // when it should be applied.
857330f729Sjoerg       continue;
867330f729Sjoerg     }
877330f729Sjoerg     Mapping[Range.Offset] = Range.Length;
887330f729Sjoerg   }
897330f729Sjoerg   Result.PPSkippedRangeMapping = std::move(Mapping);
907330f729Sjoerg 
917330f729Sjoerg   return Result;
927330f729Sjoerg }
937330f729Sjoerg 
947330f729Sjoerg CachedFileSystemEntry
createDirectoryEntry(llvm::vfs::Status && Stat)957330f729Sjoerg CachedFileSystemEntry::createDirectoryEntry(llvm::vfs::Status &&Stat) {
967330f729Sjoerg   assert(Stat.isDirectory() && "not a directory!");
977330f729Sjoerg   auto Result = CachedFileSystemEntry();
987330f729Sjoerg   Result.MaybeStat = std::move(Stat);
997330f729Sjoerg   return Result;
1007330f729Sjoerg }
1017330f729Sjoerg 
1027330f729Sjoerg DependencyScanningFilesystemSharedCache::
DependencyScanningFilesystemSharedCache()1037330f729Sjoerg     DependencyScanningFilesystemSharedCache() {
1047330f729Sjoerg   // This heuristic was chosen using a empirical testing on a
1057330f729Sjoerg   // reasonably high core machine (iMacPro 18 cores / 36 threads). The cache
1067330f729Sjoerg   // sharding gives a performance edge by reducing the lock contention.
1077330f729Sjoerg   // FIXME: A better heuristic might also consider the OS to account for
1087330f729Sjoerg   // the different cost of lock contention on different OSes.
109*e038c9c4Sjoerg   NumShards =
110*e038c9c4Sjoerg       std::max(2u, llvm::hardware_concurrency().compute_thread_count() / 4);
1117330f729Sjoerg   CacheShards = std::make_unique<CacheShard[]>(NumShards);
1127330f729Sjoerg }
1137330f729Sjoerg 
1147330f729Sjoerg /// Returns a cache entry for the corresponding key.
1157330f729Sjoerg ///
1167330f729Sjoerg /// A new cache entry is created if the key is not in the cache. This is a
1177330f729Sjoerg /// thread safe call.
1187330f729Sjoerg DependencyScanningFilesystemSharedCache::SharedFileSystemEntry &
get(StringRef Key)1197330f729Sjoerg DependencyScanningFilesystemSharedCache::get(StringRef Key) {
1207330f729Sjoerg   CacheShard &Shard = CacheShards[llvm::hash_value(Key) % NumShards];
1217330f729Sjoerg   std::unique_lock<std::mutex> LockGuard(Shard.CacheLock);
1227330f729Sjoerg   auto It = Shard.Cache.try_emplace(Key);
1237330f729Sjoerg   return It.first->getValue();
1247330f729Sjoerg }
1257330f729Sjoerg 
1267330f729Sjoerg /// Whitelist file extensions that should be minimized, treating no extension as
1277330f729Sjoerg /// a source file that should be minimized.
1287330f729Sjoerg ///
1297330f729Sjoerg /// This is kinda hacky, it would be better if we knew what kind of file Clang
1307330f729Sjoerg /// was expecting instead.
shouldMinimize(StringRef Filename)1317330f729Sjoerg static bool shouldMinimize(StringRef Filename) {
1327330f729Sjoerg   StringRef Ext = llvm::sys::path::extension(Filename);
1337330f729Sjoerg   if (Ext.empty())
1347330f729Sjoerg     return true; // C++ standard library
1357330f729Sjoerg   return llvm::StringSwitch<bool>(Ext)
1367330f729Sjoerg     .CasesLower(".c", ".cc", ".cpp", ".c++", ".cxx", true)
1377330f729Sjoerg     .CasesLower(".h", ".hh", ".hpp", ".h++", ".hxx", true)
1387330f729Sjoerg     .CasesLower(".m", ".mm", true)
1397330f729Sjoerg     .CasesLower(".i", ".ii", ".mi", ".mmi", true)
1407330f729Sjoerg     .CasesLower(".def", ".inc", true)
1417330f729Sjoerg     .Default(false);
1427330f729Sjoerg }
1437330f729Sjoerg 
1447330f729Sjoerg 
shouldCacheStatFailures(StringRef Filename)1457330f729Sjoerg static bool shouldCacheStatFailures(StringRef Filename) {
1467330f729Sjoerg   StringRef Ext = llvm::sys::path::extension(Filename);
1477330f729Sjoerg   if (Ext.empty())
1487330f729Sjoerg     return false; // This may be the module cache directory.
1497330f729Sjoerg   return shouldMinimize(Filename); // Only cache stat failures on source files.
1507330f729Sjoerg }
1517330f729Sjoerg 
1527330f729Sjoerg llvm::ErrorOr<const CachedFileSystemEntry *>
getOrCreateFileSystemEntry(const StringRef Filename)1537330f729Sjoerg DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
1547330f729Sjoerg     const StringRef Filename) {
1557330f729Sjoerg   if (const CachedFileSystemEntry *Entry = getCachedEntry(Filename)) {
1567330f729Sjoerg     return Entry;
1577330f729Sjoerg   }
1587330f729Sjoerg 
1597330f729Sjoerg   // FIXME: Handle PCM/PCH files.
1607330f729Sjoerg   // FIXME: Handle module map files.
1617330f729Sjoerg 
1627330f729Sjoerg   bool KeepOriginalSource = IgnoredFiles.count(Filename) ||
1637330f729Sjoerg                             !shouldMinimize(Filename);
1647330f729Sjoerg   DependencyScanningFilesystemSharedCache::SharedFileSystemEntry
1657330f729Sjoerg       &SharedCacheEntry = SharedCache.get(Filename);
1667330f729Sjoerg   const CachedFileSystemEntry *Result;
1677330f729Sjoerg   {
1687330f729Sjoerg     std::unique_lock<std::mutex> LockGuard(SharedCacheEntry.ValueLock);
1697330f729Sjoerg     CachedFileSystemEntry &CacheEntry = SharedCacheEntry.Value;
1707330f729Sjoerg 
1717330f729Sjoerg     if (!CacheEntry.isValid()) {
1727330f729Sjoerg       llvm::vfs::FileSystem &FS = getUnderlyingFS();
1737330f729Sjoerg       auto MaybeStatus = FS.status(Filename);
1747330f729Sjoerg       if (!MaybeStatus) {
1757330f729Sjoerg         if (!shouldCacheStatFailures(Filename))
1767330f729Sjoerg           // HACK: We need to always restat non source files if the stat fails.
1777330f729Sjoerg           //   This is because Clang first looks up the module cache and module
1787330f729Sjoerg           //   files before building them, and then looks for them again. If we
1797330f729Sjoerg           //   cache the stat failure, it won't see them the second time.
1807330f729Sjoerg           return MaybeStatus.getError();
1817330f729Sjoerg         else
1827330f729Sjoerg           CacheEntry = CachedFileSystemEntry(MaybeStatus.getError());
1837330f729Sjoerg       } else if (MaybeStatus->isDirectory())
1847330f729Sjoerg         CacheEntry = CachedFileSystemEntry::createDirectoryEntry(
1857330f729Sjoerg             std::move(*MaybeStatus));
1867330f729Sjoerg       else
1877330f729Sjoerg         CacheEntry = CachedFileSystemEntry::createFileEntry(
1887330f729Sjoerg             Filename, FS, !KeepOriginalSource);
1897330f729Sjoerg     }
1907330f729Sjoerg 
1917330f729Sjoerg     Result = &CacheEntry;
1927330f729Sjoerg   }
1937330f729Sjoerg 
1947330f729Sjoerg   // Store the result in the local cache.
1957330f729Sjoerg   setCachedEntry(Filename, Result);
1967330f729Sjoerg   return Result;
1977330f729Sjoerg }
1987330f729Sjoerg 
1997330f729Sjoerg llvm::ErrorOr<llvm::vfs::Status>
status(const Twine & Path)2007330f729Sjoerg DependencyScanningWorkerFilesystem::status(const Twine &Path) {
2017330f729Sjoerg   SmallString<256> OwnedFilename;
2027330f729Sjoerg   StringRef Filename = Path.toStringRef(OwnedFilename);
2037330f729Sjoerg   const llvm::ErrorOr<const CachedFileSystemEntry *> Result =
2047330f729Sjoerg       getOrCreateFileSystemEntry(Filename);
2057330f729Sjoerg   if (!Result)
2067330f729Sjoerg     return Result.getError();
2077330f729Sjoerg   return (*Result)->getStatus();
2087330f729Sjoerg }
2097330f729Sjoerg 
2107330f729Sjoerg namespace {
2117330f729Sjoerg 
2127330f729Sjoerg /// The VFS that is used by clang consumes the \c CachedFileSystemEntry using
2137330f729Sjoerg /// this subclass.
2147330f729Sjoerg class MinimizedVFSFile final : public llvm::vfs::File {
2157330f729Sjoerg public:
MinimizedVFSFile(std::unique_ptr<llvm::MemoryBuffer> Buffer,llvm::vfs::Status Stat)2167330f729Sjoerg   MinimizedVFSFile(std::unique_ptr<llvm::MemoryBuffer> Buffer,
2177330f729Sjoerg                    llvm::vfs::Status Stat)
2187330f729Sjoerg       : Buffer(std::move(Buffer)), Stat(std::move(Stat)) {}
2197330f729Sjoerg 
220*e038c9c4Sjoerg   static llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
221*e038c9c4Sjoerg   create(const CachedFileSystemEntry *Entry,
222*e038c9c4Sjoerg          ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings);
2237330f729Sjoerg 
status()224*e038c9c4Sjoerg   llvm::ErrorOr<llvm::vfs::Status> status() override { return Stat; }
2257330f729Sjoerg 
2267330f729Sjoerg   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
getBuffer(const Twine & Name,int64_t FileSize,bool RequiresNullTerminator,bool IsVolatile)2277330f729Sjoerg   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
2287330f729Sjoerg             bool IsVolatile) override {
2297330f729Sjoerg     return std::move(Buffer);
2307330f729Sjoerg   }
2317330f729Sjoerg 
close()2327330f729Sjoerg   std::error_code close() override { return {}; }
2337330f729Sjoerg 
2347330f729Sjoerg private:
2357330f729Sjoerg   std::unique_ptr<llvm::MemoryBuffer> Buffer;
2367330f729Sjoerg   llvm::vfs::Status Stat;
2377330f729Sjoerg };
2387330f729Sjoerg 
239*e038c9c4Sjoerg } // end anonymous namespace
240*e038c9c4Sjoerg 
create(const CachedFileSystemEntry * Entry,ExcludedPreprocessorDirectiveSkipMapping * PPSkipMappings)241*e038c9c4Sjoerg llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> MinimizedVFSFile::create(
242*e038c9c4Sjoerg     const CachedFileSystemEntry *Entry,
2437330f729Sjoerg     ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings) {
2447330f729Sjoerg   if (Entry->isDirectory())
2457330f729Sjoerg     return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
2467330f729Sjoerg         std::make_error_code(std::errc::is_a_directory));
2477330f729Sjoerg   llvm::ErrorOr<StringRef> Contents = Entry->getContents();
2487330f729Sjoerg   if (!Contents)
2497330f729Sjoerg     return Contents.getError();
2507330f729Sjoerg   auto Result = std::make_unique<MinimizedVFSFile>(
2517330f729Sjoerg       llvm::MemoryBuffer::getMemBuffer(*Contents, Entry->getName(),
2527330f729Sjoerg                                        /*RequiresNullTerminator=*/false),
2537330f729Sjoerg       *Entry->getStatus());
2547330f729Sjoerg   if (!Entry->getPPSkippedRangeMapping().empty() && PPSkipMappings)
255*e038c9c4Sjoerg     (*PPSkipMappings)[Result->Buffer->getBufferStart()] =
2567330f729Sjoerg         &Entry->getPPSkippedRangeMapping();
2577330f729Sjoerg   return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
2587330f729Sjoerg       std::unique_ptr<llvm::vfs::File>(std::move(Result)));
2597330f729Sjoerg }
2607330f729Sjoerg 
2617330f729Sjoerg llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
openFileForRead(const Twine & Path)2627330f729Sjoerg DependencyScanningWorkerFilesystem::openFileForRead(const Twine &Path) {
2637330f729Sjoerg   SmallString<256> OwnedFilename;
2647330f729Sjoerg   StringRef Filename = Path.toStringRef(OwnedFilename);
2657330f729Sjoerg 
2667330f729Sjoerg   const llvm::ErrorOr<const CachedFileSystemEntry *> Result =
2677330f729Sjoerg       getOrCreateFileSystemEntry(Filename);
2687330f729Sjoerg   if (!Result)
2697330f729Sjoerg     return Result.getError();
270*e038c9c4Sjoerg   return MinimizedVFSFile::create(Result.get(), PPSkipMappings);
2717330f729Sjoerg }
272