File: DependencyScanningCASFilesystem.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (364 lines) | stat: -rw-r--r-- 12,614 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
//===- DependencyScanningCASFilesystem.cpp - clang-scan-deps fs -----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "clang/Tooling/DependencyScanning/DependencyScanningCASFilesystem.h"
#include "clang/Basic/Version.h"
#include "clang/Lex/DependencyDirectivesScanner.h"
#include "llvm/CAS/ActionCache.h"
#include "llvm/CAS/CachingOnDiskFileSystem.h"
#include "llvm/CAS/HierarchicalTreeBuilder.h"
#include "llvm/CAS/ObjectStore.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Threading.h"

using namespace clang;
using namespace tooling;
using namespace dependencies;

template <typename T> static T reportAsFatalIfError(Expected<T> ValOrErr) {
  if (!ValOrErr)
    llvm::report_fatal_error(ValOrErr.takeError());
  return std::move(*ValOrErr);
}

static void reportAsFatalIfError(llvm::Error E) {
  if (E)
    llvm::report_fatal_error(std::move(E));
}

using llvm::Error;

DependencyScanningCASFilesystem::DependencyScanningCASFilesystem(
    IntrusiveRefCntPtr<llvm::cas::CachingOnDiskFileSystem> WorkerFS,
    llvm::cas::ActionCache &Cache)
    : FS(WorkerFS), Entries(EntryAlloc), CAS(WorkerFS->getCAS()), Cache(Cache) {
}

DependencyScanningCASFilesystem::~DependencyScanningCASFilesystem() = default;

static Expected<cas::ObjectRef>
storeDepDirectives(cas::ObjectStore &CAS,
                   ArrayRef<dependency_directives_scan::Directive> Directives) {
  llvm::SmallString<1024> Buffer;
  llvm::raw_svector_ostream OS(Buffer);
  llvm::support::endian::Writer W(OS, llvm::support::endianness::little);
  size_t NumTokens = 0;
  for (const auto &Directive : Directives)
    NumTokens += Directive.Tokens.size();
  W.write(NumTokens);
  for (const auto &Directive : Directives) {
    for (const auto &Token : Directive.Tokens) {
      W.write(Token.Offset);
      W.write(Token.Length);
      W.write(static_cast<std::underlying_type<decltype(Token.Kind)>::type>(
          Token.Kind));
      W.write(Token.Flags);
    }
  }

  size_t TokenIdx = 0;
  W.write(Directives.size());
  for (const auto &Directive : Directives) {
    W.write(static_cast<std::underlying_type<decltype(Directive.Kind)>::type>(
        Directive.Kind));
    W.write(TokenIdx);
    W.write(Directive.Tokens.size());
    TokenIdx += Directive.Tokens.size();
  }

  return CAS.storeFromString(std::nullopt, Buffer);
}

template <typename T> static void readle(StringRef &Slice, T &Out) {
  using namespace llvm::support::endian;
  if (Slice.size() < sizeof(T))
    llvm::report_fatal_error("buffer too small");
  Out = read<T, llvm::support::little>(Slice.begin());
  Slice = Slice.drop_front(sizeof(T));
}

static Error loadDepDirectives(
    cas::ObjectStore &CAS, cas::ObjectRef Ref,
    llvm::SmallVectorImpl<dependency_directives_scan::Token> &DepTokens,
    llvm::SmallVectorImpl<dependency_directives_scan::Directive>
        &DepDirectives) {
  using namespace dependency_directives_scan;
  auto Blob = CAS.getProxy(Ref);
  if (!Blob)
    return Blob.takeError();

  StringRef Data = Blob->getData();
  StringRef Cursor = Data;

  size_t NumTokens = 0;
  readle(Cursor, NumTokens);
  DepTokens.reserve(NumTokens);
  for (size_t I = 0; I < NumTokens; ++I) {
    DepTokens.emplace_back(0, 0, (tok::TokenKind)0, 0);
    auto &Token = DepTokens.back();
    readle(Cursor, Token.Offset);
    readle(Cursor, Token.Length);
    std::underlying_type<decltype(Token.Kind)>::type Kind;
    readle(Cursor, Kind);
    Token.Kind = static_cast<tok::TokenKind>(Kind);
    readle(Cursor, Token.Flags);
  }

  size_t NumDirectives = 0;
  readle(Cursor, NumDirectives);
  DepDirectives.reserve(NumDirectives);
  for (size_t I = 0; I < NumDirectives; ++I) {
    std::underlying_type<DirectiveKind>::type Kind;
    readle(Cursor, Kind);
    size_t TokenStart, NumTokens;
    readle(Cursor, TokenStart);
    readle(Cursor, NumTokens);
    assert(NumTokens <= DepTokens.size() &&
           TokenStart <= DepTokens.size() - NumTokens);
    DepDirectives.emplace_back(
        static_cast<DirectiveKind>(Kind),
        ArrayRef<Token>(DepTokens.begin() + TokenStart,
                        DepTokens.begin() + TokenStart + NumTokens));
  }
  assert(Cursor.empty());
  return Error::success();
}

void DependencyScanningCASFilesystem::scanForDirectives(
    llvm::cas::ObjectRef InputDataID, StringRef Identifier,
    SmallVectorImpl<dependency_directives_scan::Token> &Tokens,
    SmallVectorImpl<dependency_directives_scan::Directive> &Directives) {
  using namespace llvm;
  using namespace llvm::cas;

  // Get a blob for the clang version string.
  if (!ClangFullVersionID)
    ClangFullVersionID = reportAsFatalIfError(
        CAS.storeFromString(std::nullopt, getClangFullVersion()));

  // Get a blob for the dependency directives scan command.
  if (!DepDirectivesID)
    DepDirectivesID =
        reportAsFatalIfError(CAS.storeFromString(std::nullopt, "directives"));

  // Get an empty blob.
  if (!EmptyBlobID)
    EmptyBlobID = reportAsFatalIfError(CAS.storeFromString(std::nullopt, ""));

  // Construct a tree for the input.
  std::optional<CASID> InputID;
  {
    HierarchicalTreeBuilder Builder;
    Builder.push(*ClangFullVersionID, TreeEntry::Regular, "version");
    Builder.push(*DepDirectivesID, TreeEntry::Regular, "command");
    Builder.push(InputDataID, TreeEntry::Regular, "data");
    InputID = reportAsFatalIfError(Builder.create(CAS)).getID();
  }

  // Check the result cache.
  if (std::optional<CASID> OutputID =
          reportAsFatalIfError(Cache.get(*InputID))) {
    if (std::optional<ObjectRef> OutputRef = CAS.getReference(*OutputID)) {
      if (OutputRef == EmptyBlobID)
        return; // Cached directive scanning failure.
      reportAsFatalIfError(
          loadDepDirectives(CAS, *OutputRef, Tokens, Directives));
      return;
    }
  }

  StringRef InputData =
      reportAsFatalIfError(CAS.getProxy(InputDataID)).getData();

  if (scanSourceForDependencyDirectives(InputData, Tokens, Directives)) {
    // FIXME: Propagate the diagnostic if desired by the client.
    // Failure. Cache empty directives.
    Tokens.clear();
    Directives.clear();
    reportAsFatalIfError(Cache.put(*InputID, CAS.getID(*EmptyBlobID)));
    return;
  }

  // Success. Add to the CAS and get back persistent output data.
  cas::ObjectRef DirectivesID =
      reportAsFatalIfError(storeDepDirectives(CAS, Directives));
  // Cache the computation.
  reportAsFatalIfError(Cache.put(*InputID, CAS.getID(DirectivesID)));
}

Expected<StringRef>
DependencyScanningCASFilesystem::getOriginal(cas::CASID InputDataID) {
  Expected<cas::ObjectProxy> Blob = CAS.getProxy(InputDataID);
  if (Blob)
    return Blob->getData();
  return Blob.takeError();
}

static bool shouldCacheStatFailures(StringRef Filename) {
  StringRef Ext = llvm::sys::path::extension(Filename);
  if (Ext.empty())
    return false; // This may be the module cache directory.

  // rdar://127079541
  // With Swift, misconfigured Xcode projects currently may fail with
  // negative 'stat' caching of `.framework` directories enabled,
  // because they do not always explicitly specify their target
  // dependencies and may be either getting lucky wih build timing, or
  // compiling against wrong dependenceis a lot of the time: e.g. an
  // SDK variant of a dependency module, instead of one in the
  // project's own build directory. Temporarily disable negative
  // 'stat' caching here until all such projects are fixed.
  if (Ext == ".framework")
    return false;
  
  return true;
}

llvm::cas::CachingOnDiskFileSystem &
DependencyScanningCASFilesystem::getCachingFS() {
  return static_cast<llvm::cas::CachingOnDiskFileSystem &>(*FS);
}

DependencyScanningCASFilesystem::LookupPathResult
DependencyScanningCASFilesystem::lookupPath(const Twine &Path) {
  SmallString<256> PathStorage;
  StringRef PathRef = Path.toStringRef(PathStorage);

  {
    auto I = Entries.find(PathRef);
    if (I != Entries.end()) {
      // FIXME: Gross hack to ensure this file gets tracked as part of the
      // compilation. Instead, we should add an explicit hook somehow /
      // somewhere.
      (void)getCachingFS().status(PathRef);
      return LookupPathResult{&I->second, std::error_code()};
    }
  }

  std::optional<cas::CASID> FileID;
  llvm::ErrorOr<llvm::vfs::Status> MaybeStatus =
      getCachingFS().statusAndFileID(PathRef, FileID);
  if (!MaybeStatus) {
    if (shouldCacheStatFailures(PathRef))
      Entries[PathRef].EC = MaybeStatus.getError();
    return LookupPathResult{nullptr, MaybeStatus.getError()};
  }

  // Underlying file system caches directories. No need to duplicate.
  if (MaybeStatus->isDirectory())
    return LookupPathResult{nullptr, std::move(MaybeStatus)};

  auto &Entry = Entries[PathRef];
  Entry.CASContents = CAS.getReference(*FileID);
  llvm::ErrorOr<StringRef> Buffer = expectedToErrorOr(getOriginal(*FileID));
  if (!Buffer) {
    // Cache CAS failures. Not going to recover later.
    Entry.EC = Buffer.getError();
    return LookupPathResult{&Entry, std::error_code()};
  }

  Entry.Buffer = std::move(*Buffer);
  Entry.Status = llvm::vfs::Status(
      PathRef, MaybeStatus->getUniqueID(),
      MaybeStatus->getLastModificationTime(), MaybeStatus->getUser(),
      MaybeStatus->getGroup(), Entry.Buffer->size(), MaybeStatus->getType(),
      MaybeStatus->getPermissions());
  return LookupPathResult{&Entry, std::error_code()};
}

llvm::ErrorOr<llvm::vfs::Status>
DependencyScanningCASFilesystem::status(const Twine &Path) {
  LookupPathResult Result = lookupPath(Path);
  if (!Result.Entry)
    return std::move(Result.Status);
  if (Result.Entry->EC)
    return Result.Entry->EC;
  return Result.Entry->Status;
}

bool DependencyScanningCASFilesystem::exists(const Twine &Path) {
  // Existence check does not require caching the result at the dependency
  // scanning level. The CachingOnDiskFileSystem tracks the exists call, which
  // ensures it is included in any resulting CASFileSystem.
  return getCachingFS().exists(Path);
}

IntrusiveRefCntPtr<llvm::cas::ThreadSafeFileSystem>
DependencyScanningCASFilesystem::createThreadSafeProxyFS() {
  llvm::report_fatal_error("not implemented");
}

namespace {

class DepScanFile final : public llvm::vfs::File {
public:
  DepScanFile(StringRef Buffer, std::optional<cas::ObjectRef> CASContents,
              llvm::vfs::Status Stat)
      : Buffer(Buffer), CASContents(std::move(CASContents)),
        Stat(std::move(Stat)) {}

  llvm::ErrorOr<llvm::vfs::Status> status() override { return Stat; }

  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
  getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
            bool IsVolatile) override {
    SmallString<256> Storage;
    return llvm::MemoryBuffer::getMemBuffer(Buffer, Name.toStringRef(Storage));
  }

  llvm::ErrorOr<std::optional<cas::ObjectRef>>
  getObjectRefForContent() override {
    return CASContents;
  }

  std::error_code close() override { return {}; }

private:
  StringRef Buffer;
  std::optional<cas::ObjectRef> CASContents;
  llvm::vfs::Status Stat;
};

} // end anonymous namespace

llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
DependencyScanningCASFilesystem::openFileForRead(const Twine &Path) {
  LookupPathResult Result = lookupPath(Path);
  if (!Result.Entry) {
    if (std::error_code EC = Result.Status.getError())
      return EC;
    assert(Result.Status->getType() ==
           llvm::sys::fs::file_type::directory_file);
    return std::make_error_code(std::errc::is_a_directory);
  }
  if (Result.Entry->EC)
    return Result.Entry->EC;

  return std::make_unique<DepScanFile>(
      *Result.Entry->Buffer, Result.Entry->CASContents, Result.Entry->Status);
}

std::optional<ArrayRef<dependency_directives_scan::Directive>>
DependencyScanningCASFilesystem::getDirectiveTokens(const Twine &Path) {
  LookupPathResult Result = lookupPath(Path);

  if (Result.Entry) {
    if (Result.Entry->DepDirectives.empty()) {
      SmallString<256> PathStorage;
      StringRef PathRef = Path.toStringRef(PathStorage);
      FileEntry &Entry = const_cast<FileEntry &>(*Result.Entry);
      scanForDirectives(*Entry.CASContents, PathRef, Entry.DepTokens,
                        Entry.DepDirectives);
    }

    if (!Result.Entry->DepDirectives.empty())
      return ArrayRef(Result.Entry->DepDirectives);
  }
  return std::nullopt;
}