clang 24.0.0git
IncrementalParser.cpp
Go to the documentation of this file.
1//===--------- IncrementalParser.cpp - Incremental Compilation -----------===//
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// This file implements the class which performs incremental code compilation.
10//
11//===----------------------------------------------------------------------===//
12
13#include "IncrementalParser.h"
14#include "IncrementalAction.h"
15
17#include "clang/AST/Decl.h"
21#include "clang/Parse/Parser.h"
22#include "clang/Sema/Sema.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/IR/Module.h"
25#include "llvm/Support/CrashRecoveryContext.h"
26#include "llvm/Support/Error.h"
27
28#include <sstream>
29
30#define DEBUG_TYPE "clang-repl"
31
32namespace clang {
33
34// IncrementalParser::IncrementalParser() {}
35
37 IncrementalAction *Act, llvm::Error &Err,
38 std::list<PartialTranslationUnit> &PTUs)
39 : S(Instance.getSema()), Act(Act), PTUs(PTUs) {
40 llvm::ErrorAsOutParameter EAO(&Err);
41 Consumer = &S.getASTConsumer();
42 P.reset(new Parser(S.getPreprocessor(), S, /*SkipBodies=*/false));
43
44 if (ExternalASTSource *External = S.getASTContext().getExternalSource())
45 External->StartTranslationUnit(Consumer);
46
47 P->Initialize();
48}
49
51
53IncrementalParser::ParseOrWrapTopLevelDecl() {
54 // Recover resources if we crash before exiting this method.
55 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(&S);
56 Sema::GlobalEagerInstantiationScope GlobalInstantiations(S, /*Enabled=*/true,
57 /*AtEndOfTU=*/true);
58 Sema::LocalEagerInstantiationScope LocalInstantiations(S, /*AtEndOfTU=*/true);
59
60 // Add a new PTU.
62 C.addTranslationUnitDecl();
63
64 // Skip previous eof due to last incremental input.
65 if (P->getCurToken().is(tok::annot_repl_input_end)) {
66 P->ConsumeAnyToken();
67 // FIXME: Clang does not call ExitScope on finalizing the regular TU, we
68 // might want to do that around HandleEndOfTranslationUnit.
69 P->ExitScope();
70 S.CurContext = nullptr;
71 // Start a new PTU.
72 P->EnterScope(Scope::DeclScope);
73 S.ActOnTranslationUnitScope(P->getCurScope());
74 }
75
77 Sema::ModuleImportState ImportState;
78 for (bool AtEOF = P->ParseFirstTopLevelDecl(ADecl, ImportState); !AtEOF;
79 AtEOF = P->ParseTopLevelDecl(ADecl, ImportState)) {
80 if (ADecl && !Consumer->HandleTopLevelDecl(ADecl.get()))
81 return llvm::make_error<llvm::StringError>("Parsing failed. "
82 "The consumer rejected a decl",
83 std::error_code());
84 }
85
86 DiagnosticsEngine &Diags = S.getDiagnostics();
87 if (Diags.hasErrorOccurred()) {
88 CleanUpPTU(C.getTranslationUnitDecl());
89
90 Diags.Reset(/*soft=*/true);
91 Diags.getClient()->clear();
92 return llvm::make_error<llvm::StringError>("Parsing failed.",
93 std::error_code());
94 }
95
96 // Process any TopLevelDecls generated by #pragma weak.
97 for (Decl *D : S.WeakTopLevelDecls()) {
98 DeclGroupRef DGR(D);
99 Consumer->HandleTopLevelDecl(DGR);
100 }
101
102 LocalInstantiations.perform();
103 GlobalInstantiations.perform();
104
105 Consumer->HandleTranslationUnit(C);
106
107 return C.getTranslationUnitDecl();
108}
109
111IncrementalParser::Parse(llvm::StringRef input) {
112 Preprocessor &PP = S.getPreprocessor();
113 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode!?");
114
115 std::ostringstream SourceName;
116 SourceName << "input_line_" << InputCount++;
117
118 // Create an uninitialized memory buffer, copy code in and append "\n"
119 size_t InputSize = input.size(); // don't include trailing 0
120 // MemBuffer size should *not* include terminating zero
121 std::unique_ptr<llvm::MemoryBuffer> MB(
122 llvm::WritableMemoryBuffer::getNewUninitMemBuffer(InputSize + 1,
123 SourceName.str()));
124 char *MBStart = const_cast<char *>(MB->getBufferStart());
125 memcpy(MBStart, input.data(), InputSize);
126 MBStart[InputSize] = '\n';
127
128 SourceManager &SM = S.getSourceManager();
129
130 // FIXME: Create SourceLocation, which will allow clang to order the overload
131 // candidates for example
133
134 // Create FileID for the current buffer.
135 FileID FID;
136 // Create FileEntry and FileID for the current buffer.
138 SourceName.str(), InputSize, 0 /* mod time*/);
139 SM.overrideFileContents(FE, std::move(MB));
140
141 // Ensure HeaderFileInfo exists before lookup to prevent assertion
143 HS.getFileInfo(FE);
144
145 FID = SM.createFileID(FE, NewLoc, SrcMgr::C_User);
146
147 // NewLoc only used for diags.
148 if (PP.EnterSourceFile(FID, /*DirLookup=*/nullptr, NewLoc))
149 return llvm::make_error<llvm::StringError>("Parsing failed. "
150 "Cannot enter source file.",
151 std::error_code());
152
153 auto PTU = ParseOrWrapTopLevelDecl();
154 if (!PTU)
155 return PTU.takeError();
156
157 if (PP.getLangOpts().DelayedTemplateParsing) {
158 // Microsoft-specific:
159 // Late parsed templates can leave unswallowed "macro"-like tokens.
160 // They will seriously confuse the Parser when entering the next
161 // source file. So lex until we are EOF.
162 Token Tok;
163 do {
164 PP.Lex(Tok);
165 } while (Tok.isNot(tok::annot_repl_input_end));
166 } else {
167 Token AssertTok;
168 PP.Lex(AssertTok);
169 assert(AssertTok.is(tok::annot_repl_input_end) &&
170 "Lexer must be EOF when starting incremental parse!");
171 }
172
173 return PTU;
174}
175
176void IncrementalParser::withdrawMostRecentTU(
177 TranslationUnitDecl *MostRecentTU) {
178 TranslationUnitDecl *Prev = MostRecentTU->getPreviousDecl();
179 if (!Prev)
180 return;
181 assert(MostRecentTU->getMostRecentDecl() == MostRecentTU &&
182 "Not the most recent translation unit!");
183
184 // Rebuild A -> ... -> Prev -> MostRecentTU as A -> ... -> Prev.
185 MostRecentTU->getFirstDecl()->RedeclLink.setLatest(Prev);
186
187 // getTranslationUnitDecl() requires the active unit to be the latest one.
189 if (C.TraversalScope.size() == 1 && C.TraversalScope.back() == MostRecentTU)
190 C.TraversalScope = {Prev};
191 C.TUDecl = Prev;
192}
193
195 if (StoredDeclsMap *Map = MostRecentTU->getPrimaryContext()->getLookupPtr()) {
196 // Collect the keys to erase: erasing during iteration invalidates the map
197 // iterator under backward-shift deletion.
199 for (auto &&[Key, List] : *Map) {
200 DeclContextLookupResult R = List.getLookupResult();
201 std::vector<NamedDecl *> NamedDeclsToRemove;
202 bool RemoveAll = true;
203 for (NamedDecl *D : R) {
204 if (D->getTranslationUnitDecl() == MostRecentTU)
205 NamedDeclsToRemove.push_back(D);
206 else
207 RemoveAll = false;
208 }
209 if (LLVM_LIKELY(RemoveAll)) {
210 KeysToErase.push_back(Key);
211 } else {
212 for (NamedDecl *D : NamedDeclsToRemove)
213 List.remove(D);
214 }
215 }
216 for (DeclarationName Key : KeysToErase)
217 Map->erase(Key);
218 }
219
220 // Check if we need to clean up the IdResolver chain.
221 auto RemoveFromIdResolver = [&](NamedDecl *D) {
222 if (D->getDeclName().getFETokenInfo() && !D->getLangOpts().ObjC &&
223 !D->getLangOpts().CPlusPlus)
224 S.IdResolver.RemoveDecl(D);
225 };
226
227 ExternCContextDecl *ECCD = S.getASTContext().getExternCContextDecl();
228 if (StoredDeclsMap *Map = ECCD->getPrimaryContext()->getLookupPtr()) {
229 for (auto &&[Key, List] : *Map) {
230 DeclContextLookupResult R = List.getLookupResult();
231 llvm::SmallVector<NamedDecl *, 4> NamedDeclsToRemove;
232 for (NamedDecl *D : R) {
233 // Implicitly generated C decl is not attached to the current TU but
234 // lexically attached to the recent TU, so we need to check the lexical
235 // context.
236 DeclContext *LDC = D->getLexicalDeclContext();
237 while (LDC && !isa<TranslationUnitDecl>(LDC))
238 LDC = LDC->getLexicalParent();
239 TranslationUnitDecl *TopTU = cast_or_null<TranslationUnitDecl>(LDC);
240 if (TopTU == MostRecentTU)
241 NamedDeclsToRemove.push_back(D);
242 }
243 for (NamedDecl *D : NamedDeclsToRemove) {
244 List.remove(D);
245 RemoveFromIdResolver(D);
246 }
247 }
248 }
249
250 for (Decl *D : MostRecentTU->decls()) {
251 auto *ND = dyn_cast<NamedDecl>(D);
252 if (!ND || ND->getDeclName().isEmpty())
253 continue;
254 RemoveFromIdResolver(ND);
255 }
256
257 // Lookup alone is not enough: the redeclaration chain still reaches these.
258 withdrawMostRecentTU(MostRecentTU);
259}
260
263 std::unique_ptr<llvm::Module> M /*={}*/) {
264 PTUs.emplace_back(PartialTranslationUnit());
265 PartialTranslationUnit &LastPTU = PTUs.back();
266 LastPTU.TUPart = TU;
267
268 if (!M)
269 M = Act->GenModule();
270
271 assert((!Act->getCodeGen() || M) && "Must have a llvm::Module at this point");
272
273 LastPTU.TheModule = std::move(M);
274 LLVM_DEBUG(llvm::dbgs() << "compile-ptu " << PTUs.size() - 1
275 << ": [TU=" << LastPTU.TUPart);
276 if (LastPTU.TheModule)
277 LLVM_DEBUG(llvm::dbgs() << ", M=" << LastPTU.TheModule.get() << " ("
278 << LastPTU.TheModule->getName() << ")");
279 LLVM_DEBUG(llvm::dbgs() << "]\n");
280 return LastPTU;
281}
282} // end namespace clang
Defines the clang::ASTContext interface.
Token Tok
The Token.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
The results of name lookup within a DeclContext.
Definition DeclBase.h:1399
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2403
StoredDeclsMap * getLookupPtr() const
Retrieve the internal representation of the lookup structure.
Definition DeclBase.h:2711
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
The name of a declaration.
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:248
Abstract interface for external sources of AST nodes.
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
HeaderFileInfo & getFileInfo(FileEntryRef FE)
Return the HeaderFileInfo structure for the specified FileEntry, in preparation for updating it in so...
A custom action enabling the incremental processing functionality.
IncrementalParser(CompilerInstance &Instance, IncrementalAction *Act, llvm::Error &Err, std::list< PartialTranslationUnit > &PTUs)
IncrementalAction * Act
The FrontendAction used during incremental parsing.
std::list< PartialTranslationUnit > & PTUs
unsigned InputCount
Counts the number of direct user input lines that have been parsed.
void CleanUpPTU(TranslationUnitDecl *MostRecentTU)
PartialTranslationUnit & RegisterPTU(TranslationUnitDecl *TU, std::unique_ptr< llvm::Module > M={})
Register a PTU produced by Parse.
virtual llvm::Expected< TranslationUnitDecl * > Parse(llvm::StringRef Input)
Parses incremental input by creating an in-memory file.
std::unique_ptr< Parser > P
Parser.
ASTConsumer * Consumer
Consumer to process the produced top level decls. Owned by Act.
Sema & S
The Sema performing the incremental compilation.
This represents a decl that may have a name.
Definition Decl.h:275
Parser - This implements a parser for the C family of languages.
Definition Parser.h:256
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:304
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
void Lex(Token &Result)
Lex the next token for this preprocessor.
bool EnterSourceFile(FileID FID, ConstSearchDirIterator Dir, SourceLocation Loc, bool IsFirstIncludeOfFile=true)
Add a source file to the top of the include stack and start lexing tokens from it instead of the curr...
HeaderSearch & getHeaderSearchInfo() const
const LangOptions & getLangOpts() const
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
DeclLink RedeclLink
Points to the next redeclaration in the chain.
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition Sema.cpp:173
ASTContext & getASTContext() const
Definition Sema.h:935
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1444
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:9926
Encodes a location in the source.
This class handles loading and caching of source files into memory.
FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
FileManager & getFileManager() const
FileID getMainFileID() const
Returns the FileID of the main source file.
void overrideFileContents(FileEntryRef SourceFile, const llvm::MemoryBufferRef &Buffer)
Override the contents of the given source file by providing an already-allocated buffer.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
The top declaration context.
Definition Decl.h:106
TranslationUnitDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
TranslationUnitDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
The class keeps track of various objects created as part of processing incremental inputs.
std::unique_ptr< llvm::Module > TheModule
The llvm IR produced for the input.