[VectorCombine] Enable transform 'foldSingleElementStore' for scalable vector types
[llvm-project.git] / clang-tools-extra / clangd / TUScheduler.cpp
blobdd2ce16147a5dd9b13d35b1192235630c38f54ab
1 //===--- TUScheduler.cpp -----------------------------------------*-C++-*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 // TUScheduler manages a worker per active file. This ASTWorker processes
9 // updates (modifications to file contents) and reads (actions performed on
10 // preamble/AST) to the file.
12 // Each ASTWorker owns a dedicated thread to process updates and reads to the
13 // relevant file. Any request gets queued in FIFO order to be processed by that
14 // thread.
16 // An update request replaces current praser inputs to ensure any subsequent
17 // read sees the version of the file they were requested. It will also issue a
18 // build for new inputs.
20 // ASTWorker processes the file in two parts, a preamble and a main-file
21 // section. A preamble can be reused between multiple versions of the file until
22 // invalidated by a modification to a header, compile commands or modification
23 // to relevant part of the current file. Such a preamble is called compatible.
24 // An update is considered dead if no read was issued for that version and
25 // diagnostics weren't requested by client or could be generated for a later
26 // version of the file. ASTWorker eliminates such requests as they are
27 // redundant.
29 // In the presence of stale (non-compatible) preambles, ASTWorker won't publish
30 // diagnostics for update requests. Read requests will be served with ASTs build
31 // with stale preambles, unless the read is picky and requires a compatible
32 // preamble. In such cases it will block until new preamble is built.
34 // ASTWorker owns a PreambleThread for building preambles. If the preamble gets
35 // invalidated by an update request, a new build will be requested on
36 // PreambleThread. Since PreambleThread only receives requests for newer
37 // versions of the file, in case of multiple requests it will only build the
38 // last one and skip requests in between. Unless client force requested
39 // diagnostics(WantDiagnostics::Yes).
41 // When a new preamble is built, a "golden" AST is immediately built from that
42 // version of the file. This ensures diagnostics get updated even if the queue
43 // is full.
45 // Some read requests might just need preamble. Since preambles can be read
46 // concurrently, ASTWorker runs these requests on their own thread. These
47 // requests will receive latest build preamble, which might possibly be stale.
49 #include "TUScheduler.h"
50 #include "CompileCommands.h"
51 #include "Compiler.h"
52 #include "Config.h"
53 #include "Diagnostics.h"
54 #include "GlobalCompilationDatabase.h"
55 #include "ParsedAST.h"
56 #include "Preamble.h"
57 #include "clang-include-cleaner/Record.h"
58 #include "support/Cancellation.h"
59 #include "support/Context.h"
60 #include "support/Logger.h"
61 #include "support/MemoryTree.h"
62 #include "support/Path.h"
63 #include "support/ThreadCrashReporter.h"
64 #include "support/Threading.h"
65 #include "support/Trace.h"
66 #include "clang/Frontend/CompilerInvocation.h"
67 #include "clang/Tooling/CompilationDatabase.h"
68 #include "llvm/ADT/FunctionExtras.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/SmallVector.h"
72 #include "llvm/ADT/StringExtras.h"
73 #include "llvm/ADT/StringRef.h"
74 #include "llvm/Support/Allocator.h"
75 #include "llvm/Support/Errc.h"
76 #include "llvm/Support/ErrorHandling.h"
77 #include "llvm/Support/FormatVariadic.h"
78 #include "llvm/Support/Path.h"
79 #include "llvm/Support/Threading.h"
80 #include "llvm/Support/raw_ostream.h"
81 #include <algorithm>
82 #include <atomic>
83 #include <chrono>
84 #include <condition_variable>
85 #include <functional>
86 #include <memory>
87 #include <mutex>
88 #include <optional>
89 #include <queue>
90 #include <string>
91 #include <thread>
92 #include <type_traits>
93 #include <utility>
94 #include <vector>
96 namespace clang {
97 namespace clangd {
98 using std::chrono::steady_clock;
100 namespace {
101 // Tracks latency (in seconds) of FS operations done during a preamble build.
102 // build_type allows to split by expected VFS cache state (cold on first
103 // preamble, somewhat warm after that when building first preamble for new file,
104 // likely ~everything cached on preamble rebuild.
105 constexpr trace::Metric
106 PreambleBuildFilesystemLatency("preamble_fs_latency",
107 trace::Metric::Distribution, "build_type");
108 // Tracks latency of FS operations done during a preamble build as a ratio of
109 // preamble build time. build_type is same as above.
110 constexpr trace::Metric PreambleBuildFilesystemLatencyRatio(
111 "preamble_fs_latency_ratio", trace::Metric::Distribution, "build_type");
113 constexpr trace::Metric PreambleBuildSize("preamble_build_size",
114 trace::Metric::Distribution);
115 constexpr trace::Metric PreambleSerializedSize("preamble_serialized_size",
116 trace::Metric::Distribution);
118 void reportPreambleBuild(const PreambleBuildStats &Stats,
119 bool IsFirstPreamble) {
120 auto RecordWithLabel = [&Stats](llvm::StringRef Label) {
121 PreambleBuildFilesystemLatency.record(Stats.FileSystemTime, Label);
122 if (Stats.TotalBuildTime > 0) // Avoid division by zero.
123 PreambleBuildFilesystemLatencyRatio.record(
124 Stats.FileSystemTime / Stats.TotalBuildTime, Label);
127 static llvm::once_flag OnceFlag;
128 llvm::call_once(OnceFlag, [&] { RecordWithLabel("first_build"); });
129 RecordWithLabel(IsFirstPreamble ? "first_build_for_file" : "rebuild");
131 PreambleBuildSize.record(Stats.BuildSize);
132 PreambleSerializedSize.record(Stats.SerializedSize);
135 class ASTWorker;
136 } // namespace
138 static clang::clangd::Key<std::string> FileBeingProcessed;
140 std::optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
141 if (auto *File = Context::current().get(FileBeingProcessed))
142 return llvm::StringRef(*File);
143 return std::nullopt;
146 /// An LRU cache of idle ASTs.
147 /// Because we want to limit the overall number of these we retain, the cache
148 /// owns ASTs (and may evict them) while their workers are idle.
149 /// Workers borrow ASTs when active, and return them when done.
150 class TUScheduler::ASTCache {
151 public:
152 using Key = const ASTWorker *;
154 ASTCache(unsigned MaxRetainedASTs) : MaxRetainedASTs(MaxRetainedASTs) {}
156 /// Returns result of getUsedBytes() for the AST cached by \p K.
157 /// If no AST is cached, 0 is returned.
158 std::size_t getUsedBytes(Key K) {
159 std::lock_guard<std::mutex> Lock(Mut);
160 auto It = findByKey(K);
161 if (It == LRU.end() || !It->second)
162 return 0;
163 return It->second->getUsedBytes();
166 /// Store the value in the pool, possibly removing the last used AST.
167 /// The value should not be in the pool when this function is called.
168 void put(Key K, std::unique_ptr<ParsedAST> V) {
169 std::unique_lock<std::mutex> Lock(Mut);
170 assert(findByKey(K) == LRU.end());
172 LRU.insert(LRU.begin(), {K, std::move(V)});
173 if (LRU.size() <= MaxRetainedASTs)
174 return;
175 // We're past the limit, remove the last element.
176 std::unique_ptr<ParsedAST> ForCleanup = std::move(LRU.back().second);
177 LRU.pop_back();
178 // Run the expensive destructor outside the lock.
179 Lock.unlock();
180 ForCleanup.reset();
183 /// Returns the cached value for \p K, or std::nullopt if the value is not in
184 /// the cache anymore. If nullptr was cached for \p K, this function will
185 /// return a null unique_ptr wrapped into an optional.
186 /// If \p AccessMetric is set records whether there was a hit or miss.
187 std::optional<std::unique_ptr<ParsedAST>>
188 take(Key K, const trace::Metric *AccessMetric = nullptr) {
189 // Record metric after unlocking the mutex.
190 std::unique_lock<std::mutex> Lock(Mut);
191 auto Existing = findByKey(K);
192 if (Existing == LRU.end()) {
193 if (AccessMetric)
194 AccessMetric->record(1, "miss");
195 return std::nullopt;
197 if (AccessMetric)
198 AccessMetric->record(1, "hit");
199 std::unique_ptr<ParsedAST> V = std::move(Existing->second);
200 LRU.erase(Existing);
201 // GCC 4.8 fails to compile `return V;`, as it tries to call the copy
202 // constructor of unique_ptr, so we call the move ctor explicitly to avoid
203 // this miscompile.
204 return std::optional<std::unique_ptr<ParsedAST>>(std::move(V));
207 private:
208 using KVPair = std::pair<Key, std::unique_ptr<ParsedAST>>;
210 std::vector<KVPair>::iterator findByKey(Key K) {
211 return llvm::find_if(LRU, [K](const KVPair &P) { return P.first == K; });
214 std::mutex Mut;
215 unsigned MaxRetainedASTs;
216 /// Items sorted in LRU order, i.e. first item is the most recently accessed
217 /// one.
218 std::vector<KVPair> LRU; /* GUARDED_BY(Mut) */
221 /// A map from header files to an opened "proxy" file that includes them.
222 /// If you open the header, the compile command from the proxy file is used.
224 /// This inclusion information could also naturally live in the index, but there
225 /// are advantages to using open files instead:
226 /// - it's easier to achieve a *stable* choice of proxy, which is important
227 /// to avoid invalidating the preamble
228 /// - context-sensitive flags for libraries with multiple configurations
229 /// (e.g. C++ stdlib sensitivity to -std version)
230 /// - predictable behavior, e.g. guarantees that go-to-def landing on a header
231 /// will have a suitable command available
232 /// - fewer scaling problems to solve (project include graphs are big!)
234 /// Implementation details:
235 /// - We only record this for mainfiles where the command was trustworthy
236 /// (i.e. not inferred). This avoids a bad inference "infecting" other files.
237 /// - Once we've picked a proxy file for a header, we stick with it until the
238 /// proxy file is invalidated *and* a new candidate proxy file is built.
239 /// Switching proxies is expensive, as the compile flags will (probably)
240 /// change and therefore we'll end up rebuilding the header's preamble.
241 /// - We don't capture the actual compile command, but just the filename we
242 /// should query to get it. This avoids getting out of sync with the CDB.
244 /// All methods are threadsafe. In practice, update() comes from preamble
245 /// threads, remove()s mostly from the main thread, and get() from ASTWorker.
246 /// Writes are rare and reads are cheap, so we don't expect much contention.
247 class TUScheduler::HeaderIncluderCache {
248 // We should be a little careful how we store the include graph of open
249 // files, as each can have a large number of transitive headers.
250 // This representation is O(unique transitive source files).
251 llvm::BumpPtrAllocator Arena;
252 struct Association {
253 llvm::StringRef MainFile;
254 // Circular-linked-list of associations with the same mainFile.
255 // Null indicates that the mainfile was removed.
256 Association *Next;
258 llvm::StringMap<Association, llvm::BumpPtrAllocator &> HeaderToMain;
259 llvm::StringMap<Association *, llvm::BumpPtrAllocator &> MainToFirst;
260 std::atomic<size_t> UsedBytes; // Updated after writes.
261 mutable std::mutex Mu;
263 void invalidate(Association *First) {
264 Association *Current = First;
265 do {
266 Association *Next = Current->Next;
267 Current->Next = nullptr;
268 Current = Next;
269 } while (Current != First);
272 // Create the circular list and return the head of it.
273 Association *associate(llvm::StringRef MainFile,
274 llvm::ArrayRef<std::string> Headers) {
275 Association *First = nullptr, *Prev = nullptr;
276 for (const std::string &Header : Headers) {
277 auto &Assoc = HeaderToMain[Header];
278 if (Assoc.Next)
279 continue; // Already has a valid association.
281 Assoc.MainFile = MainFile;
282 Assoc.Next = Prev;
283 Prev = &Assoc;
284 if (!First)
285 First = &Assoc;
287 if (First)
288 First->Next = Prev;
289 return First;
292 void updateMemoryUsage() {
293 auto StringMapHeap = [](const auto &Map) {
294 // StringMap stores the hashtable on the heap.
295 // It contains pointers to the entries, and a hashcode for each.
296 return Map.getNumBuckets() * (sizeof(void *) + sizeof(unsigned));
298 size_t Usage = Arena.getTotalMemory() + StringMapHeap(MainToFirst) +
299 StringMapHeap(HeaderToMain) + sizeof(*this);
300 UsedBytes.store(Usage, std::memory_order_release);
303 public:
304 HeaderIncluderCache() : HeaderToMain(Arena), MainToFirst(Arena) {
305 updateMemoryUsage();
308 // Associate each header with MainFile (unless already associated).
309 // Headers not in the list will have their associations removed.
310 void update(PathRef MainFile, llvm::ArrayRef<std::string> Headers) {
311 std::lock_guard<std::mutex> Lock(Mu);
312 auto It = MainToFirst.try_emplace(MainFile, nullptr);
313 Association *&First = It.first->second;
314 if (First)
315 invalidate(First);
316 First = associate(It.first->first(), Headers);
317 updateMemoryUsage();
320 // Mark MainFile as gone.
321 // This will *not* disassociate headers with MainFile immediately, but they
322 // will be eligible for association with other files that get update()d.
323 void remove(PathRef MainFile) {
324 std::lock_guard<std::mutex> Lock(Mu);
325 Association *&First = MainToFirst[MainFile];
326 if (First) {
327 invalidate(First);
328 First = nullptr;
330 // MainToFirst entry should stay alive, as Associations might be pointing at
331 // its key.
334 /// Get the mainfile associated with Header, or the empty string if none.
335 std::string get(PathRef Header) const {
336 std::lock_guard<std::mutex> Lock(Mu);
337 return HeaderToMain.lookup(Header).MainFile.str();
340 size_t getUsedBytes() const {
341 return UsedBytes.load(std::memory_order_acquire);
345 namespace {
347 bool isReliable(const tooling::CompileCommand &Cmd) {
348 return Cmd.Heuristic.empty();
351 /// Threadsafe manager for updating a TUStatus and emitting it after each
352 /// update.
353 class SynchronizedTUStatus {
354 public:
355 SynchronizedTUStatus(PathRef FileName, ParsingCallbacks &Callbacks)
356 : FileName(FileName), Callbacks(Callbacks) {}
358 void update(llvm::function_ref<void(TUStatus &)> Mutator) {
359 std::lock_guard<std::mutex> Lock(StatusMu);
360 Mutator(Status);
361 emitStatusLocked();
364 /// Prevents emitting of further updates.
365 void stop() {
366 std::lock_guard<std::mutex> Lock(StatusMu);
367 CanPublish = false;
370 private:
371 void emitStatusLocked() {
372 if (CanPublish)
373 Callbacks.onFileUpdated(FileName, Status);
376 const Path FileName;
378 std::mutex StatusMu;
379 TUStatus Status;
380 bool CanPublish = true;
381 ParsingCallbacks &Callbacks;
384 // An attempt to acquire resources for a task using PreambleThrottler.
385 // Initially it is unsatisfied, it (hopefully) becomes satisfied later but may
386 // be destroyed before then. Destruction releases all resources.
387 class PreambleThrottlerRequest {
388 public:
389 // The condition variable is signalled when the request is satisfied.
390 PreambleThrottlerRequest(llvm::StringRef Filename,
391 PreambleThrottler *Throttler,
392 std::condition_variable &CV)
393 : Throttler(Throttler),
394 Satisfied(Throttler == nullptr) {
395 // If there is no throttler, this dummy request is always satisfied.
396 if (!Throttler)
397 return;
398 ID = Throttler->acquire(Filename, [&] {
399 Satisfied.store(true, std::memory_order_release);
400 CV.notify_all();
404 bool satisfied() const { return Satisfied.load(std::memory_order_acquire); }
406 // When the request is destroyed:
407 // - if resources are not yet obtained, stop trying to get them.
408 // - if resources were obtained, release them.
409 ~PreambleThrottlerRequest() {
410 if (Throttler)
411 Throttler->release(ID);
414 private:
415 PreambleThrottler::RequestID ID;
416 PreambleThrottler *Throttler;
417 std::atomic<bool> Satisfied = {false};
420 /// Responsible for building preambles. Whenever the thread is idle and the
421 /// preamble is outdated, it starts to build a fresh preamble from the latest
422 /// inputs. If RunSync is true, preambles are built synchronously in update()
423 /// instead.
424 class PreambleThread {
425 public:
426 PreambleThread(llvm::StringRef FileName, ParsingCallbacks &Callbacks,
427 bool StorePreambleInMemory, bool RunSync,
428 PreambleThrottler *Throttler, SynchronizedTUStatus &Status,
429 TUScheduler::HeaderIncluderCache &HeaderIncluders,
430 ASTWorker &AW)
431 : FileName(FileName), Callbacks(Callbacks),
432 StoreInMemory(StorePreambleInMemory), RunSync(RunSync),
433 Throttler(Throttler), Status(Status), ASTPeer(AW),
434 HeaderIncluders(HeaderIncluders) {}
436 /// It isn't guaranteed that each requested version will be built. If there
437 /// are multiple update requests while building a preamble, only the last one
438 /// will be built.
439 void update(std::unique_ptr<CompilerInvocation> CI, ParseInputs PI,
440 std::vector<Diag> CIDiags, WantDiagnostics WantDiags) {
441 Request Req = {std::move(CI), std::move(PI), std::move(CIDiags), WantDiags,
442 Context::current().clone()};
443 if (RunSync) {
444 build(std::move(Req));
445 Status.update([](TUStatus &Status) {
446 Status.PreambleActivity = PreambleAction::Idle;
448 return;
451 std::unique_lock<std::mutex> Lock(Mutex);
452 // If NextReq was requested with WantDiagnostics::Yes we cannot just drop
453 // that on the floor. Block until we start building it. This won't
454 // dead-lock as we are blocking the caller thread, while builds continue
455 // on preamble thread.
456 ReqCV.wait(Lock, [this] {
457 return !NextReq || NextReq->WantDiags != WantDiagnostics::Yes;
459 NextReq = std::move(Req);
461 // Let the worker thread know there's a request, notify_one is safe as there
462 // should be a single worker thread waiting on it.
463 ReqCV.notify_all();
466 void run() {
467 while (true) {
468 std::optional<PreambleThrottlerRequest> Throttle;
470 std::unique_lock<std::mutex> Lock(Mutex);
471 assert(!CurrentReq && "Already processing a request?");
472 // Wait until stop is called or there is a request.
473 ReqCV.wait(Lock, [&] { return NextReq || Done; });
474 if (Done)
475 break;
478 Throttle.emplace(FileName, Throttler, ReqCV);
479 std::optional<trace::Span> Tracer;
480 // If acquire succeeded synchronously, avoid status jitter.
481 if (!Throttle->satisfied()) {
482 Tracer.emplace("PreambleThrottle");
483 Status.update([&](TUStatus &Status) {
484 Status.PreambleActivity = PreambleAction::Queued;
487 ReqCV.wait(Lock, [&] { return Throttle->satisfied() || Done; });
489 if (Done)
490 break;
491 // While waiting for the throttler, the request may have been updated!
492 // That's fine though, there's still guaranteed to be some request.
494 CurrentReq = std::move(*NextReq);
495 NextReq.reset();
499 WithContext Guard(std::move(CurrentReq->Ctx));
500 // Note that we don't make use of the ContextProvider here.
501 // Preamble tasks are always scheduled by ASTWorker tasks, and we
502 // reuse the context/config that was created at that level.
504 // Build the preamble and let the waiters know about it.
505 build(std::move(*CurrentReq));
507 // Releasing the throttle before destroying the request assists testing.
508 Throttle.reset();
509 bool IsEmpty = false;
511 std::lock_guard<std::mutex> Lock(Mutex);
512 CurrentReq.reset();
513 IsEmpty = !NextReq;
515 if (IsEmpty) {
516 // We don't perform this above, before waiting for a request to make
517 // tests more deterministic. As there can be a race between this thread
518 // and client thread(clangdserver).
519 Status.update([](TUStatus &Status) {
520 Status.PreambleActivity = PreambleAction::Idle;
523 ReqCV.notify_all();
525 dlog("Preamble worker for {0} stopped", FileName);
528 /// Signals the run loop to exit.
529 void stop() {
530 dlog("Preamble worker for {0} received stop", FileName);
532 std::lock_guard<std::mutex> Lock(Mutex);
533 Done = true;
534 NextReq.reset();
536 // Let the worker thread know that it should stop.
537 ReqCV.notify_all();
540 bool blockUntilIdle(Deadline Timeout) const {
541 std::unique_lock<std::mutex> Lock(Mutex);
542 return wait(Lock, ReqCV, Timeout, [&] { return !NextReq && !CurrentReq; });
545 private:
546 /// Holds inputs required for building a preamble. CI is guaranteed to be
547 /// non-null.
548 struct Request {
549 std::unique_ptr<CompilerInvocation> CI;
550 ParseInputs Inputs;
551 std::vector<Diag> CIDiags;
552 WantDiagnostics WantDiags;
553 Context Ctx;
556 bool isDone() {
557 std::lock_guard<std::mutex> Lock(Mutex);
558 return Done;
561 /// Builds a preamble for \p Req, might reuse LatestBuild if possible.
562 /// Notifies ASTWorker after build finishes.
563 void build(Request Req);
565 mutable std::mutex Mutex;
566 bool Done = false; /* GUARDED_BY(Mutex) */
567 std::optional<Request> NextReq; /* GUARDED_BY(Mutex) */
568 std::optional<Request> CurrentReq; /* GUARDED_BY(Mutex) */
569 // Signaled whenever a thread populates NextReq or worker thread builds a
570 // Preamble.
571 mutable std::condition_variable ReqCV; /* GUARDED_BY(Mutex) */
572 // Accessed only by preamble thread.
573 std::shared_ptr<const PreambleData> LatestBuild;
575 const Path FileName;
576 ParsingCallbacks &Callbacks;
577 const bool StoreInMemory;
578 const bool RunSync;
579 PreambleThrottler *Throttler;
581 SynchronizedTUStatus &Status;
582 ASTWorker &ASTPeer;
583 TUScheduler::HeaderIncluderCache &HeaderIncluders;
586 class ASTWorkerHandle;
588 /// Owns one instance of the AST, schedules updates and reads of it.
589 /// Also responsible for building and providing access to the preamble.
590 /// Each ASTWorker processes the async requests sent to it on a separate
591 /// dedicated thread.
592 /// The ASTWorker that manages the AST is shared by both the processing thread
593 /// and the TUScheduler. The TUScheduler should discard an ASTWorker when
594 /// remove() is called, but its thread may be busy and we don't want to block.
595 /// So the workers are accessed via an ASTWorkerHandle. Destroying the handle
596 /// signals the worker to exit its run loop and gives up shared ownership of the
597 /// worker.
598 class ASTWorker {
599 friend class ASTWorkerHandle;
600 ASTWorker(PathRef FileName, const GlobalCompilationDatabase &CDB,
601 TUScheduler::ASTCache &LRUCache,
602 TUScheduler::HeaderIncluderCache &HeaderIncluders,
603 Semaphore &Barrier, bool RunSync, const TUScheduler::Options &Opts,
604 ParsingCallbacks &Callbacks);
606 public:
607 /// Create a new ASTWorker and return a handle to it.
608 /// The processing thread is spawned using \p Tasks. However, when \p Tasks
609 /// is null, all requests will be processed on the calling thread
610 /// synchronously instead. \p Barrier is acquired when processing each
611 /// request, it is used to limit the number of actively running threads.
612 static ASTWorkerHandle
613 create(PathRef FileName, const GlobalCompilationDatabase &CDB,
614 TUScheduler::ASTCache &IdleASTs,
615 TUScheduler::HeaderIncluderCache &HeaderIncluders,
616 AsyncTaskRunner *Tasks, Semaphore &Barrier,
617 const TUScheduler::Options &Opts, ParsingCallbacks &Callbacks);
618 ~ASTWorker();
620 void update(ParseInputs Inputs, WantDiagnostics, bool ContentChanged);
621 void
622 runWithAST(llvm::StringRef Name,
623 llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action,
624 TUScheduler::ASTActionInvalidation);
625 bool blockUntilIdle(Deadline Timeout) const;
627 std::shared_ptr<const PreambleData> getPossiblyStalePreamble(
628 std::shared_ptr<const ASTSignals> *ASTSignals = nullptr) const;
630 /// Used to inform ASTWorker about a new preamble build by PreambleThread.
631 /// Diagnostics are only published through this callback. This ensures they
632 /// are always for newer versions of the file, as the callback gets called in
633 /// the same order as update requests.
634 void updatePreamble(std::unique_ptr<CompilerInvocation> CI, ParseInputs PI,
635 std::shared_ptr<const PreambleData> Preamble,
636 std::vector<Diag> CIDiags, WantDiagnostics WantDiags);
638 /// Returns compile command from the current file inputs.
639 tooling::CompileCommand getCurrentCompileCommand() const;
641 /// Wait for the first build of preamble to finish. Preamble itself can be
642 /// accessed via getPossiblyStalePreamble(). Note that this function will
643 /// return after an unsuccessful build of the preamble too, i.e. result of
644 /// getPossiblyStalePreamble() can be null even after this function returns.
645 void waitForFirstPreamble() const;
647 TUScheduler::FileStats stats() const;
648 bool isASTCached() const;
650 private:
651 // Details of an update request that are relevant to scheduling.
652 struct UpdateType {
653 // Do we want diagnostics from this version?
654 // If Yes, we must always build this version.
655 // If No, we only need to build this version if it's read.
656 // If Auto, we build if it's read or if the debounce expires.
657 WantDiagnostics Diagnostics;
658 // Did the main-file content of the document change?
659 // If so, we're allowed to cancel certain invalidated preceding reads.
660 bool ContentChanged;
663 /// Publishes diagnostics for \p Inputs. It will build an AST or reuse the
664 /// cached one if applicable. Assumes LatestPreamble is compatible for \p
665 /// Inputs.
666 void generateDiagnostics(std::unique_ptr<CompilerInvocation> Invocation,
667 ParseInputs Inputs, std::vector<Diag> CIDiags);
669 void updateASTSignals(ParsedAST &AST);
671 // Must be called exactly once on processing thread. Will return after
672 // stop() is called on a separate thread and all pending requests are
673 // processed.
674 void run();
675 /// Signal that run() should finish processing pending requests and exit.
676 void stop();
678 /// Adds a new task to the end of the request queue.
679 void startTask(llvm::StringRef Name, llvm::unique_function<void()> Task,
680 std::optional<UpdateType> Update,
681 TUScheduler::ASTActionInvalidation);
682 /// Runs a task synchronously.
683 void runTask(llvm::StringRef Name, llvm::function_ref<void()> Task);
685 /// Determines the next action to perform.
686 /// All actions that should never run are discarded.
687 /// Returns a deadline for the next action. If it's expired, run now.
688 /// scheduleLocked() is called again at the deadline, or if requests arrive.
689 Deadline scheduleLocked();
690 /// Should the first task in the queue be skipped instead of run?
691 bool shouldSkipHeadLocked() const;
693 struct Request {
694 llvm::unique_function<void()> Action;
695 std::string Name;
696 steady_clock::time_point AddTime;
697 Context Ctx;
698 std::optional<Context> QueueCtx;
699 std::optional<UpdateType> Update;
700 TUScheduler::ASTActionInvalidation InvalidationPolicy;
701 Canceler Invalidate;
704 /// Handles retention of ASTs.
705 TUScheduler::ASTCache &IdleASTs;
706 TUScheduler::HeaderIncluderCache &HeaderIncluders;
707 const bool RunSync;
708 /// Time to wait after an update to see whether another update obsoletes it.
709 const DebouncePolicy UpdateDebounce;
710 /// File that ASTWorker is responsible for.
711 const Path FileName;
712 /// Callback to create processing contexts for tasks.
713 const std::function<Context(llvm::StringRef)> ContextProvider;
714 const GlobalCompilationDatabase &CDB;
715 /// Callback invoked when preamble or main file AST is built.
716 ParsingCallbacks &Callbacks;
718 Semaphore &Barrier;
719 /// Whether the 'onMainAST' callback ran for the current FileInputs.
720 bool RanASTCallback = false;
721 /// Guards members used by both TUScheduler and the worker thread.
722 mutable std::mutex Mutex;
723 /// File inputs, currently being used by the worker.
724 /// Writes and reads from unknown threads are locked. Reads from the worker
725 /// thread are not locked, as it's the only writer.
726 ParseInputs FileInputs; /* GUARDED_BY(Mutex) */
727 /// Times of recent AST rebuilds, used for UpdateDebounce computation.
728 llvm::SmallVector<DebouncePolicy::clock::duration>
729 RebuildTimes; /* GUARDED_BY(Mutex) */
730 /// Set to true to signal run() to finish processing.
731 bool Done; /* GUARDED_BY(Mutex) */
732 std::deque<Request> Requests; /* GUARDED_BY(Mutex) */
733 std::optional<Request> CurrentRequest; /* GUARDED_BY(Mutex) */
734 /// Signalled whenever a new request has been scheduled or processing of a
735 /// request has completed.
736 mutable std::condition_variable RequestsCV;
737 std::shared_ptr<const ASTSignals> LatestASTSignals; /* GUARDED_BY(Mutex) */
738 /// Latest build preamble for current TU.
739 /// std::nullopt means no builds yet, null means there was an error while
740 /// building. Only written by ASTWorker's thread.
741 std::optional<std::shared_ptr<const PreambleData>> LatestPreamble;
742 std::deque<Request> PreambleRequests; /* GUARDED_BY(Mutex) */
743 /// Signaled whenever LatestPreamble changes state or there's a new
744 /// PreambleRequest.
745 mutable std::condition_variable PreambleCV;
746 /// Guards the callback that publishes results of AST-related computations
747 /// (diagnostics) and file statuses.
748 std::mutex PublishMu;
749 // Used to prevent remove document + add document races that lead to
750 // out-of-order callbacks for publishing results of onMainAST callback.
752 // The lifetime of the old/new ASTWorkers will overlap, but their handles
753 // don't. When the old handle is destroyed, the old worker will stop reporting
754 // any results to the user.
755 bool CanPublishResults = true; /* GUARDED_BY(PublishMu) */
756 std::atomic<unsigned> ASTBuildCount = {0};
757 std::atomic<unsigned> PreambleBuildCount = {0};
759 SynchronizedTUStatus Status;
760 PreambleThread PreamblePeer;
763 /// A smart-pointer-like class that points to an active ASTWorker.
764 /// In destructor, signals to the underlying ASTWorker that no new requests will
765 /// be sent and the processing loop may exit (after running all pending
766 /// requests).
767 class ASTWorkerHandle {
768 friend class ASTWorker;
769 ASTWorkerHandle(std::shared_ptr<ASTWorker> Worker)
770 : Worker(std::move(Worker)) {
771 assert(this->Worker);
774 public:
775 ASTWorkerHandle(const ASTWorkerHandle &) = delete;
776 ASTWorkerHandle &operator=(const ASTWorkerHandle &) = delete;
777 ASTWorkerHandle(ASTWorkerHandle &&) = default;
778 ASTWorkerHandle &operator=(ASTWorkerHandle &&) = default;
780 ~ASTWorkerHandle() {
781 if (Worker)
782 Worker->stop();
785 ASTWorker &operator*() {
786 assert(Worker && "Handle was moved from");
787 return *Worker;
790 ASTWorker *operator->() {
791 assert(Worker && "Handle was moved from");
792 return Worker.get();
795 /// Returns an owning reference to the underlying ASTWorker that can outlive
796 /// the ASTWorkerHandle. However, no new requests to an active ASTWorker can
797 /// be schedule via the returned reference, i.e. only reads of the preamble
798 /// are possible.
799 std::shared_ptr<const ASTWorker> lock() { return Worker; }
801 private:
802 std::shared_ptr<ASTWorker> Worker;
805 ASTWorkerHandle
806 ASTWorker::create(PathRef FileName, const GlobalCompilationDatabase &CDB,
807 TUScheduler::ASTCache &IdleASTs,
808 TUScheduler::HeaderIncluderCache &HeaderIncluders,
809 AsyncTaskRunner *Tasks, Semaphore &Barrier,
810 const TUScheduler::Options &Opts,
811 ParsingCallbacks &Callbacks) {
812 std::shared_ptr<ASTWorker> Worker(
813 new ASTWorker(FileName, CDB, IdleASTs, HeaderIncluders, Barrier,
814 /*RunSync=*/!Tasks, Opts, Callbacks));
815 if (Tasks) {
816 Tasks->runAsync("ASTWorker:" + llvm::sys::path::filename(FileName),
817 [Worker]() { Worker->run(); });
818 Tasks->runAsync("PreambleWorker:" + llvm::sys::path::filename(FileName),
819 [Worker]() { Worker->PreamblePeer.run(); });
822 return ASTWorkerHandle(std::move(Worker));
825 ASTWorker::ASTWorker(PathRef FileName, const GlobalCompilationDatabase &CDB,
826 TUScheduler::ASTCache &LRUCache,
827 TUScheduler::HeaderIncluderCache &HeaderIncluders,
828 Semaphore &Barrier, bool RunSync,
829 const TUScheduler::Options &Opts,
830 ParsingCallbacks &Callbacks)
831 : IdleASTs(LRUCache), HeaderIncluders(HeaderIncluders), RunSync(RunSync),
832 UpdateDebounce(Opts.UpdateDebounce), FileName(FileName),
833 ContextProvider(Opts.ContextProvider), CDB(CDB), Callbacks(Callbacks),
834 Barrier(Barrier), Done(false), Status(FileName, Callbacks),
835 PreamblePeer(FileName, Callbacks, Opts.StorePreamblesInMemory, RunSync,
836 Opts.PreambleThrottler, Status, HeaderIncluders, *this) {
837 // Set a fallback command because compile command can be accessed before
838 // `Inputs` is initialized. Other fields are only used after initialization
839 // from client inputs.
840 FileInputs.CompileCommand = CDB.getFallbackCommand(FileName);
843 ASTWorker::~ASTWorker() {
844 // Make sure we remove the cached AST, if any.
845 IdleASTs.take(this);
846 #ifndef NDEBUG
847 std::lock_guard<std::mutex> Lock(Mutex);
848 assert(Done && "handle was not destroyed");
849 assert(Requests.empty() && !CurrentRequest &&
850 "unprocessed requests when destroying ASTWorker");
851 #endif
854 void ASTWorker::update(ParseInputs Inputs, WantDiagnostics WantDiags,
855 bool ContentChanged) {
856 llvm::StringLiteral TaskName = "Update";
857 auto Task = [=]() mutable {
858 // Get the actual command as `Inputs` does not have a command.
859 // FIXME: some build systems like Bazel will take time to preparing
860 // environment to build the file, it would be nice if we could emit a
861 // "PreparingBuild" status to inform users, it is non-trivial given the
862 // current implementation.
863 auto Cmd = CDB.getCompileCommand(FileName);
864 // If we don't have a reliable command for this file, it may be a header.
865 // Try to find a file that includes it, to borrow its command.
866 if (!Cmd || !isReliable(*Cmd)) {
867 std::string ProxyFile = HeaderIncluders.get(FileName);
868 if (!ProxyFile.empty()) {
869 auto ProxyCmd = CDB.getCompileCommand(ProxyFile);
870 if (!ProxyCmd || !isReliable(*ProxyCmd)) {
871 // This command is supposed to be reliable! It's probably gone.
872 HeaderIncluders.remove(ProxyFile);
873 } else {
874 // We have a reliable command for an including file, use it.
875 Cmd = tooling::transferCompileCommand(std::move(*ProxyCmd), FileName);
879 if (Cmd)
880 Inputs.CompileCommand = std::move(*Cmd);
881 else
882 Inputs.CompileCommand = CDB.getFallbackCommand(FileName);
884 bool InputsAreTheSame =
885 std::tie(FileInputs.CompileCommand, FileInputs.Contents) ==
886 std::tie(Inputs.CompileCommand, Inputs.Contents);
887 // Cached AST is invalidated.
888 if (!InputsAreTheSame) {
889 IdleASTs.take(this);
890 RanASTCallback = false;
893 // Update current inputs so that subsequent reads can see them.
895 std::lock_guard<std::mutex> Lock(Mutex);
896 FileInputs = Inputs;
899 log("ASTWorker building file {0} version {1} with command {2}\n[{3}]\n{4}",
900 FileName, Inputs.Version, Inputs.CompileCommand.Heuristic,
901 Inputs.CompileCommand.Directory,
902 printArgv(Inputs.CompileCommand.CommandLine));
904 StoreDiags CompilerInvocationDiagConsumer;
905 std::vector<std::string> CC1Args;
906 std::unique_ptr<CompilerInvocation> Invocation = buildCompilerInvocation(
907 Inputs, CompilerInvocationDiagConsumer, &CC1Args);
908 // Log cc1 args even (especially!) if creating invocation failed.
909 if (!CC1Args.empty())
910 vlog("Driver produced command: cc1 {0}", printArgv(CC1Args));
911 std::vector<Diag> CompilerInvocationDiags =
912 CompilerInvocationDiagConsumer.take();
913 if (!Invocation) {
914 elog("Could not build CompilerInvocation for file {0}", FileName);
915 // Remove the old AST if it's still in cache.
916 IdleASTs.take(this);
917 RanASTCallback = false;
918 // Report the diagnostics we collected when parsing the command line.
919 Callbacks.onFailedAST(FileName, Inputs.Version,
920 std::move(CompilerInvocationDiags),
921 [&](llvm::function_ref<void()> Publish) {
922 // Ensure we only publish results from the worker
923 // if the file was not removed, making sure there
924 // are not race conditions.
925 std::lock_guard<std::mutex> Lock(PublishMu);
926 if (CanPublishResults)
927 Publish();
929 // Note that this might throw away a stale preamble that might still be
930 // useful, but this is how we communicate a build error.
931 LatestPreamble.emplace();
932 // Make sure anyone waiting for the preamble gets notified it could not be
933 // built.
934 PreambleCV.notify_all();
935 return;
938 // Inform preamble peer, before attempting to build diagnostics so that they
939 // can be built concurrently.
940 PreamblePeer.update(std::make_unique<CompilerInvocation>(*Invocation),
941 Inputs, CompilerInvocationDiags, WantDiags);
943 // Emit diagnostics from (possibly) stale preamble while waiting for a
944 // rebuild. Newly built preamble cannot emit diagnostics before this call
945 // finishes (ast callbacks are called from astpeer thread), hence we
946 // guarantee eventual consistency.
947 if (LatestPreamble && WantDiags != WantDiagnostics::No)
948 generateDiagnostics(std::move(Invocation), std::move(Inputs),
949 std::move(CompilerInvocationDiags));
951 std::unique_lock<std::mutex> Lock(Mutex);
952 PreambleCV.wait(Lock, [this] {
953 // Block until we reiceve a preamble request, unless a preamble already
954 // exists, as patching an empty preamble would imply rebuilding it from
955 // scratch.
956 // We block here instead of the consumer to prevent any deadlocks. Since
957 // LatestPreamble is only populated by ASTWorker thread.
958 return LatestPreamble || !PreambleRequests.empty() || Done;
961 startTask(TaskName, std::move(Task), UpdateType{WantDiags, ContentChanged},
962 TUScheduler::NoInvalidation);
965 void ASTWorker::runWithAST(
966 llvm::StringRef Name,
967 llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action,
968 TUScheduler::ASTActionInvalidation Invalidation) {
969 // Tracks ast cache accesses for read operations.
970 static constexpr trace::Metric ASTAccessForRead(
971 "ast_access_read", trace::Metric::Counter, "result");
972 auto Task = [=, Action = std::move(Action)]() mutable {
973 if (auto Reason = isCancelled())
974 return Action(llvm::make_error<CancelledError>(Reason));
975 std::optional<std::unique_ptr<ParsedAST>> AST =
976 IdleASTs.take(this, &ASTAccessForRead);
977 if (!AST) {
978 StoreDiags CompilerInvocationDiagConsumer;
979 std::unique_ptr<CompilerInvocation> Invocation =
980 buildCompilerInvocation(FileInputs, CompilerInvocationDiagConsumer);
981 // Try rebuilding the AST.
982 vlog("ASTWorker rebuilding evicted AST to run {0}: {1} version {2}", Name,
983 FileName, FileInputs.Version);
984 // FIXME: We might need to build a patched ast once preamble thread starts
985 // running async. Currently getPossiblyStalePreamble below will always
986 // return a compatible preamble as ASTWorker::update blocks.
987 std::optional<ParsedAST> NewAST;
988 if (Invocation) {
989 NewAST = ParsedAST::build(FileName, FileInputs, std::move(Invocation),
990 CompilerInvocationDiagConsumer.take(),
991 getPossiblyStalePreamble());
992 ++ASTBuildCount;
994 AST = NewAST ? std::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
996 // Make sure we put the AST back into the LRU cache.
997 auto _ = llvm::make_scope_exit(
998 [&AST, this]() { IdleASTs.put(this, std::move(*AST)); });
999 // Run the user-provided action.
1000 if (!*AST)
1001 return Action(error(llvm::errc::invalid_argument, "invalid AST"));
1002 vlog("ASTWorker running {0} on version {2} of {1}", Name, FileName,
1003 FileInputs.Version);
1004 Action(InputsAndAST{FileInputs, **AST});
1006 startTask(Name, std::move(Task), /*Update=*/std::nullopt, Invalidation);
1009 /// To be called from ThreadCrashReporter's signal handler.
1010 static void crashDumpCompileCommand(llvm::raw_ostream &OS,
1011 const tooling::CompileCommand &Command) {
1012 OS << " Filename: " << Command.Filename << "\n";
1013 OS << " Directory: " << Command.Directory << "\n";
1014 OS << " Command Line:";
1015 for (auto &Arg : Command.CommandLine) {
1016 OS << " " << Arg;
1018 OS << "\n";
1021 /// To be called from ThreadCrashReporter's signal handler.
1022 static void crashDumpFileContents(llvm::raw_ostream &OS,
1023 const std::string &Contents) {
1024 // Avoid flooding the terminal with source code by default, but allow clients
1025 // to opt in. Use an env var to preserve backwards compatibility of the
1026 // command line interface, while allowing it to be set outside the clangd
1027 // launch site for more flexibility.
1028 if (getenv("CLANGD_CRASH_DUMP_SOURCE")) {
1029 OS << " Contents:\n";
1030 OS << Contents << "\n";
1034 /// To be called from ThreadCrashReporter's signal handler.
1035 static void crashDumpParseInputs(llvm::raw_ostream &OS,
1036 const ParseInputs &FileInputs) {
1037 auto &Command = FileInputs.CompileCommand;
1038 crashDumpCompileCommand(OS, Command);
1039 OS << " Version: " << FileInputs.Version << "\n";
1040 crashDumpFileContents(OS, FileInputs.Contents);
1043 void PreambleThread::build(Request Req) {
1044 assert(Req.CI && "Got preamble request with null compiler invocation");
1045 const ParseInputs &Inputs = Req.Inputs;
1046 bool ReusedPreamble = false;
1048 Status.update([&](TUStatus &Status) {
1049 Status.PreambleActivity = PreambleAction::Building;
1051 auto _ = llvm::make_scope_exit([this, &Req, &ReusedPreamble] {
1052 ASTPeer.updatePreamble(std::move(Req.CI), std::move(Req.Inputs),
1053 LatestBuild, std::move(Req.CIDiags),
1054 std::move(Req.WantDiags));
1055 if (!ReusedPreamble)
1056 Callbacks.onPreamblePublished(FileName);
1059 if (!LatestBuild || Inputs.ForceRebuild) {
1060 vlog("Building first preamble for {0} version {1}", FileName,
1061 Inputs.Version);
1062 } else if (isPreambleCompatible(*LatestBuild, Inputs, FileName, *Req.CI)) {
1063 vlog("Reusing preamble version {0} for version {1} of {2}",
1064 LatestBuild->Version, Inputs.Version, FileName);
1065 ReusedPreamble = true;
1066 return;
1067 } else {
1068 vlog("Rebuilding invalidated preamble for {0} version {1} (previous was "
1069 "version {2})",
1070 FileName, Inputs.Version, LatestBuild->Version);
1073 ThreadCrashReporter ScopedReporter([&Inputs]() {
1074 llvm::errs() << "Signalled while building preamble\n";
1075 crashDumpParseInputs(llvm::errs(), Inputs);
1078 PreambleBuildStats Stats;
1079 bool IsFirstPreamble = !LatestBuild;
1080 LatestBuild = clang::clangd::buildPreamble(
1081 FileName, *Req.CI, Inputs, StoreInMemory,
1082 [&](CapturedASTCtx ASTCtx,
1083 std::shared_ptr<const include_cleaner::PragmaIncludes> PI) {
1084 Callbacks.onPreambleAST(FileName, Inputs.Version, std::move(ASTCtx),
1085 std::move(PI));
1087 &Stats);
1088 if (!LatestBuild)
1089 return;
1090 reportPreambleBuild(Stats, IsFirstPreamble);
1091 if (isReliable(LatestBuild->CompileCommand))
1092 HeaderIncluders.update(FileName, LatestBuild->Includes.allHeaders());
1095 void ASTWorker::updatePreamble(std::unique_ptr<CompilerInvocation> CI,
1096 ParseInputs PI,
1097 std::shared_ptr<const PreambleData> Preamble,
1098 std::vector<Diag> CIDiags,
1099 WantDiagnostics WantDiags) {
1100 llvm::StringLiteral TaskName = "Build AST";
1101 // Store preamble and build diagnostics with new preamble if requested.
1102 auto Task = [this, Preamble = std::move(Preamble), CI = std::move(CI),
1103 CIDiags = std::move(CIDiags),
1104 WantDiags = std::move(WantDiags)]() mutable {
1105 // Update the preamble inside ASTWorker queue to ensure atomicity. As a task
1106 // running inside ASTWorker assumes internals won't change until it
1107 // finishes.
1108 if (!LatestPreamble || Preamble != *LatestPreamble) {
1109 ++PreambleBuildCount;
1110 // Cached AST is no longer valid.
1111 IdleASTs.take(this);
1112 RanASTCallback = false;
1113 std::lock_guard<std::mutex> Lock(Mutex);
1114 // LatestPreamble might be the last reference to old preamble, do not
1115 // trigger destructor while holding the lock.
1116 if (LatestPreamble)
1117 std::swap(*LatestPreamble, Preamble);
1118 else
1119 LatestPreamble = std::move(Preamble);
1121 // Notify anyone waiting for a preamble.
1122 PreambleCV.notify_all();
1123 // Give up our ownership to old preamble before starting expensive AST
1124 // build.
1125 Preamble.reset();
1126 // We only need to build the AST if diagnostics were requested.
1127 if (WantDiags == WantDiagnostics::No)
1128 return;
1129 // Since the file may have been edited since we started building this
1130 // preamble, we use the current contents of the file instead. This provides
1131 // more up-to-date diagnostics, and avoids diagnostics going backwards (we
1132 // may have already emitted staler-preamble diagnostics for the new
1133 // version).
1134 // We still have eventual consistency: at some point updatePreamble() will
1135 // catch up to the current file.
1136 // Report diagnostics with the new preamble to ensure progress. Otherwise
1137 // diagnostics might get stale indefinitely if user keeps invalidating the
1138 // preamble.
1139 generateDiagnostics(std::move(CI), FileInputs, std::move(CIDiags));
1141 if (RunSync) {
1142 runTask(TaskName, Task);
1143 return;
1146 std::lock_guard<std::mutex> Lock(Mutex);
1147 PreambleRequests.push_back({std::move(Task), std::string(TaskName),
1148 steady_clock::now(), Context::current().clone(),
1149 std::nullopt, std::nullopt,
1150 TUScheduler::NoInvalidation, nullptr});
1152 PreambleCV.notify_all();
1153 RequestsCV.notify_all();
1156 void ASTWorker::updateASTSignals(ParsedAST &AST) {
1157 auto Signals = std::make_shared<const ASTSignals>(ASTSignals::derive(AST));
1158 // Existing readers of ASTSignals will have their copy preserved until the
1159 // read is completed. The last reader deletes the old ASTSignals.
1161 std::lock_guard<std::mutex> Lock(Mutex);
1162 std::swap(LatestASTSignals, Signals);
1166 void ASTWorker::generateDiagnostics(
1167 std::unique_ptr<CompilerInvocation> Invocation, ParseInputs Inputs,
1168 std::vector<Diag> CIDiags) {
1169 // Tracks ast cache accesses for publishing diags.
1170 static constexpr trace::Metric ASTAccessForDiag(
1171 "ast_access_diag", trace::Metric::Counter, "result");
1172 assert(Invocation);
1173 assert(LatestPreamble);
1174 // No need to rebuild the AST if we won't send the diagnostics.
1176 std::lock_guard<std::mutex> Lock(PublishMu);
1177 if (!CanPublishResults)
1178 return;
1180 // Used to check whether we can update AST cache.
1181 bool InputsAreLatest =
1182 std::tie(FileInputs.CompileCommand, FileInputs.Contents) ==
1183 std::tie(Inputs.CompileCommand, Inputs.Contents);
1184 // Take a shortcut and don't report the diagnostics, since they should be the
1185 // same. All the clients should handle the lack of OnUpdated() call anyway to
1186 // handle empty result from buildAST.
1187 // FIXME: the AST could actually change if non-preamble includes changed,
1188 // but we choose to ignore it.
1189 if (InputsAreLatest && RanASTCallback)
1190 return;
1192 // Get the AST for diagnostics, either build it or use the cached one.
1193 std::string TaskName = llvm::formatv("Build AST ({0})", Inputs.Version);
1194 Status.update([&](TUStatus &Status) {
1195 Status.ASTActivity.K = ASTAction::Building;
1196 Status.ASTActivity.Name = std::move(TaskName);
1198 // We might be able to reuse the last we've built for a read request.
1199 // FIXME: It might be better to not reuse this AST. That way queued AST builds
1200 // won't be required for diags.
1201 std::optional<std::unique_ptr<ParsedAST>> AST =
1202 IdleASTs.take(this, &ASTAccessForDiag);
1203 if (!AST || !InputsAreLatest) {
1204 auto RebuildStartTime = DebouncePolicy::clock::now();
1205 std::optional<ParsedAST> NewAST = ParsedAST::build(
1206 FileName, Inputs, std::move(Invocation), CIDiags, *LatestPreamble);
1207 auto RebuildDuration = DebouncePolicy::clock::now() - RebuildStartTime;
1208 ++ASTBuildCount;
1209 // Try to record the AST-build time, to inform future update debouncing.
1210 // This is best-effort only: if the lock is held, don't bother.
1211 std::unique_lock<std::mutex> Lock(Mutex, std::try_to_lock);
1212 if (Lock.owns_lock()) {
1213 // Do not let RebuildTimes grow beyond its small-size (i.e.
1214 // capacity).
1215 if (RebuildTimes.size() == RebuildTimes.capacity())
1216 RebuildTimes.erase(RebuildTimes.begin());
1217 RebuildTimes.push_back(RebuildDuration);
1218 Lock.unlock();
1220 Status.update([&](TUStatus &Status) {
1221 Status.Details.ReuseAST = false;
1222 Status.Details.BuildFailed = !NewAST;
1224 AST = NewAST ? std::make_unique<ParsedAST>(std::move(*NewAST)) : nullptr;
1225 } else {
1226 log("Skipping rebuild of the AST for {0}, inputs are the same.", FileName);
1227 Status.update([](TUStatus &Status) {
1228 Status.Details.ReuseAST = true;
1229 Status.Details.BuildFailed = false;
1233 // Publish diagnostics.
1234 auto RunPublish = [&](llvm::function_ref<void()> Publish) {
1235 // Ensure we only publish results from the worker if the file was not
1236 // removed, making sure there are not race conditions.
1237 std::lock_guard<std::mutex> Lock(PublishMu);
1238 if (CanPublishResults)
1239 Publish();
1241 if (*AST) {
1242 trace::Span Span("Running main AST callback");
1243 Callbacks.onMainAST(FileName, **AST, RunPublish);
1244 updateASTSignals(**AST);
1245 } else {
1246 // Failed to build the AST, at least report diagnostics from the
1247 // command line if there were any.
1248 // FIXME: we might have got more errors while trying to build the
1249 // AST, surface them too.
1250 Callbacks.onFailedAST(FileName, Inputs.Version, CIDiags, RunPublish);
1253 // AST might've been built for an older version of the source, as ASTWorker
1254 // queue raced ahead while we were waiting on the preamble. In that case the
1255 // queue can't reuse the AST.
1256 if (InputsAreLatest) {
1257 RanASTCallback = *AST != nullptr;
1258 IdleASTs.put(this, std::move(*AST));
1262 std::shared_ptr<const PreambleData> ASTWorker::getPossiblyStalePreamble(
1263 std::shared_ptr<const ASTSignals> *ASTSignals) const {
1264 std::lock_guard<std::mutex> Lock(Mutex);
1265 if (ASTSignals)
1266 *ASTSignals = LatestASTSignals;
1267 return LatestPreamble ? *LatestPreamble : nullptr;
1270 void ASTWorker::waitForFirstPreamble() const {
1271 std::unique_lock<std::mutex> Lock(Mutex);
1272 PreambleCV.wait(Lock, [this] { return LatestPreamble || Done; });
1275 tooling::CompileCommand ASTWorker::getCurrentCompileCommand() const {
1276 std::unique_lock<std::mutex> Lock(Mutex);
1277 return FileInputs.CompileCommand;
1280 TUScheduler::FileStats ASTWorker::stats() const {
1281 TUScheduler::FileStats Result;
1282 Result.ASTBuilds = ASTBuildCount;
1283 Result.PreambleBuilds = PreambleBuildCount;
1284 // Note that we don't report the size of ASTs currently used for processing
1285 // the in-flight requests. We used this information for debugging purposes
1286 // only, so this should be fine.
1287 Result.UsedBytesAST = IdleASTs.getUsedBytes(this);
1288 if (auto Preamble = getPossiblyStalePreamble())
1289 Result.UsedBytesPreamble = Preamble->Preamble.getSize();
1290 return Result;
1293 bool ASTWorker::isASTCached() const { return IdleASTs.getUsedBytes(this) != 0; }
1295 void ASTWorker::stop() {
1297 std::lock_guard<std::mutex> Lock(PublishMu);
1298 CanPublishResults = false;
1301 std::lock_guard<std::mutex> Lock(Mutex);
1302 assert(!Done && "stop() called twice");
1303 Done = true;
1305 PreamblePeer.stop();
1306 // We are no longer going to build any preambles, let the waiters know that.
1307 PreambleCV.notify_all();
1308 Status.stop();
1309 RequestsCV.notify_all();
1312 void ASTWorker::runTask(llvm::StringRef Name, llvm::function_ref<void()> Task) {
1313 ThreadCrashReporter ScopedReporter([this, Name]() {
1314 llvm::errs() << "Signalled during AST worker action: " << Name << "\n";
1315 crashDumpParseInputs(llvm::errs(), FileInputs);
1317 trace::Span Tracer(Name);
1318 WithContext WithProvidedContext(ContextProvider(FileName));
1319 Task();
1322 void ASTWorker::startTask(llvm::StringRef Name,
1323 llvm::unique_function<void()> Task,
1324 std::optional<UpdateType> Update,
1325 TUScheduler::ASTActionInvalidation Invalidation) {
1326 if (RunSync) {
1327 assert(!Done && "running a task after stop()");
1328 runTask(Name, Task);
1329 return;
1333 std::lock_guard<std::mutex> Lock(Mutex);
1334 assert(!Done && "running a task after stop()");
1335 // Cancel any requests invalidated by this request.
1336 if (Update && Update->ContentChanged) {
1337 for (auto &R : llvm::reverse(Requests)) {
1338 if (R.InvalidationPolicy == TUScheduler::InvalidateOnUpdate)
1339 R.Invalidate();
1340 if (R.Update && R.Update->ContentChanged)
1341 break; // Older requests were already invalidated by the older update.
1345 // Allow this request to be cancelled if invalidated.
1346 Context Ctx = Context::current().derive(FileBeingProcessed, FileName);
1347 Canceler Invalidate = nullptr;
1348 if (Invalidation) {
1349 WithContext WC(std::move(Ctx));
1350 std::tie(Ctx, Invalidate) = cancelableTask(
1351 /*Reason=*/static_cast<int>(ErrorCode::ContentModified));
1353 // Trace the time the request spends in the queue, and the requests that
1354 // it's going to wait for.
1355 std::optional<Context> QueueCtx;
1356 if (trace::enabled()) {
1357 // Tracers that follow threads and need strict nesting will see a tiny
1358 // instantaneous event "we're enqueueing", and sometime later it runs.
1359 WithContext WC(Ctx.clone());
1360 trace::Span Tracer("Queued:" + Name);
1361 if (Tracer.Args) {
1362 if (CurrentRequest)
1363 SPAN_ATTACH(Tracer, "CurrentRequest", CurrentRequest->Name);
1364 llvm::json::Array PreambleRequestsNames;
1365 for (const auto &Req : PreambleRequests)
1366 PreambleRequestsNames.push_back(Req.Name);
1367 SPAN_ATTACH(Tracer, "PreambleRequestsNames",
1368 std::move(PreambleRequestsNames));
1369 llvm::json::Array RequestsNames;
1370 for (const auto &Req : Requests)
1371 RequestsNames.push_back(Req.Name);
1372 SPAN_ATTACH(Tracer, "RequestsNames", std::move(RequestsNames));
1374 // For tracers that follow contexts, keep the trace span's context alive
1375 // until we dequeue the request, so they see the full duration.
1376 QueueCtx = Context::current().clone();
1378 Requests.push_back({std::move(Task), std::string(Name), steady_clock::now(),
1379 std::move(Ctx), std::move(QueueCtx), Update,
1380 Invalidation, std::move(Invalidate)});
1382 RequestsCV.notify_all();
1385 void ASTWorker::run() {
1386 while (true) {
1388 std::unique_lock<std::mutex> Lock(Mutex);
1389 assert(!CurrentRequest && "A task is already running, multiple workers?");
1390 for (auto Wait = scheduleLocked(); !Wait.expired();
1391 Wait = scheduleLocked()) {
1392 assert(PreambleRequests.empty() &&
1393 "Preamble updates should be scheduled immediately");
1394 if (Done) {
1395 if (Requests.empty())
1396 return;
1397 // Even though Done is set, finish pending requests.
1398 break; // However, skip delays to shutdown fast.
1401 // Tracing: we have a next request, attribute this sleep to it.
1402 std::optional<WithContext> Ctx;
1403 std::optional<trace::Span> Tracer;
1404 if (!Requests.empty()) {
1405 Ctx.emplace(Requests.front().Ctx.clone());
1406 Tracer.emplace("Debounce");
1407 SPAN_ATTACH(*Tracer, "next_request", Requests.front().Name);
1408 if (!(Wait == Deadline::infinity())) {
1409 Status.update([&](TUStatus &Status) {
1410 Status.ASTActivity.K = ASTAction::Queued;
1411 Status.ASTActivity.Name = Requests.front().Name;
1413 SPAN_ATTACH(*Tracer, "sleep_ms",
1414 std::chrono::duration_cast<std::chrono::milliseconds>(
1415 Wait.time() - steady_clock::now())
1416 .count());
1420 wait(Lock, RequestsCV, Wait);
1422 // Any request in ReceivedPreambles is at least as old as the
1423 // Requests.front(), so prefer them first to preserve LSP order.
1424 if (!PreambleRequests.empty()) {
1425 CurrentRequest = std::move(PreambleRequests.front());
1426 PreambleRequests.pop_front();
1427 } else {
1428 CurrentRequest = std::move(Requests.front());
1429 Requests.pop_front();
1431 } // unlock Mutex
1433 // Inform tracing that the request was dequeued.
1434 CurrentRequest->QueueCtx.reset();
1436 // It is safe to perform reads to CurrentRequest without holding the lock as
1437 // only writer is also this thread.
1439 std::unique_lock<Semaphore> Lock(Barrier, std::try_to_lock);
1440 if (!Lock.owns_lock()) {
1441 Status.update([&](TUStatus &Status) {
1442 Status.ASTActivity.K = ASTAction::Queued;
1443 Status.ASTActivity.Name = CurrentRequest->Name;
1445 Lock.lock();
1447 WithContext Guard(std::move(CurrentRequest->Ctx));
1448 Status.update([&](TUStatus &Status) {
1449 Status.ASTActivity.K = ASTAction::RunningAction;
1450 Status.ASTActivity.Name = CurrentRequest->Name;
1452 runTask(CurrentRequest->Name, CurrentRequest->Action);
1455 bool IsEmpty = false;
1457 std::lock_guard<std::mutex> Lock(Mutex);
1458 CurrentRequest.reset();
1459 IsEmpty = Requests.empty() && PreambleRequests.empty();
1461 if (IsEmpty) {
1462 Status.update([&](TUStatus &Status) {
1463 Status.ASTActivity.K = ASTAction::Idle;
1464 Status.ASTActivity.Name = "";
1467 RequestsCV.notify_all();
1471 Deadline ASTWorker::scheduleLocked() {
1472 // Process new preambles immediately.
1473 if (!PreambleRequests.empty())
1474 return Deadline::zero();
1475 if (Requests.empty())
1476 return Deadline::infinity(); // Wait for new requests.
1477 // Handle cancelled requests first so the rest of the scheduler doesn't.
1478 for (auto I = Requests.begin(), E = Requests.end(); I != E; ++I) {
1479 if (!isCancelled(I->Ctx)) {
1480 // Cancellations after the first read don't affect current scheduling.
1481 if (I->Update == std::nullopt)
1482 break;
1483 continue;
1485 // Cancelled reads are moved to the front of the queue and run immediately.
1486 if (I->Update == std::nullopt) {
1487 Request R = std::move(*I);
1488 Requests.erase(I);
1489 Requests.push_front(std::move(R));
1490 return Deadline::zero();
1492 // Cancelled updates are downgraded to auto-diagnostics, and may be elided.
1493 if (I->Update->Diagnostics == WantDiagnostics::Yes)
1494 I->Update->Diagnostics = WantDiagnostics::Auto;
1497 while (shouldSkipHeadLocked()) {
1498 vlog("ASTWorker skipping {0} for {1}", Requests.front().Name, FileName);
1499 Requests.pop_front();
1501 assert(!Requests.empty() && "skipped the whole queue");
1502 // Some updates aren't dead yet, but never end up being used.
1503 // e.g. the first keystroke is live until obsoleted by the second.
1504 // We debounce "maybe-unused" writes, sleeping in case they become dead.
1505 // But don't delay reads (including updates where diagnostics are needed).
1506 for (const auto &R : Requests)
1507 if (R.Update == std::nullopt ||
1508 R.Update->Diagnostics == WantDiagnostics::Yes)
1509 return Deadline::zero();
1510 // Front request needs to be debounced, so determine when we're ready.
1511 Deadline D(Requests.front().AddTime + UpdateDebounce.compute(RebuildTimes));
1512 return D;
1515 // Returns true if Requests.front() is a dead update that can be skipped.
1516 bool ASTWorker::shouldSkipHeadLocked() const {
1517 assert(!Requests.empty());
1518 auto Next = Requests.begin();
1519 auto Update = Next->Update;
1520 if (!Update) // Only skip updates.
1521 return false;
1522 ++Next;
1523 // An update is live if its AST might still be read.
1524 // That is, if it's not immediately followed by another update.
1525 if (Next == Requests.end() || !Next->Update)
1526 return false;
1527 // The other way an update can be live is if its diagnostics might be used.
1528 switch (Update->Diagnostics) {
1529 case WantDiagnostics::Yes:
1530 return false; // Always used.
1531 case WantDiagnostics::No:
1532 return true; // Always dead.
1533 case WantDiagnostics::Auto:
1534 // Used unless followed by an update that generates diagnostics.
1535 for (; Next != Requests.end(); ++Next)
1536 if (Next->Update && Next->Update->Diagnostics != WantDiagnostics::No)
1537 return true; // Prefer later diagnostics.
1538 return false;
1540 llvm_unreachable("Unknown WantDiagnostics");
1543 bool ASTWorker::blockUntilIdle(Deadline Timeout) const {
1544 auto WaitUntilASTWorkerIsIdle = [&] {
1545 std::unique_lock<std::mutex> Lock(Mutex);
1546 return wait(Lock, RequestsCV, Timeout, [&] {
1547 return PreambleRequests.empty() && Requests.empty() && !CurrentRequest;
1550 // Make sure ASTWorker has processed all requests, which might issue new
1551 // updates to PreamblePeer.
1552 if (!WaitUntilASTWorkerIsIdle())
1553 return false;
1554 // Now that ASTWorker processed all requests, ensure PreamblePeer has served
1555 // all update requests. This might create new PreambleRequests for the
1556 // ASTWorker.
1557 if (!PreamblePeer.blockUntilIdle(Timeout))
1558 return false;
1559 assert(Requests.empty() &&
1560 "No new normal tasks can be scheduled concurrently with "
1561 "blockUntilIdle(): ASTWorker isn't threadsafe");
1562 // Finally make sure ASTWorker has processed all of the preamble updates.
1563 return WaitUntilASTWorkerIsIdle();
1566 // Render a TUAction to a user-facing string representation.
1567 // TUAction represents clangd-internal states, we don't intend to expose them
1568 // to users (say C++ programmers) directly to avoid confusion, we use terms that
1569 // are familiar by C++ programmers.
1570 std::string renderTUAction(const PreambleAction PA, const ASTAction &AA) {
1571 llvm::SmallVector<std::string, 2> Result;
1572 switch (PA) {
1573 case PreambleAction::Building:
1574 Result.push_back("parsing includes");
1575 break;
1576 case PreambleAction::Queued:
1577 Result.push_back("includes are queued");
1578 break;
1579 case PreambleAction::Idle:
1580 // We handle idle specially below.
1581 break;
1583 switch (AA.K) {
1584 case ASTAction::Queued:
1585 Result.push_back("file is queued");
1586 break;
1587 case ASTAction::RunningAction:
1588 Result.push_back("running " + AA.Name);
1589 break;
1590 case ASTAction::Building:
1591 Result.push_back("parsing main file");
1592 break;
1593 case ASTAction::Idle:
1594 // We handle idle specially below.
1595 break;
1597 if (Result.empty())
1598 return "idle";
1599 return llvm::join(Result, ", ");
1602 } // namespace
1604 unsigned getDefaultAsyncThreadsCount() {
1605 return llvm::heavyweight_hardware_concurrency().compute_thread_count();
1608 FileStatus TUStatus::render(PathRef File) const {
1609 FileStatus FStatus;
1610 FStatus.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
1611 FStatus.state = renderTUAction(PreambleActivity, ASTActivity);
1612 return FStatus;
1615 struct TUScheduler::FileData {
1616 /// Latest inputs, passed to TUScheduler::update().
1617 std::string Contents;
1618 ASTWorkerHandle Worker;
1621 TUScheduler::TUScheduler(const GlobalCompilationDatabase &CDB,
1622 const Options &Opts,
1623 std::unique_ptr<ParsingCallbacks> Callbacks)
1624 : CDB(CDB), Opts(Opts),
1625 Callbacks(Callbacks ? std::move(Callbacks)
1626 : std::make_unique<ParsingCallbacks>()),
1627 Barrier(Opts.AsyncThreadsCount), QuickRunBarrier(Opts.AsyncThreadsCount),
1628 IdleASTs(
1629 std::make_unique<ASTCache>(Opts.RetentionPolicy.MaxRetainedASTs)),
1630 HeaderIncluders(std::make_unique<HeaderIncluderCache>()) {
1631 // Avoid null checks everywhere.
1632 if (!Opts.ContextProvider) {
1633 this->Opts.ContextProvider = [](llvm::StringRef) {
1634 return Context::current().clone();
1637 if (0 < Opts.AsyncThreadsCount) {
1638 PreambleTasks.emplace();
1639 WorkerThreads.emplace();
1643 TUScheduler::~TUScheduler() {
1644 // Notify all workers that they need to stop.
1645 Files.clear();
1647 // Wait for all in-flight tasks to finish.
1648 if (PreambleTasks)
1649 PreambleTasks->wait();
1650 if (WorkerThreads)
1651 WorkerThreads->wait();
1654 bool TUScheduler::blockUntilIdle(Deadline D) const {
1655 for (auto &File : Files)
1656 if (!File.getValue()->Worker->blockUntilIdle(D))
1657 return false;
1658 if (PreambleTasks)
1659 if (!PreambleTasks->wait(D))
1660 return false;
1661 return true;
1664 bool TUScheduler::update(PathRef File, ParseInputs Inputs,
1665 WantDiagnostics WantDiags) {
1666 std::unique_ptr<FileData> &FD = Files[File];
1667 bool NewFile = FD == nullptr;
1668 bool ContentChanged = false;
1669 if (!FD) {
1670 // Create a new worker to process the AST-related tasks.
1671 ASTWorkerHandle Worker = ASTWorker::create(
1672 File, CDB, *IdleASTs, *HeaderIncluders,
1673 WorkerThreads ? &*WorkerThreads : nullptr, Barrier, Opts, *Callbacks);
1674 FD = std::unique_ptr<FileData>(
1675 new FileData{Inputs.Contents, std::move(Worker)});
1676 ContentChanged = true;
1677 } else if (FD->Contents != Inputs.Contents) {
1678 ContentChanged = true;
1679 FD->Contents = Inputs.Contents;
1681 FD->Worker->update(std::move(Inputs), WantDiags, ContentChanged);
1682 // There might be synthetic update requests, don't change the LastActiveFile
1683 // in such cases.
1684 if (ContentChanged)
1685 LastActiveFile = File.str();
1686 return NewFile;
1689 void TUScheduler::remove(PathRef File) {
1690 bool Removed = Files.erase(File);
1691 if (!Removed)
1692 elog("Trying to remove file from TUScheduler that is not tracked: {0}",
1693 File);
1694 // We don't call HeaderIncluders.remove(File) here.
1695 // If we did, we'd avoid potentially stale header/mainfile associations.
1696 // However, it would mean that closing a mainfile could invalidate the
1697 // preamble of several open headers.
1700 void TUScheduler::run(llvm::StringRef Name, llvm::StringRef Path,
1701 llvm::unique_function<void()> Action) {
1702 runWithSemaphore(Name, Path, std::move(Action), Barrier);
1705 void TUScheduler::runQuick(llvm::StringRef Name, llvm::StringRef Path,
1706 llvm::unique_function<void()> Action) {
1707 // Use QuickRunBarrier to serialize quick tasks: we are ignoring
1708 // the parallelism level set by the user, don't abuse it
1709 runWithSemaphore(Name, Path, std::move(Action), QuickRunBarrier);
1712 void TUScheduler::runWithSemaphore(llvm::StringRef Name, llvm::StringRef Path,
1713 llvm::unique_function<void()> Action,
1714 Semaphore &Sem) {
1715 if (Path.empty())
1716 Path = LastActiveFile;
1717 else
1718 LastActiveFile = Path.str();
1719 if (!PreambleTasks) {
1720 WithContext WithProvidedContext(Opts.ContextProvider(Path));
1721 return Action();
1723 PreambleTasks->runAsync(Name, [this, &Sem, Ctx = Context::current().clone(),
1724 Path(Path.str()),
1725 Action = std::move(Action)]() mutable {
1726 std::lock_guard<Semaphore> BarrierLock(Sem);
1727 WithContext WC(std::move(Ctx));
1728 WithContext WithProvidedContext(Opts.ContextProvider(Path));
1729 Action();
1733 void TUScheduler::runWithAST(
1734 llvm::StringRef Name, PathRef File,
1735 llvm::unique_function<void(llvm::Expected<InputsAndAST>)> Action,
1736 TUScheduler::ASTActionInvalidation Invalidation) {
1737 auto It = Files.find(File);
1738 if (It == Files.end()) {
1739 Action(llvm::make_error<LSPError>(
1740 "trying to get AST for non-added document", ErrorCode::InvalidParams));
1741 return;
1743 LastActiveFile = File.str();
1745 It->second->Worker->runWithAST(Name, std::move(Action), Invalidation);
1748 void TUScheduler::runWithPreamble(llvm::StringRef Name, PathRef File,
1749 PreambleConsistency Consistency,
1750 Callback<InputsAndPreamble> Action) {
1751 auto It = Files.find(File);
1752 if (It == Files.end()) {
1753 Action(llvm::make_error<LSPError>(
1754 "trying to get preamble for non-added document",
1755 ErrorCode::InvalidParams));
1756 return;
1758 LastActiveFile = File.str();
1760 if (!PreambleTasks) {
1761 trace::Span Tracer(Name);
1762 SPAN_ATTACH(Tracer, "file", File);
1763 std::shared_ptr<const ASTSignals> Signals;
1764 std::shared_ptr<const PreambleData> Preamble =
1765 It->second->Worker->getPossiblyStalePreamble(&Signals);
1766 WithContext WithProvidedContext(Opts.ContextProvider(File));
1767 Action(InputsAndPreamble{It->second->Contents,
1768 It->second->Worker->getCurrentCompileCommand(),
1769 Preamble.get(), Signals.get()});
1770 return;
1773 std::shared_ptr<const ASTWorker> Worker = It->second->Worker.lock();
1774 auto Task = [Worker, Consistency, Name = Name.str(), File = File.str(),
1775 Contents = It->second->Contents,
1776 Command = Worker->getCurrentCompileCommand(),
1777 Ctx = Context::current().derive(FileBeingProcessed,
1778 std::string(File)),
1779 Action = std::move(Action), this]() mutable {
1780 ThreadCrashReporter ScopedReporter([&Name, &Contents, &Command]() {
1781 llvm::errs() << "Signalled during preamble action: " << Name << "\n";
1782 crashDumpCompileCommand(llvm::errs(), Command);
1783 crashDumpFileContents(llvm::errs(), Contents);
1785 std::shared_ptr<const PreambleData> Preamble;
1786 if (Consistency == PreambleConsistency::Stale) {
1787 // Wait until the preamble is built for the first time, if preamble
1788 // is required. This avoids extra work of processing the preamble
1789 // headers in parallel multiple times.
1790 Worker->waitForFirstPreamble();
1792 std::shared_ptr<const ASTSignals> Signals;
1793 Preamble = Worker->getPossiblyStalePreamble(&Signals);
1795 std::lock_guard<Semaphore> BarrierLock(Barrier);
1796 WithContext Guard(std::move(Ctx));
1797 trace::Span Tracer(Name);
1798 SPAN_ATTACH(Tracer, "file", File);
1799 WithContext WithProvidedContext(Opts.ContextProvider(File));
1800 Action(InputsAndPreamble{Contents, Command, Preamble.get(), Signals.get()});
1803 PreambleTasks->runAsync("task:" + llvm::sys::path::filename(File),
1804 std::move(Task));
1807 llvm::StringMap<TUScheduler::FileStats> TUScheduler::fileStats() const {
1808 llvm::StringMap<TUScheduler::FileStats> Result;
1809 for (const auto &PathAndFile : Files)
1810 Result.try_emplace(PathAndFile.first(),
1811 PathAndFile.second->Worker->stats());
1812 return Result;
1815 std::vector<Path> TUScheduler::getFilesWithCachedAST() const {
1816 std::vector<Path> Result;
1817 for (auto &&PathAndFile : Files) {
1818 if (!PathAndFile.second->Worker->isASTCached())
1819 continue;
1820 Result.push_back(std::string(PathAndFile.first()));
1822 return Result;
1825 DebouncePolicy::clock::duration
1826 DebouncePolicy::compute(llvm::ArrayRef<clock::duration> History) const {
1827 assert(Min <= Max && "Invalid policy");
1828 if (History.empty())
1829 return Max; // Arbitrary.
1831 // Base the result on the median rebuild.
1832 // nth_element needs a mutable array, take the chance to bound the data size.
1833 History = History.take_back(15);
1834 llvm::SmallVector<clock::duration, 15> Recent(History.begin(), History.end());
1835 auto *Median = Recent.begin() + Recent.size() / 2;
1836 std::nth_element(Recent.begin(), Median, Recent.end());
1838 clock::duration Target =
1839 std::chrono::duration_cast<clock::duration>(RebuildRatio * *Median);
1840 if (Target > Max)
1841 return Max;
1842 if (Target < Min)
1843 return Min;
1844 return Target;
1847 DebouncePolicy DebouncePolicy::fixed(clock::duration T) {
1848 DebouncePolicy P;
1849 P.Min = P.Max = T;
1850 return P;
1853 void TUScheduler::profile(MemoryTree &MT) const {
1854 for (const auto &Elem : fileStats()) {
1855 MT.detail(Elem.first())
1856 .child("preamble")
1857 .addUsage(Opts.StorePreamblesInMemory ? Elem.second.UsedBytesPreamble
1858 : 0);
1859 MT.detail(Elem.first()).child("ast").addUsage(Elem.second.UsedBytesAST);
1860 MT.child("header_includer_cache").addUsage(HeaderIncluders->getUsedBytes());
1863 } // namespace clangd
1864 } // namespace clang