clang 23.0.0git
CrossTranslationUnit.h
Go to the documentation of this file.
1//===--- CrossTranslationUnit.h - -------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides an interface to load binary AST dumps on demand. This
10// feature can be utilized for tools that require cross translation unit
11// support.
12//
13//===----------------------------------------------------------------------===//
14#ifndef LLVM_CLANG_CROSSTU_CROSSTRANSLATIONUNIT_H
15#define LLVM_CLANG_CROSSTU_CROSSTRANSLATIONUNIT_H
16
19#include "clang/Basic/LLVM.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/Support/Error.h"
24#include "llvm/Support/Path.h"
25#include <optional>
26
27namespace clang {
29class ASTContext;
30class ASTImporter;
31class ASTUnit;
32class DeclContext;
33class FunctionDecl;
34class VarDecl;
35class NamedDecl;
37
38namespace cross_tu {
39
60
61class IndexError : public llvm::ErrorInfo<IndexError> {
62public:
63 static char ID;
64 IndexError(index_error_code C) : Code(C), LineNo(0) {}
65 IndexError(index_error_code C, std::string FileName, int LineNo = 0)
66 : Code(C), FileName(std::move(FileName)), LineNo(LineNo) {}
67 IndexError(index_error_code C, std::string FileName, std::string ConfigToName,
68 std::string ConfigFromName)
69 : Code(C), FileName(std::move(FileName)),
70 ConfigToName(std::move(ConfigToName)),
71 ConfigFromName(std::move(ConfigFromName)) {}
72 void log(raw_ostream &OS) const override;
73 std::error_code convertToErrorCode() const override;
74 index_error_code getCode() const { return Code; }
75 int getLineNum() const { return LineNo; }
76 std::string getFileName() const { return FileName; }
77 std::string getConfigToName() const { return ConfigToName; }
78 std::string getConfigFromName() const { return ConfigFromName; }
79
80private:
82 std::string FileName;
83 int LineNo;
84 std::string ConfigToName;
85 std::string ConfigFromName;
86};
87
88/// This function parses an index file that determines which
89/// translation unit contains which definition. The IndexPath is not prefixed
90/// with CTUDir, so an absolute path is expected for consistent results.
91///
92/// The index file format is the following:
93/// each line consists of an USR and a filepath separated by a space.
94///
95/// \return Returns a map where the USR is the key and the filepath is the value
96/// or an error.
98parseCrossTUIndex(StringRef IndexPath);
99
100std::string createCrossTUIndexString(const llvm::StringMap<std::string> &Index);
101
102using InvocationListTy = llvm::StringMap<llvm::SmallVector<std::string, 32>>;
103/// Parse the YAML formatted invocation list file content \p FileContent.
104/// The format is expected to be a mapping from absolute source file
105/// paths in the filesystem to a list of command-line parts, which
106/// constitute the invocation needed to compile that file. That invocation
107/// will be used to produce the AST of the TU.
109 StringRef FileContent,
110 llvm::sys::path::Style PathStyle = llvm::sys::path::Style::posix,
111 StringRef FilePath = "");
112
113/// Returns true if it makes sense to import a foreign variable definition.
114/// For instance, we don't want to import variables that have non-trivial types
115/// because the constructor might have side-effects.
116bool shouldImport(const VarDecl *VD, const ASTContext &ACtx);
117
118/// This class is used for tools that requires cross translation
119/// unit capability.
120///
121/// This class can load definitions from external AST sources.
122/// The loaded definition will be merged back to the original AST using the
123/// AST Importer.
124/// In order to use this class, an index file is required that describes
125/// the locations of the AST files for each definition.
126///
127/// Note that this class also implements caching.
129public:
132
133 /// This function loads a function or variable definition from an
134 /// external AST file and merges it into the original AST.
135 ///
136 /// This method should only be used on functions that have no definitions or
137 /// variables that have no initializer in
138 /// the current translation unit. A function definition with the same
139 /// declaration will be looked up in the index file which should be in the
140 /// \p CrossTUDir directory, called \p IndexName. In case the declaration is
141 /// found in the index the corresponding AST will be loaded and the
142 /// definition will be merged into the original AST using the AST Importer.
143 ///
144 /// \return The declaration with the definition will be returned.
145 /// If no suitable definition is found in the index file or multiple
146 /// definitions found error will be returned.
147 ///
148 /// Note that the AST files should also be in the \p CrossTUDir.
150 getCrossTUDefinition(const FunctionDecl *FD, StringRef CrossTUDir,
151 StringRef IndexName, bool DisplayCTUProgress = false);
153 getCrossTUDefinition(const VarDecl *VD, StringRef CrossTUDir,
154 StringRef IndexName, bool DisplayCTUProgress = false);
155
156 /// This function loads a definition from an external AST file.
157 ///
158 /// A definition with the same declaration will be looked up in the
159 /// index file which should be in the \p CrossTUDir directory, called
160 /// \p IndexName. In case the declaration is found in the index the
161 /// corresponding AST will be loaded. If the number of TUs imported
162 /// reaches \p CTULoadTreshold, no loading is performed.
163 ///
164 /// \return Returns a pointer to the ASTUnit that contains the definition of
165 /// the looked up name or an Error.
166 /// The returned pointer is never a nullptr.
167 ///
168 /// Note that the AST files should also be in the \p CrossTUDir.
169 llvm::Expected<ASTUnit *> loadExternalAST(StringRef LookupName,
170 StringRef CrossTUDir,
171 StringRef IndexName,
172 bool DisplayCTUProgress = false);
173
174 /// This function merges a definition from a separate AST Unit into
175 /// the current one which was created by the compiler instance that
176 /// was passed to the constructor.
177 ///
178 /// \return Returns the resulting definition or an error.
180 ASTUnit *Unit);
182 ASTUnit *Unit);
183
184 /// Get a name to identify a decl.
185 static std::optional<std::string> getLookupName(const Decl *D);
186
187 /// Emit diagnostics for the user for potential configuration errors.
189
190 /// Returns the MacroExpansionContext for the imported TU to which the given
191 /// source-location corresponds.
192 /// \p ToLoc Source location in the imported-to AST.
193 /// \note If any error happens such as \p ToLoc is a non-imported
194 /// source-location, empty is returned.
195 /// \note Macro expansion tracking for imported TUs is not implemented yet.
196 /// It returns empty unconditionally.
197 std::optional<clang::MacroExpansionContext>
199 const clang::SourceLocation &ToLoc) const;
200
201 /// Returns true if the given Decl is newly created during the import.
202 bool isImportedAsNew(const Decl *ToDecl) const;
203
204 /// Returns true if the given Decl is mapped (or created) during an import
205 /// but there was an unrecoverable error (the AST node cannot be erased, it
206 /// is marked with an Error object in this case).
207 bool hasError(const Decl *ToDecl) const;
208
209private:
210 void lazyInitImporterSharedSt(TranslationUnitDecl *ToTU);
211 ASTImporter &getOrCreateASTImporter(ASTUnit *Unit);
212 template <typename T>
213 llvm::Expected<const T *> getCrossTUDefinitionImpl(const T *D,
214 StringRef CrossTUDir,
215 StringRef IndexName,
216 bool DisplayCTUProgress);
217 template <typename T>
218 const T *findDefInDeclContext(const DeclContext *DC,
219 StringRef LookupName);
220 template <typename T>
221 llvm::Expected<const T *> importDefinitionImpl(const T *D, ASTUnit *Unit);
222
223 using ImporterMapTy =
224 llvm::DenseMap<TranslationUnitDecl *, std::unique_ptr<ASTImporter>>;
225
226 ImporterMapTy ASTUnitImporterMap;
227
228 ASTContext &Context;
229 std::shared_ptr<ASTImporterSharedState> ImporterSharedSt;
230
231 using LoadResultTy = llvm::Expected<std::unique_ptr<ASTUnit>>;
232
233 /// Loads ASTUnits from AST-dumps or source-files.
234 class ASTLoader {
235 public:
236 ASTLoader(CompilerInstance &CI, StringRef CTUDir,
237 StringRef InvocationListFilePath);
238
239 /// Load the ASTUnit by its identifier found in the index file. If the
240 /// identifier is suffixed with '.ast' it is considered a dump. Otherwise
241 /// it is treated as source-file, and on-demand parsed. Relative paths are
242 /// prefixed with CTUDir.
243 LoadResultTy load(StringRef Identifier);
244
245 /// Lazily initialize the invocation list information, which is needed for
246 /// on-demand parsing.
247 llvm::Error lazyInitInvocationList();
248
249 private:
250 /// The style used for storage and lookup of filesystem paths.
251 /// Defaults to posix.
252 const llvm::sys::path::Style PathStyle = llvm::sys::path::Style::posix;
253
254 /// Loads an AST from a pch-dump.
255 LoadResultTy loadFromDump(StringRef Identifier);
256 /// Loads an AST from a source-file.
257 LoadResultTy loadFromSource(StringRef Identifier);
258
260 StringRef CTUDir;
261 /// The path to the file containing the invocation list, which is in YAML
262 /// format, and contains a mapping from source files to compiler invocations
263 /// that produce the AST used for analysis.
264 StringRef InvocationListFilePath;
265 /// In case of on-demand parsing, the invocations for parsing the source
266 /// files is stored.
267 std::optional<InvocationListTy> InvocationList;
268 std::optional<IndexError> PreviousError;
269 };
270
271 /// Maintain number of AST loads and check for reaching the load limit.
272 class ASTLoadGuard {
273 public:
274 ASTLoadGuard(unsigned Limit) : Limit(Limit) {}
275
276 /// Indicates, whether a new load operation is permitted, it is within the
277 /// threshold.
278 operator bool() const { return Count < Limit; }
279
280 /// Tell that a new AST was loaded successfully.
281 void indicateLoadSuccess() { ++Count; }
282
283 private:
284 /// The number of ASTs actually imported.
285 unsigned Count{0u};
286 /// The limit (threshold) value for number of loaded ASTs.
287 const unsigned Limit;
288 };
289
290 /// Storage and load of ASTUnits, cached access, and providing searchability
291 /// are the concerns of ASTUnitStorage class.
292 class ASTUnitStorage {
293 public:
294 ASTUnitStorage(CompilerInstance &CI);
295 /// Loads an ASTUnit for a function.
296 ///
297 /// \param FunctionName USR name of the function.
298 /// \param CrossTUDir Path to the directory used to store CTU related files.
299 /// \param IndexName Name of the file inside \p CrossTUDir which maps
300 /// function USR names to file paths. These files contain the corresponding
301 /// AST-dumps.
302 /// \param DisplayCTUProgress Display a message about loading new ASTs.
303 ///
304 /// \return An Expected instance which contains the ASTUnit pointer or the
305 /// error occurred during the load.
306 llvm::Expected<ASTUnit *> getASTUnitForFunction(StringRef FunctionName,
307 StringRef CrossTUDir,
308 StringRef IndexName,
309 bool DisplayCTUProgress);
310 /// Identifies the path of the file which can be used to load the ASTUnit
311 /// for a given function.
312 ///
313 /// \param FunctionName USR name of the function.
314 /// \param CrossTUDir Path to the directory used to store CTU related files.
315 /// \param IndexName Name of the file inside \p CrossTUDir which maps
316 /// function USR names to file paths. These files contain the corresponding
317 /// AST-dumps.
318 ///
319 /// \return An Expected instance containing the filepath.
320 llvm::Expected<std::string> getFileForFunction(StringRef FunctionName,
321 StringRef CrossTUDir,
322 StringRef IndexName);
323
324 private:
325 llvm::Error ensureCTUIndexLoaded(StringRef CrossTUDir, StringRef IndexName);
326 llvm::Expected<ASTUnit *> getASTUnitForFile(StringRef FileName,
327 bool DisplayCTUProgress);
328
329 template <typename... T> using BaseMapTy = llvm::StringMap<T...>;
330 using OwningMapTy = BaseMapTy<std::unique_ptr<clang::ASTUnit>>;
331 using NonOwningMapTy = BaseMapTy<clang::ASTUnit *>;
332
333 OwningMapTy FileASTUnitMap;
334 NonOwningMapTy NameASTUnitMap;
335
336 using IndexMapTy = BaseMapTy<std::string>;
337 IndexMapTy NameFileMap;
338
339 /// Loads the AST based on the identifier found in the index.
340 ASTLoader Loader;
341
342 /// Limit the number of loaded ASTs. It is used to limit the memory usage
343 /// of the CrossTranslationUnitContext. The ASTUnitStorage has the
344 /// information whether the AST to load is actually loaded or returned from
345 /// cache. This information is needed to maintain the counter.
346 ASTLoadGuard LoadGuard;
347 };
348
349 ASTUnitStorage ASTStorage;
350
351 bool HasEmittedLoadThresholdRemark = false;
352};
353
354} // namespace cross_tu
355} // namespace clang
356
357#endif // LLVM_CLANG_CROSSTU_CROSSTRANSLATIONUNIT_H
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
Imports selected nodes from one AST context into another context, merging AST nodes where appropriate...
Definition ASTImporter.h:62
Utility class for loading a ASTContext from an AST file.
Definition ASTUnit.h:93
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Represents a function declaration or definition.
Definition Decl.h:2015
This represents a decl that may have a name.
Definition Decl.h:274
Encodes a location in the source.
The top declaration context.
Definition Decl.h:105
Represents a variable declaration or definition.
Definition Decl.h:926
llvm::Expected< const FunctionDecl * > getCrossTUDefinition(const FunctionDecl *FD, StringRef CrossTUDir, StringRef IndexName, bool DisplayCTUProgress=false)
This function loads a function or variable definition from an external AST file and merges it into th...
llvm::Expected< const FunctionDecl * > importDefinition(const FunctionDecl *FD, ASTUnit *Unit)
This function merges a definition from a separate AST Unit into the current one which was created by ...
void emitCrossTUDiagnostics(const IndexError &IE, SourceLocation Loc)
Emit diagnostics for the user for potential configuration errors.
static std::optional< std::string > getLookupName(const Decl *D)
Get a name to identify a decl.
std::optional< clang::MacroExpansionContext > getMacroExpansionContextForSourceLocation(const clang::SourceLocation &ToLoc) const
Returns the MacroExpansionContext for the imported TU to which the given source-location corresponds.
bool hasError(const Decl *ToDecl) const
Returns true if the given Decl is mapped (or created) during an import but there was an unrecoverable...
bool isImportedAsNew(const Decl *ToDecl) const
Returns true if the given Decl is newly created during the import.
llvm::Expected< ASTUnit * > loadExternalAST(StringRef LookupName, StringRef CrossTUDir, StringRef IndexName, bool DisplayCTUProgress=false)
This function loads a definition from an external AST file.
index_error_code getCode() const
IndexError(index_error_code C, std::string FileName, int LineNo=0)
std::error_code convertToErrorCode() const override
std::string getConfigFromName() const
std::string getConfigToName() const
IndexError(index_error_code C, std::string FileName, std::string ConfigToName, std::string ConfigFromName)
bool shouldImport(const VarDecl *VD, const ASTContext &ACtx)
Returns true if it makes sense to import a foreign variable definition.
llvm::Expected< llvm::StringMap< std::string > > parseCrossTUIndex(StringRef IndexPath)
This function parses an index file that determines which translation unit contains which definition.
std::string createCrossTUIndexString(const llvm::StringMap< std::string > &Index)
llvm::Expected< InvocationListTy > parseInvocationList(StringRef FileContent, llvm::sys::path::Style PathStyle=llvm::sys::path::Style::posix, StringRef FilePath="")
Parse the YAML formatted invocation list file content FileContent.
llvm::StringMap< llvm::SmallVector< std::string, 32 > > InvocationListTy
The JSON file list parser is used to communicate input to InstallAPI.
#define log(__x)
Definition tgmath.h:460