clang-tools  14.0.0git
Background.h
Go to the documentation of this file.
1 //===--- Background.h - Build an index in a background thread ----*- 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 
9 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_BACKGROUND_H
10 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_BACKGROUND_H
11 
13 #include "SourceCode.h"
15 #include "index/FileIndex.h"
16 #include "index/Index.h"
17 #include "index/Serialization.h"
18 #include "support/Context.h"
19 #include "support/MemoryTree.h"
20 #include "support/Path.h"
21 #include "support/Threading.h"
22 #include "support/ThreadsafeFS.h"
23 #include "support/Trace.h"
24 #include "clang/Tooling/CompilationDatabase.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/Support/Threading.h"
27 #include <atomic>
28 #include <condition_variable>
29 #include <deque>
30 #include <mutex>
31 #include <queue>
32 #include <string>
33 #include <thread>
34 #include <vector>
35 
36 namespace clang {
37 namespace clangd {
38 
39 // Handles storage and retrieval of index shards. Both store and load
40 // operations can be called from multiple-threads concurrently.
42 public:
43  virtual ~BackgroundIndexStorage() = default;
44 
45  // Shards of the index are stored and retrieved independently, keyed by shard
46  // identifier - in practice this is a source file name
47  virtual llvm::Error storeShard(llvm::StringRef ShardIdentifier,
48  IndexFileOut Shard) const = 0;
49 
50  // Tries to load shard with given identifier, returns nullptr if shard
51  // couldn't be loaded.
52  virtual std::unique_ptr<IndexFileIn>
53  loadShard(llvm::StringRef ShardIdentifier) const = 0;
54 
55  // The factory provides storage for each File.
56  // It keeps ownership of the storage instances, and should manage caching
57  // itself. Factory must be threadsafe and never returns nullptr.
58  using Factory = llvm::unique_function<BackgroundIndexStorage *(PathRef)>;
59 
60  // Creates an Index Storage that saves shards into disk. Index storage uses
61  // CDBDirectory + ".cache/clangd/index/" as the folder to save shards.
62  // CDBDirectory is the first directory containing a CDB in parent directories
63  // of a file, or user cache directory if none was found, e.g. stdlib headers.
65  std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo);
66 };
67 
68 // A priority queue of tasks which can be run on (external) worker threads.
70 public:
71  /// A work item on the thread pool's queue.
72  struct Task {
73  explicit Task(std::function<void()> Run) : Run(std::move(Run)) {}
74 
75  std::function<void()> Run;
76  llvm::ThreadPriority ThreadPri = llvm::ThreadPriority::Background;
77  unsigned QueuePri = 0; // Higher-priority tasks will run first.
78  std::string Tag; // Allows priority to be boosted later.
79  uint64_t Key = 0; // If the key matches a previous task, drop this one.
80  // (in practice this means we never reindex a file).
81 
82  bool operator<(const Task &O) const { return QueuePri < O.QueuePri; }
83  };
84 
85  // Describes the number of tasks processed by the queue.
86  struct Stats {
87  unsigned Enqueued = 0; // Total number of tasks ever enqueued.
88  unsigned Active = 0; // Tasks being currently processed by a worker.
89  unsigned Completed = 0; // Tasks that have been finished.
90  unsigned LastIdle = 0; // Number of completed tasks when last empty.
91  };
92 
93  BackgroundQueue(std::function<void(Stats)> OnProgress = nullptr)
94  : OnProgress(OnProgress) {}
95 
96  // Add tasks to the queue.
97  void push(Task);
98  void append(std::vector<Task>);
99  // Boost priority of current and new tasks with matching Tag, if they are
100  // lower priority.
101  // Reducing the boost of a tag affects future tasks but not current ones.
102  void boost(llvm::StringRef Tag, unsigned NewPriority);
103 
104  // Process items on the queue until the queue is stopped.
105  // If the queue becomes empty, OnIdle will be called (on one worker).
106  void work(std::function<void()> OnIdle = nullptr);
107 
108  // Stop processing new tasks, allowing all work() calls to return soon.
109  void stop();
110 
111  // Disables thread priority lowering to ensure progress on loaded systems.
112  // Only affects tasks that run after the call.
113  static void preventThreadStarvationInTests();
114  LLVM_NODISCARD bool
115  blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds);
116 
117 private:
118  void notifyProgress() const; // Requires lock Mu
119  bool adjust(Task &T);
120 
121  std::mutex Mu;
122  Stats Stat;
123  std::condition_variable CV;
124  bool ShouldStop = false;
125  std::vector<Task> Queue; // max-heap
126  llvm::StringMap<unsigned> Boosts;
127  std::function<void(Stats)> OnProgress;
128  llvm::DenseSet<uint64_t> SeenKeys;
129 };
130 
131 // Builds an in-memory index by by running the static indexer action over
132 // all commands in a compilation database. Indexing happens in the background.
133 // FIXME: it should watch for changes to files on disk.
134 class BackgroundIndex : public SwapIndex {
135 public:
136  struct Options {
137  // Arbitrary value to ensure some concurrency in tests.
138  // In production an explicit value is specified.
139  size_t ThreadPoolSize = 4;
140  // Callback that provides notifications as indexing makes progress.
141  std::function<void(BackgroundQueue::Stats)> OnProgress = nullptr;
142  // Function called to obtain the Context to use while indexing the specified
143  // file. Called with the empty string for other tasks.
144  // (When called, the context from BackgroundIndex construction is active).
145  std::function<Context(PathRef)> ContextProvider = nullptr;
146  };
147 
148  /// Creates a new background index and starts its threads.
149  /// The current Context will be propagated to each worker thread.
151  BackgroundIndexStorage::Factory IndexStorageFactory,
152  Options Opts);
153  ~BackgroundIndex(); // Blocks while the current task finishes.
154 
155  // Enqueue translation units for indexing.
156  // The indexing happens in a background thread, so the symbols will be
157  // available sometime later.
158  void enqueue(const std::vector<std::string> &ChangedFiles) {
159  Queue.push(changedFilesTask(ChangedFiles));
160  }
161 
162  /// Boosts priority of indexing related to Path.
163  /// Typically used to index TUs when headers are opened.
164  void boostRelated(llvm::StringRef Path);
165 
166  // Cause background threads to stop after ther current task, any remaining
167  // tasks will be discarded.
168  void stop() {
169  Rebuilder.shutdown();
170  Queue.stop();
171  }
172 
173  // Wait until the queue is empty, to allow deterministic testing.
174  LLVM_NODISCARD bool
175  blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds = 10) {
176  return Queue.blockUntilIdleForTest(TimeoutSeconds);
177  }
178 
179  void profile(MemoryTree &MT) const;
180 
181 private:
182  /// Represents the state of a single file when indexing was performed.
183  struct ShardVersion {
184  FileDigest Digest{{0}};
185  bool HadErrors = false;
186  };
187 
188  /// Given index results from a TU, only update symbols coming from files with
189  /// different digests than \p ShardVersionsSnapshot. Also stores new index
190  /// information on IndexStorage.
191  void update(llvm::StringRef MainFile, IndexFileIn Index,
192  const llvm::StringMap<ShardVersion> &ShardVersionsSnapshot,
193  bool HadErrors);
194 
195  // configuration
196  const ThreadsafeFS &TFS;
197  const GlobalCompilationDatabase &CDB;
198  std::function<Context(PathRef)> ContextProvider;
199 
200  llvm::Error index(tooling::CompileCommand);
201 
202  FileSymbols IndexedSymbols;
203  BackgroundIndexRebuilder Rebuilder;
204  llvm::StringMap<ShardVersion> ShardVersions; // Key is absolute file path.
205  std::mutex ShardVersionsMu;
206 
207  BackgroundIndexStorage::Factory IndexStorageFactory;
208  // Tries to load shards for the MainFiles and their dependencies.
209  std::vector<std::string> loadProject(std::vector<std::string> MainFiles);
210 
211  BackgroundQueue::Task
212  changedFilesTask(const std::vector<std::string> &ChangedFiles);
213  BackgroundQueue::Task indexFileTask(std::string Path);
214 
215  // from lowest to highest priority
216  enum QueuePriority {
217  IndexFile,
218  IndexBoostedFile,
219  LoadShards,
220  };
221  BackgroundQueue Queue;
222  AsyncTaskRunner ThreadPool;
223  GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
224 };
225 
226 } // namespace clangd
227 } // namespace clang
228 
229 #endif
clang::clangd::BackgroundQueue
Definition: Background.h:69
clang::clangd::BackgroundQueue::Task
A work item on the thread pool's queue.
Definition: Background.h:72
clang::clangd::BackgroundQueue::Stats
Definition: Background.h:86
clang::clangd::BackgroundIndexStorage::createDiskBackedStorageFactory
static Factory createDiskBackedStorageFactory(std::function< llvm::Optional< ProjectInfo >(PathRef)> GetProjectInfo)
Definition: BackgroundIndexStorage.cpp:146
clang::clangd::BackgroundQueue::Task::Task
Task(std::function< void()> Run)
Definition: Background.h:73
clang::clangd::BackgroundIndexStorage::~BackgroundIndexStorage
virtual ~BackgroundIndexStorage()=default
clang::clangd::BackgroundQueue::Task::Tag
std::string Tag
Definition: Background.h:78
clang::clangd::Path
std::string Path
A typedef to represent a file path.
Definition: Path.h:26
Path.h
clang::clangd::BackgroundQueue::append
void append(std::vector< Task >)
Definition: BackgroundQueue.cpp:101
clang::clangd::BackgroundIndex::Options::ContextProvider
std::function< Context(PathRef)> ContextProvider
Definition: Background.h:145
clang::clangd::BackgroundQueue::push
void push(Task)
Definition: BackgroundQueue.cpp:88
clang::clangd::SwapIndex
Definition: Index.h:161
Index.h
clang::clangd::BackgroundQueue::Task::ThreadPri
llvm::ThreadPriority ThreadPri
Definition: Background.h:76
Trace.h
clang::clangd::BackgroundQueue::work
void work(std::function< void()> OnIdle=nullptr)
Definition: BackgroundQueue.cpp:21
BackgroundRebuild.h
clang::clangd::GlobalCompilationDatabase
Provides compilation arguments used for parsing C and C++ files.
Definition: GlobalCompilationDatabase.h:36
clang::clangd::IndexFileOut
Definition: Serialization.h:55
ThreadsafeFS.h
clang::clangd::BackgroundQueue::Stats::LastIdle
unsigned LastIdle
Definition: Background.h:90
clang::clangd::BackgroundQueue::stop
void stop()
Definition: BackgroundQueue.cpp:67
clang::clangd::BackgroundQueue::Stats::Completed
unsigned Completed
Definition: Background.h:89
clang::clangd::BackgroundIndex::boostRelated
void boostRelated(llvm::StringRef Path)
Boosts priority of indexing related to Path.
Definition: Background.cpp:177
clang::clangd::MemoryTree
A tree that can be used to represent memory usage of nested components while preserving the hierarchy...
Definition: MemoryTree.h:32
GlobalCompilationDatabase.h
clang::clangd::BackgroundQueue::boost
void boost(llvm::StringRef Tag, unsigned NewPriority)
Definition: BackgroundQueue.cpp:116
Threading.h
clang::clangd::BackgroundQueue::preventThreadStarvationInTests
static void preventThreadStarvationInTests()
Definition: BackgroundQueue.cpp:17
clang::clangd::BackgroundIndex::Options::ThreadPoolSize
size_t ThreadPoolSize
Definition: Background.h:139
clang::clangd::BackgroundIndex::blockUntilIdleForTest
LLVM_NODISCARD bool blockUntilIdleForTest(llvm::Optional< double > TimeoutSeconds=10)
Definition: Background.h:175
clang::clangd::BackgroundQueue::blockUntilIdleForTest
LLVM_NODISCARD bool blockUntilIdleForTest(llvm::Optional< double > TimeoutSeconds)
Definition: BackgroundQueue.cpp:135
Serialization.h
clang::clangd::Key
Values in a Context are indexed by typed keys.
Definition: Context.h:40
FileIndex.h
clang::clangd::BackgroundIndexStorage::loadShard
virtual std::unique_ptr< IndexFileIn > loadShard(llvm::StringRef ShardIdentifier) const =0
clang::clangd::BackgroundIndex::Options::OnProgress
std::function< void(BackgroundQueue::Stats)> OnProgress
Definition: Background.h:141
clang::clangd::BackgroundIndex::enqueue
void enqueue(const std::vector< std::string > &ChangedFiles)
Definition: Background.h:158
clang::clangd::BackgroundIndexRebuilder::shutdown
void shutdown()
Definition: BackgroundRebuild.cpp:100
clang::clangd::BackgroundQueue::Stats::Enqueued
unsigned Enqueued
Definition: Background.h:87
clang::clangd::BackgroundIndex::Options
Definition: Background.h:136
SourceCode.h
clang::clangd::BackgroundIndexStorage::Factory
llvm::unique_function< BackgroundIndexStorage *(PathRef)> Factory
Definition: Background.h:58
clang::clangd::BackgroundQueue::BackgroundQueue
BackgroundQueue(std::function< void(Stats)> OnProgress=nullptr)
Definition: Background.h:93
clang::clangd::PathRef
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:29
clang::clangd::ThreadsafeFS
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
Definition: ThreadsafeFS.h:28
clang::clangd::BackgroundIndexStorage::storeShard
virtual llvm::Error storeShard(llvm::StringRef ShardIdentifier, IndexFileOut Shard) const =0
clang::clangd::BackgroundQueue::Stats::Active
unsigned Active
Definition: Background.h:88
clang::clangd::FileDigest
std::array< uint8_t, 8 > FileDigest
Definition: SourceCode.h:41
clang::clangd::BackgroundIndexStorage
Definition: Background.h:41
MemoryTree.h
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::clangd::BackgroundQueue::Task::Run
std::function< void()> Run
Definition: Background.h:75
clang::clangd::BackgroundIndex::BackgroundIndex
BackgroundIndex(const ThreadsafeFS &, const GlobalCompilationDatabase &CDB, BackgroundIndexStorage::Factory IndexStorageFactory, Options Opts)
Creates a new background index and starts its threads.
Definition: Background.cpp:95
clang::clangd::BackgroundQueue::Task::QueuePri
unsigned QueuePri
Definition: Background.h:77
MainFile
std::string MainFile
Definition: HeadersTests.cpp:134
clang::clangd::BackgroundIndex
Definition: Background.h:134
clang::clangd::BackgroundIndex::stop
void stop()
Definition: Background.h:168
Tag
HTMLTag Tag
Definition: HTMLGenerator.cpp:90
clang::clangd::Context
A context is an immutable container for per-request data that must be propagated through layers that ...
Definition: Context.h:69
clang::clangd::BackgroundIndex::profile
void profile(MemoryTree &MT) const
Definition: Background.cpp:422
clang::clangd::BackgroundIndex::~BackgroundIndex
~BackgroundIndex()
Definition: Background.cpp:119
Context.h
clang::clangd::BackgroundQueue::Task::operator<
bool operator<(const Task &O) const
Definition: Background.h:82