blob: 917294499fb83ca02a4ad42bc9c6dd2e4789181b [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdUnit.cpp -----------------------------------------*- C++-*-===//
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 "ClangdUnit.h"
Sam McCall98775c52017-12-04 13:49:59 +000011#include "Compiler.h"
Ilya Biryukov83ca8a22017-09-20 10:46:58 +000012#include "Logger.h"
Sam McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000014#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Frontend/CompilerInvocation.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000016#include "clang/Frontend/FrontendActions.h"
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000017#include "clang/Frontend/Utils.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000018#include "clang/Index/IndexDataConsumer.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000019#include "clang/Index/IndexingAction.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000020#include "clang/Lex/Lexer.h"
21#include "clang/Lex/MacroInfo.h"
22#include "clang/Lex/Preprocessor.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000023#include "clang/Sema/Sema.h"
24#include "clang/Serialization/ASTWriter.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000025#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov04db3682017-07-21 13:29:29 +000026#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Support/CrashRecoveryContext.h"
Krasimir Georgieva1de3c92017-06-15 09:11:57 +000029#include "llvm/Support/Format.h"
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000030#include <algorithm>
Ilya Biryukov02d58702017-08-01 15:51:38 +000031#include <chrono>
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +000032
Ilya Biryukov38d79772017-05-16 09:38:59 +000033using namespace clang::clangd;
34using namespace clang;
35
Ilya Biryukov04db3682017-07-21 13:29:29 +000036namespace {
37
Ilya Biryukovdf842342018-01-25 14:32:21 +000038template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
39 return Vec.capacity() * sizeof(T);
40}
41
Ilya Biryukov04db3682017-07-21 13:29:29 +000042class DeclTrackingASTConsumer : public ASTConsumer {
43public:
44 DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls)
45 : TopLevelDecls(TopLevelDecls) {}
46
47 bool HandleTopLevelDecl(DeclGroupRef DG) override {
48 for (const Decl *D : DG) {
49 // ObjCMethodDecl are not actually top-level decls.
50 if (isa<ObjCMethodDecl>(D))
51 continue;
52
53 TopLevelDecls.push_back(D);
54 }
55 return true;
56 }
57
58private:
59 std::vector<const Decl *> &TopLevelDecls;
60};
61
62class ClangdFrontendAction : public SyntaxOnlyAction {
63public:
64 std::vector<const Decl *> takeTopLevelDecls() {
65 return std::move(TopLevelDecls);
66 }
67
68protected:
69 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
70 StringRef InFile) override {
71 return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
72 }
73
74private:
75 std::vector<const Decl *> TopLevelDecls;
76};
77
Ilya Biryukov02d58702017-08-01 15:51:38 +000078class CppFilePreambleCallbacks : public PreambleCallbacks {
Ilya Biryukov04db3682017-07-21 13:29:29 +000079public:
80 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
81 return std::move(TopLevelDeclIDs);
82 }
83
84 void AfterPCHEmitted(ASTWriter &Writer) override {
85 TopLevelDeclIDs.reserve(TopLevelDecls.size());
86 for (Decl *D : TopLevelDecls) {
87 // Invalid top-level decls may not have been serialized.
88 if (D->isInvalidDecl())
89 continue;
90 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
91 }
92 }
93
94 void HandleTopLevelDecl(DeclGroupRef DG) override {
95 for (Decl *D : DG) {
96 if (isa<ObjCMethodDecl>(D))
97 continue;
98 TopLevelDecls.push_back(D);
99 }
100 }
101
102private:
103 std::vector<Decl *> TopLevelDecls;
104 std::vector<serialization::DeclID> TopLevelDeclIDs;
105};
106
107/// Convert from clang diagnostic level to LSP severity.
108static int getSeverity(DiagnosticsEngine::Level L) {
109 switch (L) {
110 case DiagnosticsEngine::Remark:
111 return 4;
112 case DiagnosticsEngine::Note:
113 return 3;
114 case DiagnosticsEngine::Warning:
115 return 2;
116 case DiagnosticsEngine::Fatal:
117 case DiagnosticsEngine::Error:
118 return 1;
119 case DiagnosticsEngine::Ignored:
120 return 0;
121 }
122 llvm_unreachable("Unknown diagnostic level!");
123}
124
Sam McCall8111d3b2017-12-13 08:48:42 +0000125// Checks whether a location is within a half-open range.
126// Note that clang also uses closed source ranges, which this can't handle!
127bool locationInRange(SourceLocation L, CharSourceRange R,
128 const SourceManager &M) {
129 assert(R.isCharRange());
130 if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
131 M.getFileID(R.getBegin()) != M.getFileID(L))
132 return false;
133 return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
134}
135
136// Converts a half-open clang source range to an LSP range.
137// Note that clang also uses closed source ranges, which this can't handle!
138Range toRange(CharSourceRange R, const SourceManager &M) {
139 // Clang is 1-based, LSP uses 0-based indexes.
140 return {{static_cast<int>(M.getSpellingLineNumber(R.getBegin())) - 1,
141 static_cast<int>(M.getSpellingColumnNumber(R.getBegin())) - 1},
142 {static_cast<int>(M.getSpellingLineNumber(R.getEnd())) - 1,
143 static_cast<int>(M.getSpellingColumnNumber(R.getEnd())) - 1}};
144}
145
146// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
147// LSP needs a single range.
148Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
149 auto &M = D.getSourceManager();
150 auto Loc = M.getFileLoc(D.getLocation());
151 // Accept the first range that contains the location.
152 for (const auto &CR : D.getRanges()) {
153 auto R = Lexer::makeFileCharRange(CR, M, L);
154 if (locationInRange(Loc, R, M))
155 return toRange(R, M);
156 }
157 // The range may be given as a fixit hint instead.
158 for (const auto &F : D.getFixItHints()) {
159 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
160 if (locationInRange(Loc, R, M))
161 return toRange(R, M);
162 }
163 // If no suitable range is found, just use the token at the location.
164 auto R = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Loc), M, L);
165 if (!R.isValid()) // Fall back to location only, let the editor deal with it.
166 R = CharSourceRange::getCharRange(Loc);
167 return toRange(R, M);
168}
169
170TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
171 const LangOptions &L) {
172 TextEdit Result;
173 Result.range = toRange(Lexer::makeFileCharRange(FixIt.RemoveRange, M, L), M);
174 Result.newText = FixIt.CodeToInsert;
175 return Result;
176}
177
178llvm::Optional<DiagWithFixIts> toClangdDiag(const clang::Diagnostic &D,
179 DiagnosticsEngine::Level Level,
180 const LangOptions &LangOpts) {
181 if (!D.hasSourceManager() || !D.getLocation().isValid() ||
182 !D.getSourceManager().isInMainFile(D.getLocation()))
Ilya Biryukov04db3682017-07-21 13:29:29 +0000183 return llvm::None;
184
Sam McCall8111d3b2017-12-13 08:48:42 +0000185 DiagWithFixIts Result;
186 Result.Diag.range = diagnosticRange(D, LangOpts);
187 Result.Diag.severity = getSeverity(Level);
188 SmallString<64> Message;
189 D.FormatDiagnostic(Message);
190 Result.Diag.message = Message.str();
191 for (const FixItHint &Fix : D.getFixItHints())
192 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
193 return std::move(Result);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000194}
195
196class StoreDiagsConsumer : public DiagnosticConsumer {
197public:
198 StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {}
199
Sam McCall8111d3b2017-12-13 08:48:42 +0000200 // Track language options in case we need to expand token ranges.
201 void BeginSourceFile(const LangOptions &Opts, const Preprocessor *) override {
202 LangOpts = Opts;
203 }
204
205 void EndSourceFile() override { LangOpts = llvm::None; }
206
Ilya Biryukov04db3682017-07-21 13:29:29 +0000207 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
208 const clang::Diagnostic &Info) override {
209 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
210
Sam McCall8111d3b2017-12-13 08:48:42 +0000211 if (LangOpts)
212 if (auto D = toClangdDiag(Info, DiagLevel, *LangOpts))
213 Output.push_back(std::move(*D));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000214 }
215
216private:
217 std::vector<DiagWithFixIts> &Output;
Sam McCall8111d3b2017-12-13 08:48:42 +0000218 llvm::Optional<LangOptions> LangOpts;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000219};
220
Ilya Biryukov02d58702017-08-01 15:51:38 +0000221template <class T> bool futureIsReady(std::shared_future<T> const &Future) {
222 return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
223}
224
Ilya Biryukov04db3682017-07-21 13:29:29 +0000225} // namespace
226
Ilya Biryukov02d58702017-08-01 15:51:38 +0000227void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
228 AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000229}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000230
Ilya Biryukov02d58702017-08-01 15:51:38 +0000231llvm::Optional<ParsedAST>
Sam McCalld1a7a372018-01-31 13:40:48 +0000232ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI,
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000233 std::shared_ptr<const PreambleData> Preamble,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000234 std::unique_ptr<llvm::MemoryBuffer> Buffer,
235 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000236 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000237
238 std::vector<DiagWithFixIts> ASTDiags;
239 StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags);
240
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000241 const PrecompiledPreamble *PreamblePCH =
242 Preamble ? &Preamble->Preamble : nullptr;
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000243 auto Clang = prepareCompilerInstance(
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000244 std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs),
Benjamin Kramer5349eed2017-10-28 17:32:56 +0000245 std::move(VFS), /*ref*/ UnitDiagsConsumer);
Ilya Biryukovcec63352018-01-29 14:30:28 +0000246 if (!Clang)
247 return llvm::None;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000248
249 // Recover resources if we crash before exiting this method.
250 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
251 Clang.get());
252
253 auto Action = llvm::make_unique<ClangdFrontendAction>();
Ilya Biryukove5128f72017-09-20 07:24:15 +0000254 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
255 if (!Action->BeginSourceFile(*Clang, MainInput)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000256 log("BeginSourceFile() failed when building AST for " +
257 MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000258 return llvm::None;
259 }
Ilya Biryukove5128f72017-09-20 07:24:15 +0000260 if (!Action->Execute())
Sam McCalld1a7a372018-01-31 13:40:48 +0000261 log("Execute() failed when building AST for " + MainInput.getFile());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000262
263 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
264 // has a longer lifetime.
Sam McCall98775c52017-12-04 13:49:59 +0000265 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
Ilya Biryukov04db3682017-07-21 13:29:29 +0000266
267 std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000268 return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action),
269 std::move(ParsedDecls), std::move(ASTDiags));
Ilya Biryukov04db3682017-07-21 13:29:29 +0000270}
271
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000272namespace {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000273
274SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr,
Ilya Biryukov04db3682017-07-21 13:29:29 +0000275 const FileEntry *FE, Position Pos) {
276 SourceLocation InputLoc =
277 Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1);
278 return Mgr.getMacroArgExpandedLocation(InputLoc);
279}
280
Ilya Biryukov02d58702017-08-01 15:51:38 +0000281} // namespace
Ilya Biryukov04db3682017-07-21 13:29:29 +0000282
Ilya Biryukov02d58702017-08-01 15:51:38 +0000283void ParsedAST::ensurePreambleDeclsDeserialized() {
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000284 if (PreambleDeclsDeserialized || !Preamble)
Ilya Biryukov04db3682017-07-21 13:29:29 +0000285 return;
286
287 std::vector<const Decl *> Resolved;
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000288 Resolved.reserve(Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000289
290 ExternalASTSource &Source = *getASTContext().getExternalSource();
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000291 for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000292 // Resolve the declaration ID to an actual declaration, possibly
293 // deserializing the declaration in the process.
294 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
295 Resolved.push_back(D);
296 }
297
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000298 TopLevelDecls.reserve(TopLevelDecls.size() +
299 Preamble->TopLevelDeclIDs.size());
Ilya Biryukov04db3682017-07-21 13:29:29 +0000300 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
301
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000302 PreambleDeclsDeserialized = true;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000303}
304
Ilya Biryukov02d58702017-08-01 15:51:38 +0000305ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000306
Ilya Biryukov02d58702017-08-01 15:51:38 +0000307ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
Ilya Biryukov04db3682017-07-21 13:29:29 +0000308
Ilya Biryukov02d58702017-08-01 15:51:38 +0000309ParsedAST::~ParsedAST() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000310 if (Action) {
311 Action->EndSourceFile();
312 }
313}
314
Ilya Biryukov02d58702017-08-01 15:51:38 +0000315ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
316
317const ASTContext &ParsedAST::getASTContext() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000318 return Clang->getASTContext();
319}
320
Ilya Biryukov02d58702017-08-01 15:51:38 +0000321Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
Ilya Biryukov04db3682017-07-21 13:29:29 +0000322
Eric Liu76f6b442018-01-09 17:32:00 +0000323std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
324 return Clang->getPreprocessorPtr();
325}
326
Ilya Biryukov02d58702017-08-01 15:51:38 +0000327const Preprocessor &ParsedAST::getPreprocessor() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000328 return Clang->getPreprocessor();
329}
330
Ilya Biryukov02d58702017-08-01 15:51:38 +0000331ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000332 ensurePreambleDeclsDeserialized();
333 return TopLevelDecls;
334}
335
Ilya Biryukov02d58702017-08-01 15:51:38 +0000336const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000337 return Diags;
338}
339
Ilya Biryukovdf842342018-01-25 14:32:21 +0000340std::size_t ParsedAST::getUsedBytes() const {
341 auto &AST = getASTContext();
342 // FIXME(ibiryukov): we do not account for the dynamically allocated part of
343 // SmallVector<FixIt> inside each Diag.
344 return AST.getASTAllocatedMemory() + AST.getSideTableAllocatedMemory() +
345 ::getUsedBytes(TopLevelDecls) + ::getUsedBytes(Diags);
346}
347
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000348PreambleData::PreambleData(PrecompiledPreamble Preamble,
349 std::vector<serialization::DeclID> TopLevelDeclIDs,
350 std::vector<DiagWithFixIts> Diags)
351 : Preamble(std::move(Preamble)),
352 TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {}
353
354ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble,
355 std::unique_ptr<CompilerInstance> Clang,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000356 std::unique_ptr<FrontendAction> Action,
357 std::vector<const Decl *> TopLevelDecls,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000358 std::vector<DiagWithFixIts> Diags)
Ilya Biryukov2660cc92017-11-24 13:04:21 +0000359 : Preamble(std::move(Preamble)), Clang(std::move(Clang)),
360 Action(std::move(Action)), Diags(std::move(Diags)),
361 TopLevelDecls(std::move(TopLevelDecls)),
362 PreambleDeclsDeserialized(false) {
Ilya Biryukov04db3682017-07-21 13:29:29 +0000363 assert(this->Clang);
364 assert(this->Action);
365}
366
Ilya Biryukov02d58702017-08-01 15:51:38 +0000367ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper)
368 : AST(std::move(Wrapper.AST)) {}
369
370ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST)
371 : AST(std::move(AST)) {}
372
Ilya Biryukov02d58702017-08-01 15:51:38 +0000373std::shared_ptr<CppFile>
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000374CppFile::Create(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000375 std::shared_ptr<PCHContainerOperations> PCHs,
376 ASTParsedCallback ASTCallback) {
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000377 return std::shared_ptr<CppFile>(new CppFile(FileName, StorePreamblesInMemory,
378 std::move(PCHs),
379 std::move(ASTCallback)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000380}
381
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000382CppFile::CppFile(PathRef FileName, bool StorePreamblesInMemory,
Eric Liubfac8f72017-12-19 18:00:37 +0000383 std::shared_ptr<PCHContainerOperations> PCHs,
384 ASTParsedCallback ASTCallback)
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000385 : FileName(FileName), StorePreamblesInMemory(StorePreamblesInMemory),
Ilya Biryukovdf842342018-01-25 14:32:21 +0000386 RebuildCounter(0), RebuildInProgress(false), ASTMemUsage(0),
387 PreambleMemUsage(0), PCHs(std::move(PCHs)),
Eric Liubfac8f72017-12-19 18:00:37 +0000388 ASTCallback(std::move(ASTCallback)) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000389 log("Created CppFile for " + FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000390
391 std::lock_guard<std::mutex> Lock(Mutex);
392 LatestAvailablePreamble = nullptr;
393 PreamblePromise.set_value(nullptr);
394 PreambleFuture = PreamblePromise.get_future();
395
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000396 ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000397 ASTFuture = ASTPromise.get_future();
398}
399
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000400void CppFile::cancelRebuild() { deferCancelRebuild()(); }
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000401
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000402UniqueFunction<void()> CppFile::deferCancelRebuild() {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000403 std::unique_lock<std::mutex> Lock(Mutex);
404 // Cancel an ongoing rebuild, if any, and wait for it to finish.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000405 unsigned RequestRebuildCounter = ++this->RebuildCounter;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000406 // Rebuild asserts that futures aren't ready if rebuild is cancelled.
407 // We want to keep this invariant.
408 if (futureIsReady(PreambleFuture)) {
409 PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>();
410 PreambleFuture = PreamblePromise.get_future();
411 }
412 if (futureIsReady(ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000413 ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000414 ASTFuture = ASTPromise.get_future();
415 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000416
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000417 Lock.unlock();
418 // Notify about changes to RebuildCounter.
419 RebuildCond.notify_all();
420
421 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000422 return [That, RequestRebuildCounter]() {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000423 std::unique_lock<std::mutex> Lock(That->Mutex);
424 CppFile *This = &*That;
425 This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() {
426 return !This->RebuildInProgress ||
427 This->RebuildCounter != RequestRebuildCounter;
428 });
429
430 // This computation got cancelled itself, do nothing.
431 if (This->RebuildCounter != RequestRebuildCounter)
432 return;
433
434 // Set empty results for Promises.
Ilya Biryukovdf842342018-01-25 14:32:21 +0000435 That->PreambleMemUsage = 0;
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000436 That->PreamblePromise.set_value(nullptr);
Ilya Biryukovdf842342018-01-25 14:32:21 +0000437 That->ASTMemUsage = 0;
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000438 That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None));
Ilya Biryukov98a1fd72017-10-10 16:12:54 +0000439 };
Ilya Biryukov02d58702017-08-01 15:51:38 +0000440}
441
442llvm::Optional<std::vector<DiagWithFixIts>>
Sam McCalld1a7a372018-01-31 13:40:48 +0000443CppFile::rebuild(ParseInputs &&Inputs) {
444 return deferRebuild(std::move(Inputs))();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000445}
446
Sam McCalld1a7a372018-01-31 13:40:48 +0000447UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()>
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000448CppFile::deferRebuild(ParseInputs &&Inputs) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000449 std::shared_ptr<const PreambleData> OldPreamble;
450 std::shared_ptr<PCHContainerOperations> PCHs;
451 unsigned RequestRebuildCounter;
452 {
453 std::unique_lock<std::mutex> Lock(Mutex);
454 // Increase RebuildCounter to cancel all ongoing FinishRebuild operations.
455 // They will try to exit as early as possible and won't call set_value on
456 // our promises.
457 RequestRebuildCounter = ++this->RebuildCounter;
458 PCHs = this->PCHs;
459
460 // Remember the preamble to be used during rebuild.
461 OldPreamble = this->LatestAvailablePreamble;
462 // Setup std::promises and std::futures for Preamble and AST. Corresponding
463 // futures will wait until the rebuild process is finished.
464 if (futureIsReady(this->PreambleFuture)) {
465 this->PreamblePromise =
466 std::promise<std::shared_ptr<const PreambleData>>();
467 this->PreambleFuture = this->PreamblePromise.get_future();
468 }
469 if (futureIsReady(this->ASTFuture)) {
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000470 this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000471 this->ASTFuture = this->ASTPromise.get_future();
472 }
473 } // unlock Mutex.
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000474 // Notify about changes to RebuildCounter.
475 RebuildCond.notify_all();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000476
477 // A helper to function to finish the rebuild. May be run on a different
478 // thread.
479
480 // Don't let this CppFile die before rebuild is finished.
481 std::shared_ptr<CppFile> That = shared_from_this();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000482 auto FinishRebuild =
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000483 [OldPreamble, RequestRebuildCounter, PCHs,
Sam McCalld1a7a372018-01-31 13:40:48 +0000484 That](ParseInputs Inputs) mutable /* to allow changing OldPreamble. */
Ilya Biryukov02d58702017-08-01 15:51:38 +0000485 -> llvm::Optional<std::vector<DiagWithFixIts>> {
Sam McCalld1a7a372018-01-31 13:40:48 +0000486 log("Rebuilding file " + That->FileName + " with command [" +
487 Inputs.CompileCommand.Directory + "] " +
488 llvm::join(Inputs.CompileCommand.CommandLine, " "));
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000489
Ilya Biryukov02d58702017-08-01 15:51:38 +0000490 // Only one execution of this method is possible at a time.
491 // RebuildGuard will wait for any ongoing rebuilds to finish and will put us
492 // into a state for doing a rebuild.
493 RebuildGuard Rebuild(*That, RequestRebuildCounter);
494 if (Rebuild.wasCancelledBeforeConstruction())
495 return llvm::None;
496
497 std::vector<const char *> ArgStrs;
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000498 for (const auto &S : Inputs.CompileCommand.CommandLine)
Ilya Biryukov02d58702017-08-01 15:51:38 +0000499 ArgStrs.push_back(S.c_str());
500
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000501 Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000502
503 std::unique_ptr<CompilerInvocation> CI;
504 {
505 // FIXME(ibiryukov): store diagnostics from CommandLine when we start
506 // reporting them.
Sam McCall98775c52017-12-04 13:49:59 +0000507 IgnoreDiagnostics IgnoreDiagnostics;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000508 IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
509 CompilerInstance::createDiagnostics(new DiagnosticOptions,
Sam McCall98775c52017-12-04 13:49:59 +0000510 &IgnoreDiagnostics, false);
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000511 CI = createInvocationFromCommandLine(ArgStrs, CommandLineDiagsEngine,
512 Inputs.FS);
Sam McCall98775c52017-12-04 13:49:59 +0000513 // createInvocationFromCommandLine sets DisableFree.
514 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000515 }
516 assert(CI && "Couldn't create CompilerInvocation");
517
518 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000519 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000520
521 // A helper function to rebuild the preamble or reuse the existing one. Does
Ilya Biryukov11a02522017-11-17 19:05:56 +0000522 // not mutate any fields of CppFile, only does the actual computation.
523 // Lamdba is marked mutable to call reset() on OldPreamble.
524 auto DoRebuildPreamble =
525 [&]() mutable -> std::shared_ptr<const PreambleData> {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000526 auto Bounds =
527 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000528 if (OldPreamble &&
529 OldPreamble->Preamble.CanReuse(*CI, ContentsBuffer.get(), Bounds,
530 Inputs.FS.get())) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000531 log("Reusing preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000532 return OldPreamble;
533 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000534 log("Premble for file " + Twine(That->FileName) +
535 " cannot be reused. Attempting to rebuild it.");
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000536 // We won't need the OldPreamble anymore, release it so it can be
537 // deleted (if there are no other references to it).
Ilya Biryukov11a02522017-11-17 19:05:56 +0000538 OldPreamble.reset();
Ilya Biryukov02d58702017-08-01 15:51:38 +0000539
Sam McCalld1a7a372018-01-31 13:40:48 +0000540 trace::Span Tracer("Preamble");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000541 SPAN_ATTACH(Tracer, "File", That->FileName);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000542 std::vector<DiagWithFixIts> PreambleDiags;
543 StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags);
544 IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
545 CompilerInstance::createDiagnostics(
546 &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false);
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000547
548 // Skip function bodies when building the preamble to speed up building
549 // the preamble and make it smaller.
550 assert(!CI->getFrontendOpts().SkipFunctionBodies);
551 CI->getFrontendOpts().SkipFunctionBodies = true;
552
Ilya Biryukov02d58702017-08-01 15:51:38 +0000553 CppFilePreambleCallbacks SerializedDeclsCollector;
554 auto BuiltPreamble = PrecompiledPreamble::Build(
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000555 *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, Inputs.FS,
556 PCHs,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000557 /*StoreInMemory=*/That->StorePreamblesInMemory,
Ilya Biryukov02d58702017-08-01 15:51:38 +0000558 SerializedDeclsCollector);
559
Ilya Biryukovda8daa32017-12-28 13:10:15 +0000560 // When building the AST for the main file, we do want the function
561 // bodies.
562 CI->getFrontendOpts().SkipFunctionBodies = false;
563
Ilya Biryukov02d58702017-08-01 15:51:38 +0000564 if (BuiltPreamble) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000565 log("Built preamble of size " + Twine(BuiltPreamble->getSize()) +
566 " for file " + Twine(That->FileName));
Ilya Biryukoveaeea042017-12-21 14:05:28 +0000567
Ilya Biryukov02d58702017-08-01 15:51:38 +0000568 return std::make_shared<PreambleData>(
569 std::move(*BuiltPreamble),
570 SerializedDeclsCollector.takeTopLevelDeclIDs(),
571 std::move(PreambleDiags));
572 } else {
Sam McCalld1a7a372018-01-31 13:40:48 +0000573 log("Could not build a preamble for file " + Twine(That->FileName));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000574 return nullptr;
575 }
576 };
577
578 // Compute updated Preamble.
579 std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble();
580 // Publish the new Preamble.
581 {
582 std::lock_guard<std::mutex> Lock(That->Mutex);
583 // We always set LatestAvailablePreamble to the new value, hoping that it
584 // will still be usable in the further requests.
585 That->LatestAvailablePreamble = NewPreamble;
586 if (RequestRebuildCounter != That->RebuildCounter)
587 return llvm::None; // Our rebuild request was cancelled, do nothing.
Ilya Biryukovdf842342018-01-25 14:32:21 +0000588 That->PreambleMemUsage =
589 NewPreamble ? NewPreamble->Preamble.getSize() : 0;
Ilya Biryukov02d58702017-08-01 15:51:38 +0000590 That->PreamblePromise.set_value(NewPreamble);
591 } // unlock Mutex
592
593 // Prepare the Preamble and supplementary data for rebuilding AST.
Ilya Biryukov02d58702017-08-01 15:51:38 +0000594 std::vector<DiagWithFixIts> Diagnostics;
595 if (NewPreamble) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000596 Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(),
597 NewPreamble->Diags.end());
598 }
599
600 // Compute updated AST.
Sam McCall8567cb32017-11-02 09:21:51 +0000601 llvm::Optional<ParsedAST> NewAST;
602 {
Sam McCalld1a7a372018-01-31 13:40:48 +0000603 trace::Span Tracer("Build");
Sam McCall9cfd9c92017-11-23 17:12:04 +0000604 SPAN_ATTACH(Tracer, "File", That->FileName);
Sam McCalld1a7a372018-01-31 13:40:48 +0000605 NewAST = ParsedAST::Build(std::move(CI), std::move(NewPreamble),
606 std::move(ContentsBuffer), PCHs, Inputs.FS);
Sam McCall8567cb32017-11-02 09:21:51 +0000607 }
Ilya Biryukov02d58702017-08-01 15:51:38 +0000608
609 if (NewAST) {
610 Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(),
611 NewAST->getDiagnostics().end());
Eric Liubfac8f72017-12-19 18:00:37 +0000612 if (That->ASTCallback)
Sam McCalld1a7a372018-01-31 13:40:48 +0000613 That->ASTCallback(That->FileName, NewAST.getPointer());
Ilya Biryukov02d58702017-08-01 15:51:38 +0000614 } else {
615 // Don't report even Preamble diagnostics if we coulnd't build AST.
616 Diagnostics.clear();
617 }
618
619 // Publish the new AST.
620 {
621 std::lock_guard<std::mutex> Lock(That->Mutex);
622 if (RequestRebuildCounter != That->RebuildCounter)
623 return Diagnostics; // Our rebuild request was cancelled, don't set
624 // ASTPromise.
625
Ilya Biryukovdf842342018-01-25 14:32:21 +0000626 That->ASTMemUsage = NewAST ? NewAST->getUsedBytes() : 0;
Ilya Biryukov574b7532017-08-02 09:08:39 +0000627 That->ASTPromise.set_value(
628 std::make_shared<ParsedASTWrapper>(std::move(NewAST)));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000629 } // unlock Mutex
630
631 return Diagnostics;
632 };
633
Ilya Biryukov82b59ae2018-01-23 15:07:52 +0000634 return BindWithForward(FinishRebuild, std::move(Inputs));
Ilya Biryukov02d58702017-08-01 15:51:38 +0000635}
636
637std::shared_future<std::shared_ptr<const PreambleData>>
638CppFile::getPreamble() const {
639 std::lock_guard<std::mutex> Lock(Mutex);
640 return PreambleFuture;
641}
642
643std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const {
644 std::lock_guard<std::mutex> Lock(Mutex);
645 return LatestAvailablePreamble;
646}
647
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000648std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000649 std::lock_guard<std::mutex> Lock(Mutex);
650 return ASTFuture;
651}
652
Ilya Biryukovdf842342018-01-25 14:32:21 +0000653std::size_t CppFile::getUsedBytes() const {
654 std::lock_guard<std::mutex> Lock(Mutex);
655 // FIXME: We should not store extra size fields. When we store AST and
656 // Preamble directly, not inside futures, we could compute the sizes from the
657 // stored AST and the preamble in this function directly.
658 return ASTMemUsage + PreambleMemUsage;
659}
660
Ilya Biryukov02d58702017-08-01 15:51:38 +0000661CppFile::RebuildGuard::RebuildGuard(CppFile &File,
662 unsigned RequestRebuildCounter)
663 : File(File), RequestRebuildCounter(RequestRebuildCounter) {
664 std::unique_lock<std::mutex> Lock(File.Mutex);
665 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
666 if (WasCancelledBeforeConstruction)
667 return;
668
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000669 File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() {
670 return !File.RebuildInProgress ||
671 File.RebuildCounter != RequestRebuildCounter;
672 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000673
674 WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter;
675 if (WasCancelledBeforeConstruction)
676 return;
677
678 File.RebuildInProgress = true;
679}
680
681bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const {
682 return WasCancelledBeforeConstruction;
683}
684
685CppFile::RebuildGuard::~RebuildGuard() {
686 if (WasCancelledBeforeConstruction)
687 return;
688
689 std::unique_lock<std::mutex> Lock(File.Mutex);
690 assert(File.RebuildInProgress);
691 File.RebuildInProgress = false;
692
693 if (File.RebuildCounter == RequestRebuildCounter) {
694 // Our rebuild request was successful.
695 assert(futureIsReady(File.ASTFuture));
696 assert(futureIsReady(File.PreambleFuture));
697 } else {
698 // Our rebuild request was cancelled, because further reparse was requested.
699 assert(!futureIsReady(File.ASTFuture));
700 assert(!futureIsReady(File.PreambleFuture));
701 }
702
703 Lock.unlock();
704 File.RebuildCond.notify_all();
705}
Haojian Wu345099c2017-11-09 11:30:04 +0000706
707SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit,
708 const Position &Pos,
709 const FileEntry *FE) {
710 // The language server protocol uses zero-based line and column numbers.
711 // Clang uses one-based numbers.
712
713 const ASTContext &AST = Unit.getASTContext();
714 const SourceManager &SourceMgr = AST.getSourceManager();
715
716 SourceLocation InputLocation =
717 getMacroArgExpandedLocation(SourceMgr, FE, Pos);
718 if (Pos.character == 0) {
719 return InputLocation;
720 }
721
722 // This handle cases where the position is in the middle of a token or right
723 // after the end of a token. In theory we could just use GetBeginningOfToken
724 // to find the start of the token at the input position, but this doesn't
725 // work when right after the end, i.e. foo|.
726 // So try to go back by one and see if we're still inside the an identifier
727 // token. If so, Take the beginning of this token.
728 // (It should be the same identifier because you can't have two adjacent
729 // identifiers without another token in between.)
730 SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation(
731 SourceMgr, FE, Position{Pos.line, Pos.character - 1});
732 Token Result;
733 if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr,
734 AST.getLangOpts(), false)) {
735 // getRawToken failed, just use InputLocation.
736 return InputLocation;
737 }
738
739 if (Result.is(tok::raw_identifier)) {
740 return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr,
741 AST.getLangOpts());
742 }
743
744 return InputLocation;
745}