1a7dea167SDimitry Andric //===- DependencyScanningFilesystem.cpp - clang-scan-deps fs --------------===//
2a7dea167SDimitry Andric //
3a7dea167SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4a7dea167SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5a7dea167SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a7dea167SDimitry Andric //
7a7dea167SDimitry Andric //===----------------------------------------------------------------------===//
8a7dea167SDimitry Andric 
9a7dea167SDimitry Andric #include "clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h"
10a7dea167SDimitry Andric #include "clang/Lex/DependencyDirectivesSourceMinimizer.h"
11a7dea167SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
12a7dea167SDimitry Andric #include "llvm/Support/Threading.h"
13a7dea167SDimitry Andric 
14a7dea167SDimitry Andric using namespace clang;
15a7dea167SDimitry Andric using namespace tooling;
16a7dea167SDimitry Andric using namespace dependencies;
17a7dea167SDimitry Andric 
18a7dea167SDimitry Andric CachedFileSystemEntry CachedFileSystemEntry::createFileEntry(
19a7dea167SDimitry Andric     StringRef Filename, llvm::vfs::FileSystem &FS, bool Minimize) {
20a7dea167SDimitry Andric   // Load the file and its content from the file system.
21a7dea167SDimitry Andric   llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> MaybeFile =
22a7dea167SDimitry Andric       FS.openFileForRead(Filename);
23a7dea167SDimitry Andric   if (!MaybeFile)
24a7dea167SDimitry Andric     return MaybeFile.getError();
25a7dea167SDimitry Andric   llvm::ErrorOr<llvm::vfs::Status> Stat = (*MaybeFile)->status();
26a7dea167SDimitry Andric   if (!Stat)
27a7dea167SDimitry Andric     return Stat.getError();
28a7dea167SDimitry Andric 
29a7dea167SDimitry Andric   llvm::vfs::File &F = **MaybeFile;
30a7dea167SDimitry Andric   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MaybeBuffer =
31a7dea167SDimitry Andric       F.getBuffer(Stat->getName());
32a7dea167SDimitry Andric   if (!MaybeBuffer)
33a7dea167SDimitry Andric     return MaybeBuffer.getError();
34a7dea167SDimitry Andric 
35a7dea167SDimitry Andric   llvm::SmallString<1024> MinimizedFileContents;
36a7dea167SDimitry Andric   // Minimize the file down to directives that might affect the dependencies.
37a7dea167SDimitry Andric   const auto &Buffer = *MaybeBuffer;
38a7dea167SDimitry Andric   SmallVector<minimize_source_to_dependency_directives::Token, 64> Tokens;
39a7dea167SDimitry Andric   if (!Minimize || minimizeSourceToDependencyDirectives(
40a7dea167SDimitry Andric                        Buffer->getBuffer(), MinimizedFileContents, Tokens)) {
41a7dea167SDimitry Andric     // Use the original file unless requested otherwise, or
42a7dea167SDimitry Andric     // if the minimization failed.
43a7dea167SDimitry Andric     // FIXME: Propage the diagnostic if desired by the client.
44a7dea167SDimitry Andric     CachedFileSystemEntry Result;
45a7dea167SDimitry Andric     Result.MaybeStat = std::move(*Stat);
46a7dea167SDimitry Andric     Result.Contents.reserve(Buffer->getBufferSize() + 1);
47a7dea167SDimitry Andric     Result.Contents.append(Buffer->getBufferStart(), Buffer->getBufferEnd());
48a7dea167SDimitry Andric     // Implicitly null terminate the contents for Clang's lexer.
49a7dea167SDimitry Andric     Result.Contents.push_back('\0');
50a7dea167SDimitry Andric     Result.Contents.pop_back();
51a7dea167SDimitry Andric     return Result;
52a7dea167SDimitry Andric   }
53a7dea167SDimitry Andric 
54a7dea167SDimitry Andric   CachedFileSystemEntry Result;
55a7dea167SDimitry Andric   size_t Size = MinimizedFileContents.size();
56a7dea167SDimitry Andric   Result.MaybeStat = llvm::vfs::Status(Stat->getName(), Stat->getUniqueID(),
57a7dea167SDimitry Andric                                        Stat->getLastModificationTime(),
58a7dea167SDimitry Andric                                        Stat->getUser(), Stat->getGroup(), Size,
59a7dea167SDimitry Andric                                        Stat->getType(), Stat->getPermissions());
60a7dea167SDimitry Andric   // The contents produced by the minimizer must be null terminated.
61a7dea167SDimitry Andric   assert(MinimizedFileContents.data()[MinimizedFileContents.size()] == '\0' &&
62a7dea167SDimitry Andric          "not null terminated contents");
63a7dea167SDimitry Andric   // Even though there's an implicit null terminator in the minimized contents,
64a7dea167SDimitry Andric   // we want to temporarily make it explicit. This will ensure that the
65a7dea167SDimitry Andric   // std::move will preserve it even if it needs to do a copy if the
66a7dea167SDimitry Andric   // SmallString still has the small capacity.
67a7dea167SDimitry Andric   MinimizedFileContents.push_back('\0');
68a7dea167SDimitry Andric   Result.Contents = std::move(MinimizedFileContents);
69a7dea167SDimitry Andric   // Now make the null terminator implicit again, so that Clang's lexer can find
70a7dea167SDimitry Andric   // it right where the buffer ends.
71a7dea167SDimitry Andric   Result.Contents.pop_back();
72a7dea167SDimitry Andric 
73a7dea167SDimitry Andric   // Compute the skipped PP ranges that speedup skipping over inactive
74a7dea167SDimitry Andric   // preprocessor blocks.
75a7dea167SDimitry Andric   llvm::SmallVector<minimize_source_to_dependency_directives::SkippedRange, 32>
76a7dea167SDimitry Andric       SkippedRanges;
77a7dea167SDimitry Andric   minimize_source_to_dependency_directives::computeSkippedRanges(Tokens,
78a7dea167SDimitry Andric                                                                  SkippedRanges);
79a7dea167SDimitry Andric   PreprocessorSkippedRangeMapping Mapping;
80a7dea167SDimitry Andric   for (const auto &Range : SkippedRanges) {
81a7dea167SDimitry Andric     if (Range.Length < 16) {
82a7dea167SDimitry Andric       // Ignore small ranges as non-profitable.
83a7dea167SDimitry Andric       // FIXME: This is a heuristic, its worth investigating the tradeoffs
84a7dea167SDimitry Andric       // when it should be applied.
85a7dea167SDimitry Andric       continue;
86a7dea167SDimitry Andric     }
87a7dea167SDimitry Andric     Mapping[Range.Offset] = Range.Length;
88a7dea167SDimitry Andric   }
89a7dea167SDimitry Andric   Result.PPSkippedRangeMapping = std::move(Mapping);
90a7dea167SDimitry Andric 
91a7dea167SDimitry Andric   return Result;
92a7dea167SDimitry Andric }
93a7dea167SDimitry Andric 
94a7dea167SDimitry Andric CachedFileSystemEntry
95a7dea167SDimitry Andric CachedFileSystemEntry::createDirectoryEntry(llvm::vfs::Status &&Stat) {
96a7dea167SDimitry Andric   assert(Stat.isDirectory() && "not a directory!");
97a7dea167SDimitry Andric   auto Result = CachedFileSystemEntry();
98a7dea167SDimitry Andric   Result.MaybeStat = std::move(Stat);
99a7dea167SDimitry Andric   return Result;
100a7dea167SDimitry Andric }
101a7dea167SDimitry Andric 
102fe6060f1SDimitry Andric DependencyScanningFilesystemSharedCache::SingleCache::SingleCache() {
103a7dea167SDimitry Andric   // This heuristic was chosen using a empirical testing on a
104a7dea167SDimitry Andric   // reasonably high core machine (iMacPro 18 cores / 36 threads). The cache
105a7dea167SDimitry Andric   // sharding gives a performance edge by reducing the lock contention.
106a7dea167SDimitry Andric   // FIXME: A better heuristic might also consider the OS to account for
107a7dea167SDimitry Andric   // the different cost of lock contention on different OSes.
1085ffd83dbSDimitry Andric   NumShards =
1095ffd83dbSDimitry Andric       std::max(2u, llvm::hardware_concurrency().compute_thread_count() / 4);
110a7dea167SDimitry Andric   CacheShards = std::make_unique<CacheShard[]>(NumShards);
111a7dea167SDimitry Andric }
112a7dea167SDimitry Andric 
113a7dea167SDimitry Andric DependencyScanningFilesystemSharedCache::SharedFileSystemEntry &
114fe6060f1SDimitry Andric DependencyScanningFilesystemSharedCache::SingleCache::get(StringRef Key) {
115a7dea167SDimitry Andric   CacheShard &Shard = CacheShards[llvm::hash_value(Key) % NumShards];
116a7dea167SDimitry Andric   std::unique_lock<std::mutex> LockGuard(Shard.CacheLock);
117a7dea167SDimitry Andric   auto It = Shard.Cache.try_emplace(Key);
118a7dea167SDimitry Andric   return It.first->getValue();
119a7dea167SDimitry Andric }
120a7dea167SDimitry Andric 
121fe6060f1SDimitry Andric DependencyScanningFilesystemSharedCache::SharedFileSystemEntry &
122fe6060f1SDimitry Andric DependencyScanningFilesystemSharedCache::get(StringRef Key, bool Minimized) {
123fe6060f1SDimitry Andric   SingleCache &Cache = Minimized ? CacheMinimized : CacheOriginal;
124fe6060f1SDimitry Andric   return Cache.get(Key);
125fe6060f1SDimitry Andric }
126fe6060f1SDimitry Andric 
127480093f4SDimitry Andric /// Whitelist file extensions that should be minimized, treating no extension as
128480093f4SDimitry Andric /// a source file that should be minimized.
129480093f4SDimitry Andric ///
130480093f4SDimitry Andric /// This is kinda hacky, it would be better if we knew what kind of file Clang
131480093f4SDimitry Andric /// was expecting instead.
132*4824e7fdSDimitry Andric static bool shouldMinimizeBasedOnExtension(StringRef Filename) {
133480093f4SDimitry Andric   StringRef Ext = llvm::sys::path::extension(Filename);
134480093f4SDimitry Andric   if (Ext.empty())
135480093f4SDimitry Andric     return true; // C++ standard library
136480093f4SDimitry Andric   return llvm::StringSwitch<bool>(Ext)
137480093f4SDimitry Andric     .CasesLower(".c", ".cc", ".cpp", ".c++", ".cxx", true)
138480093f4SDimitry Andric     .CasesLower(".h", ".hh", ".hpp", ".h++", ".hxx", true)
139480093f4SDimitry Andric     .CasesLower(".m", ".mm", true)
140480093f4SDimitry Andric     .CasesLower(".i", ".ii", ".mi", ".mmi", true)
141480093f4SDimitry Andric     .CasesLower(".def", ".inc", true)
142480093f4SDimitry Andric     .Default(false);
143480093f4SDimitry Andric }
144480093f4SDimitry Andric 
145480093f4SDimitry Andric 
146480093f4SDimitry Andric static bool shouldCacheStatFailures(StringRef Filename) {
147480093f4SDimitry Andric   StringRef Ext = llvm::sys::path::extension(Filename);
148480093f4SDimitry Andric   if (Ext.empty())
149480093f4SDimitry Andric     return false; // This may be the module cache directory.
150*4824e7fdSDimitry Andric   // Only cache stat failures on source files.
151*4824e7fdSDimitry Andric   return shouldMinimizeBasedOnExtension(Filename);
152480093f4SDimitry Andric }
153480093f4SDimitry Andric 
154*4824e7fdSDimitry Andric void DependencyScanningWorkerFilesystem::disableMinimization(
155fe6060f1SDimitry Andric     StringRef RawFilename) {
156fe6060f1SDimitry Andric   llvm::SmallString<256> Filename;
157fe6060f1SDimitry Andric   llvm::sys::path::native(RawFilename, Filename);
158*4824e7fdSDimitry Andric   NotToBeMinimized.insert(Filename);
159*4824e7fdSDimitry Andric }
160*4824e7fdSDimitry Andric 
161*4824e7fdSDimitry Andric bool DependencyScanningWorkerFilesystem::shouldMinimize(StringRef RawFilename) {
162*4824e7fdSDimitry Andric   if (!shouldMinimizeBasedOnExtension(RawFilename))
163*4824e7fdSDimitry Andric     return false;
164*4824e7fdSDimitry Andric 
165*4824e7fdSDimitry Andric   llvm::SmallString<256> Filename;
166*4824e7fdSDimitry Andric   llvm::sys::path::native(RawFilename, Filename);
167*4824e7fdSDimitry Andric   return !NotToBeMinimized.contains(Filename);
168*4824e7fdSDimitry Andric }
169*4824e7fdSDimitry Andric 
170*4824e7fdSDimitry Andric CachedFileSystemEntry DependencyScanningWorkerFilesystem::createFileSystemEntry(
171*4824e7fdSDimitry Andric     llvm::ErrorOr<llvm::vfs::Status> &&MaybeStatus, StringRef Filename,
172*4824e7fdSDimitry Andric     bool ShouldMinimize) {
173*4824e7fdSDimitry Andric   if (!MaybeStatus)
174*4824e7fdSDimitry Andric     return CachedFileSystemEntry(MaybeStatus.getError());
175*4824e7fdSDimitry Andric 
176*4824e7fdSDimitry Andric   if (MaybeStatus->isDirectory())
177*4824e7fdSDimitry Andric     return CachedFileSystemEntry::createDirectoryEntry(std::move(*MaybeStatus));
178*4824e7fdSDimitry Andric 
179*4824e7fdSDimitry Andric   return CachedFileSystemEntry::createFileEntry(Filename, getUnderlyingFS(),
180*4824e7fdSDimitry Andric                                                 ShouldMinimize);
181fe6060f1SDimitry Andric }
182fe6060f1SDimitry Andric 
183a7dea167SDimitry Andric llvm::ErrorOr<const CachedFileSystemEntry *>
184a7dea167SDimitry Andric DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
185a7dea167SDimitry Andric     const StringRef Filename) {
186*4824e7fdSDimitry Andric   bool ShouldMinimize = shouldMinimize(Filename);
187fe6060f1SDimitry Andric 
188fe6060f1SDimitry Andric   if (const auto *Entry = Cache.getCachedEntry(Filename, ShouldMinimize))
189a7dea167SDimitry Andric     return Entry;
190a7dea167SDimitry Andric 
191a7dea167SDimitry Andric   // FIXME: Handle PCM/PCH files.
192a7dea167SDimitry Andric   // FIXME: Handle module map files.
193a7dea167SDimitry Andric 
194a7dea167SDimitry Andric   DependencyScanningFilesystemSharedCache::SharedFileSystemEntry
195fe6060f1SDimitry Andric       &SharedCacheEntry = SharedCache.get(Filename, ShouldMinimize);
196a7dea167SDimitry Andric   const CachedFileSystemEntry *Result;
197a7dea167SDimitry Andric   {
198a7dea167SDimitry Andric     std::unique_lock<std::mutex> LockGuard(SharedCacheEntry.ValueLock);
199a7dea167SDimitry Andric     CachedFileSystemEntry &CacheEntry = SharedCacheEntry.Value;
200a7dea167SDimitry Andric 
201a7dea167SDimitry Andric     if (!CacheEntry.isValid()) {
202*4824e7fdSDimitry Andric       auto MaybeStatus = getUnderlyingFS().status(Filename);
203*4824e7fdSDimitry Andric       if (!MaybeStatus && !shouldCacheStatFailures(Filename))
204480093f4SDimitry Andric         // HACK: We need to always restat non source files if the stat fails.
205480093f4SDimitry Andric         //   This is because Clang first looks up the module cache and module
206480093f4SDimitry Andric         //   files before building them, and then looks for them again. If we
207480093f4SDimitry Andric         //   cache the stat failure, it won't see them the second time.
208480093f4SDimitry Andric         return MaybeStatus.getError();
209*4824e7fdSDimitry Andric       CacheEntry = createFileSystemEntry(std::move(MaybeStatus), Filename,
210fe6060f1SDimitry Andric                                          ShouldMinimize);
211a7dea167SDimitry Andric     }
212a7dea167SDimitry Andric 
213a7dea167SDimitry Andric     Result = &CacheEntry;
214a7dea167SDimitry Andric   }
215a7dea167SDimitry Andric 
216a7dea167SDimitry Andric   // Store the result in the local cache.
217fe6060f1SDimitry Andric   Cache.setCachedEntry(Filename, ShouldMinimize, Result);
218a7dea167SDimitry Andric   return Result;
219a7dea167SDimitry Andric }
220a7dea167SDimitry Andric 
221a7dea167SDimitry Andric llvm::ErrorOr<llvm::vfs::Status>
222a7dea167SDimitry Andric DependencyScanningWorkerFilesystem::status(const Twine &Path) {
223a7dea167SDimitry Andric   SmallString<256> OwnedFilename;
224a7dea167SDimitry Andric   StringRef Filename = Path.toStringRef(OwnedFilename);
225a7dea167SDimitry Andric   const llvm::ErrorOr<const CachedFileSystemEntry *> Result =
226a7dea167SDimitry Andric       getOrCreateFileSystemEntry(Filename);
227a7dea167SDimitry Andric   if (!Result)
228a7dea167SDimitry Andric     return Result.getError();
229a7dea167SDimitry Andric   return (*Result)->getStatus();
230a7dea167SDimitry Andric }
231a7dea167SDimitry Andric 
232a7dea167SDimitry Andric namespace {
233a7dea167SDimitry Andric 
234a7dea167SDimitry Andric /// The VFS that is used by clang consumes the \c CachedFileSystemEntry using
235a7dea167SDimitry Andric /// this subclass.
236a7dea167SDimitry Andric class MinimizedVFSFile final : public llvm::vfs::File {
237a7dea167SDimitry Andric public:
238a7dea167SDimitry Andric   MinimizedVFSFile(std::unique_ptr<llvm::MemoryBuffer> Buffer,
239a7dea167SDimitry Andric                    llvm::vfs::Status Stat)
240a7dea167SDimitry Andric       : Buffer(std::move(Buffer)), Stat(std::move(Stat)) {}
241a7dea167SDimitry Andric 
242e8d8bef9SDimitry Andric   static llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
243e8d8bef9SDimitry Andric   create(const CachedFileSystemEntry *Entry,
244e8d8bef9SDimitry Andric          ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings);
245a7dea167SDimitry Andric 
246e8d8bef9SDimitry Andric   llvm::ErrorOr<llvm::vfs::Status> status() override { return Stat; }
247a7dea167SDimitry Andric 
248a7dea167SDimitry Andric   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
249a7dea167SDimitry Andric   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
250a7dea167SDimitry Andric             bool IsVolatile) override {
251a7dea167SDimitry Andric     return std::move(Buffer);
252a7dea167SDimitry Andric   }
253a7dea167SDimitry Andric 
254a7dea167SDimitry Andric   std::error_code close() override { return {}; }
255a7dea167SDimitry Andric 
256a7dea167SDimitry Andric private:
257a7dea167SDimitry Andric   std::unique_ptr<llvm::MemoryBuffer> Buffer;
258a7dea167SDimitry Andric   llvm::vfs::Status Stat;
259a7dea167SDimitry Andric };
260a7dea167SDimitry Andric 
261e8d8bef9SDimitry Andric } // end anonymous namespace
262e8d8bef9SDimitry Andric 
263e8d8bef9SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> MinimizedVFSFile::create(
264e8d8bef9SDimitry Andric     const CachedFileSystemEntry *Entry,
265a7dea167SDimitry Andric     ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings) {
266a7dea167SDimitry Andric   if (Entry->isDirectory())
267a7dea167SDimitry Andric     return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
268a7dea167SDimitry Andric         std::make_error_code(std::errc::is_a_directory));
269a7dea167SDimitry Andric   llvm::ErrorOr<StringRef> Contents = Entry->getContents();
270a7dea167SDimitry Andric   if (!Contents)
271a7dea167SDimitry Andric     return Contents.getError();
272a7dea167SDimitry Andric   auto Result = std::make_unique<MinimizedVFSFile>(
273a7dea167SDimitry Andric       llvm::MemoryBuffer::getMemBuffer(*Contents, Entry->getName(),
274a7dea167SDimitry Andric                                        /*RequiresNullTerminator=*/false),
275a7dea167SDimitry Andric       *Entry->getStatus());
276a7dea167SDimitry Andric   if (!Entry->getPPSkippedRangeMapping().empty() && PPSkipMappings)
277e8d8bef9SDimitry Andric     (*PPSkipMappings)[Result->Buffer->getBufferStart()] =
278a7dea167SDimitry Andric         &Entry->getPPSkippedRangeMapping();
279a7dea167SDimitry Andric   return llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>(
280a7dea167SDimitry Andric       std::unique_ptr<llvm::vfs::File>(std::move(Result)));
281a7dea167SDimitry Andric }
282a7dea167SDimitry Andric 
283a7dea167SDimitry Andric llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
284a7dea167SDimitry Andric DependencyScanningWorkerFilesystem::openFileForRead(const Twine &Path) {
285a7dea167SDimitry Andric   SmallString<256> OwnedFilename;
286a7dea167SDimitry Andric   StringRef Filename = Path.toStringRef(OwnedFilename);
287a7dea167SDimitry Andric 
288a7dea167SDimitry Andric   const llvm::ErrorOr<const CachedFileSystemEntry *> Result =
289a7dea167SDimitry Andric       getOrCreateFileSystemEntry(Filename);
290a7dea167SDimitry Andric   if (!Result)
291a7dea167SDimitry Andric     return Result.getError();
292e8d8bef9SDimitry Andric   return MinimizedVFSFile::create(Result.get(), PPSkipMappings);
293a7dea167SDimitry Andric }
294