Debian Codegraph @

clang/lib/CrossTU/CrossTranslationUnit.cpp

raw
1 //===--- CrossTranslationUnit.cpp - -----------------------------*- 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 implements the CrossTranslationUnit interface.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "clang/CrossTU/CrossTranslationUnit.h"
13 #include "clang/AST/ASTImporter.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/ParentMapContext.h"
16 #include "clang/Basic/DiagnosticDriver.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/CrossTU/CrossTUDiagnostic.h"
19 #include "clang/Driver/CreateASTUnitFromArgs.h"
20 #include "clang/Frontend/ASTUnit.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Frontend/TextDiagnosticPrinter.h"
23 #include "clang/Index/USRGeneration.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/IOSandbox.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/YAMLParser.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/TargetParser/Triple.h"
33 #include <algorithm>
34 #include <fstream>
35 #include <optional>
36 #include <sstream>
37 #include <tuple>
38
39 namespace clang {
40 namespace cross_tu {
41
42 namespace {
43
44 #define DEBUG_TYPE "CrossTranslationUnit"
45 STATISTIC(NumGetCTUCalled, "The # of getCTUDefinition function called");
46 STATISTIC(
47 NumNotInOtherTU,
48 "The # of getCTUDefinition called but the function is not in any other TU");
49 STATISTIC(NumGetCTUSuccess,
50 "The # of getCTUDefinition successfully returned the "
51 "requested function's body");
52 STATISTIC(NumUnsupportedNodeFound, "The # of imports when the ASTImporter "
53 "encountered an unsupported AST Node");
54 STATISTIC(NumNameConflicts, "The # of imports when the ASTImporter "
55 "encountered an ODR error");
56 STATISTIC(NumTripleMismatch, "The # of triple mismatches");
57 STATISTIC(NumLangMismatch, "The # of language mismatches");
58 STATISTIC(NumLangDialectMismatch, "The # of language dialect mismatches");
59 STATISTIC(NumASTLoadThresholdReached,
60 "The # of ASTs not loaded because of threshold");
61
62 // Same as Triple's equality operator, but we check a field only if that is
63 // known in both instances.
64 bool hasEqualKnownFields(const llvm::Triple &Lhs, const llvm::Triple &Rhs) {
65 using llvm::Triple;
66 if (Lhs.getArch() != Triple::UnknownArch &&
67 Rhs.getArch() != Triple::UnknownArch && Lhs.getArch() != Rhs.getArch())
68 return false;
69 if (Lhs.getSubArch() != Triple::NoSubArch &&
70 Rhs.getSubArch() != Triple::NoSubArch &&
71 Lhs.getSubArch() != Rhs.getSubArch())
72 return false;
73 if (Lhs.getVendor() != Triple::UnknownVendor &&
74 Rhs.getVendor() != Triple::UnknownVendor &&
75 Lhs.getVendor() != Rhs.getVendor())
76 return false;
77 if (!Lhs.isOSUnknown() && !Rhs.isOSUnknown() &&
78 Lhs.getOS() != Rhs.getOS())
79 return false;
80 if (Lhs.getEnvironment() != Triple::UnknownEnvironment &&
81 Rhs.getEnvironment() != Triple::UnknownEnvironment &&
82 Lhs.getEnvironment() != Rhs.getEnvironment())
83 return false;
84 if (Lhs.getObjectFormat() != Triple::UnknownObjectFormat &&
85 Rhs.getObjectFormat() != Triple::UnknownObjectFormat &&
86 Lhs.getObjectFormat() != Rhs.getObjectFormat())
87 return false;
88 return true;
89 }
90
91 // FIXME: This class is will be removed after the transition to llvm::Error.
92 class IndexErrorCategory : public std::error_category {
93 public:
94 const char *name() const noexcept override { return "clang.index"; }
95
96 std::string message(int Condition) const override {
97 switch (static_cast<index_error_code>(Condition)) {
98 case index_error_code::success:
99 // There should not be a success error. Jump to unreachable directly.
100 // Add this case to make the compiler stop complaining.
101 break;
102 case index_error_code::unspecified:
103 return "An unknown error has occurred.";
104 case index_error_code::missing_index_file:
105 return "The index file is missing.";
106 case index_error_code::invalid_index_format:
107 return "Invalid index file format.";
108 case index_error_code::multiple_definitions:
109 return "Multiple definitions in the index file.";
110 case index_error_code::missing_definition:
111 return "Missing definition from the index file.";
112 case index_error_code::failed_import:
113 return "Failed to import the definition.";
114 case index_error_code::failed_to_get_external_ast:
115 return "Failed to load external AST source.";
116 case index_error_code::failed_to_generate_usr:
117 return "Failed to generate USR.";
118 case index_error_code::triple_mismatch:
119 return "Triple mismatch";
120 case index_error_code::lang_mismatch:
121 return "Language mismatch";
122 case index_error_code::lang_dialect_mismatch:
123 return "Language dialect mismatch";
124 case index_error_code::load_threshold_reached:
125 return "Load threshold reached";
126 case index_error_code::invocation_list_ambiguous:
127 return "Invocation list file contains multiple references to the same "
128 "source file.";
129 case index_error_code::invocation_list_file_not_found:
130 return "Invocation list file is not found.";
131 case index_error_code::invocation_list_empty:
132 return "Invocation list file is empty.";
133 case index_error_code::invocation_list_wrong_format:
134 return "Invocation list file is in wrong format.";
135 case index_error_code::invocation_list_lookup_unsuccessful:
136 return "Invocation list file does not contain the requested source file.";
137 }
138 llvm_unreachable("Unrecognized index_error_code.");
139 }
140 };
141
142 static llvm::ManagedStatic<IndexErrorCategory> Category;
143 } // end anonymous namespace
144
145 char IndexError::ID;
146
147 void IndexError::log(raw_ostream &OS) const {
148 OS << Category->message(static_cast<int>(Code)) << '\n';
149 }
150
151 std::error_code IndexError::convertToErrorCode() const {
152 return std::error_code(static_cast<int>(Code), *Category);
153 }
154
155 /// Parse one line of the input CTU index file.
156 ///
157 /// @param[in] LineRef The input CTU index item in format
158 /// "<USR-Length>:<USR> <File-Path>".
159 /// @param[out] LookupName The lookup name in format "<USR-Length>:<USR>".
160 /// @param[out] FilePath The file path "<File-Path>".
161 static bool parseCrossTUIndexItem(StringRef LineRef, StringRef &LookupName,
162 StringRef &FilePath) {
163 // `LineRef` is "<USR-Length>:<USR> <File-Path>" now.
164
165 size_t USRLength = 0;
166 if (LineRef.consumeInteger(10, USRLength))
167 return false;
168 assert(USRLength && "USRLength should be greater than zero.");
169
170 if (!LineRef.consume_front(":"))
171 return false;
172
173 // `LineRef` is now just "<USR> <File-Path>".
174
175 // Check LookupName length out of bound and incorrect delimiter.
176 if (USRLength >= LineRef.size() || ' ' != LineRef[USRLength])
177 return false;
178
179 LookupName = LineRef.substr(0, USRLength);
180 FilePath = LineRef.substr(USRLength + 1);
181 return true;
182 }
183
184 llvm::Expected<llvm::StringMap<std::string>>
185 parseCrossTUIndex(StringRef IndexPath) {
186 std::ifstream ExternalMapFile{std::string(IndexPath)};
187 if (!ExternalMapFile)
188 return llvm::make_error<IndexError>(index_error_code::missing_index_file,
189 IndexPath.str());
190
191 llvm::StringMap<std::string> Result;
192 std::string Line;
193 unsigned LineNo = 1;
194 while (std::getline(ExternalMapFile, Line)) {
195 // Split lookup name and file path
196 StringRef LookupName, FilePathInIndex;
197 if (!parseCrossTUIndexItem(Line, LookupName, FilePathInIndex))
198 return llvm::make_error<IndexError>(
199 index_error_code::invalid_index_format, IndexPath.str(), LineNo);
200
201 // Store paths with posix-style directory separator.
202 SmallString<32> FilePath(FilePathInIndex);
203 llvm::sys::path::native(FilePath, llvm::sys::path::Style::posix);
204
205 bool InsertionOccured;
206 std::tie(std::ignore, InsertionOccured) =
207 Result.try_emplace(LookupName, FilePath.begin(), FilePath.end());
208 if (!InsertionOccured)
209 return llvm::make_error<IndexError>(
210 index_error_code::multiple_definitions, IndexPath.str(), LineNo);
211
212 ++LineNo;
213 }
214 return Result;
215 }
216
217 std::string
218 createCrossTUIndexString(const llvm::StringMap<std::string> &Index) {
219 std::ostringstream Result;
220 for (const auto &E : Index)
221 Result << E.getKey().size() << ':' << E.getKey().str() << ' '
222 << E.getValue() << '\n';
223 return Result.str();
224 }
225
226 bool shouldImport(const VarDecl *VD, const ASTContext &ACtx) {
227 CanQualType CT = ACtx.getCanonicalType(VD->getType());
228 return CT.isConstQualified() && VD->getType().isTrivialType(ACtx);
229 }
230
231 static bool hasBodyOrInit(const FunctionDecl *D, const FunctionDecl *&DefD) {
232 return D->hasBody(DefD);
233 }
234 static bool hasBodyOrInit(const VarDecl *D, const VarDecl *&DefD) {
235 return D->getAnyInitializer(DefD);
236 }
237 template <typename T> static bool hasBodyOrInit(const T *D) {
238 const T *Unused;
239 return hasBodyOrInit(D, Unused);
240 }
241
242 CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI)
243 : Context(CI.getASTContext()), ASTStorage(CI) {
244 if (CI.getAnalyzerOpts().ShouldEmitErrorsOnInvalidConfigValue &&
245 !CI.getAnalyzerOpts().CTUDir.empty()) {
246 auto S = CI.getVirtualFileSystem().status(CI.getAnalyzerOpts().CTUDir);
247 if (!S || S->getType() != llvm::sys::fs::file_type::directory_file)
248 CI.getDiagnostics().Report(diag::err_analyzer_config_invalid_input)
249 << "ctu-dir"
250 << "a filename";
251 }
252 }
253
254 CrossTranslationUnitContext::~CrossTranslationUnitContext() {}
255
256 std::optional<std::string>
257 CrossTranslationUnitContext::getLookupName(const Decl *D) {
258 SmallString<128> DeclUSR;
259 bool Ret = index::generateUSRForDecl(D, DeclUSR);
260 if (Ret)
261 return {};
262 return std::string(DeclUSR);
263 }
264
265 /// Recursively visits the decls of a DeclContext, and returns one with the
266 /// given USR.
267 template <typename T>
268 const T *
269 CrossTranslationUnitContext::findDefInDeclContext(const DeclContext *DC,
270 StringRef LookupName) {
271 assert(DC && "Declaration Context must not be null");
272 for (const Decl *D : DC->decls()) {
273 const auto *SubDC = dyn_cast<DeclContext>(D);
274 if (SubDC)
275 if (const auto *ND = findDefInDeclContext<T>(SubDC, LookupName))
276 return ND;
277
278 const auto *ND = dyn_cast<T>(D);
279 const T *ResultDecl;
280 if (!ND || !hasBodyOrInit(ND, ResultDecl))
281 continue;
282 std::optional<std::string> ResultLookupName = getLookupName(ResultDecl);
283 if (!ResultLookupName || *ResultLookupName != LookupName)
284 continue;
285 return ResultDecl;
286 }
287 return nullptr;
288 }
289
290 template <typename T>
291 llvm::Expected<const T *> CrossTranslationUnitContext::getCrossTUDefinitionImpl(
292 const T *D, StringRef CrossTUDir, StringRef IndexName,
293 bool DisplayCTUProgress) {
294 assert(D && "D is missing, bad call to this function!");
295 assert(!hasBodyOrInit(D) &&
296 "D has a body or init in current translation unit!");
297 ++NumGetCTUCalled;
298 const std::optional<std::string> LookupName = getLookupName(D);
299 if (!LookupName)
300 return llvm::make_error<IndexError>(
301 index_error_code::failed_to_generate_usr);
302 llvm::Expected<ASTUnit *> ASTUnitOrError =
303 loadExternalAST(*LookupName, CrossTUDir, IndexName, DisplayCTUProgress);
304 if (!ASTUnitOrError)
305 return ASTUnitOrError.takeError();
306 ASTUnit *Unit = *ASTUnitOrError;
307 assert(&Unit->getFileManager() ==
308 &Unit->getASTContext().getSourceManager().getFileManager());
309
310 const llvm::Triple &TripleTo = Context.getTargetInfo().getTriple();
311 const llvm::Triple &TripleFrom =
312 Unit->getASTContext().getTargetInfo().getTriple();
313 // The imported AST had been generated for a different target.
314 // Some parts of the triple in the loaded ASTContext can be unknown while the
315 // very same parts in the target ASTContext are known. Thus we check for the
316 // known parts only.
317 if (!hasEqualKnownFields(TripleTo, TripleFrom)) {
318 // TODO: Pass the SourceLocation of the CallExpression for more precise
319 // diagnostics.
320 ++NumTripleMismatch;
321 return llvm::make_error<IndexError>(index_error_code::triple_mismatch,
322 std::string(Unit->getMainFileName()),
323 TripleTo.str(), TripleFrom.str());
324 }
325
326 const auto &LangTo = Context.getLangOpts();
327 const auto &LangFrom = Unit->getASTContext().getLangOpts();
328
329 // FIXME: Currenty we do not support CTU across C++ and C and across
330 // different dialects of C++.
331 if (LangTo.CPlusPlus != LangFrom.CPlusPlus) {
332 ++NumLangMismatch;
333 return llvm::make_error<IndexError>(index_error_code::lang_mismatch);
334 }
335
336 // If CPP dialects are different then return with error.
337 //
338 // Consider this STL code:
339 // template<typename _Alloc>
340 // struct __alloc_traits
341 // #if __cplusplus >= 201103L
342 // : std::allocator_traits<_Alloc>
343 // #endif
344 // { // ...
345 // };
346 // This class template would create ODR errors during merging the two units,
347 // since in one translation unit the class template has a base class, however
348 // in the other unit it has none.
349 if (LangTo.CPlusPlus11 != LangFrom.CPlusPlus11 ||
350 LangTo.CPlusPlus14 != LangFrom.CPlusPlus14 ||
351 LangTo.CPlusPlus17 != LangFrom.CPlusPlus17 ||
352 LangTo.CPlusPlus20 != LangFrom.CPlusPlus20) {
353 ++NumLangDialectMismatch;
354 return llvm::make_error<IndexError>(
355 index_error_code::lang_dialect_mismatch);
356 }
357
358 TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl();
359 if (const T *ResultDecl = findDefInDeclContext<T>(TU, *LookupName))
360 return importDefinition(ResultDecl, Unit);
361 return llvm::make_error<IndexError>(index_error_code::failed_import);
362 }
363
364 llvm::Expected<const FunctionDecl *>
365 CrossTranslationUnitContext::getCrossTUDefinition(const FunctionDecl *FD,
366 StringRef CrossTUDir,
367 StringRef IndexName,
368 bool DisplayCTUProgress) {
369 return getCrossTUDefinitionImpl(FD, CrossTUDir, IndexName,
370 DisplayCTUProgress);
371 }
372
373 llvm::Expected<const VarDecl *>
374 CrossTranslationUnitContext::getCrossTUDefinition(const VarDecl *VD,
375 StringRef CrossTUDir,
376 StringRef IndexName,
377 bool DisplayCTUProgress) {
378 return getCrossTUDefinitionImpl(VD, CrossTUDir, IndexName,
379 DisplayCTUProgress);
380 }
381
382 void CrossTranslationUnitContext::emitCrossTUDiagnostics(const IndexError &IE) {
383 switch (IE.getCode()) {
384 case index_error_code::missing_index_file:
385 Context.getDiagnostics().Report(diag::err_ctu_error_opening)
386 << IE.getFileName();
387 break;
388 case index_error_code::invalid_index_format:
389 Context.getDiagnostics().Report(diag::err_extdefmap_parsing)
390 << IE.getFileName() << IE.getLineNum();
391 break;
392 case index_error_code::multiple_definitions:
393 Context.getDiagnostics().Report(diag::err_multiple_def_index)
394 << IE.getLineNum();
395 break;
396 case index_error_code::triple_mismatch:
397 Context.getDiagnostics().Report(diag::warn_ctu_incompat_triple)
398 << IE.getFileName() << IE.getTripleToName() << IE.getTripleFromName();
399 break;
400 default:
401 break;
402 }
403 }
404
405 CrossTranslationUnitContext::ASTUnitStorage::ASTUnitStorage(
406 CompilerInstance &CI)
407 : Loader(CI, CI.getAnalyzerOpts().CTUDir,
408 CI.getAnalyzerOpts().CTUInvocationList),
409 LoadGuard(CI.getASTContext().getLangOpts().CPlusPlus
410 ? CI.getAnalyzerOpts().CTUImportCppThreshold
411 : CI.getAnalyzerOpts().CTUImportThreshold) {}
412
413 llvm::Expected<ASTUnit *>
414 CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFile(
415 StringRef FileName, bool DisplayCTUProgress) {
416 // Try the cache first.
417 auto ASTCacheEntry = FileASTUnitMap.find(FileName);
418 if (ASTCacheEntry == FileASTUnitMap.end()) {
419
420 // Do not load if the limit is reached.
421 if (!LoadGuard) {
422 ++NumASTLoadThresholdReached;
423 return llvm::make_error<IndexError>(
424 index_error_code::load_threshold_reached);
425 }
426
427 auto LoadAttempt = Loader.load(FileName);
428
429 if (!LoadAttempt)
430 return LoadAttempt.takeError();
431
432 std::unique_ptr<ASTUnit> LoadedUnit = std::move(LoadAttempt.get());
433
434 // Need the raw pointer and the unique_ptr as well.
435 ASTUnit *Unit = LoadedUnit.get();
436
437 // Update the cache.
438 FileASTUnitMap[FileName] = std::move(LoadedUnit);
439
440 LoadGuard.indicateLoadSuccess();
441
442 if (DisplayCTUProgress)
443 llvm::errs() << "CTU loaded AST file: " << FileName << "\n";
444
445 return Unit;
446
447 } else {
448 // Found in the cache.
449 return ASTCacheEntry->second.get();
450 }
451 }
452
453 llvm::Expected<ASTUnit *>
454 CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFunction(
455 StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName,
456 bool DisplayCTUProgress) {
457 // Try the cache first.
458 auto ASTCacheEntry = NameASTUnitMap.find(FunctionName);
459 if (ASTCacheEntry == NameASTUnitMap.end()) {
460 // Load the ASTUnit from the pre-dumped AST file specified by ASTFileName.
461
462 // Ensure that the Index is loaded, as we need to search in it.
463 if (llvm::Error IndexLoadError =
464 ensureCTUIndexLoaded(CrossTUDir, IndexName))
465 return std::move(IndexLoadError);
466
467 // Check if there is an entry in the index for the function.
468 auto It = NameFileMap.find(FunctionName);
469 if (It == NameFileMap.end()) {
470 ++NumNotInOtherTU;
471 return llvm::make_error<IndexError>(index_error_code::missing_definition);
472 }
473
474 // Search in the index for the filename where the definition of FunctionName
475 // resides.
476 if (llvm::Expected<ASTUnit *> FoundForFile =
477 getASTUnitForFile(It->second, DisplayCTUProgress)) {
478
479 // Update the cache.
480 NameASTUnitMap[FunctionName] = *FoundForFile;
481 return *FoundForFile;
482
483 } else {
484 return FoundForFile.takeError();
485 }
486 } else {
487 // Found in the cache.
488 return ASTCacheEntry->second;
489 }
490 }
491
492 llvm::Expected<std::string>
493 CrossTranslationUnitContext::ASTUnitStorage::getFileForFunction(
494 StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName) {
495 if (llvm::Error IndexLoadError = ensureCTUIndexLoaded(CrossTUDir, IndexName))
496 return std::move(IndexLoadError);
497 return NameFileMap[FunctionName];
498 }
499
500 llvm::Error CrossTranslationUnitContext::ASTUnitStorage::ensureCTUIndexLoaded(
501 StringRef CrossTUDir, StringRef IndexName) {
502 // Dont initialize if the map is filled.
503 if (!NameFileMap.empty())
504 return llvm::Error::success();
505
506 // Get the absolute path to the index file.
507 SmallString<256> IndexFile = CrossTUDir;
508 if (llvm::sys::path::is_absolute(IndexName))
509 IndexFile = IndexName;
510 else
511 llvm::sys::path::append(IndexFile, IndexName);
512
513 if (auto IndexMapping = parseCrossTUIndex(IndexFile)) {
514 // Initialize member map.
515 NameFileMap = *IndexMapping;
516 return llvm::Error::success();
517 } else {
518 // Error while parsing CrossTU index file.
519 return IndexMapping.takeError();
520 };
521 }
522
523 llvm::Expected<ASTUnit *> CrossTranslationUnitContext::loadExternalAST(
524 StringRef LookupName, StringRef CrossTUDir, StringRef IndexName,
525 bool DisplayCTUProgress) {
526 // FIXME: The current implementation only supports loading decls with
527 // a lookup name from a single translation unit. If multiple
528 // translation units contains decls with the same lookup name an
529 // error will be returned.
530
531 // Try to get the value from the heavily cached storage.
532 llvm::Expected<ASTUnit *> Unit = ASTStorage.getASTUnitForFunction(
533 LookupName, CrossTUDir, IndexName, DisplayCTUProgress);
534
535 if (!Unit)
536 return Unit.takeError();
537
538 // Check whether the backing pointer of the Expected is a nullptr.
539 if (!*Unit)
540 return llvm::make_error<IndexError>(
541 index_error_code::failed_to_get_external_ast);
542
543 return Unit;
544 }
545
546 CrossTranslationUnitContext::ASTLoader::ASTLoader(
547 CompilerInstance &CI, StringRef CTUDir, StringRef InvocationListFilePath)
548 : CI(CI), CTUDir(CTUDir), InvocationListFilePath(InvocationListFilePath) {}
549
550 CrossTranslationUnitContext::LoadResultTy
551 CrossTranslationUnitContext::ASTLoader::load(StringRef Identifier) {
552 llvm::SmallString<256> Path;
553 if (llvm::sys::path::is_absolute(Identifier, PathStyle)) {
554 Path = Identifier;
555 } else {
556 Path = CTUDir;
557 llvm::sys::path::append(Path, PathStyle, Identifier);
558 }
559
560 // The path is stored in the InvocationList member in posix style. To
561 // successfully lookup an entry based on filepath, it must be converted.
562 llvm::sys::path::native(Path, PathStyle);
563
564 // Normalize by removing relative path components.
565 llvm::sys::path::remove_dots(Path, /*remove_dot_dot*/ true, PathStyle);
566
567 if (Path.ends_with(".ast"))
568 return loadFromDump(Path);
569 else
570 return loadFromSource(Path);
571 }
572
573 CrossTranslationUnitContext::LoadResultTy
574 CrossTranslationUnitContext::ASTLoader::loadFromDump(StringRef ASTDumpPath) {
575 auto DiagOpts = std::make_shared<DiagnosticOptions>();
576 TextDiagnosticPrinter *DiagClient =
577 new TextDiagnosticPrinter(llvm::errs(), *DiagOpts);
578 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
579 DiagnosticIDs::create(), *DiagOpts, DiagClient);
580 return ASTUnit::LoadFromASTFile(
581 ASTDumpPath, CI.getPCHContainerOperations()->getRawReader(),
582 ASTUnit::LoadEverything, CI.getVirtualFileSystemPtr(), DiagOpts, Diags,
583 CI.getFileSystemOpts(), CI.getHeaderSearchOpts());
584 }
585
586 /// Load the AST from a source-file, which is supposed to be located inside the
587 /// YAML formatted invocation list file under the filesystem path specified by
588 /// \p InvocationList. The invocation list should contain absolute paths.
589 /// \p SourceFilePath is the absolute path of the source file that contains the
590 /// function definition the analysis is looking for. The Index is built by the
591 /// \p clang-extdef-mapping tool, which is also supposed to be generating
592 /// absolute paths.
593 ///
594 /// Proper diagnostic emission requires absolute paths, so even if a future
595 /// change introduces the handling of relative paths, this must be taken into
596 /// consideration.
597 CrossTranslationUnitContext::LoadResultTy
598 CrossTranslationUnitContext::ASTLoader::loadFromSource(
599 StringRef SourceFilePath) {
600
601 if (llvm::Error InitError = lazyInitInvocationList())
602 return std::move(InitError);
603 assert(InvocationList);
604
605 auto Invocation = InvocationList->find(SourceFilePath);
606 if (Invocation == InvocationList->end())
607 return llvm::make_error<IndexError>(
608 index_error_code::invocation_list_lookup_unsuccessful);
609
610 const InvocationListTy::mapped_type &InvocationCommand = Invocation->second;
611
612 SmallVector<const char *, 32> CommandLineArgs(InvocationCommand.size());
613 std::transform(InvocationCommand.begin(), InvocationCommand.end(),
614 CommandLineArgs.begin(),
615 [](auto &&CmdPart) { return CmdPart.c_str(); });
616
617 auto DiagOpts = std::make_shared<DiagnosticOptions>(CI.getDiagnosticOpts());
618 auto *DiagClient = new ForwardingDiagnosticConsumer{CI.getDiagnosticClient()};
619 IntrusiveRefCntPtr<DiagnosticIDs> DiagID{
620 CI.getDiagnostics().getDiagnosticIDs()};
621 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagID, *DiagOpts,
622 DiagClient);
623
624 // This runs the driver which isn't expected to be free of sandbox violations.
625 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
626 return CreateASTUnitFromCommandLine(
627 CommandLineArgs.begin(), (CommandLineArgs.end()),
628 CI.getPCHContainerOperations(), DiagOpts, Diags,
629 CI.getHeaderSearchOpts().ResourceDir);
630 }
631
632 llvm::Expected<InvocationListTy>
633 parseInvocationList(StringRef FileContent, llvm::sys::path::Style PathStyle) {
634 InvocationListTy InvocationList;
635
636 /// LLVM YAML parser is used to extract information from invocation list file.
637 llvm::SourceMgr SM;
638 llvm::yaml::Stream InvocationFile(FileContent, SM);
639
640 /// Only the first document is processed.
641 llvm::yaml::document_iterator FirstInvocationFile = InvocationFile.begin();
642
643 /// There has to be at least one document available.
644 if (FirstInvocationFile == InvocationFile.end())
645 return llvm::make_error<IndexError>(
646 index_error_code::invocation_list_empty);
647
648 llvm::yaml::Node *DocumentRoot = FirstInvocationFile->getRoot();
649 if (!DocumentRoot)
650 return llvm::make_error<IndexError>(
651 index_error_code::invocation_list_wrong_format);
652
653 /// According to the format specified the document must be a mapping, where
654 /// the keys are paths to source files, and values are sequences of invocation
655 /// parts.
656 auto *Mappings = dyn_cast<llvm::yaml::MappingNode>(DocumentRoot);
657 if (!Mappings)
658 return llvm::make_error<IndexError>(
659 index_error_code::invocation_list_wrong_format);
660
661 for (auto &NextMapping : *Mappings) {
662 /// The keys should be strings, which represent a source-file path.
663 auto *Key = dyn_cast<llvm::yaml::ScalarNode>(NextMapping.getKey());
664 if (!Key)
665 return llvm::make_error<IndexError>(
666 index_error_code::invocation_list_wrong_format);
667
668 SmallString<32> ValueStorage;
669 StringRef SourcePath = Key->getValue(ValueStorage);
670
671 // Store paths with PathStyle directory separator.
672 SmallString<32> NativeSourcePath(SourcePath);
673 llvm::sys::path::native(NativeSourcePath, PathStyle);
674
675 StringRef InvocationKey = NativeSourcePath;
676
677 if (InvocationList.contains(InvocationKey))
678 return llvm::make_error<IndexError>(
679 index_error_code::invocation_list_ambiguous);
680
681 /// The values should be sequences of strings, each representing a part of
682 /// the invocation.
683 auto *Args = dyn_cast<llvm::yaml::SequenceNode>(NextMapping.getValue());
684 if (!Args)
685 return llvm::make_error<IndexError>(
686 index_error_code::invocation_list_wrong_format);
687
688 for (auto &Arg : *Args) {
689 auto *CmdString = dyn_cast<llvm::yaml::ScalarNode>(&Arg);
690 if (!CmdString)
691 return llvm::make_error<IndexError>(
692 index_error_code::invocation_list_wrong_format);
693 /// Every conversion starts with an empty working storage, as it is not
694 /// clear if this is a requirement of the YAML parser.
695 ValueStorage.clear();
696 InvocationList[InvocationKey].emplace_back(
697 CmdString->getValue(ValueStorage));
698 }
699
700 if (InvocationList[InvocationKey].empty())
701 return llvm::make_error<IndexError>(
702 index_error_code::invocation_list_wrong_format);
703 }
704
705 return InvocationList;
706 }
707
708 llvm::Error CrossTranslationUnitContext::ASTLoader::lazyInitInvocationList() {
709 /// Lazily initialize the invocation list member used for on-demand parsing.
710 if (InvocationList)
711 return llvm::Error::success();
712 if (index_error_code::success != PreviousParsingResult)
713 return llvm::make_error<IndexError>(PreviousParsingResult);
714
715 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileContent =
716 CI.getVirtualFileSystem().getBufferForFile(InvocationListFilePath);
717 if (!FileContent) {
718 PreviousParsingResult = index_error_code::invocation_list_file_not_found;
719 return llvm::make_error<IndexError>(PreviousParsingResult);
720 }
721 std::unique_ptr<llvm::MemoryBuffer> ContentBuffer = std::move(*FileContent);
722 assert(ContentBuffer && "If no error was produced after loading, the pointer "
723 "should not be nullptr.");
724
725 llvm::Expected<InvocationListTy> ExpectedInvocationList =
726 parseInvocationList(ContentBuffer->getBuffer(), PathStyle);
727
728 // Handle the error to store the code for next call to this function.
729 if (!ExpectedInvocationList) {
730 llvm::handleAllErrors(
731 ExpectedInvocationList.takeError(),
732 [&](const IndexError &E) { PreviousParsingResult = E.getCode(); });
733 return llvm::make_error<IndexError>(PreviousParsingResult);
734 }
735
736 InvocationList = *ExpectedInvocationList;
737
738 return llvm::Error::success();
739 }
740
741 template <typename T>
742 llvm::Expected<const T *>
743 CrossTranslationUnitContext::importDefinitionImpl(const T *D, ASTUnit *Unit) {
744 assert(hasBodyOrInit(D) && "Decls to be imported should have body or init.");
745
746 assert(&D->getASTContext() == &Unit->getASTContext() &&
747 "ASTContext of Decl and the unit should match.");
748 ASTImporter &Importer = getOrCreateASTImporter(Unit);
749
750 auto ToDeclOrError = Importer.Import(D);
751 if (!ToDeclOrError) {
752 handleAllErrors(ToDeclOrError.takeError(), [&](const ASTImportError &IE) {
753 switch (IE.Error) {
754 case ASTImportError::NameConflict:
755 ++NumNameConflicts;
756 break;
757 case ASTImportError::UnsupportedConstruct:
758 ++NumUnsupportedNodeFound;
759 break;
760 case ASTImportError::Unknown:
761 llvm_unreachable("Unknown import error happened.");
762 break;
763 }
764 });
765 return llvm::make_error<IndexError>(index_error_code::failed_import);
766 }
767 auto *ToDecl = cast<T>(*ToDeclOrError);
768 assert(hasBodyOrInit(ToDecl) && "Imported Decl should have body or init.");
769 ++NumGetCTUSuccess;
770
771 // Parent map is invalidated after changing the AST.
772 ToDecl->getASTContext().getParentMapContext().clear();
773
774 return ToDecl;
775 }
776
777 llvm::Expected<const FunctionDecl *>
778 CrossTranslationUnitContext::importDefinition(const FunctionDecl *FD,
779 ASTUnit *Unit) {
780 return importDefinitionImpl(FD, Unit);
781 }
782
783 llvm::Expected<const VarDecl *>
784 CrossTranslationUnitContext::importDefinition(const VarDecl *VD,
785 ASTUnit *Unit) {
786 return importDefinitionImpl(VD, Unit);
787 }
788
789 void CrossTranslationUnitContext::lazyInitImporterSharedSt(
790 TranslationUnitDecl *ToTU) {
791 if (!ImporterSharedSt)
792 ImporterSharedSt = std::make_shared<ASTImporterSharedState>(*ToTU);
793 }
794
795 ASTImporter &
796 CrossTranslationUnitContext::getOrCreateASTImporter(ASTUnit *Unit) {
797 ASTContext &From = Unit->getASTContext();
798
799 auto I = ASTUnitImporterMap.find(From.getTranslationUnitDecl());
800 if (I != ASTUnitImporterMap.end())
801 return *I->second;
802 lazyInitImporterSharedSt(Context.getTranslationUnitDecl());
803 ASTImporter *NewImporter = new ASTImporter(
804 Context, Context.getSourceManager().getFileManager(), From,
805 From.getSourceManager().getFileManager(), false, ImporterSharedSt);
806 ASTUnitImporterMap[From.getTranslationUnitDecl()].reset(NewImporter);
807 return *NewImporter;
808 }
809
810 std::optional<clang::MacroExpansionContext>
811 CrossTranslationUnitContext::getMacroExpansionContextForSourceLocation(
812 const clang::SourceLocation &ToLoc) const {
813 // FIXME: Implement: Record such a context for every imported ASTUnit; lookup.
814 return std::nullopt;
815 }
816
817 bool CrossTranslationUnitContext::isImportedAsNew(const Decl *ToDecl) const {
818 if (!ImporterSharedSt)
819 return false;
820 return ImporterSharedSt->isNewDecl(const_cast<Decl *>(ToDecl));
821 }
822
823 bool CrossTranslationUnitContext::hasError(const Decl *ToDecl) const {
824 if (!ImporterSharedSt)
825 return false;
826 return static_cast<bool>(
827 ImporterSharedSt->getImportDeclErrorIfAny(const_cast<Decl *>(ToDecl)));
828 }
829
830 } // namespace cross_tu
831 } // namespace clang