Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 1 | //===-- Background.cpp - Build an index in a background thread ------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "index/Background.h" |
| 11 | #include "ClangdUnit.h" |
| 12 | #include "Compiler.h" |
| 13 | #include "Logger.h" |
Kadir Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 14 | #include "SourceCode.h" |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 15 | #include "Threading.h" |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 16 | #include "Trace.h" |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 17 | #include "URI.h" |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 18 | #include "index/IndexAction.h" |
| 19 | #include "index/MemIndex.h" |
| 20 | #include "index/Serialization.h" |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 21 | #include "index/SymbolCollector.h" |
| 22 | #include "clang/Basic/SourceLocation.h" |
| 23 | #include "clang/Basic/SourceManager.h" |
| 24 | #include "llvm/ADT/STLExtras.h" |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/ScopeExit.h" |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 26 | #include "llvm/ADT/StringMap.h" |
| 27 | #include "llvm/ADT/StringRef.h" |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 28 | #include "llvm/Support/SHA1.h" |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 29 | |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame] | 30 | #include <chrono> |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 31 | #include <memory> |
Sam McCall | 7d0e484 | 2018-11-26 13:35:02 +0000 | [diff] [blame] | 32 | #include <numeric> |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 33 | #include <queue> |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 34 | #include <random> |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 35 | #include <string> |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame] | 36 | #include <thread> |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 37 | |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 38 | namespace clang { |
| 39 | namespace clangd { |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 40 | namespace { |
| 41 | // Resolves URI to file paths with cache. |
| 42 | class URIToFileCache { |
| 43 | public: |
| 44 | URIToFileCache(llvm::StringRef HintPath) : HintPath(HintPath) {} |
| 45 | |
| 46 | llvm::StringRef resolve(llvm::StringRef FileURI) { |
| 47 | auto I = URIToPathCache.try_emplace(FileURI); |
| 48 | if (I.second) { |
| 49 | auto U = URI::parse(FileURI); |
| 50 | if (!U) { |
| 51 | elog("Failed to parse URI {0}: {1}", FileURI, U.takeError()); |
| 52 | assert(false && "Failed to parse URI"); |
| 53 | return ""; |
| 54 | } |
| 55 | auto Path = URI::resolve(*U, HintPath); |
| 56 | if (!Path) { |
| 57 | elog("Failed to resolve URI {0}: {1}", FileURI, Path.takeError()); |
| 58 | assert(false && "Failed to resolve URI"); |
| 59 | return ""; |
| 60 | } |
| 61 | I.first->second = *Path; |
| 62 | } |
| 63 | return I.first->second; |
| 64 | } |
| 65 | |
| 66 | private: |
| 67 | std::string HintPath; |
| 68 | llvm::StringMap<std::string> URIToPathCache; |
| 69 | }; |
| 70 | |
| 71 | // We keep only the node "U" and its edges. Any node other than "U" will be |
| 72 | // empty in the resultant graph. |
| 73 | IncludeGraph getSubGraph(const URI &U, const IncludeGraph &FullGraph) { |
| 74 | IncludeGraph IG; |
| 75 | |
| 76 | std::string FileURI = U.toString(); |
| 77 | auto Entry = IG.try_emplace(FileURI).first; |
| 78 | auto &Node = Entry->getValue(); |
| 79 | Node = FullGraph.lookup(Entry->getKey()); |
| 80 | Node.URI = Entry->getKey(); |
| 81 | |
| 82 | // URIs inside nodes must point into the keys of the same IncludeGraph. |
| 83 | for (auto &Include : Node.DirectIncludes) { |
| 84 | auto I = IG.try_emplace(Include).first; |
| 85 | I->getValue().URI = I->getKey(); |
| 86 | Include = I->getKey(); |
| 87 | } |
| 88 | |
| 89 | return IG; |
| 90 | } |
Haojian Wu | 9d0d9f8 | 2018-12-13 13:07:29 +0000 | [diff] [blame] | 91 | |
| 92 | // Creates a filter to not collect index results from files with unchanged |
| 93 | // digests. |
| 94 | // \p FileDigests contains file digests for the current indexed files, and all |
| 95 | // changed files will be added to \p FilesToUpdate. |
| 96 | decltype(SymbolCollector::Options::FileFilter) |
| 97 | createFileFilter(const llvm::StringMap<FileDigest> &FileDigests, |
| 98 | llvm::StringMap<FileDigest> &FilesToUpdate) { |
| 99 | return [&FileDigests, &FilesToUpdate](const SourceManager &SM, FileID FID) { |
Kadir Cetinkaya | dd67793 | 2018-12-19 10:46:21 +0000 | [diff] [blame] | 100 | const auto *F = SM.getFileEntryForID(FID); |
| 101 | if (!F) |
Haojian Wu | 9d0d9f8 | 2018-12-13 13:07:29 +0000 | [diff] [blame] | 102 | return false; // Skip invalid files. |
Kadir Cetinkaya | dd67793 | 2018-12-19 10:46:21 +0000 | [diff] [blame] | 103 | auto AbsPath = getCanonicalPath(F, SM); |
| 104 | if (!AbsPath) |
Haojian Wu | 9d0d9f8 | 2018-12-13 13:07:29 +0000 | [diff] [blame] | 105 | return false; // Skip files without absolute path. |
Haojian Wu | 9d0d9f8 | 2018-12-13 13:07:29 +0000 | [diff] [blame] | 106 | auto Digest = digestFile(SM, FID); |
| 107 | if (!Digest) |
| 108 | return false; |
Kadir Cetinkaya | dd67793 | 2018-12-19 10:46:21 +0000 | [diff] [blame] | 109 | auto D = FileDigests.find(*AbsPath); |
Haojian Wu | 9d0d9f8 | 2018-12-13 13:07:29 +0000 | [diff] [blame] | 110 | if (D != FileDigests.end() && D->second == Digest) |
| 111 | return false; // Skip files that haven't changed. |
| 112 | |
Kadir Cetinkaya | dd67793 | 2018-12-19 10:46:21 +0000 | [diff] [blame] | 113 | FilesToUpdate[*AbsPath] = *Digest; |
Haojian Wu | 9d0d9f8 | 2018-12-13 13:07:29 +0000 | [diff] [blame] | 114 | return true; |
| 115 | }; |
| 116 | } |
| 117 | |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 118 | } // namespace |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 119 | |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 120 | BackgroundIndex::BackgroundIndex( |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 121 | Context BackgroundContext, llvm::StringRef ResourceDir, |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 122 | const FileSystemProvider &FSProvider, const GlobalCompilationDatabase &CDB, |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame] | 123 | BackgroundIndexStorage::Factory IndexStorageFactory, |
| 124 | size_t BuildIndexPeriodMs, size_t ThreadPoolSize) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 125 | : SwapIndex(llvm::make_unique<MemIndex>()), ResourceDir(ResourceDir), |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 126 | FSProvider(FSProvider), CDB(CDB), |
| 127 | BackgroundContext(std::move(BackgroundContext)), |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame] | 128 | BuildIndexPeriodMs(BuildIndexPeriodMs), |
| 129 | SymbolsUpdatedSinceLastIndex(false), |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 130 | IndexStorageFactory(std::move(IndexStorageFactory)), |
| 131 | CommandsChanged( |
| 132 | CDB.watch([&](const std::vector<std::string> &ChangedFiles) { |
| 133 | enqueue(ChangedFiles); |
| 134 | })) { |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 135 | assert(ThreadPoolSize > 0 && "Thread pool size can't be zero."); |
Haojian Wu | 1bf52c5 | 2018-11-16 09:41:14 +0000 | [diff] [blame] | 136 | assert(this->IndexStorageFactory && "Storage factory can not be null!"); |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 137 | while (ThreadPoolSize--) |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 138 | ThreadPool.emplace_back([this] { run(); }); |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame] | 139 | if (BuildIndexPeriodMs > 0) { |
| 140 | log("BackgroundIndex: build symbol index periodically every {0} ms.", |
| 141 | BuildIndexPeriodMs); |
| 142 | ThreadPool.emplace_back([this] { buildIndex(); }); |
| 143 | } |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 144 | } |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 145 | |
| 146 | BackgroundIndex::~BackgroundIndex() { |
| 147 | stop(); |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 148 | for (auto &Thread : ThreadPool) |
| 149 | Thread.join(); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 150 | } |
| 151 | |
| 152 | void BackgroundIndex::stop() { |
| 153 | { |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame] | 154 | std::lock_guard<std::mutex> QueueLock(QueueMu); |
| 155 | std::lock_guard<std::mutex> IndexLock(IndexMu); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 156 | ShouldStop = true; |
| 157 | } |
| 158 | QueueCV.notify_all(); |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame] | 159 | IndexCV.notify_all(); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 160 | } |
| 161 | |
| 162 | void BackgroundIndex::run() { |
Kadir Cetinkaya | 6675be8 | 2018-10-30 12:13:27 +0000 | [diff] [blame] | 163 | WithContext Background(BackgroundContext.clone()); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 164 | while (true) { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 165 | llvm::Optional<Task> Task; |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 166 | ThreadPriority Priority; |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 167 | { |
| 168 | std::unique_lock<std::mutex> Lock(QueueMu); |
| 169 | QueueCV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); }); |
| 170 | if (ShouldStop) { |
| 171 | Queue.clear(); |
| 172 | QueueCV.notify_all(); |
| 173 | return; |
| 174 | } |
| 175 | ++NumActiveTasks; |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 176 | std::tie(Task, Priority) = std::move(Queue.front()); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 177 | Queue.pop_front(); |
| 178 | } |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 179 | |
| 180 | if (Priority != ThreadPriority::Normal) |
| 181 | setCurrentThreadPriority(Priority); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 182 | (*Task)(); |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 183 | if (Priority != ThreadPriority::Normal) |
| 184 | setCurrentThreadPriority(ThreadPriority::Normal); |
| 185 | |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 186 | { |
| 187 | std::unique_lock<std::mutex> Lock(QueueMu); |
| 188 | assert(NumActiveTasks > 0 && "before decrementing"); |
| 189 | --NumActiveTasks; |
| 190 | } |
| 191 | QueueCV.notify_all(); |
| 192 | } |
| 193 | } |
| 194 | |
Sam McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 195 | bool BackgroundIndex::blockUntilIdleForTest( |
| 196 | llvm::Optional<double> TimeoutSeconds) { |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 197 | std::unique_lock<std::mutex> Lock(QueueMu); |
Sam McCall | 422c828 | 2018-11-26 16:00:11 +0000 | [diff] [blame] | 198 | return wait(Lock, QueueCV, timeoutSeconds(TimeoutSeconds), |
| 199 | [&] { return Queue.empty() && NumActiveTasks == 0; }); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 200 | } |
| 201 | |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 202 | void BackgroundIndex::enqueue(const std::vector<std::string> &ChangedFiles) { |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 203 | enqueueTask( |
| 204 | [this, ChangedFiles] { |
| 205 | trace::Span Tracer("BackgroundIndexEnqueue"); |
| 206 | // We're doing this asynchronously, because we'll read shards here too. |
| 207 | // FIXME: read shards here too. |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 208 | |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 209 | log("Enqueueing {0} commands for indexing", ChangedFiles.size()); |
| 210 | SPAN_ATTACH(Tracer, "files", int64_t(ChangedFiles.size())); |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 211 | |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 212 | // We shuffle the files because processing them in a random order should |
| 213 | // quickly give us good coverage of headers in the project. |
| 214 | std::vector<unsigned> Permutation(ChangedFiles.size()); |
| 215 | std::iota(Permutation.begin(), Permutation.end(), 0); |
| 216 | std::mt19937 Generator(std::random_device{}()); |
| 217 | std::shuffle(Permutation.begin(), Permutation.end(), Generator); |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 218 | |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 219 | for (const unsigned I : Permutation) |
| 220 | enqueue(ChangedFiles[I]); |
| 221 | }, |
| 222 | ThreadPriority::Normal); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 223 | } |
| 224 | |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 225 | void BackgroundIndex::enqueue(const std::string &File) { |
| 226 | ProjectInfo Project; |
| 227 | if (auto Cmd = CDB.getCompileCommand(File, &Project)) { |
| 228 | auto *Storage = IndexStorageFactory(Project.SourceRoot); |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 229 | // Set priority to low, since background indexing is a long running |
| 230 | // task we do not want to eat up cpu when there are any other high |
| 231 | // priority threads. |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 232 | enqueueTask(Bind( |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 233 | [this, File, Storage](tooling::CompileCommand Cmd) { |
| 234 | Cmd.CommandLine.push_back("-resource-dir=" + ResourceDir); |
| 235 | if (auto Error = index(std::move(Cmd), Storage)) |
| 236 | log("Indexing {0} failed: {1}", File, std::move(Error)); |
| 237 | }, |
| 238 | std::move(*Cmd)), |
| 239 | ThreadPriority::Low); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 240 | } |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 241 | } |
| 242 | |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 243 | void BackgroundIndex::enqueueTask(Task T, ThreadPriority Priority) { |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 244 | { |
| 245 | std::lock_guard<std::mutex> Lock(QueueMu); |
Kadir Cetinkaya | 375c54f | 2018-12-17 12:30:27 +0000 | [diff] [blame] | 246 | auto I = Queue.end(); |
| 247 | // We first store the tasks with Normal priority in the front of the queue. |
| 248 | // Then we store low priority tasks. Normal priority tasks are pretty rare, |
| 249 | // they should not grow beyond single-digit numbers, so it is OK to do |
| 250 | // linear search and insert after that. |
| 251 | if (Priority == ThreadPriority::Normal) { |
| 252 | I = llvm::find_if(Queue, [](const std::pair<Task, ThreadPriority> &Elem) { |
| 253 | return Elem.second == ThreadPriority::Low; |
| 254 | }); |
| 255 | } |
| 256 | Queue.insert(I, {std::move(T), Priority}); |
Sam McCall | 6e2d2a3 | 2018-11-26 09:51:50 +0000 | [diff] [blame] | 257 | } |
| 258 | QueueCV.notify_all(); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 259 | } |
| 260 | |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 261 | /// Given index results from a TU, only update files in \p FilesToUpdate. |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 262 | void BackgroundIndex::update(llvm::StringRef MainFile, IndexFileIn Index, |
| 263 | const llvm::StringMap<FileDigest> &FilesToUpdate, |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 264 | BackgroundIndexStorage *IndexStorage) { |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 265 | // Partition symbols/references into files. |
| 266 | struct File { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 267 | llvm::DenseSet<const Symbol *> Symbols; |
| 268 | llvm::DenseSet<const Ref *> Refs; |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 269 | }; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 270 | llvm::StringMap<File> Files; |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 271 | URIToFileCache URICache(MainFile); |
Kadir Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 272 | for (const auto &Sym : *Index.Symbols) { |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 273 | if (Sym.CanonicalDeclaration) { |
| 274 | auto DeclPath = URICache.resolve(Sym.CanonicalDeclaration.FileURI); |
| 275 | if (FilesToUpdate.count(DeclPath) != 0) |
| 276 | Files[DeclPath].Symbols.insert(&Sym); |
| 277 | } |
| 278 | // For symbols with different declaration and definition locations, we store |
| 279 | // the full symbol in both the header file and the implementation file, so |
| 280 | // that merging can tell the preferred symbols (from canonical headers) from |
| 281 | // other symbols (e.g. forward declarations). |
| 282 | if (Sym.Definition && |
| 283 | Sym.Definition.FileURI != Sym.CanonicalDeclaration.FileURI) { |
| 284 | auto DefPath = URICache.resolve(Sym.Definition.FileURI); |
| 285 | if (FilesToUpdate.count(DefPath) != 0) |
| 286 | Files[DefPath].Symbols.insert(&Sym); |
| 287 | } |
| 288 | } |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 289 | llvm::DenseMap<const Ref *, SymbolID> RefToIDs; |
Kadir Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 290 | for (const auto &SymRefs : *Index.Refs) { |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 291 | for (const auto &R : SymRefs.second) { |
| 292 | auto Path = URICache.resolve(R.Location.FileURI); |
| 293 | if (FilesToUpdate.count(Path) != 0) { |
| 294 | auto &F = Files[Path]; |
| 295 | RefToIDs[&R] = SymRefs.first; |
| 296 | F.Refs.insert(&R); |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | // Build and store new slabs for each updated file. |
| 302 | for (const auto &F : Files) { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 303 | llvm::StringRef Path = F.first(); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 304 | vlog("Update symbols in {0}", Path); |
| 305 | SymbolSlab::Builder Syms; |
| 306 | RefSlab::Builder Refs; |
| 307 | for (const auto *S : F.second.Symbols) |
| 308 | Syms.insert(*S); |
| 309 | for (const auto *R : F.second.Refs) |
| 310 | Refs.insert(RefToIDs[R], *R); |
| 311 | |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 312 | auto SS = llvm::make_unique<SymbolSlab>(std::move(Syms).build()); |
| 313 | auto RS = llvm::make_unique<RefSlab>(std::move(Refs).build()); |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 314 | auto IG = llvm::make_unique<IncludeGraph>( |
| 315 | getSubGraph(URI::create(Path), Index.Sources.getValue())); |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 316 | |
| 317 | auto Hash = FilesToUpdate.lookup(Path); |
| 318 | // We need to store shards before updating the index, since the latter |
| 319 | // consumes slabs. |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 320 | if (IndexStorage) { |
| 321 | IndexFileOut Shard; |
| 322 | Shard.Symbols = SS.get(); |
| 323 | Shard.Refs = RS.get(); |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 324 | Shard.Sources = IG.get(); |
Kadir Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 325 | |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 326 | if (auto Error = IndexStorage->storeShard(Path, Shard)) |
| 327 | elog("Failed to write background-index shard for file {0}: {1}", Path, |
| 328 | std::move(Error)); |
| 329 | } |
| 330 | |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 331 | std::lock_guard<std::mutex> Lock(DigestsMu); |
| 332 | // This can override a newer version that is added in another thread, |
| 333 | // if this thread sees the older version but finishes later. This should be |
| 334 | // rare in practice. |
Kadir Cetinkaya | 06553bf | 2018-11-16 09:03:56 +0000 | [diff] [blame] | 335 | IndexedFileDigests[Path] = Hash; |
| 336 | IndexedSymbols.update(Path, std::move(SS), std::move(RS)); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 337 | } |
| 338 | } |
| 339 | |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame] | 340 | void BackgroundIndex::buildIndex() { |
| 341 | assert(BuildIndexPeriodMs > 0); |
| 342 | while (true) { |
| 343 | { |
| 344 | std::unique_lock<std::mutex> Lock(IndexMu); |
| 345 | if (ShouldStop) // Avoid waiting if stopped. |
| 346 | break; |
| 347 | // Wait until this is notified to stop or `BuildIndexPeriodMs` has past. |
| 348 | IndexCV.wait_for(Lock, std::chrono::milliseconds(BuildIndexPeriodMs)); |
| 349 | if (ShouldStop) // Avoid rebuilding index if stopped. |
| 350 | break; |
| 351 | } |
| 352 | if (!SymbolsUpdatedSinceLastIndex.exchange(false)) |
| 353 | continue; |
| 354 | // There can be symbol update right after the flag is reset above and before |
| 355 | // index is rebuilt below. The new index would contain the updated symbols |
| 356 | // but the flag would still be true. This is fine as we would simply run an |
| 357 | // extra index build. |
| 358 | reset( |
| 359 | IndexedSymbols.buildIndex(IndexType::Heavy, DuplicateHandling::Merge)); |
| 360 | log("BackgroundIndex: rebuilt symbol index."); |
| 361 | } |
| 362 | } |
| 363 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 364 | llvm::Error BackgroundIndex::index(tooling::CompileCommand Cmd, |
| 365 | BackgroundIndexStorage *IndexStorage) { |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 366 | trace::Span Tracer("BackgroundIndex"); |
| 367 | SPAN_ATTACH(Tracer, "file", Cmd.Filename); |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 368 | llvm::SmallString<128> AbsolutePath; |
| 369 | if (llvm::sys::path::is_absolute(Cmd.Filename)) { |
Kadir Cetinkaya | ed18e78 | 2018-11-15 10:34:39 +0000 | [diff] [blame] | 370 | AbsolutePath = Cmd.Filename; |
| 371 | } else { |
| 372 | AbsolutePath = Cmd.Directory; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 373 | llvm::sys::path::append(AbsolutePath, Cmd.Filename); |
Kadir Cetinkaya | ed18e78 | 2018-11-15 10:34:39 +0000 | [diff] [blame] | 374 | } |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 375 | |
| 376 | auto FS = FSProvider.getFileSystem(); |
| 377 | auto Buf = FS->getBufferForFile(AbsolutePath); |
| 378 | if (!Buf) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 379 | return llvm::errorCodeToError(Buf.getError()); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 380 | auto Hash = digest(Buf->get()->getBuffer()); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 381 | |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 382 | // Take a snapshot of the digests to avoid locking for each file in the TU. |
| 383 | llvm::StringMap<FileDigest> DigestsSnapshot; |
| 384 | { |
| 385 | std::lock_guard<std::mutex> Lock(DigestsMu); |
| 386 | if (IndexedFileDigests.lookup(AbsolutePath) == Hash) { |
| 387 | vlog("No need to index {0}, already up to date", AbsolutePath); |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 388 | return llvm::Error::success(); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 389 | } |
| 390 | |
| 391 | DigestsSnapshot = IndexedFileDigests; |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 392 | } |
| 393 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 394 | log("Indexing {0} (digest:={1})", Cmd.Filename, llvm::toHex(Hash)); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 395 | ParseInputs Inputs; |
| 396 | Inputs.FS = std::move(FS); |
| 397 | Inputs.FS->setCurrentWorkingDirectory(Cmd.Directory); |
| 398 | Inputs.CompileCommand = std::move(Cmd); |
| 399 | auto CI = buildCompilerInvocation(Inputs); |
| 400 | if (!CI) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 401 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 402 | "Couldn't build compiler invocation"); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 403 | IgnoreDiagnostics IgnoreDiags; |
| 404 | auto Clang = prepareCompilerInstance( |
| 405 | std::move(CI), /*Preamble=*/nullptr, std::move(*Buf), |
| 406 | std::make_shared<PCHContainerOperations>(), Inputs.FS, IgnoreDiags); |
| 407 | if (!Clang) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 408 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 409 | "Couldn't build compiler instance"); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 410 | |
| 411 | SymbolCollector::Options IndexOpts; |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 412 | llvm::StringMap<FileDigest> FilesToUpdate; |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 413 | IndexOpts.FileFilter = createFileFilter(DigestsSnapshot, FilesToUpdate); |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 414 | IndexFileIn Index; |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 415 | auto Action = createStaticIndexingAction( |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 416 | IndexOpts, [&](SymbolSlab S) { Index.Symbols = std::move(S); }, |
| 417 | [&](RefSlab R) { Index.Refs = std::move(R); }, |
| 418 | [&](IncludeGraph IG) { Index.Sources = std::move(IG); }); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 419 | |
| 420 | // We're going to run clang here, and it could potentially crash. |
| 421 | // We could use CrashRecoveryContext to try to make indexing crashes nonfatal, |
| 422 | // but the leaky "recovery" is pretty scary too in a long-running process. |
| 423 | // If crashes are a real problem, maybe we should fork a child process. |
| 424 | |
| 425 | const FrontendInputFile &Input = Clang->getFrontendOpts().Inputs.front(); |
| 426 | if (!Action->BeginSourceFile(*Clang, Input)) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 427 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 428 | "BeginSourceFile() failed"); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 429 | if (!Action->Execute()) |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 430 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 431 | "Execute() failed"); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 432 | Action->EndSourceFile(); |
Haojian Wu | d5a78e6 | 2018-12-14 12:39:08 +0000 | [diff] [blame] | 433 | if (Clang->hasDiagnostics() && |
| 434 | Clang->getDiagnostics().hasUncompilableErrorOccurred()) { |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 435 | return llvm::createStringError( |
| 436 | llvm::inconvertibleErrorCode(), |
| 437 | "IndexingAction failed: has uncompilable errors"); |
Haojian Wu | d5a78e6 | 2018-12-14 12:39:08 +0000 | [diff] [blame] | 438 | } |
| 439 | |
| 440 | assert(Index.Symbols && Index.Refs && Index.Sources |
| 441 | && "Symbols, Refs and Sources must be set."); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 442 | |
Kadir Cetinkaya | 219c0fa | 2018-12-04 11:31:57 +0000 | [diff] [blame] | 443 | log("Indexed {0} ({1} symbols, {2} refs, {3} files)", |
| 444 | Inputs.CompileCommand.Filename, Index.Symbols->size(), |
| 445 | Index.Refs->numRefs(), Index.Sources->size()); |
| 446 | SPAN_ATTACH(Tracer, "symbols", int(Index.Symbols->size())); |
| 447 | SPAN_ATTACH(Tracer, "refs", int(Index.Refs->numRefs())); |
| 448 | SPAN_ATTACH(Tracer, "sources", int(Index.Sources->size())); |
Kadir Cetinkaya | d08eab4 | 2018-11-27 16:08:53 +0000 | [diff] [blame] | 449 | |
| 450 | update(AbsolutePath, std::move(Index), FilesToUpdate, IndexStorage); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 451 | { |
| 452 | // Make sure hash for the main file is always updated even if there is no |
| 453 | // index data in it. |
| 454 | std::lock_guard<std::mutex> Lock(DigestsMu); |
| 455 | IndexedFileDigests[AbsolutePath] = Hash; |
| 456 | } |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 457 | |
Eric Liu | 667e8ef | 2018-12-18 15:39:33 +0000 | [diff] [blame] | 458 | if (BuildIndexPeriodMs > 0) |
| 459 | SymbolsUpdatedSinceLastIndex = true; |
| 460 | else |
| 461 | reset( |
| 462 | IndexedSymbols.buildIndex(IndexType::Light, DuplicateHandling::Merge)); |
Eric Liu | ad588af | 2018-11-06 10:55:21 +0000 | [diff] [blame] | 463 | |
Ilya Biryukov | f2001aa | 2019-01-07 15:45:19 +0000 | [diff] [blame] | 464 | return llvm::Error::success(); |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 465 | } |
| 466 | |
Sam McCall | 8dc9dbb | 2018-10-15 13:34:10 +0000 | [diff] [blame] | 467 | } // namespace clangd |
| 468 | } // namespace clang |