clang 23.0.0git
CrossTranslationUnit.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
14#include "clang/AST/Decl.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
39namespace clang {
40namespace cross_tu {
41
42namespace {
43
44#define DEBUG_TYPE "CrossTranslationUnit"
45STATISTIC(NumGetCTUCalled, "The # of getCTUDefinition function called");
47 NumNotInOtherTU,
48 "The # of getCTUDefinition called but the function is not in any other TU");
49STATISTIC(NumGetCTUSuccess,
50 "The # of getCTUDefinition successfully returned the "
51 "requested function's body");
52STATISTIC(NumUnsupportedNodeFound, "The # of imports when the ASTImporter "
53 "encountered an unsupported AST Node");
54STATISTIC(NumNameConflicts, "The # of imports when the ASTImporter "
55 "encountered an ODR error");
56STATISTIC(NumTripleMismatch, "The # of triple mismatches");
57STATISTIC(NumLangMismatch, "The # of language mismatches");
58STATISTIC(NumLangDialectMismatch, "The # of language dialect mismatches");
59STATISTIC(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.
64bool 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.
92class IndexErrorCategory : public std::error_category {
93public:
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)) {
99 // There should not be a success error. Jump to unreachable directly.
100 // Add this case to make the compiler stop complaining.
101 break;
103 return "An unknown error has occurred.";
105 return "The index file is missing.";
107 return "Invalid index file format.";
109 return "Multiple definitions in the index file.";
111 return "Missing definition from the index file.";
113 return "Failed to import the definition.";
115 return "Failed to load external AST source.";
117 return "Failed to generate USR.";
119 return "Triple mismatch";
121 return "Language mismatch";
123 return "Language dialect mismatch";
125 return "Load threshold reached";
127 return "Invocation list file contains multiple references to the same "
128 "source file.";
130 return "Invocation list file is not found.";
132 return "Invocation list file is empty.";
134 return "Invocation list file is in wrong format.";
136 return "Invocation list file does not contain the requested source file.";
137 }
138 llvm_unreachable("Unrecognized index_error_code.");
139 }
140};
141
142static llvm::ManagedStatic<IndexErrorCategory> Category;
143} // end anonymous namespace
144
145char IndexError::ID;
146
147void IndexError::log(raw_ostream &OS) const {
148 OS << Category->message(static_cast<int>(Code)) << '\n';
149}
150
151std::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>".
161static 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
185parseCrossTUIndex(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 InsertionOccurred;
206 std::tie(std::ignore, InsertionOccurred) =
207 Result.try_emplace(LookupName, FilePath.begin(), FilePath.end());
208 if (!InsertionOccurred)
209 return llvm::make_error<IndexError>(
210 index_error_code::multiple_definitions, IndexPath.str(), LineNo);
211
212 ++LineNo;
213 }
214 return Result;
215}
216
217std::string
218createCrossTUIndexString(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
226bool shouldImport(const VarDecl *VD, const ASTContext &ACtx) {
227 CanQualType CT = ACtx.getCanonicalType(VD->getType());
228 return CT.isConstQualified() && VD->getType().isTrivialType(ACtx);
229}
230
231static bool hasBodyOrInit(const FunctionDecl *D, const FunctionDecl *&DefD) {
232 return D->hasBody(DefD);
233}
234static bool hasBodyOrInit(const VarDecl *D, const VarDecl *&DefD) {
235 return D->getAnyInitializer(DefD);
236}
237template <typename T> static bool hasBodyOrInit(const T *D) {
238 const T *Unused;
239 return hasBodyOrInit(D, Unused);
240}
241
243 : Context(CI.getASTContext()), ASTStorage(CI) {
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
255
256std::optional<std::string>
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.
267template <typename T>
268const T *
269CrossTranslationUnitContext::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
290template <typename T>
291llvm::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>(
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>(
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
364llvm::Expected<const FunctionDecl *>
366 StringRef CrossTUDir,
367 StringRef IndexName,
368 bool DisplayCTUProgress) {
369 return getCrossTUDefinitionImpl(FD, CrossTUDir, IndexName,
370 DisplayCTUProgress);
371}
372
375 StringRef CrossTUDir,
376 StringRef IndexName,
377 bool DisplayCTUProgress) {
378 return getCrossTUDefinitionImpl(VD, CrossTUDir, IndexName,
379 DisplayCTUProgress);
380}
381
383 switch (IE.getCode()) {
385 Context.getDiagnostics().Report(diag::err_ctu_error_opening)
386 << IE.getFileName();
387 break;
389 Context.getDiagnostics().Report(diag::err_extdefmap_parsing)
390 << IE.getFileName() << IE.getLineNum();
391 break;
393 Context.getDiagnostics().Report(diag::err_multiple_def_index)
394 << IE.getLineNum();
395 break;
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
405CrossTranslationUnitContext::ASTUnitStorage::ASTUnitStorage(
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
414CrossTranslationUnitContext::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>(
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
453llvm::Expected<ASTUnit *>
454CrossTranslationUnitContext::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
492llvm::Expected<std::string>
493CrossTranslationUnitContext::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
500llvm::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
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>(
542
543 return Unit;
544}
545
546CrossTranslationUnitContext::ASTLoader::ASTLoader(
547 CompilerInstance &CI, StringRef CTUDir, StringRef InvocationListFilePath)
548 : CI(CI), CTUDir(CTUDir), InvocationListFilePath(InvocationListFilePath) {}
549
550CrossTranslationUnitContext::LoadResultTy
551CrossTranslationUnitContext::ASTLoader::load(StringRef Identifier) {
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
573CrossTranslationUnitContext::LoadResultTy
574CrossTranslationUnitContext::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);
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.
597CrossTranslationUnitContext::LoadResultTy
598CrossTranslationUnitContext::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>(
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();
627 CommandLineArgs.begin(), (CommandLineArgs.end()),
628 CI.getPCHContainerOperations(), DiagOpts, Diags,
629 CI.getHeaderSearchOpts().ResourceDir);
630}
631
632llvm::Expected<InvocationListTy>
633parseInvocationList(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>(
647
648 llvm::yaml::Node *DocumentRoot = FirstInvocationFile->getRoot();
649 if (!DocumentRoot)
650 return llvm::make_error<IndexError>(
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>(
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>(
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>(
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>(
687
688 for (auto &Arg : *Args) {
689 auto *CmdString = dyn_cast<llvm::yaml::ScalarNode>(&Arg);
690 if (!CmdString)
691 return llvm::make_error<IndexError>(
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>(
703 }
704
705 return InvocationList;
706}
707
708llvm::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) {
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
741template <typename T>
742llvm::Expected<const T *>
743CrossTranslationUnitContext::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
777llvm::Expected<const FunctionDecl *>
779 ASTUnit *Unit) {
780 return importDefinitionImpl(FD, Unit);
781}
782
785 ASTUnit *Unit) {
786 return importDefinitionImpl(VD, Unit);
787}
788
789void CrossTranslationUnitContext::lazyInitImporterSharedSt(
790 TranslationUnitDecl *ToTU) {
791 if (!ImporterSharedSt)
792 ImporterSharedSt = std::make_shared<ASTImporterSharedState>(*ToTU);
793}
794
796CrossTranslationUnitContext::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
810std::optional<clang::MacroExpansionContext>
812 const clang::SourceLocation &ToLoc) const {
813 // FIXME: Implement: Record such a context for every imported ASTUnit; lookup.
814 return std::nullopt;
815}
816
818 if (!ImporterSharedSt)
819 return false;
820 return ImporterSharedSt->isNewDecl(const_cast<Decl *>(ToDecl));
821}
822
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
STATISTIC(NumObjCCallEdges, "Number of Objective-C method call edges")
#define SM(sm)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:851
TranslationUnitDecl * getTranslationUnitDecl() const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
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
static std::unique_ptr< ASTUnit > LoadFromASTFile(StringRef Filename, const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, const HeaderSearchOptions &HSOpts, const LangOptions *LangOpts=nullptr, bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, bool AllowASTWithCompilerErrors=false, bool UserFilesAreVolatile=false)
Create a ASTUnit from an AST file.
Definition ASTUnit.cpp:693
@ LoadEverything
Load everything, including Sema.
Definition ASTUnit.h:714
const ASTContext & getASTContext() const
Definition ASTUnit.h:449
unsigned ShouldEmitErrorsOnInvalidConfigValue
bool isConstQualified() const
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
AnalyzerOptions & getAnalyzerOpts()
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Represents a function declaration or definition.
Definition Decl.h:2000
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3199
bool isTrivialType(const ASTContext &Context) const
Return true if this is a trivial type per (C++0x [basic.types]p9)
Definition Type.cpp:2758
Encodes a location in the source.
FileManager & getFileManager() const
The top declaration context.
Definition Decl.h:105
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
void emitCrossTUDiagnostics(const IndexError &IE)
Emit diagnostics for the user for potential configuration errors.
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 ...
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
std::string getTripleToName() const
std::error_code convertToErrorCode() const override
void log(raw_ostream &OS) const override
std::string getTripleFromName() const
Defines the clang::TargetInfo interface.
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)
Parse the YAML formatted invocation list file content FileContent.
static bool hasBodyOrInit(const FunctionDecl *D, const FunctionDecl *&DefD)
static bool parseCrossTUIndexItem(StringRef LineRef, StringRef &LookupName, StringRef &FilePath)
Parse one line of the input CTU index file.
llvm::StringMap< llvm::SmallVector< std::string, 32 > > InvocationListTy
bool generateUSRForDecl(const Decl *D, SmallVectorImpl< char > &Buf)
Generate a USR for a Decl, including the USR prefix.
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ CPlusPlus
std::unique_ptr< ASTUnit > CreateASTUnitFromCommandLine(const char **ArgBegin, const char **ArgEnd, std::shared_ptr< PCHContainerOperations > PCHContainerOps, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, StringRef ResourceFilesPath, bool StorePreamblesInMemory=false, StringRef PreambleStoragePath=StringRef(), bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, ArrayRef< ASTUnit::RemappedFile > RemappedFiles={}, bool RemappedFilesKeepOriginalName=true, unsigned PrecompilePreambleAfterNParses=0, TranslationUnitKind TUKind=TU_Complete, bool CacheCodeCompletionResults=false, bool IncludeBriefCommentsInCodeCompletion=false, bool AllowPCHWithCompilerErrors=false, SkipFunctionBodiesScope SkipFunctionBodies=SkipFunctionBodiesScope::None, bool SingleFileParse=false, bool UserFilesAreVolatile=false, bool ForSerialization=false, bool RetainExcludedConditionalBlocks=false, std::optional< StringRef > ModuleFormat=std::nullopt, std::unique_ptr< ASTUnit > *ErrAST=nullptr, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Create an ASTUnit from a vector of command line arguments, which must specify exactly one source file...
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327