ExternalASTMerger.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. //===- ExternalASTMerger.cpp - Merging External AST Interface ---*- 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 ExternalASTMerger, which vends a combination of
  10. // ASTs from several different ASTContext/FileManager pairs
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/ExternalASTMerger.h"
  19. using namespace clang;
  20. namespace {
  21. template <typename T> struct Source {
  22. T t;
  23. Source(T t) : t(t) {}
  24. operator T() { return t; }
  25. template <typename U = T> U &get() { return t; }
  26. template <typename U = T> const U &get() const { return t; }
  27. template <typename U> operator Source<U>() { return Source<U>(t); }
  28. };
  29. typedef std::pair<Source<NamedDecl *>, ASTImporter *> Candidate;
  30. /// For the given DC, return the DC that is safe to perform lookups on. This is
  31. /// the DC we actually want to work with most of the time.
  32. const DeclContext *CanonicalizeDC(const DeclContext *DC) {
  33. if (isa<LinkageSpecDecl>(DC))
  34. return DC->getRedeclContext();
  35. return DC;
  36. }
  37. Source<const DeclContext *>
  38. LookupSameContext(Source<TranslationUnitDecl *> SourceTU, const DeclContext *DC,
  39. ASTImporter &ReverseImporter) {
  40. DC = CanonicalizeDC(DC);
  41. if (DC->isTranslationUnit()) {
  42. return SourceTU;
  43. }
  44. Source<const DeclContext *> SourceParentDC =
  45. LookupSameContext(SourceTU, DC->getParent(), ReverseImporter);
  46. if (!SourceParentDC) {
  47. // If we couldn't find the parent DC in this TranslationUnit, give up.
  48. return nullptr;
  49. }
  50. auto *ND = cast<NamedDecl>(DC);
  51. DeclarationName Name = ND->getDeclName();
  52. auto SourceNameOrErr = ReverseImporter.Import(Name);
  53. if (!SourceNameOrErr) {
  54. llvm::consumeError(SourceNameOrErr.takeError());
  55. return nullptr;
  56. }
  57. Source<DeclarationName> SourceName = *SourceNameOrErr;
  58. DeclContext::lookup_result SearchResult =
  59. SourceParentDC.get()->lookup(SourceName.get());
  60. size_t SearchResultSize = SearchResult.size();
  61. if (SearchResultSize == 0 || SearchResultSize > 1) {
  62. // There are two cases here. First, we might not find the name.
  63. // We might also find multiple copies, in which case we have no
  64. // guarantee that the one we wanted is the one we pick. (E.g.,
  65. // if we have two specializations of the same template it is
  66. // very hard to determine which is the one you want.)
  67. //
  68. // The Origins map fixes this problem by allowing the origin to be
  69. // explicitly recorded, so we trigger that recording by returning
  70. // nothing (rather than a possibly-inaccurate guess) here.
  71. return nullptr;
  72. } else {
  73. NamedDecl *SearchResultDecl = SearchResult[0];
  74. if (isa<DeclContext>(SearchResultDecl) &&
  75. SearchResultDecl->getKind() == DC->getDeclKind())
  76. return cast<DeclContext>(SearchResultDecl)->getPrimaryContext();
  77. return nullptr; // This type of lookup is unsupported
  78. }
  79. }
  80. /// A custom implementation of ASTImporter, for ExternalASTMerger's purposes.
  81. ///
  82. /// There are several modifications:
  83. ///
  84. /// - It enables lazy lookup (via the HasExternalLexicalStorage flag and a few
  85. /// others), which instructs Clang to refer to ExternalASTMerger. Also, it
  86. /// forces MinimalImport to true, which is necessary to make this work.
  87. /// - It maintains a reverse importer for use with names. This allows lookup of
  88. /// arbitrary names in the source context.
  89. /// - It updates the ExternalASTMerger's origin map as needed whenever a
  90. /// it sees a DeclContext.
  91. class LazyASTImporter : public ASTImporter {
  92. private:
  93. ExternalASTMerger &Parent;
  94. ASTImporter Reverse;
  95. const ExternalASTMerger::OriginMap &FromOrigins;
  96. llvm::raw_ostream &logs() { return Parent.logs(); }
  97. public:
  98. LazyASTImporter(ExternalASTMerger &_Parent, ASTContext &ToContext,
  99. FileManager &ToFileManager, ASTContext &FromContext,
  100. FileManager &FromFileManager,
  101. const ExternalASTMerger::OriginMap &_FromOrigins)
  102. : ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager,
  103. /*MinimalImport=*/true),
  104. Parent(_Parent), Reverse(FromContext, FromFileManager, ToContext,
  105. ToFileManager, /*MinimalImport=*/true), FromOrigins(_FromOrigins) {}
  106. /// Whenever a DeclContext is imported, ensure that ExternalASTSource's origin
  107. /// map is kept up to date. Also set the appropriate flags.
  108. void Imported(Decl *From, Decl *To) override {
  109. if (auto *ToDC = dyn_cast<DeclContext>(To)) {
  110. const bool LoggingEnabled = Parent.LoggingEnabled();
  111. if (LoggingEnabled)
  112. logs() << "(ExternalASTMerger*)" << (void*)&Parent
  113. << " imported (DeclContext*)" << (void*)ToDC
  114. << ", (ASTContext*)" << (void*)&getToContext()
  115. << " from (DeclContext*)" << (void*)llvm::cast<DeclContext>(From)
  116. << ", (ASTContext*)" << (void*)&getFromContext()
  117. << "\n";
  118. Source<DeclContext *> FromDC(
  119. cast<DeclContext>(From)->getPrimaryContext());
  120. if (FromOrigins.count(FromDC) &&
  121. Parent.HasImporterForOrigin(*FromOrigins.at(FromDC).AST)) {
  122. if (LoggingEnabled)
  123. logs() << "(ExternalASTMerger*)" << (void*)&Parent
  124. << " forced origin (DeclContext*)"
  125. << (void*)FromOrigins.at(FromDC).DC
  126. << ", (ASTContext*)"
  127. << (void*)FromOrigins.at(FromDC).AST
  128. << "\n";
  129. Parent.ForceRecordOrigin(ToDC, FromOrigins.at(FromDC));
  130. } else {
  131. if (LoggingEnabled)
  132. logs() << "(ExternalASTMerger*)" << (void*)&Parent
  133. << " maybe recording origin (DeclContext*)" << (void*)FromDC
  134. << ", (ASTContext*)" << (void*)&getFromContext()
  135. << "\n";
  136. Parent.MaybeRecordOrigin(ToDC, {FromDC, &getFromContext()});
  137. }
  138. }
  139. if (auto *ToTag = dyn_cast<TagDecl>(To)) {
  140. ToTag->setHasExternalLexicalStorage();
  141. ToTag->getPrimaryContext()->setMustBuildLookupTable();
  142. assert(Parent.CanComplete(ToTag));
  143. } else if (auto *ToNamespace = dyn_cast<NamespaceDecl>(To)) {
  144. ToNamespace->setHasExternalVisibleStorage();
  145. assert(Parent.CanComplete(ToNamespace));
  146. } else if (auto *ToContainer = dyn_cast<ObjCContainerDecl>(To)) {
  147. ToContainer->setHasExternalLexicalStorage();
  148. ToContainer->getPrimaryContext()->setMustBuildLookupTable();
  149. assert(Parent.CanComplete(ToContainer));
  150. }
  151. }
  152. ASTImporter &GetReverse() { return Reverse; }
  153. };
  154. bool HasDeclOfSameType(llvm::ArrayRef<Candidate> Decls, const Candidate &C) {
  155. if (isa<FunctionDecl>(C.first.get()))
  156. return false;
  157. return llvm::any_of(Decls, [&](const Candidate &D) {
  158. return C.first.get()->getKind() == D.first.get()->getKind();
  159. });
  160. }
  161. } // end namespace
  162. ASTImporter &ExternalASTMerger::ImporterForOrigin(ASTContext &OriginContext) {
  163. for (const std::unique_ptr<ASTImporter> &I : Importers)
  164. if (&I->getFromContext() == &OriginContext)
  165. return *I;
  166. llvm_unreachable("We should have an importer for this origin!");
  167. }
  168. namespace {
  169. LazyASTImporter &LazyImporterForOrigin(ExternalASTMerger &Merger,
  170. ASTContext &OriginContext) {
  171. return static_cast<LazyASTImporter &>(
  172. Merger.ImporterForOrigin(OriginContext));
  173. }
  174. }
  175. bool ExternalASTMerger::HasImporterForOrigin(ASTContext &OriginContext) {
  176. for (const std::unique_ptr<ASTImporter> &I : Importers)
  177. if (&I->getFromContext() == &OriginContext)
  178. return true;
  179. return false;
  180. }
  181. template <typename CallbackType>
  182. void ExternalASTMerger::ForEachMatchingDC(const DeclContext *DC,
  183. CallbackType Callback) {
  184. if (Origins.count(DC)) {
  185. ExternalASTMerger::DCOrigin Origin = Origins[DC];
  186. LazyASTImporter &Importer = LazyImporterForOrigin(*this, *Origin.AST);
  187. Callback(Importer, Importer.GetReverse(), Origin.DC);
  188. } else {
  189. bool DidCallback = false;
  190. for (const std::unique_ptr<ASTImporter> &Importer : Importers) {
  191. Source<TranslationUnitDecl *> SourceTU =
  192. Importer->getFromContext().getTranslationUnitDecl();
  193. ASTImporter &Reverse =
  194. static_cast<LazyASTImporter *>(Importer.get())->GetReverse();
  195. if (auto SourceDC = LookupSameContext(SourceTU, DC, Reverse)) {
  196. DidCallback = true;
  197. if (Callback(*Importer, Reverse, SourceDC))
  198. break;
  199. }
  200. }
  201. if (!DidCallback && LoggingEnabled())
  202. logs() << "(ExternalASTMerger*)" << (void*)this
  203. << " asserting for (DeclContext*)" << (const void*)DC
  204. << ", (ASTContext*)" << (void*)&Target.AST
  205. << "\n";
  206. assert(DidCallback && "Couldn't find a source context matching our DC");
  207. }
  208. }
  209. void ExternalASTMerger::CompleteType(TagDecl *Tag) {
  210. assert(Tag->hasExternalLexicalStorage());
  211. ForEachMatchingDC(Tag, [&](ASTImporter &Forward, ASTImporter &Reverse,
  212. Source<const DeclContext *> SourceDC) -> bool {
  213. auto *SourceTag = const_cast<TagDecl *>(cast<TagDecl>(SourceDC.get()));
  214. if (SourceTag->hasExternalLexicalStorage())
  215. SourceTag->getASTContext().getExternalSource()->CompleteType(SourceTag);
  216. if (!SourceTag->getDefinition())
  217. return false;
  218. Forward.MapImported(SourceTag, Tag);
  219. if (llvm::Error Err = Forward.ImportDefinition(SourceTag))
  220. llvm::consumeError(std::move(Err));
  221. Tag->setCompleteDefinition(SourceTag->isCompleteDefinition());
  222. return true;
  223. });
  224. }
  225. void ExternalASTMerger::CompleteType(ObjCInterfaceDecl *Interface) {
  226. assert(Interface->hasExternalLexicalStorage());
  227. ForEachMatchingDC(
  228. Interface, [&](ASTImporter &Forward, ASTImporter &Reverse,
  229. Source<const DeclContext *> SourceDC) -> bool {
  230. auto *SourceInterface = const_cast<ObjCInterfaceDecl *>(
  231. cast<ObjCInterfaceDecl>(SourceDC.get()));
  232. if (SourceInterface->hasExternalLexicalStorage())
  233. SourceInterface->getASTContext().getExternalSource()->CompleteType(
  234. SourceInterface);
  235. if (!SourceInterface->getDefinition())
  236. return false;
  237. Forward.MapImported(SourceInterface, Interface);
  238. if (llvm::Error Err = Forward.ImportDefinition(SourceInterface))
  239. llvm::consumeError(std::move(Err));
  240. return true;
  241. });
  242. }
  243. bool ExternalASTMerger::CanComplete(DeclContext *Interface) {
  244. assert(Interface->hasExternalLexicalStorage() ||
  245. Interface->hasExternalVisibleStorage());
  246. bool FoundMatchingDC = false;
  247. ForEachMatchingDC(Interface,
  248. [&](ASTImporter &Forward, ASTImporter &Reverse,
  249. Source<const DeclContext *> SourceDC) -> bool {
  250. FoundMatchingDC = true;
  251. return true;
  252. });
  253. return FoundMatchingDC;
  254. }
  255. namespace {
  256. bool IsSameDC(const DeclContext *D1, const DeclContext *D2) {
  257. if (isa<ObjCContainerDecl>(D1) && isa<ObjCContainerDecl>(D2))
  258. return true; // There are many cases where Objective-C is ambiguous.
  259. if (auto *T1 = dyn_cast<TagDecl>(D1))
  260. if (auto *T2 = dyn_cast<TagDecl>(D2))
  261. if (T1->getFirstDecl() == T2->getFirstDecl())
  262. return true;
  263. return D1 == D2 || D1 == CanonicalizeDC(D2);
  264. }
  265. }
  266. void ExternalASTMerger::MaybeRecordOrigin(const DeclContext *ToDC,
  267. DCOrigin Origin) {
  268. LazyASTImporter &Importer = LazyImporterForOrigin(*this, *Origin.AST);
  269. ASTImporter &Reverse = Importer.GetReverse();
  270. Source<const DeclContext *> FoundFromDC =
  271. LookupSameContext(Origin.AST->getTranslationUnitDecl(), ToDC, Reverse);
  272. const bool DoRecord = !FoundFromDC || !IsSameDC(FoundFromDC.get(), Origin.DC);
  273. if (DoRecord)
  274. RecordOriginImpl(ToDC, Origin, Importer);
  275. if (LoggingEnabled())
  276. logs() << "(ExternalASTMerger*)" << (void*)this
  277. << (DoRecord ? " decided " : " decided NOT")
  278. << " to record origin (DeclContext*)" << (void*)Origin.DC
  279. << ", (ASTContext*)" << (void*)&Origin.AST
  280. << "\n";
  281. }
  282. void ExternalASTMerger::ForceRecordOrigin(const DeclContext *ToDC,
  283. DCOrigin Origin) {
  284. RecordOriginImpl(ToDC, Origin, ImporterForOrigin(*Origin.AST));
  285. }
  286. void ExternalASTMerger::RecordOriginImpl(const DeclContext *ToDC, DCOrigin Origin,
  287. ASTImporter &Importer) {
  288. Origins[ToDC] = Origin;
  289. Importer.ASTImporter::MapImported(cast<Decl>(Origin.DC), const_cast<Decl*>(cast<Decl>(ToDC)));
  290. }
  291. ExternalASTMerger::ExternalASTMerger(const ImporterTarget &Target,
  292. llvm::ArrayRef<ImporterSource> Sources) : LogStream(&llvm::nulls()), Target(Target) {
  293. AddSources(Sources);
  294. }
  295. void ExternalASTMerger::AddSources(llvm::ArrayRef<ImporterSource> Sources) {
  296. for (const ImporterSource &S : Sources) {
  297. assert(&S.AST != &Target.AST);
  298. Importers.push_back(std::make_unique<LazyASTImporter>(
  299. *this, Target.AST, Target.FM, S.AST, S.FM, S.OM));
  300. }
  301. }
  302. void ExternalASTMerger::RemoveSources(llvm::ArrayRef<ImporterSource> Sources) {
  303. if (LoggingEnabled())
  304. for (const ImporterSource &S : Sources)
  305. logs() << "(ExternalASTMerger*)" << (void*)this
  306. << " removing source (ASTContext*)" << (void*)&S.AST
  307. << "\n";
  308. Importers.erase(
  309. std::remove_if(Importers.begin(), Importers.end(),
  310. [&Sources](std::unique_ptr<ASTImporter> &Importer) -> bool {
  311. for (const ImporterSource &S : Sources) {
  312. if (&Importer->getFromContext() == &S.AST)
  313. return true;
  314. }
  315. return false;
  316. }),
  317. Importers.end());
  318. for (OriginMap::iterator OI = Origins.begin(), OE = Origins.end(); OI != OE; ) {
  319. std::pair<const DeclContext *, DCOrigin> Origin = *OI;
  320. bool Erase = false;
  321. for (const ImporterSource &S : Sources) {
  322. if (&S.AST == Origin.second.AST) {
  323. Erase = true;
  324. break;
  325. }
  326. }
  327. if (Erase)
  328. OI = Origins.erase(OI);
  329. else
  330. ++OI;
  331. }
  332. }
  333. template <typename DeclTy>
  334. static bool importSpecializations(DeclTy *D, ASTImporter *Importer) {
  335. for (auto *Spec : D->specializations()) {
  336. auto ImportedSpecOrError = Importer->Import(Spec);
  337. if (!ImportedSpecOrError) {
  338. llvm::consumeError(ImportedSpecOrError.takeError());
  339. return true;
  340. }
  341. }
  342. return false;
  343. }
  344. /// Imports specializations from template declarations that can be specialized.
  345. static bool importSpecializationsIfNeeded(Decl *D, ASTImporter *Importer) {
  346. if (!isa<TemplateDecl>(D))
  347. return false;
  348. if (auto *FunctionTD = dyn_cast<FunctionTemplateDecl>(D))
  349. return importSpecializations(FunctionTD, Importer);
  350. else if (auto *ClassTD = dyn_cast<ClassTemplateDecl>(D))
  351. return importSpecializations(ClassTD, Importer);
  352. else if (auto *VarTD = dyn_cast<VarTemplateDecl>(D))
  353. return importSpecializations(VarTD, Importer);
  354. return false;
  355. }
  356. bool ExternalASTMerger::FindExternalVisibleDeclsByName(const DeclContext *DC,
  357. DeclarationName Name) {
  358. llvm::SmallVector<NamedDecl *, 1> Decls;
  359. llvm::SmallVector<Candidate, 4> Candidates;
  360. auto FilterFoundDecl = [&Candidates](const Candidate &C) {
  361. if (!HasDeclOfSameType(Candidates, C))
  362. Candidates.push_back(C);
  363. };
  364. ForEachMatchingDC(DC,
  365. [&](ASTImporter &Forward, ASTImporter &Reverse,
  366. Source<const DeclContext *> SourceDC) -> bool {
  367. auto FromNameOrErr = Reverse.Import(Name);
  368. if (!FromNameOrErr) {
  369. llvm::consumeError(FromNameOrErr.takeError());
  370. return false;
  371. }
  372. DeclContextLookupResult Result =
  373. SourceDC.get()->lookup(*FromNameOrErr);
  374. for (NamedDecl *FromD : Result) {
  375. FilterFoundDecl(std::make_pair(FromD, &Forward));
  376. }
  377. return false;
  378. });
  379. if (Candidates.empty())
  380. return false;
  381. Decls.reserve(Candidates.size());
  382. for (const Candidate &C : Candidates) {
  383. Decl *LookupRes = C.first.get();
  384. ASTImporter *Importer = C.second;
  385. auto NDOrErr = Importer->Import(LookupRes);
  386. assert(NDOrErr);
  387. (void)static_cast<bool>(NDOrErr);
  388. NamedDecl *ND = cast_or_null<NamedDecl>(*NDOrErr);
  389. assert(ND);
  390. // If we don't import specialization, they are not available via lookup
  391. // because the lookup result is imported TemplateDecl and it does not
  392. // reference its specializations until they are imported explicitly.
  393. bool IsSpecImportFailed =
  394. importSpecializationsIfNeeded(LookupRes, Importer);
  395. assert(!IsSpecImportFailed);
  396. (void)IsSpecImportFailed;
  397. Decls.push_back(ND);
  398. }
  399. SetExternalVisibleDeclsForName(DC, Name, Decls);
  400. return true;
  401. }
  402. void ExternalASTMerger::FindExternalLexicalDecls(
  403. const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
  404. SmallVectorImpl<Decl *> &Result) {
  405. ForEachMatchingDC(DC, [&](ASTImporter &Forward, ASTImporter &Reverse,
  406. Source<const DeclContext *> SourceDC) -> bool {
  407. for (const Decl *SourceDecl : SourceDC.get()->decls()) {
  408. if (IsKindWeWant(SourceDecl->getKind())) {
  409. auto ImportedDeclOrErr = Forward.Import(SourceDecl);
  410. if (ImportedDeclOrErr)
  411. assert(!(*ImportedDeclOrErr) ||
  412. IsSameDC((*ImportedDeclOrErr)->getDeclContext(), DC));
  413. else
  414. llvm::consumeError(ImportedDeclOrErr.takeError());
  415. }
  416. }
  417. return false;
  418. });
  419. }