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/Basic/TargetInfo.h" 16 #include "clang/CrossTU/CrossTUDiagnostic.h" 17 #include "clang/Frontend/ASTUnit.h" 18 #include "clang/Frontend/CompilerInstance.h" 19 #include "clang/Frontend/TextDiagnosticPrinter.h" 20 #include "clang/Index/USRGeneration.h" 21 #include "llvm/ADT/Triple.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Support/ErrorHandling.h" 24 #include "llvm/Support/ManagedStatic.h" 25 #include "llvm/Support/Path.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include <fstream> 28 #include <sstream> 29 30 namespace clang { 31 namespace cross_tu { 32 33 namespace { 34 35 #define DEBUG_TYPE "CrossTranslationUnit" 36 STATISTIC(NumGetCTUCalled, "The # of getCTUDefinition function called"); 37 STATISTIC( 38 NumNotInOtherTU, 39 "The # of getCTUDefinition called but the function is not in any other TU"); 40 STATISTIC(NumGetCTUSuccess, 41 "The # of getCTUDefinition successfully returned the " 42 "requested function's body"); 43 STATISTIC(NumUnsupportedNodeFound, "The # of imports when the ASTImporter " 44 "encountered an unsupported AST Node"); 45 STATISTIC(NumNameConflicts, "The # of imports when the ASTImporter " 46 "encountered an ODR error"); 47 STATISTIC(NumTripleMismatch, "The # of triple mismatches"); 48 STATISTIC(NumLangMismatch, "The # of language mismatches"); 49 STATISTIC(NumLangDialectMismatch, "The # of language dialect mismatches"); 50 STATISTIC(NumASTLoadThresholdReached, 51 "The # of ASTs not loaded because of threshold"); 52 53 // Same as Triple's equality operator, but we check a field only if that is 54 // known in both instances. 55 bool hasEqualKnownFields(const llvm::Triple &Lhs, const llvm::Triple &Rhs) { 56 using llvm::Triple; 57 if (Lhs.getArch() != Triple::UnknownArch && 58 Rhs.getArch() != Triple::UnknownArch && Lhs.getArch() != Rhs.getArch()) 59 return false; 60 if (Lhs.getSubArch() != Triple::NoSubArch && 61 Rhs.getSubArch() != Triple::NoSubArch && 62 Lhs.getSubArch() != Rhs.getSubArch()) 63 return false; 64 if (Lhs.getVendor() != Triple::UnknownVendor && 65 Rhs.getVendor() != Triple::UnknownVendor && 66 Lhs.getVendor() != Rhs.getVendor()) 67 return false; 68 if (!Lhs.isOSUnknown() && !Rhs.isOSUnknown() && 69 Lhs.getOS() != Rhs.getOS()) 70 return false; 71 if (Lhs.getEnvironment() != Triple::UnknownEnvironment && 72 Rhs.getEnvironment() != Triple::UnknownEnvironment && 73 Lhs.getEnvironment() != Rhs.getEnvironment()) 74 return false; 75 if (Lhs.getObjectFormat() != Triple::UnknownObjectFormat && 76 Rhs.getObjectFormat() != Triple::UnknownObjectFormat && 77 Lhs.getObjectFormat() != Rhs.getObjectFormat()) 78 return false; 79 return true; 80 } 81 82 // FIXME: This class is will be removed after the transition to llvm::Error. 83 class IndexErrorCategory : public std::error_category { 84 public: 85 const char *name() const noexcept override { return "clang.index"; } 86 87 std::string message(int Condition) const override { 88 switch (static_cast<index_error_code>(Condition)) { 89 case index_error_code::unspecified: 90 return "An unknown error has occurred."; 91 case index_error_code::missing_index_file: 92 return "The index file is missing."; 93 case index_error_code::invalid_index_format: 94 return "Invalid index file format."; 95 case index_error_code::multiple_definitions: 96 return "Multiple definitions in the index file."; 97 case index_error_code::missing_definition: 98 return "Missing definition from the index file."; 99 case index_error_code::failed_import: 100 return "Failed to import the definition."; 101 case index_error_code::failed_to_get_external_ast: 102 return "Failed to load external AST source."; 103 case index_error_code::failed_to_generate_usr: 104 return "Failed to generate USR."; 105 case index_error_code::triple_mismatch: 106 return "Triple mismatch"; 107 case index_error_code::lang_mismatch: 108 return "Language mismatch"; 109 case index_error_code::lang_dialect_mismatch: 110 return "Language dialect mismatch"; 111 case index_error_code::load_threshold_reached: 112 return "Load threshold reached"; 113 } 114 llvm_unreachable("Unrecognized index_error_code."); 115 } 116 }; 117 118 static llvm::ManagedStatic<IndexErrorCategory> Category; 119 } // end anonymous namespace 120 121 char IndexError::ID; 122 123 void IndexError::log(raw_ostream &OS) const { 124 OS << Category->message(static_cast<int>(Code)) << '\n'; 125 } 126 127 std::error_code IndexError::convertToErrorCode() const { 128 return std::error_code(static_cast<int>(Code), *Category); 129 } 130 131 llvm::Expected<llvm::StringMap<std::string>> 132 parseCrossTUIndex(StringRef IndexPath, StringRef CrossTUDir) { 133 std::ifstream ExternalMapFile(IndexPath); 134 if (!ExternalMapFile) 135 return llvm::make_error<IndexError>(index_error_code::missing_index_file, 136 IndexPath.str()); 137 138 llvm::StringMap<std::string> Result; 139 std::string Line; 140 unsigned LineNo = 1; 141 while (std::getline(ExternalMapFile, Line)) { 142 const size_t Pos = Line.find(" "); 143 if (Pos > 0 && Pos != std::string::npos) { 144 StringRef LineRef{Line}; 145 StringRef LookupName = LineRef.substr(0, Pos); 146 if (Result.count(LookupName)) 147 return llvm::make_error<IndexError>( 148 index_error_code::multiple_definitions, IndexPath.str(), LineNo); 149 StringRef FileName = LineRef.substr(Pos + 1); 150 SmallString<256> FilePath = CrossTUDir; 151 llvm::sys::path::append(FilePath, FileName); 152 Result[LookupName] = FilePath.str().str(); 153 } else 154 return llvm::make_error<IndexError>( 155 index_error_code::invalid_index_format, IndexPath.str(), LineNo); 156 LineNo++; 157 } 158 return Result; 159 } 160 161 std::string 162 createCrossTUIndexString(const llvm::StringMap<std::string> &Index) { 163 std::ostringstream Result; 164 for (const auto &E : Index) 165 Result << E.getKey().str() << " " << E.getValue() << '\n'; 166 return Result.str(); 167 } 168 169 bool containsConst(const VarDecl *VD, const ASTContext &ACtx) { 170 CanQualType CT = ACtx.getCanonicalType(VD->getType()); 171 if (!CT.isConstQualified()) { 172 const RecordType *RTy = CT->getAs<RecordType>(); 173 if (!RTy || !RTy->hasConstFields()) 174 return false; 175 } 176 return true; 177 } 178 179 static bool hasBodyOrInit(const FunctionDecl *D, const FunctionDecl *&DefD) { 180 return D->hasBody(DefD); 181 } 182 static bool hasBodyOrInit(const VarDecl *D, const VarDecl *&DefD) { 183 return D->getAnyInitializer(DefD); 184 } 185 template <typename T> static bool hasBodyOrInit(const T *D) { 186 const T *Unused; 187 return hasBodyOrInit(D, Unused); 188 } 189 190 CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI) 191 : Context(CI.getASTContext()), ASTStorage(CI), 192 CTULoadThreshold(CI.getAnalyzerOpts()->CTUImportThreshold) {} 193 194 CrossTranslationUnitContext::~CrossTranslationUnitContext() {} 195 196 llvm::Optional<std::string> 197 CrossTranslationUnitContext::getLookupName(const NamedDecl *ND) { 198 SmallString<128> DeclUSR; 199 bool Ret = index::generateUSRForDecl(ND, DeclUSR); 200 if (Ret) 201 return {}; 202 return std::string(DeclUSR.str()); 203 } 204 205 /// Recursively visits the decls of a DeclContext, and returns one with the 206 /// given USR. 207 template <typename T> 208 const T * 209 CrossTranslationUnitContext::findDefInDeclContext(const DeclContext *DC, 210 StringRef LookupName) { 211 assert(DC && "Declaration Context must not be null"); 212 for (const Decl *D : DC->decls()) { 213 const auto *SubDC = dyn_cast<DeclContext>(D); 214 if (SubDC) 215 if (const auto *ND = findDefInDeclContext<T>(SubDC, LookupName)) 216 return ND; 217 218 const auto *ND = dyn_cast<T>(D); 219 const T *ResultDecl; 220 if (!ND || !hasBodyOrInit(ND, ResultDecl)) 221 continue; 222 llvm::Optional<std::string> ResultLookupName = getLookupName(ResultDecl); 223 if (!ResultLookupName || *ResultLookupName != LookupName) 224 continue; 225 return ResultDecl; 226 } 227 return nullptr; 228 } 229 230 template <typename T> 231 llvm::Expected<const T *> CrossTranslationUnitContext::getCrossTUDefinitionImpl( 232 const T *D, StringRef CrossTUDir, StringRef IndexName, 233 bool DisplayCTUProgress) { 234 assert(D && "D is missing, bad call to this function!"); 235 assert(!hasBodyOrInit(D) && 236 "D has a body or init in current translation unit!"); 237 ++NumGetCTUCalled; 238 const llvm::Optional<std::string> LookupName = getLookupName(D); 239 if (!LookupName) 240 return llvm::make_error<IndexError>( 241 index_error_code::failed_to_generate_usr); 242 llvm::Expected<ASTUnit *> ASTUnitOrError = 243 loadExternalAST(*LookupName, CrossTUDir, IndexName, DisplayCTUProgress); 244 if (!ASTUnitOrError) 245 return ASTUnitOrError.takeError(); 246 ASTUnit *Unit = *ASTUnitOrError; 247 assert(&Unit->getFileManager() == 248 &Unit->getASTContext().getSourceManager().getFileManager()); 249 250 const llvm::Triple &TripleTo = Context.getTargetInfo().getTriple(); 251 const llvm::Triple &TripleFrom = 252 Unit->getASTContext().getTargetInfo().getTriple(); 253 // The imported AST had been generated for a different target. 254 // Some parts of the triple in the loaded ASTContext can be unknown while the 255 // very same parts in the target ASTContext are known. Thus we check for the 256 // known parts only. 257 if (!hasEqualKnownFields(TripleTo, TripleFrom)) { 258 // TODO: Pass the SourceLocation of the CallExpression for more precise 259 // diagnostics. 260 ++NumTripleMismatch; 261 return llvm::make_error<IndexError>(index_error_code::triple_mismatch, 262 Unit->getMainFileName(), TripleTo.str(), 263 TripleFrom.str()); 264 } 265 266 const auto &LangTo = Context.getLangOpts(); 267 const auto &LangFrom = Unit->getASTContext().getLangOpts(); 268 269 // FIXME: Currenty we do not support CTU across C++ and C and across 270 // different dialects of C++. 271 if (LangTo.CPlusPlus != LangFrom.CPlusPlus) { 272 ++NumLangMismatch; 273 return llvm::make_error<IndexError>(index_error_code::lang_mismatch); 274 } 275 276 // If CPP dialects are different then return with error. 277 // 278 // Consider this STL code: 279 // template<typename _Alloc> 280 // struct __alloc_traits 281 // #if __cplusplus >= 201103L 282 // : std::allocator_traits<_Alloc> 283 // #endif 284 // { // ... 285 // }; 286 // This class template would create ODR errors during merging the two units, 287 // since in one translation unit the class template has a base class, however 288 // in the other unit it has none. 289 if (LangTo.CPlusPlus11 != LangFrom.CPlusPlus11 || 290 LangTo.CPlusPlus14 != LangFrom.CPlusPlus14 || 291 LangTo.CPlusPlus17 != LangFrom.CPlusPlus17 || 292 LangTo.CPlusPlus2a != LangFrom.CPlusPlus2a) { 293 ++NumLangDialectMismatch; 294 return llvm::make_error<IndexError>( 295 index_error_code::lang_dialect_mismatch); 296 } 297 298 TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl(); 299 if (const T *ResultDecl = findDefInDeclContext<T>(TU, *LookupName)) 300 return importDefinition(ResultDecl, Unit); 301 return llvm::make_error<IndexError>(index_error_code::failed_import); 302 } 303 304 llvm::Expected<const FunctionDecl *> 305 CrossTranslationUnitContext::getCrossTUDefinition(const FunctionDecl *FD, 306 StringRef CrossTUDir, 307 StringRef IndexName, 308 bool DisplayCTUProgress) { 309 return getCrossTUDefinitionImpl(FD, CrossTUDir, IndexName, 310 DisplayCTUProgress); 311 } 312 313 llvm::Expected<const VarDecl *> 314 CrossTranslationUnitContext::getCrossTUDefinition(const VarDecl *VD, 315 StringRef CrossTUDir, 316 StringRef IndexName, 317 bool DisplayCTUProgress) { 318 return getCrossTUDefinitionImpl(VD, CrossTUDir, IndexName, 319 DisplayCTUProgress); 320 } 321 322 void CrossTranslationUnitContext::emitCrossTUDiagnostics(const IndexError &IE) { 323 switch (IE.getCode()) { 324 case index_error_code::missing_index_file: 325 Context.getDiagnostics().Report(diag::err_ctu_error_opening) 326 << IE.getFileName(); 327 break; 328 case index_error_code::invalid_index_format: 329 Context.getDiagnostics().Report(diag::err_extdefmap_parsing) 330 << IE.getFileName() << IE.getLineNum(); 331 break; 332 case index_error_code::multiple_definitions: 333 Context.getDiagnostics().Report(diag::err_multiple_def_index) 334 << IE.getLineNum(); 335 break; 336 case index_error_code::triple_mismatch: 337 Context.getDiagnostics().Report(diag::warn_ctu_incompat_triple) 338 << IE.getFileName() << IE.getTripleToName() << IE.getTripleFromName(); 339 break; 340 default: 341 break; 342 } 343 } 344 345 CrossTranslationUnitContext::ASTFileLoader::ASTFileLoader( 346 const CompilerInstance &CI) 347 : CI(CI) {} 348 349 std::unique_ptr<ASTUnit> 350 CrossTranslationUnitContext::ASTFileLoader::operator()(StringRef ASTFilePath) { 351 // Load AST from ast-dump. 352 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); 353 TextDiagnosticPrinter *DiagClient = 354 new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts); 355 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 356 IntrusiveRefCntPtr<DiagnosticsEngine> Diags( 357 new DiagnosticsEngine(DiagID, &*DiagOpts, DiagClient)); 358 359 return ASTUnit::LoadFromASTFile( 360 ASTFilePath, CI.getPCHContainerOperations()->getRawReader(), 361 ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts()); 362 } 363 364 CrossTranslationUnitContext::ASTUnitStorage::ASTUnitStorage( 365 const CompilerInstance &CI) 366 : FileAccessor(CI) {} 367 368 llvm::Expected<ASTUnit *> 369 CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFile(StringRef FileName) { 370 // Try the cache first. 371 auto ASTCacheEntry = FileASTUnitMap.find(FileName); 372 if (ASTCacheEntry == FileASTUnitMap.end()) { 373 // Load the ASTUnit from the pre-dumped AST file specified by ASTFileName. 374 std::unique_ptr<ASTUnit> LoadedUnit = FileAccessor(FileName); 375 376 // Need the raw pointer and the unique_ptr as well. 377 ASTUnit* Unit = LoadedUnit.get(); 378 379 // Update the cache. 380 FileASTUnitMap[FileName] = std::move(LoadedUnit); 381 return Unit; 382 383 } else { 384 // Found in the cache. 385 return ASTCacheEntry->second.get(); 386 } 387 } 388 389 llvm::Expected<ASTUnit *> 390 CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFunction( 391 StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName) { 392 // Try the cache first. 393 auto ASTCacheEntry = NameASTUnitMap.find(FunctionName); 394 if (ASTCacheEntry == NameASTUnitMap.end()) { 395 // Load the ASTUnit from the pre-dumped AST file specified by ASTFileName. 396 397 // Ensure that the Index is loaded, as we need to search in it. 398 if (llvm::Error IndexLoadError = 399 ensureCTUIndexLoaded(CrossTUDir, IndexName)) 400 return std::move(IndexLoadError); 401 402 // Check if there is and entry in the index for the function. 403 if (!NameFileMap.count(FunctionName)) { 404 ++NumNotInOtherTU; 405 return llvm::make_error<IndexError>(index_error_code::missing_definition); 406 } 407 408 // Search in the index for the filename where the definition of FuncitonName 409 // resides. 410 if (llvm::Expected<ASTUnit *> FoundForFile = 411 getASTUnitForFile(NameFileMap[FunctionName])) { 412 413 // Update the cache. 414 NameASTUnitMap[FunctionName] = *FoundForFile; 415 return *FoundForFile; 416 417 } else { 418 return FoundForFile.takeError(); 419 } 420 } else { 421 // Found in the cache. 422 return ASTCacheEntry->second; 423 } 424 } 425 426 llvm::Expected<std::string> 427 CrossTranslationUnitContext::ASTUnitStorage::getFileForFunction( 428 StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName) { 429 if (llvm::Error IndexLoadError = ensureCTUIndexLoaded(CrossTUDir, IndexName)) 430 return std::move(IndexLoadError); 431 return NameFileMap[FunctionName]; 432 } 433 434 llvm::Error CrossTranslationUnitContext::ASTUnitStorage::ensureCTUIndexLoaded( 435 StringRef CrossTUDir, StringRef IndexName) { 436 // Dont initialize if the map is filled. 437 if (!NameFileMap.empty()) 438 return llvm::Error::success(); 439 440 // Get the absolute path to the index file. 441 SmallString<256> IndexFile = CrossTUDir; 442 if (llvm::sys::path::is_absolute(IndexName)) 443 IndexFile = IndexName; 444 else 445 llvm::sys::path::append(IndexFile, IndexName); 446 447 if (auto IndexMapping = parseCrossTUIndex(IndexFile, CrossTUDir)) { 448 // Initialize member map. 449 NameFileMap = *IndexMapping; 450 return llvm::Error::success(); 451 } else { 452 // Error while parsing CrossTU index file. 453 return IndexMapping.takeError(); 454 }; 455 } 456 457 llvm::Expected<ASTUnit *> CrossTranslationUnitContext::loadExternalAST( 458 StringRef LookupName, StringRef CrossTUDir, StringRef IndexName, 459 bool DisplayCTUProgress) { 460 // FIXME: The current implementation only supports loading decls with 461 // a lookup name from a single translation unit. If multiple 462 // translation units contains decls with the same lookup name an 463 // error will be returned. 464 465 // RAII incrementing counter is used to count successful loads. 466 LoadGuard LoadOperation(CTULoadThreshold, NumASTLoaded); 467 468 // If import threshold is reached, don't import anything. 469 if (!LoadOperation) { 470 ++NumASTLoadThresholdReached; 471 return llvm::make_error<IndexError>( 472 index_error_code::load_threshold_reached); 473 } 474 475 // Try to get the value from the heavily cached storage. 476 llvm::Expected<ASTUnit *> Unit = 477 ASTStorage.getASTUnitForFunction(LookupName, CrossTUDir, IndexName); 478 479 if (!Unit) 480 return Unit.takeError(); 481 482 // Check whether the backing pointer of the Expected is a nullptr. 483 if (!*Unit) 484 return llvm::make_error<IndexError>( 485 index_error_code::failed_to_get_external_ast); 486 487 // The backing pointer is not null, loading was successful. If anything goes 488 // wrong from this point on, the AST is already stored, so the load part is 489 // finished. 490 LoadOperation.storedSuccessfully(); 491 492 if (DisplayCTUProgress) { 493 if (llvm::Expected<std::string> FileName = 494 ASTStorage.getFileForFunction(LookupName, CrossTUDir, IndexName)) 495 llvm::errs() << "CTU loaded AST file: " << *FileName << "\n"; 496 else 497 return FileName.takeError(); 498 } 499 500 return Unit; 501 } 502 503 template <typename T> 504 llvm::Expected<const T *> 505 CrossTranslationUnitContext::importDefinitionImpl(const T *D, ASTUnit *Unit) { 506 assert(hasBodyOrInit(D) && "Decls to be imported should have body or init."); 507 508 assert(&D->getASTContext() == &Unit->getASTContext() && 509 "ASTContext of Decl and the unit should match."); 510 ASTImporter &Importer = getOrCreateASTImporter(Unit); 511 512 auto ToDeclOrError = Importer.Import(D); 513 if (!ToDeclOrError) { 514 handleAllErrors(ToDeclOrError.takeError(), 515 [&](const ImportError &IE) { 516 switch (IE.Error) { 517 case ImportError::NameConflict: 518 ++NumNameConflicts; 519 break; 520 case ImportError::UnsupportedConstruct: 521 ++NumUnsupportedNodeFound; 522 break; 523 case ImportError::Unknown: 524 llvm_unreachable("Unknown import error happened."); 525 break; 526 } 527 }); 528 return llvm::make_error<IndexError>(index_error_code::failed_import); 529 } 530 auto *ToDecl = cast<T>(*ToDeclOrError); 531 assert(hasBodyOrInit(ToDecl) && "Imported Decl should have body or init."); 532 ++NumGetCTUSuccess; 533 534 return ToDecl; 535 } 536 537 llvm::Expected<const FunctionDecl *> 538 CrossTranslationUnitContext::importDefinition(const FunctionDecl *FD, 539 ASTUnit *Unit) { 540 return importDefinitionImpl(FD, Unit); 541 } 542 543 llvm::Expected<const VarDecl *> 544 CrossTranslationUnitContext::importDefinition(const VarDecl *VD, 545 ASTUnit *Unit) { 546 return importDefinitionImpl(VD, Unit); 547 } 548 549 void CrossTranslationUnitContext::lazyInitImporterSharedSt( 550 TranslationUnitDecl *ToTU) { 551 if (!ImporterSharedSt) 552 ImporterSharedSt = std::make_shared<ASTImporterSharedState>(*ToTU); 553 } 554 555 ASTImporter & 556 CrossTranslationUnitContext::getOrCreateASTImporter(ASTUnit *Unit) { 557 ASTContext &From = Unit->getASTContext(); 558 559 auto I = ASTUnitImporterMap.find(From.getTranslationUnitDecl()); 560 if (I != ASTUnitImporterMap.end()) 561 return *I->second; 562 lazyInitImporterSharedSt(Context.getTranslationUnitDecl()); 563 ASTImporter *NewImporter = new ASTImporter( 564 Context, Context.getSourceManager().getFileManager(), From, 565 From.getSourceManager().getFileManager(), false, ImporterSharedSt); 566 NewImporter->setFileIDImportHandler([this, Unit](FileID ToID, FileID FromID) { 567 assert(ImportedFileIDs.find(ToID) == ImportedFileIDs.end() && 568 "FileID already imported, should not happen."); 569 ImportedFileIDs[ToID] = std::make_pair(FromID, Unit); 570 }); 571 ASTUnitImporterMap[From.getTranslationUnitDecl()].reset(NewImporter); 572 return *NewImporter; 573 } 574 575 llvm::Optional<std::pair<SourceLocation, ASTUnit *>> 576 CrossTranslationUnitContext::getImportedFromSourceLocation( 577 const clang::SourceLocation &ToLoc) const { 578 const SourceManager &SM = Context.getSourceManager(); 579 auto DecToLoc = SM.getDecomposedLoc(ToLoc); 580 581 auto I = ImportedFileIDs.find(DecToLoc.first); 582 if (I == ImportedFileIDs.end()) 583 return {}; 584 585 FileID FromID = I->second.first; 586 clang::ASTUnit *Unit = I->second.second; 587 SourceLocation FromLoc = 588 Unit->getSourceManager().getComposedLoc(FromID, DecToLoc.second); 589 590 return std::make_pair(FromLoc, Unit); 591 } 592 593 } // namespace cross_tu 594 } // namespace clang 595