diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp --- a/clang/lib/Sema/SemaLookup.cpp +++ b/clang/lib/Sema/SemaLookup.cpp @@ -3835,6 +3835,7 @@ if (CXXRecordDecl *Class = dyn_cast(Ctx)) Result.getSema().ForceDeclarationOfImplicitMembers(Class); + llvm::SmallVector DeclsToVisit; // We sometimes skip loading namespace-level results (they tend to be huge). bool Load = LoadExternal || !(isa(Ctx) || isa(Ctx)); @@ -3844,12 +3845,21 @@ : Ctx->noload_lookups(/*PreserveInternalState=*/false)) { for (auto *D : R) { if (auto *ND = Result.getAcceptableDecl(D)) { - Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); - Visited.add(ND); + // Rather than visit immediatelly, we put ND into a vector and visit + // all decls, in order, outside of this loop. The reason is that + // Consumer.FoundDecl() may invalidate the iterators used in the two + // loops above. + DeclsToVisit.push_back(ND); } } } + for (auto *ND : DeclsToVisit) { + Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); + Visited.add(ND); + } + DeclsToVisit.clear(); + // Traverse using directives for qualified name lookup. if (QualifiedNameLookup) { ShadowContextRAII Shadow(Visited);