Repository navigation
[clangd] Introduce --skip-preamble-build command line option - #189284
Conversation
This option allows to disable preamble optimization in clangd. By default it's false, but became true if experimental modules support is enabled.
|
@llvm/pr-subscribers-clang-tools-extra @llvm/pr-subscribers-clangd Author: Aleksandr Platonov (ArcsinX) ChangesThis option allows to disable preamble optimization in clangd. By default it's false, but became true if experimental modules support is enabled. This PR is a try to address C++20 modules problems described here #187432 Set to WIP because no tests were added yet. 8 Files Affected:
diff --git a/clang-tools-extra/clangd/ClangdServer.cpp b/clang-tools-extra/clangd/ClangdServer.cpp
index f1a87dd12d905..af80cc9c3e453 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -223,6 +223,7 @@ ClangdServer::ClangdServer(const GlobalCompilationDatabase &CDB,
UseDirtyHeaders(Opts.UseDirtyHeaders),
LineFoldingOnly(Opts.LineFoldingOnly),
PreambleParseForwardingFunctions(Opts.PreambleParseForwardingFunctions),
+ SkipPreambleBuild(Opts.SkipPreambleBuild),
ImportInsertions(Opts.ImportInsertions),
PublishInactiveRegions(Opts.PublishInactiveRegions),
WorkspaceRoot(Opts.WorkspaceRoot),
@@ -300,6 +301,7 @@ void ClangdServer::addDocument(PathRef File, llvm::StringRef Contents,
std::string ActualVersion = DraftMgr.addDraft(File, Version, Contents);
ParseOptions Opts;
Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions;
+ Opts.SkipPreambleBuild = SkipPreambleBuild;
Opts.ImportInsertions = ImportInsertions;
// Compile command is set asynchronously during update, as it can be slow.
@@ -459,6 +461,7 @@ void ClangdServer::codeComplete(PathRef File, Position Pos,
Config::current().Completion.HeaderInsertion;
CodeCompleteOpts.CodePatterns = Config::current().Completion.CodePatterns;
CodeCompleteOpts.MacroFilter = Config::current().Completion.MacroFilter;
+ ParseInput.Opts.SkipPreambleBuild = SkipPreambleBuild;
// FIXME(ibiryukov): even if Preamble is non-null, we may want to check
// both the old and the new version in case only one of them matches.
CodeCompleteResult Result = clangd::codeComplete(
diff --git a/clang-tools-extra/clangd/ClangdServer.h b/clang-tools-extra/clangd/ClangdServer.h
index 3ffaf67553dce..6ee1dfd863e3c 100644
--- a/clang-tools-extra/clangd/ClangdServer.h
+++ b/clang-tools-extra/clangd/ClangdServer.h
@@ -191,6 +191,9 @@ class ClangdServer {
// If true, parse emplace-like functions in the preamble.
bool PreambleParseForwardingFunctions = true;
+ // If true, skip preamble build.
+ bool SkipPreambleBuild = false;
+
/// Whether include fixer insertions for Objective-C code should use #import
/// instead of #include.
bool ImportInsertions = false;
@@ -508,6 +511,8 @@ class ClangdServer {
bool PreambleParseForwardingFunctions = true;
+ bool SkipPreambleBuild = false;
+
bool ImportInsertions = false;
bool PublishInactiveRegions = false;
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp
index 28f81cd5267d5..8414ffe20526a 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -1420,7 +1420,8 @@ bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
// overriding the preamble will break sema completion. Fortunately we can just
// skip all includes in this case; these completions are really simple.
PreambleBounds PreambleRegion =
- ComputePreambleBounds(CI->getLangOpts(), *ContentsBuffer, 0);
+ computePreambleBounds(CI->getLangOpts(), *ContentsBuffer,
+ Input.ParseInput.Opts.SkipPreambleBuild);
bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
(!PreambleRegion.PreambleEndsAtStartOfLine &&
Input.Offset == PreambleRegion.Size);
@@ -1433,7 +1434,10 @@ bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
if (Input.Preamble.StatCache)
VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
auto Clang = prepareCompilerInstance(
- std::move(CI), !CompletingInPreamble ? &Input.Preamble.Preamble : nullptr,
+ std::move(CI),
+ (!CompletingInPreamble && !Input.ParseInput.Opts.SkipPreambleBuild)
+ ? &Input.Preamble.Preamble
+ : nullptr,
std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
Clang->setCodeCompletionConsumer(Consumer.release());
diff --git a/clang-tools-extra/clangd/Compiler.h b/clang-tools-extra/clangd/Compiler.h
index e513e4c40794a..5e5e23d5b9682 100644
--- a/clang-tools-extra/clangd/Compiler.h
+++ b/clang-tools-extra/clangd/Compiler.h
@@ -43,6 +43,8 @@ struct ParseOptions {
bool PreambleParseForwardingFunctions = true;
bool ImportInsertions = false;
+
+ bool SkipPreambleBuild = false;
};
/// Information required to run clang, e.g. to parse AST or do code completion.
diff --git a/clang-tools-extra/clangd/ParsedAST.cpp b/clang-tools-extra/clangd/ParsedAST.cpp
index 4e873f1257a17..e2a49f384a3e9 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -464,7 +464,7 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
Patch->apply(*CI);
}
auto Clang = prepareCompilerInstance(
- std::move(CI), PreamblePCH,
+ std::move(CI), Inputs.Opts.SkipPreambleBuild ? nullptr : PreamblePCH,
llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, Filename), VFS,
*DiagConsumer);
diff --git a/clang-tools-extra/clangd/Preamble.cpp b/clang-tools-extra/clangd/Preamble.cpp
index f5e512793e98e..58da7edcf3b93 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -320,8 +320,9 @@ struct ScannedPreamble {
/// running preprocessor over \p Contents. Returned includes do not contain
/// resolved paths. \p Cmd is used to build the compiler invocation, which might
/// stat/read files.
-llvm::Expected<ScannedPreamble>
-scanPreamble(llvm::StringRef Contents, const tooling::CompileCommand &Cmd) {
+llvm::Expected<ScannedPreamble> scanPreamble(llvm::StringRef Contents,
+ const tooling::CompileCommand &Cmd,
+ bool SkipPreambleBuild) {
class EmptyFS : public ThreadsafeFS {
private:
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> viewImpl() const override {
@@ -345,7 +346,8 @@ scanPreamble(llvm::StringRef Contents, const tooling::CompileCommand &Cmd) {
// This means we're scanning (though not preprocessing) the preamble section
// twice. However, it's important to precisely follow the preamble bounds used
// elsewhere.
- auto Bounds = ComputePreambleBounds(CI->getLangOpts(), *ContentsBuffer, 0);
+ auto Bounds = computePreambleBounds(CI->getLangOpts(), *ContentsBuffer,
+ SkipPreambleBuild);
auto PreambleContents = llvm::MemoryBuffer::getMemBufferCopy(
llvm::StringRef(PI.Contents).take_front(Bounds.Size));
auto Clang = prepareCompilerInstance(
@@ -576,7 +578,8 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
// without those.
auto ContentsBuffer =
llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
- auto Bounds = ComputePreambleBounds(CI.getLangOpts(), *ContentsBuffer, 0);
+ auto Bounds = computePreambleBounds(CI.getLangOpts(), *ContentsBuffer,
+ Inputs.Opts.SkipPreambleBuild);
trace::Span Tracer("BuildPreamble");
SPAN_ATTACH(Tracer, "File", FileName);
@@ -722,7 +725,8 @@ bool isPreambleCompatible(const PreambleData &Preamble,
const CompilerInvocation &CI) {
auto ContentsBuffer =
llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
- auto Bounds = ComputePreambleBounds(CI.getLangOpts(), *ContentsBuffer, 0);
+ auto Bounds = computePreambleBounds(CI.getLangOpts(), *ContentsBuffer,
+ Inputs.Opts.SkipPreambleBuild);
auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
return compileCommandsAreEqual(Inputs.CompileCommand,
Preamble.CompileCommand) &&
@@ -785,13 +789,15 @@ PreamblePatch PreamblePatch::create(llvm::StringRef FileName,
// - If scanning for Modified fails, cannot figure out newly added ones so
// there's nothing to do but generate an empty patch.
auto BaselineScan =
- scanPreamble(Baseline.Preamble.getContents(), Modified.CompileCommand);
+ scanPreamble(Baseline.Preamble.getContents(), Modified.CompileCommand,
+ Modified.Opts.SkipPreambleBuild);
if (!BaselineScan) {
elog("Failed to scan baseline of {0}: {1}", FileName,
BaselineScan.takeError());
return PreamblePatch::unmodified(Baseline);
}
- auto ModifiedScan = scanPreamble(Modified.Contents, Modified.CompileCommand);
+ auto ModifiedScan = scanPreamble(Modified.Contents, Modified.CompileCommand,
+ Modified.Opts.SkipPreambleBuild);
if (!ModifiedScan) {
elog("Failed to scan modified contents of {0}: {1}", FileName,
ModifiedScan.takeError());
@@ -957,5 +963,12 @@ OptionalFileEntryRef PreamblePatch::getPatchEntry(llvm::StringRef MainFilePath,
auto PatchFilePath = getPatchName(MainFilePath);
return SM.getFileManager().getOptionalFileRef(PatchFilePath);
}
+
+PreambleBounds computePreambleBounds(const LangOptions &LangOpts,
+ const llvm::MemoryBufferRef &Buffer,
+ bool SkipPreambleBuild) {
+ return SkipPreambleBuild ? PreambleBounds(0, false)
+ : ComputePreambleBounds(LangOpts, Buffer, 0);
+}
} // namespace clangd
} // namespace clang
diff --git a/clang-tools-extra/clangd/Preamble.h b/clang-tools-extra/clangd/Preamble.h
index 7f2eb233ee1aa..2051930dae05d 100644
--- a/clang-tools-extra/clangd/Preamble.h
+++ b/clang-tools-extra/clangd/Preamble.h
@@ -239,6 +239,10 @@ class PreamblePatch {
MainFileMacros PatchedMacros;
};
+PreambleBounds computePreambleBounds(const LangOptions &LangOpts,
+ const llvm::MemoryBufferRef &Buffer,
+ bool SkipPreambleBuild);
+
} // namespace clangd
} // namespace clang
diff --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index 54af3662470db..7bedf83be14ac 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -525,6 +525,14 @@ opt<bool> PreambleParseForwardingFunctions{
init(ParseOptions().PreambleParseForwardingFunctions),
};
+opt<bool> SkipPreambleBuild{
+ "skip-preamble-build",
+ cat(Misc),
+ desc("If ture, skip preamble build"),
+ Hidden,
+ init(ParseOptions().SkipPreambleBuild),
+};
+
#if defined(__GLIBC__) && CLANGD_MALLOC_TRIM
opt<bool> EnableMallocTrim{
"malloc-trim",
@@ -1005,6 +1013,16 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var
}
Opts.UseDirtyHeaders = UseDirtyHeaders;
Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions;
+ if (ExperimentalModulesSupport &&
+ SkipPreambleBuild.getNumOccurrences() == 0) {
+ Opts.SkipPreambleBuild = true;
+ log("Experimental C++20 modules support is enabled. This leads to "
+ "disabling preamble build due to instability of mixed precompiled "
+ "headers and C++20 modules. To enable C++20 modules together with "
+ "preamble builds, pass --skip-preamble-build=false command line "
+ "option");
+ } else
+ Opts.SkipPreambleBuild = SkipPreambleBuild;
Opts.ImportInsertions = ImportInsertions;
Opts.QueryDriverGlobs = std::move(QueryDriverGlobs);
Opts.TweakFilter = [&](const Tweak &T) {
|
ChuanqiXu9
left a comment
There was a problem hiding this comment.
But in the current impl, for module units containing headers, how can clangd detect the change in the included header for the module units?
I checked, for me this scenario works correctly. I used example provided here #181770:
Behavior should be the same as for includes, which are outside the preamble section (e.g. include directive in the middle of the file), so I believe everything should be ok. |
No, the example in my mind is, // header.h
#pragma once
constexpr int vvv = 43;module;
#include "header.h"
export module m;
export constexpr int mm = vvv;We should be able to see the mm's value as 43. And after we change the value to 44 or 45 in header.h, we should be able to see mm's value be the corresponding value.
No, modules have different mechanism. We can't assume header will have similar affect. But after all, the mechanism comes from the |
Tried this example, and it works ok for me. Maybe you can just check this patch to make sure?
I mean that without this patch we can add |
I just tried and it doesn't work. And also it is weird that it works as it literally violates the abstraction of
I failed to understand what you want to say. If we change the file by adding a new #include, of course, it should change. But I guess you're talking about something different? |
If we have headers from your example And one more extra Test.h import m;main.cpp is #include "Dummy.h"
int dummy; // we cut preamble here
#include "Test.h"
int a = mm; If this works correctly without this patch, then #include "Test.h"
int a = mm; also should be ok with For me at |
I failed to understand your intention with the example. Why do you think this is a problem? I didn't think about this
I just tried it:
The source code is here: https://github.com/alibaba/async_simple/tree/CXX20Modules And the reason why I think the current approach is problematic is, the current approach simply breaks the design of the |
I am just trying to say, that If we support includes in the middle of the file (I believe we must), then this patch should works correctly, because roughly speaking it acts like we have an empty preamble and all headers are in the middle of the file. So, if scenarios with includes in the middle of the file doesn't work for you, we need to investigate this first.
With this patch preamble is empty, in general it doesn't matter can it be reused it or not, because all includes are in the file body and not a part of preamble. |
No, this is definitely the problem of this patch. The original example works well before the patch and not working after the patch. You can't really say an invariant of the problem exists too so it is not your problem. And also the variant you made is actually not by design of C++20 modules. Headers should belong to the global module fragments. This is by design. Attaching headers to module purview may be warned: https://godbolt.org/z/3rTM19r9P And even besides modules, again, this patch breaks the |
I think clangd should reparse opened files, when dependent file changes (independent of is this include happens in preamble section or not). In this case clangd doesn't do this if include is not in the preamble section, so this looks like another problem. This patch introduces ability to avoid preamble build and I think this works as expected. But yes, we found some problem cases but these problems have different origin. Anyway, this is just an option, which can be disabled/enabled.
I don't see any compilation warnings. Anyway, I think there can be other legal ways to make includes to be in the middle of the file.
As I said previously, it doesn't not, because we actually don't build the preamble, so we can say that we don't have the preamble and This solution provides ability to fix crashes (at least for me, because #187432 is not enough and still I faced crashes at preamble index update with that patch) and just a try to help you to improve stability of c++20 modules support in clangd. If this is not acceptable for you because of the reasons above (which I believe have different origin), maybe it's better to fix the problem in clang itself, as far as all we try to do here is to find a workaround for clang bugs. |
But here we have no warnings https://godbolt.org/z/xPeohsMEf |
This is just some implementation choices. By design, the original legacy headers should be in GMF for sure. |
If you think this is a missing feature, and the current patch introduces some problems but acceptable as modules support are experimental and we will add the feature back in the feature. Let's add them in document. And I think we can land this. |
Returning to your concern. I found that reparsing of opened files is based on preamble and this was on purpose because it was more simple to implement (just check if preamble is compatible with previous one or not). That's why this doesn't work for include directives in the middle of the file (and for our case when we don't build preamble) 596b63a (related issue clangd/clangd#107 ) So, if we decide to go with this patch, I think we have the following options:
In any case I think we need to file an issue about this problem (with a header inclusion which is outside of the preamble bounds). And this can be fixed with a check at a file save: if this file is in include structure of an opened file or not (needs additional investigation, but I think this should not be very hard) |
This seems unacceptable.
At least for modules, it is not so bad. At least support for modules in clangd is still experimental.
Yes, it is an existing issue that the files not belong to the preamble are not watched. And we need another fix for it. |
I am going to polish this PR (at least add some tests) in the nearest future, after that we review and/or merge it.
Created issue for this #189804 |
|
I've added test (based on tests from #187432 ) and now this is ready for review.
|
ChuanqiXu9
left a comment
There was a problem hiding this comment.
We need to record our conclusion somewhere in clangd's release notes: "We introduced a regression that clangd can't detect the changes in headers for TU containing import in some cases. The original change detection mechanism (it can't detect changes not in preamble) already has some problems. We plan to fix it in the future. We did this to modules now as the PCH and C++20 named module don't work well and may introduce bad crashes randomly.". You can change the wording if you like.
Maybe we can do this before the release? But if you're sure we won't fix this clang problem before the next release, I'd be happy to add this information into release notes now. |
ChuanqiXu9
left a comment
There was a problem hiding this comment.
LGTM. Let's land it. Thank you very much.
Thanks for review, I'll land this in two days to make sure nobody has any concerns |
…9284) This option allows to disable preamble optimization in clangd. By default it's false, but became true for TUs which import modules (and experimental modules support is enabled). This PR is a try to address C++20 modules problems described here llvm#187432 Fixes llvm#181770



This option allows to disable preamble optimization in clangd. By default it's false, but became true for TUs which import modules (and experimental modules support is enabled).
This PR is a try to address C++20 modules problems described here #187432
Fixes #181770