xref: /llvm-project/clang/lib/ASTMatchers/ASTMatchFinder.cpp (revision 6e33e45b943061f79ab6de1b60d04d4c6f32f8f9)
1 //===--- ASTMatchFinder.cpp - Structural query framework ------------------===//
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 //  Implements an algorithm to efficiently search for matches on AST nodes.
10 //  Uses memoization to support recursive matches like HasDescendant.
11 //
12 //  The general idea is to visit all AST nodes with a RecursiveASTVisitor,
13 //  calling the Matches(...) method of each matcher we are running on each
14 //  AST node. The matcher can recurse via the ASTMatchFinder interface.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "clang/ASTMatchers/ASTMatchFinder.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/RecursiveASTVisitor.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Support/PrettyStackTrace.h"
25 #include "llvm/Support/Timer.h"
26 #include <deque>
27 #include <memory>
28 #include <set>
29 
30 namespace clang {
31 namespace ast_matchers {
32 namespace internal {
33 namespace {
34 
35 typedef MatchFinder::MatchCallback MatchCallback;
36 
37 // The maximum number of memoization entries to store.
38 // 10k has been experimentally found to give a good trade-off
39 // of performance vs. memory consumption by running matcher
40 // that match on every statement over a very large codebase.
41 //
42 // FIXME: Do some performance optimization in general and
43 // revisit this number; also, put up micro-benchmarks that we can
44 // optimize this on.
45 static const unsigned MaxMemoizationEntries = 10000;
46 
47 enum class MatchType {
48   Ancestors,
49 
50   Descendants,
51   Child,
52 };
53 
54 // We use memoization to avoid running the same matcher on the same
55 // AST node twice.  This struct is the key for looking up match
56 // result.  It consists of an ID of the MatcherInterface (for
57 // identifying the matcher), a pointer to the AST node and the
58 // bound nodes before the matcher was executed.
59 //
60 // We currently only memoize on nodes whose pointers identify the
61 // nodes (\c Stmt and \c Decl, but not \c QualType or \c TypeLoc).
62 // For \c QualType and \c TypeLoc it is possible to implement
63 // generation of keys for each type.
64 // FIXME: Benchmark whether memoization of non-pointer typed nodes
65 // provides enough benefit for the additional amount of code.
66 struct MatchKey {
67   DynTypedMatcher::MatcherIDType MatcherID;
68   DynTypedNode Node;
69   BoundNodesTreeBuilder BoundNodes;
70   TraversalKind Traversal = TK_AsIs;
71   MatchType Type;
72 
73   bool operator<(const MatchKey &Other) const {
74     return std::tie(Traversal, Type, MatcherID, Node, BoundNodes) <
75            std::tie(Other.Traversal, Other.Type, Other.MatcherID, Other.Node,
76                     Other.BoundNodes);
77   }
78 };
79 
80 // Used to store the result of a match and possibly bound nodes.
81 struct MemoizedMatchResult {
82   bool ResultOfMatch;
83   BoundNodesTreeBuilder Nodes;
84 };
85 
86 // A RecursiveASTVisitor that traverses all children or all descendants of
87 // a node.
88 class MatchChildASTVisitor
89     : public RecursiveASTVisitor<MatchChildASTVisitor> {
90 public:
91   typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase;
92 
93   // Creates an AST visitor that matches 'matcher' on all children or
94   // descendants of a traversed node. max_depth is the maximum depth
95   // to traverse: use 1 for matching the children and INT_MAX for
96   // matching the descendants.
97   MatchChildASTVisitor(const DynTypedMatcher *Matcher, ASTMatchFinder *Finder,
98                        BoundNodesTreeBuilder *Builder, int MaxDepth,
99                        bool IgnoreImplicitChildren,
100                        ASTMatchFinder::BindKind Bind)
101       : Matcher(Matcher), Finder(Finder), Builder(Builder), CurrentDepth(0),
102         MaxDepth(MaxDepth), IgnoreImplicitChildren(IgnoreImplicitChildren),
103         Bind(Bind), Matches(false) {}
104 
105   // Returns true if a match is found in the subtree rooted at the
106   // given AST node. This is done via a set of mutually recursive
107   // functions. Here's how the recursion is done (the  *wildcard can
108   // actually be Decl, Stmt, or Type):
109   //
110   //   - Traverse(node) calls BaseTraverse(node) when it needs
111   //     to visit the descendants of node.
112   //   - BaseTraverse(node) then calls (via VisitorBase::Traverse*(node))
113   //     Traverse*(c) for each child c of 'node'.
114   //   - Traverse*(c) in turn calls Traverse(c), completing the
115   //     recursion.
116   bool findMatch(const DynTypedNode &DynNode) {
117     reset();
118     if (const Decl *D = DynNode.get<Decl>())
119       traverse(*D);
120     else if (const Stmt *S = DynNode.get<Stmt>())
121       traverse(*S);
122     else if (const NestedNameSpecifier *NNS =
123              DynNode.get<NestedNameSpecifier>())
124       traverse(*NNS);
125     else if (const NestedNameSpecifierLoc *NNSLoc =
126              DynNode.get<NestedNameSpecifierLoc>())
127       traverse(*NNSLoc);
128     else if (const QualType *Q = DynNode.get<QualType>())
129       traverse(*Q);
130     else if (const TypeLoc *T = DynNode.get<TypeLoc>())
131       traverse(*T);
132     else if (const auto *C = DynNode.get<CXXCtorInitializer>())
133       traverse(*C);
134     else if (const TemplateArgumentLoc *TALoc =
135                  DynNode.get<TemplateArgumentLoc>())
136       traverse(*TALoc);
137     else if (const Attr *A = DynNode.get<Attr>())
138       traverse(*A);
139     // FIXME: Add other base types after adding tests.
140 
141     // It's OK to always overwrite the bound nodes, as if there was
142     // no match in this recursive branch, the result set is empty
143     // anyway.
144     *Builder = ResultBindings;
145 
146     return Matches;
147   }
148 
149   // The following are overriding methods from the base visitor class.
150   // They are public only to allow CRTP to work. They are *not *part
151   // of the public API of this class.
152   bool TraverseDecl(Decl *DeclNode) {
153 
154     if (DeclNode && DeclNode->isImplicit() &&
155         Finder->isTraversalIgnoringImplicitNodes())
156       return baseTraverse(*DeclNode);
157 
158     ScopedIncrement ScopedDepth(&CurrentDepth);
159     return (DeclNode == nullptr) || traverse(*DeclNode);
160   }
161 
162   Stmt *getStmtToTraverse(Stmt *StmtNode) {
163     Stmt *StmtToTraverse = StmtNode;
164     if (auto *ExprNode = dyn_cast_or_null<Expr>(StmtNode)) {
165       auto *LambdaNode = dyn_cast_or_null<LambdaExpr>(StmtNode);
166       if (LambdaNode && Finder->isTraversalIgnoringImplicitNodes())
167         StmtToTraverse = LambdaNode;
168       else
169         StmtToTraverse =
170             Finder->getASTContext().getParentMapContext().traverseIgnored(
171                 ExprNode);
172     }
173     return StmtToTraverse;
174   }
175 
176   bool TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue = nullptr) {
177     // If we need to keep track of the depth, we can't perform data recursion.
178     if (CurrentDepth == 0 || (CurrentDepth <= MaxDepth && MaxDepth < INT_MAX))
179       Queue = nullptr;
180 
181     ScopedIncrement ScopedDepth(&CurrentDepth);
182     Stmt *StmtToTraverse = getStmtToTraverse(StmtNode);
183     if (!StmtToTraverse)
184       return true;
185 
186     if (IgnoreImplicitChildren && isa<CXXDefaultArgExpr>(StmtNode))
187       return true;
188 
189     if (!match(*StmtToTraverse))
190       return false;
191     return VisitorBase::TraverseStmt(StmtToTraverse, Queue);
192   }
193   // We assume that the QualType and the contained type are on the same
194   // hierarchy level. Thus, we try to match either of them.
195   bool TraverseType(QualType TypeNode) {
196     if (TypeNode.isNull())
197       return true;
198     ScopedIncrement ScopedDepth(&CurrentDepth);
199     // Match the Type.
200     if (!match(*TypeNode))
201       return false;
202     // The QualType is matched inside traverse.
203     return traverse(TypeNode);
204   }
205   // We assume that the TypeLoc, contained QualType and contained Type all are
206   // on the same hierarchy level. Thus, we try to match all of them.
207   bool TraverseTypeLoc(TypeLoc TypeLocNode) {
208     if (TypeLocNode.isNull())
209       return true;
210     ScopedIncrement ScopedDepth(&CurrentDepth);
211     // Match the Type.
212     if (!match(*TypeLocNode.getType()))
213       return false;
214     // Match the QualType.
215     if (!match(TypeLocNode.getType()))
216       return false;
217     // The TypeLoc is matched inside traverse.
218     return traverse(TypeLocNode);
219   }
220   bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
221     ScopedIncrement ScopedDepth(&CurrentDepth);
222     return (NNS == nullptr) || traverse(*NNS);
223   }
224   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
225     if (!NNS)
226       return true;
227     ScopedIncrement ScopedDepth(&CurrentDepth);
228     if (!match(*NNS.getNestedNameSpecifier()))
229       return false;
230     return traverse(NNS);
231   }
232   bool TraverseConstructorInitializer(CXXCtorInitializer *CtorInit) {
233     if (!CtorInit)
234       return true;
235     ScopedIncrement ScopedDepth(&CurrentDepth);
236     return traverse(*CtorInit);
237   }
238   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc TAL) {
239     ScopedIncrement ScopedDepth(&CurrentDepth);
240     return traverse(TAL);
241   }
242   bool TraverseCXXForRangeStmt(CXXForRangeStmt *Node) {
243     if (!Finder->isTraversalIgnoringImplicitNodes())
244       return VisitorBase::TraverseCXXForRangeStmt(Node);
245     if (!Node)
246       return true;
247     ScopedIncrement ScopedDepth(&CurrentDepth);
248     if (auto *Init = Node->getInit())
249       if (!traverse(*Init))
250         return false;
251     if (!match(*Node->getLoopVariable()))
252       return false;
253     if (match(*Node->getRangeInit()))
254       if (!VisitorBase::TraverseStmt(Node->getRangeInit()))
255         return false;
256     if (!match(*Node->getBody()))
257       return false;
258     return VisitorBase::TraverseStmt(Node->getBody());
259   }
260   bool TraverseCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *Node) {
261     if (!Finder->isTraversalIgnoringImplicitNodes())
262       return VisitorBase::TraverseCXXRewrittenBinaryOperator(Node);
263     if (!Node)
264       return true;
265     ScopedIncrement ScopedDepth(&CurrentDepth);
266 
267     return match(*Node->getLHS()) && match(*Node->getRHS());
268   }
269   bool TraverseAttr(Attr *A) {
270     if (A == nullptr ||
271         (A->isImplicit() &&
272          Finder->getASTContext().getParentMapContext().getTraversalKind() ==
273              TK_IgnoreUnlessSpelledInSource))
274       return true;
275     ScopedIncrement ScopedDepth(&CurrentDepth);
276     return traverse(*A);
277   }
278   bool TraverseLambdaExpr(LambdaExpr *Node) {
279     if (!Finder->isTraversalIgnoringImplicitNodes())
280       return VisitorBase::TraverseLambdaExpr(Node);
281     if (!Node)
282       return true;
283     ScopedIncrement ScopedDepth(&CurrentDepth);
284 
285     for (unsigned I = 0, N = Node->capture_size(); I != N; ++I) {
286       const auto *C = Node->capture_begin() + I;
287       if (!C->isExplicit())
288         continue;
289       if (Node->isInitCapture(C) && !match(*C->getCapturedVar()))
290         return false;
291       if (!match(*Node->capture_init_begin()[I]))
292         return false;
293     }
294 
295     if (const auto *TPL = Node->getTemplateParameterList()) {
296       for (const auto *TP : *TPL) {
297         if (!match(*TP))
298           return false;
299       }
300     }
301 
302     for (const auto *P : Node->getCallOperator()->parameters()) {
303       if (!match(*P))
304         return false;
305     }
306 
307     if (!match(*Node->getBody()))
308       return false;
309 
310     return VisitorBase::TraverseStmt(Node->getBody());
311   }
312 
313   bool shouldVisitTemplateInstantiations() const { return true; }
314   bool shouldVisitImplicitCode() const { return !IgnoreImplicitChildren; }
315 
316 private:
317   // Used for updating the depth during traversal.
318   struct ScopedIncrement {
319     explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); }
320     ~ScopedIncrement() { --(*Depth); }
321 
322    private:
323     int *Depth;
324   };
325 
326   // Resets the state of this object.
327   void reset() {
328     Matches = false;
329     CurrentDepth = 0;
330   }
331 
332   // Forwards the call to the corresponding Traverse*() method in the
333   // base visitor class.
334   bool baseTraverse(const Decl &DeclNode) {
335     return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
336   }
337   bool baseTraverse(const Stmt &StmtNode) {
338     return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
339   }
340   bool baseTraverse(QualType TypeNode) {
341     return VisitorBase::TraverseType(TypeNode);
342   }
343   bool baseTraverse(TypeLoc TypeLocNode) {
344     return VisitorBase::TraverseTypeLoc(TypeLocNode);
345   }
346   bool baseTraverse(const NestedNameSpecifier &NNS) {
347     return VisitorBase::TraverseNestedNameSpecifier(
348         const_cast<NestedNameSpecifier*>(&NNS));
349   }
350   bool baseTraverse(NestedNameSpecifierLoc NNS) {
351     return VisitorBase::TraverseNestedNameSpecifierLoc(NNS);
352   }
353   bool baseTraverse(const CXXCtorInitializer &CtorInit) {
354     return VisitorBase::TraverseConstructorInitializer(
355         const_cast<CXXCtorInitializer *>(&CtorInit));
356   }
357   bool baseTraverse(TemplateArgumentLoc TAL) {
358     return VisitorBase::TraverseTemplateArgumentLoc(TAL);
359   }
360   bool baseTraverse(const Attr &AttrNode) {
361     return VisitorBase::TraverseAttr(const_cast<Attr *>(&AttrNode));
362   }
363 
364   // Sets 'Matched' to true if 'Matcher' matches 'Node' and:
365   //   0 < CurrentDepth <= MaxDepth.
366   //
367   // Returns 'true' if traversal should continue after this function
368   // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
369   template <typename T>
370   bool match(const T &Node) {
371     if (CurrentDepth == 0 || CurrentDepth > MaxDepth) {
372       return true;
373     }
374     if (Bind != ASTMatchFinder::BK_All) {
375       BoundNodesTreeBuilder RecursiveBuilder(*Builder);
376       if (Matcher->matches(DynTypedNode::create(Node), Finder,
377                            &RecursiveBuilder)) {
378         Matches = true;
379         ResultBindings.addMatch(RecursiveBuilder);
380         return false; // Abort as soon as a match is found.
381       }
382     } else {
383       BoundNodesTreeBuilder RecursiveBuilder(*Builder);
384       if (Matcher->matches(DynTypedNode::create(Node), Finder,
385                            &RecursiveBuilder)) {
386         // After the first match the matcher succeeds.
387         Matches = true;
388         ResultBindings.addMatch(RecursiveBuilder);
389       }
390     }
391     return true;
392   }
393 
394   // Traverses the subtree rooted at 'Node'; returns true if the
395   // traversal should continue after this function returns.
396   template <typename T>
397   bool traverse(const T &Node) {
398     static_assert(IsBaseType<T>::value,
399                   "traverse can only be instantiated with base type");
400     if (!match(Node))
401       return false;
402     return baseTraverse(Node);
403   }
404 
405   const DynTypedMatcher *const Matcher;
406   ASTMatchFinder *const Finder;
407   BoundNodesTreeBuilder *const Builder;
408   BoundNodesTreeBuilder ResultBindings;
409   int CurrentDepth;
410   const int MaxDepth;
411   const bool IgnoreImplicitChildren;
412   const ASTMatchFinder::BindKind Bind;
413   bool Matches;
414 };
415 
416 // Controls the outermost traversal of the AST and allows to match multiple
417 // matchers.
418 class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
419                         public ASTMatchFinder {
420 public:
421   MatchASTVisitor(const MatchFinder::MatchersByType *Matchers,
422                   const MatchFinder::MatchFinderOptions &Options)
423       : Matchers(Matchers), Options(Options), ActiveASTContext(nullptr) {}
424 
425   ~MatchASTVisitor() override {
426     if (Options.CheckProfiling) {
427       Options.CheckProfiling->Records = std::move(TimeByBucket);
428     }
429   }
430 
431   void onStartOfTranslationUnit() {
432     const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
433     TimeBucketRegion Timer;
434     for (MatchCallback *MC : Matchers->AllCallbacks) {
435       if (EnableCheckProfiling)
436         Timer.setBucket(&TimeByBucket[MC->getID()]);
437       MC->onStartOfTranslationUnit();
438     }
439   }
440 
441   void onEndOfTranslationUnit() {
442     const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
443     TimeBucketRegion Timer;
444     for (MatchCallback *MC : Matchers->AllCallbacks) {
445       if (EnableCheckProfiling)
446         Timer.setBucket(&TimeByBucket[MC->getID()]);
447       MC->onEndOfTranslationUnit();
448     }
449   }
450 
451   void set_active_ast_context(ASTContext *NewActiveASTContext) {
452     ActiveASTContext = NewActiveASTContext;
453   }
454 
455   // The following Visit*() and Traverse*() functions "override"
456   // methods in RecursiveASTVisitor.
457 
458   bool VisitTypedefNameDecl(TypedefNameDecl *DeclNode) {
459     // When we see 'typedef A B', we add name 'B' to the set of names
460     // A's canonical type maps to.  This is necessary for implementing
461     // isDerivedFrom(x) properly, where x can be the name of the base
462     // class or any of its aliases.
463     //
464     // In general, the is-alias-of (as defined by typedefs) relation
465     // is tree-shaped, as you can typedef a type more than once.  For
466     // example,
467     //
468     //   typedef A B;
469     //   typedef A C;
470     //   typedef C D;
471     //   typedef C E;
472     //
473     // gives you
474     //
475     //   A
476     //   |- B
477     //   `- C
478     //      |- D
479     //      `- E
480     //
481     // It is wrong to assume that the relation is a chain.  A correct
482     // implementation of isDerivedFrom() needs to recognize that B and
483     // E are aliases, even though neither is a typedef of the other.
484     // Therefore, we cannot simply walk through one typedef chain to
485     // find out whether the type name matches.
486     const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
487     const Type *CanonicalType =  // root of the typedef tree
488         ActiveASTContext->getCanonicalType(TypeNode);
489     TypeAliases[CanonicalType].insert(DeclNode);
490     return true;
491   }
492 
493   bool VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
494     const ObjCInterfaceDecl *InterfaceDecl = CAD->getClassInterface();
495     CompatibleAliases[InterfaceDecl].insert(CAD);
496     return true;
497   }
498 
499   bool TraverseDecl(Decl *DeclNode);
500   bool TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue = nullptr);
501   bool TraverseType(QualType TypeNode);
502   bool TraverseTypeLoc(TypeLoc TypeNode);
503   bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
504   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
505   bool TraverseConstructorInitializer(CXXCtorInitializer *CtorInit);
506   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc TAL);
507   bool TraverseAttr(Attr *AttrNode);
508 
509   bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue) {
510     if (auto *RF = dyn_cast<CXXForRangeStmt>(S)) {
511       {
512         ASTNodeNotAsIsSourceScope RAII(this, true);
513         TraverseStmt(RF->getInit());
514         // Don't traverse under the loop variable
515         match(*RF->getLoopVariable());
516         TraverseStmt(RF->getRangeInit());
517       }
518       {
519         ASTNodeNotSpelledInSourceScope RAII(this, true);
520         for (auto *SubStmt : RF->children()) {
521           if (SubStmt != RF->getBody())
522             TraverseStmt(SubStmt);
523         }
524       }
525       TraverseStmt(RF->getBody());
526       return true;
527     } else if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
528       {
529         ASTNodeNotAsIsSourceScope RAII(this, true);
530         TraverseStmt(const_cast<Expr *>(RBO->getLHS()));
531         TraverseStmt(const_cast<Expr *>(RBO->getRHS()));
532       }
533       {
534         ASTNodeNotSpelledInSourceScope RAII(this, true);
535         for (auto *SubStmt : RBO->children()) {
536           TraverseStmt(SubStmt);
537         }
538       }
539       return true;
540     } else if (auto *LE = dyn_cast<LambdaExpr>(S)) {
541       for (auto I : llvm::zip(LE->captures(), LE->capture_inits())) {
542         auto C = std::get<0>(I);
543         ASTNodeNotSpelledInSourceScope RAII(
544             this, TraversingASTNodeNotSpelledInSource || !C.isExplicit());
545         TraverseLambdaCapture(LE, &C, std::get<1>(I));
546       }
547 
548       {
549         ASTNodeNotSpelledInSourceScope RAII(this, true);
550         TraverseDecl(LE->getLambdaClass());
551       }
552       {
553         ASTNodeNotAsIsSourceScope RAII(this, true);
554 
555         // We need to poke around to find the bits that might be explicitly
556         // written.
557         TypeLoc TL = LE->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
558         FunctionProtoTypeLoc Proto = TL.getAsAdjusted<FunctionProtoTypeLoc>();
559 
560         if (auto *TPL = LE->getTemplateParameterList()) {
561           for (NamedDecl *D : *TPL) {
562             TraverseDecl(D);
563           }
564           if (Expr *RequiresClause = TPL->getRequiresClause()) {
565             TraverseStmt(RequiresClause);
566           }
567         }
568 
569         if (LE->hasExplicitParameters()) {
570           // Visit parameters.
571           for (ParmVarDecl *Param : Proto.getParams())
572             TraverseDecl(Param);
573         }
574 
575         const auto *T = Proto.getTypePtr();
576         for (const auto &E : T->exceptions())
577           TraverseType(E);
578 
579         if (Expr *NE = T->getNoexceptExpr())
580           TraverseStmt(NE, Queue);
581 
582         if (LE->hasExplicitResultType())
583           TraverseTypeLoc(Proto.getReturnLoc());
584         TraverseStmt(LE->getTrailingRequiresClause());
585       }
586 
587       TraverseStmt(LE->getBody());
588       return true;
589     }
590     return RecursiveASTVisitor<MatchASTVisitor>::dataTraverseNode(S, Queue);
591   }
592 
593   // Matches children or descendants of 'Node' with 'BaseMatcher'.
594   bool memoizedMatchesRecursively(const DynTypedNode &Node, ASTContext &Ctx,
595                                   const DynTypedMatcher &Matcher,
596                                   BoundNodesTreeBuilder *Builder, int MaxDepth,
597                                   BindKind Bind) {
598     // For AST-nodes that don't have an identity, we can't memoize.
599     if (!Node.getMemoizationData() || !Builder->isComparable())
600       return matchesRecursively(Node, Matcher, Builder, MaxDepth, Bind);
601 
602     MatchKey Key;
603     Key.MatcherID = Matcher.getID();
604     Key.Node = Node;
605     // Note that we key on the bindings *before* the match.
606     Key.BoundNodes = *Builder;
607     Key.Traversal = Ctx.getParentMapContext().getTraversalKind();
608     // Memoize result even doing a single-level match, it might be expensive.
609     Key.Type = MaxDepth == 1 ? MatchType::Child : MatchType::Descendants;
610     MemoizationMap::iterator I = ResultCache.find(Key);
611     if (I != ResultCache.end()) {
612       *Builder = I->second.Nodes;
613       return I->second.ResultOfMatch;
614     }
615 
616     MemoizedMatchResult Result;
617     Result.Nodes = *Builder;
618     Result.ResultOfMatch =
619         matchesRecursively(Node, Matcher, &Result.Nodes, MaxDepth, Bind);
620 
621     MemoizedMatchResult &CachedResult = ResultCache[Key];
622     CachedResult = std::move(Result);
623 
624     *Builder = CachedResult.Nodes;
625     return CachedResult.ResultOfMatch;
626   }
627 
628   // Matches children or descendants of 'Node' with 'BaseMatcher'.
629   bool matchesRecursively(const DynTypedNode &Node,
630                           const DynTypedMatcher &Matcher,
631                           BoundNodesTreeBuilder *Builder, int MaxDepth,
632                           BindKind Bind) {
633     bool ScopedTraversal = TraversingASTNodeNotSpelledInSource ||
634                            TraversingASTChildrenNotSpelledInSource;
635 
636     bool IgnoreImplicitChildren = false;
637 
638     if (isTraversalIgnoringImplicitNodes()) {
639       IgnoreImplicitChildren = true;
640     }
641 
642     ASTNodeNotSpelledInSourceScope RAII(this, ScopedTraversal);
643 
644     MatchChildASTVisitor Visitor(&Matcher, this, Builder, MaxDepth,
645                                  IgnoreImplicitChildren, Bind);
646     return Visitor.findMatch(Node);
647   }
648 
649   bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
650                           const Matcher<NamedDecl> &Base,
651                           BoundNodesTreeBuilder *Builder,
652                           bool Directly) override;
653 
654   bool objcClassIsDerivedFrom(const ObjCInterfaceDecl *Declaration,
655                               const Matcher<NamedDecl> &Base,
656                               BoundNodesTreeBuilder *Builder,
657                               bool Directly) override;
658 
659   // Implements ASTMatchFinder::matchesChildOf.
660   bool matchesChildOf(const DynTypedNode &Node, ASTContext &Ctx,
661                       const DynTypedMatcher &Matcher,
662                       BoundNodesTreeBuilder *Builder, BindKind Bind) override {
663     if (ResultCache.size() > MaxMemoizationEntries)
664       ResultCache.clear();
665     return memoizedMatchesRecursively(Node, Ctx, Matcher, Builder, 1, Bind);
666   }
667   // Implements ASTMatchFinder::matchesDescendantOf.
668   bool matchesDescendantOf(const DynTypedNode &Node, ASTContext &Ctx,
669                            const DynTypedMatcher &Matcher,
670                            BoundNodesTreeBuilder *Builder,
671                            BindKind Bind) override {
672     if (ResultCache.size() > MaxMemoizationEntries)
673       ResultCache.clear();
674     return memoizedMatchesRecursively(Node, Ctx, Matcher, Builder, INT_MAX,
675                                       Bind);
676   }
677   // Implements ASTMatchFinder::matchesAncestorOf.
678   bool matchesAncestorOf(const DynTypedNode &Node, ASTContext &Ctx,
679                          const DynTypedMatcher &Matcher,
680                          BoundNodesTreeBuilder *Builder,
681                          AncestorMatchMode MatchMode) override {
682     // Reset the cache outside of the recursive call to make sure we
683     // don't invalidate any iterators.
684     if (ResultCache.size() > MaxMemoizationEntries)
685       ResultCache.clear();
686     if (MatchMode == AncestorMatchMode::AMM_ParentOnly)
687       return matchesParentOf(Node, Matcher, Builder);
688     return matchesAnyAncestorOf(Node, Ctx, Matcher, Builder);
689   }
690 
691   // Matches all registered matchers on the given node and calls the
692   // result callback for every node that matches.
693   void match(const DynTypedNode &Node) {
694     // FIXME: Improve this with a switch or a visitor pattern.
695     if (auto *N = Node.get<Decl>()) {
696       match(*N);
697     } else if (auto *N = Node.get<Stmt>()) {
698       match(*N);
699     } else if (auto *N = Node.get<Type>()) {
700       match(*N);
701     } else if (auto *N = Node.get<QualType>()) {
702       match(*N);
703     } else if (auto *N = Node.get<NestedNameSpecifier>()) {
704       match(*N);
705     } else if (auto *N = Node.get<NestedNameSpecifierLoc>()) {
706       match(*N);
707     } else if (auto *N = Node.get<TypeLoc>()) {
708       match(*N);
709     } else if (auto *N = Node.get<CXXCtorInitializer>()) {
710       match(*N);
711     } else if (auto *N = Node.get<TemplateArgumentLoc>()) {
712       match(*N);
713     } else if (auto *N = Node.get<Attr>()) {
714       match(*N);
715     }
716   }
717 
718   template <typename T> void match(const T &Node) {
719     matchDispatch(&Node);
720   }
721 
722   // Implements ASTMatchFinder::getASTContext.
723   ASTContext &getASTContext() const override { return *ActiveASTContext; }
724 
725   bool shouldVisitTemplateInstantiations() const { return true; }
726   bool shouldVisitImplicitCode() const { return true; }
727 
728   // We visit the lambda body explicitly, so instruct the RAV
729   // to not visit it on our behalf too.
730   bool shouldVisitLambdaBody() const { return false; }
731 
732   bool IsMatchingInASTNodeNotSpelledInSource() const override {
733     return TraversingASTNodeNotSpelledInSource;
734   }
735   bool isMatchingChildrenNotSpelledInSource() const override {
736     return TraversingASTChildrenNotSpelledInSource;
737   }
738   void setMatchingChildrenNotSpelledInSource(bool Set) override {
739     TraversingASTChildrenNotSpelledInSource = Set;
740   }
741 
742   bool IsMatchingInASTNodeNotAsIs() const override {
743     return TraversingASTNodeNotAsIs;
744   }
745 
746   bool TraverseTemplateInstantiations(ClassTemplateDecl *D) {
747     ASTNodeNotSpelledInSourceScope RAII(this, true);
748     return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateInstantiations(
749         D);
750   }
751 
752   bool TraverseTemplateInstantiations(VarTemplateDecl *D) {
753     ASTNodeNotSpelledInSourceScope RAII(this, true);
754     return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateInstantiations(
755         D);
756   }
757 
758   bool TraverseTemplateInstantiations(FunctionTemplateDecl *D) {
759     ASTNodeNotSpelledInSourceScope RAII(this, true);
760     return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateInstantiations(
761         D);
762   }
763 
764 private:
765   bool TraversingASTNodeNotSpelledInSource = false;
766   bool TraversingASTNodeNotAsIs = false;
767   bool TraversingASTChildrenNotSpelledInSource = false;
768 
769   class CurMatchData {
770   public:
771     CurMatchData() = default;
772 
773     template <typename NodeType>
774     void SetCallbackAndRawNode(const MatchCallback *CB, const NodeType &N) {
775       assertEmpty();
776       Callback = CB;
777       MatchingNode = &N;
778     }
779 
780     const MatchCallback *getCallback() const { return Callback; }
781 
782     void SetBoundNodes(const BoundNodes &BN) {
783       assertHoldsState();
784       BNodes = &BN;
785     }
786 
787     void clearBoundNodes() {
788       assertHoldsState();
789       BNodes = nullptr;
790     }
791 
792     template <typename T> const T *getNode() const {
793       assertHoldsState();
794       return MatchingNode.dyn_cast<const T *>();
795     }
796 
797     const BoundNodes *getBoundNodes() const {
798       assertHoldsState();
799       return BNodes;
800     }
801 
802     void reset() {
803       assertHoldsState();
804       Callback = nullptr;
805       MatchingNode = nullptr;
806     }
807 
808   private:
809     void assertHoldsState() const {
810       assert(Callback != nullptr && !MatchingNode.isNull());
811     }
812 
813     void assertEmpty() const {
814       assert(Callback == nullptr && MatchingNode.isNull() && BNodes == nullptr);
815     }
816 
817     const MatchCallback *Callback = nullptr;
818     const BoundNodes *BNodes = nullptr;
819 
820     llvm::PointerUnion<
821         const QualType *, const TypeLoc *, const NestedNameSpecifier *,
822         const NestedNameSpecifierLoc *, const CXXCtorInitializer *,
823         const TemplateArgumentLoc *, const Attr *, const DynTypedNode *>
824         MatchingNode;
825   } CurMatchState;
826 
827   struct CurMatchRAII {
828     template <typename NodeType>
829     CurMatchRAII(MatchASTVisitor &MV, const MatchCallback *CB,
830                  const NodeType &NT)
831         : MV(MV) {
832       MV.CurMatchState.SetCallbackAndRawNode(CB, NT);
833     }
834 
835     ~CurMatchRAII() { MV.CurMatchState.reset(); }
836 
837   private:
838     MatchASTVisitor &MV;
839   };
840 
841 public:
842   class TraceReporter : llvm::PrettyStackTraceEntry {
843     static void dumpNode(const ASTContext &Ctx, const DynTypedNode &Node,
844                          raw_ostream &OS) {
845       if (const auto *D = Node.get<Decl>()) {
846         OS << D->getDeclKindName() << "Decl ";
847         if (const auto *ND = dyn_cast<NamedDecl>(D)) {
848           ND->printQualifiedName(OS);
849           OS << " : ";
850         } else
851           OS << ": ";
852         D->getSourceRange().print(OS, Ctx.getSourceManager());
853       } else if (const auto *S = Node.get<Stmt>()) {
854         OS << S->getStmtClassName() << " : ";
855         S->getSourceRange().print(OS, Ctx.getSourceManager());
856       } else if (const auto *T = Node.get<Type>()) {
857         OS << T->getTypeClassName() << "Type : ";
858         QualType(T, 0).print(OS, Ctx.getPrintingPolicy());
859       } else if (const auto *QT = Node.get<QualType>()) {
860         OS << "QualType : ";
861         QT->print(OS, Ctx.getPrintingPolicy());
862       } else {
863         OS << Node.getNodeKind().asStringRef() << " : ";
864         Node.getSourceRange().print(OS, Ctx.getSourceManager());
865       }
866     }
867 
868     static void dumpNodeFromState(const ASTContext &Ctx,
869                                   const CurMatchData &State, raw_ostream &OS) {
870       if (const DynTypedNode *MatchNode = State.getNode<DynTypedNode>()) {
871         dumpNode(Ctx, *MatchNode, OS);
872       } else if (const auto *QT = State.getNode<QualType>()) {
873         dumpNode(Ctx, DynTypedNode::create(*QT), OS);
874       } else if (const auto *TL = State.getNode<TypeLoc>()) {
875         dumpNode(Ctx, DynTypedNode::create(*TL), OS);
876       } else if (const auto *NNS = State.getNode<NestedNameSpecifier>()) {
877         dumpNode(Ctx, DynTypedNode::create(*NNS), OS);
878       } else if (const auto *NNSL = State.getNode<NestedNameSpecifierLoc>()) {
879         dumpNode(Ctx, DynTypedNode::create(*NNSL), OS);
880       } else if (const auto *CtorInit = State.getNode<CXXCtorInitializer>()) {
881         dumpNode(Ctx, DynTypedNode::create(*CtorInit), OS);
882       } else if (const auto *TAL = State.getNode<TemplateArgumentLoc>()) {
883         dumpNode(Ctx, DynTypedNode::create(*TAL), OS);
884       } else if (const auto *At = State.getNode<Attr>()) {
885         dumpNode(Ctx, DynTypedNode::create(*At), OS);
886       }
887     }
888 
889   public:
890     TraceReporter(const MatchASTVisitor &MV) : MV(MV) {}
891     void print(raw_ostream &OS) const override {
892       const CurMatchData &State = MV.CurMatchState;
893       const MatchCallback *CB = State.getCallback();
894       if (!CB) {
895         OS << "ASTMatcher: Not currently matching\n";
896         return;
897       }
898 
899       assert(MV.ActiveASTContext &&
900              "ActiveASTContext should be set if there is a matched callback");
901 
902       ASTContext &Ctx = MV.getASTContext();
903 
904       if (const BoundNodes *Nodes = State.getBoundNodes()) {
905         OS << "ASTMatcher: Processing '" << CB->getID() << "' against:\n\t";
906         dumpNodeFromState(Ctx, State, OS);
907         const BoundNodes::IDToNodeMap &Map = Nodes->getMap();
908         if (Map.empty()) {
909           OS << "\nNo bound nodes\n";
910           return;
911         }
912         OS << "\n--- Bound Nodes Begin ---\n";
913         for (const auto &Item : Map) {
914           OS << "    " << Item.first << " - { ";
915           dumpNode(Ctx, Item.second, OS);
916           OS << " }\n";
917         }
918         OS << "--- Bound Nodes End ---\n";
919       } else {
920         OS << "ASTMatcher: Matching '" << CB->getID() << "' against:\n\t";
921         dumpNodeFromState(Ctx, State, OS);
922         OS << '\n';
923       }
924     }
925 
926   private:
927     const MatchASTVisitor &MV;
928   };
929 
930 private:
931   struct ASTNodeNotSpelledInSourceScope {
932     ASTNodeNotSpelledInSourceScope(MatchASTVisitor *V, bool B)
933         : MV(V), MB(V->TraversingASTNodeNotSpelledInSource) {
934       V->TraversingASTNodeNotSpelledInSource = B;
935     }
936     ~ASTNodeNotSpelledInSourceScope() {
937       MV->TraversingASTNodeNotSpelledInSource = MB;
938     }
939 
940   private:
941     MatchASTVisitor *MV;
942     bool MB;
943   };
944 
945   struct ASTNodeNotAsIsSourceScope {
946     ASTNodeNotAsIsSourceScope(MatchASTVisitor *V, bool B)
947         : MV(V), MB(V->TraversingASTNodeNotAsIs) {
948       V->TraversingASTNodeNotAsIs = B;
949     }
950     ~ASTNodeNotAsIsSourceScope() { MV->TraversingASTNodeNotAsIs = MB; }
951 
952   private:
953     MatchASTVisitor *MV;
954     bool MB;
955   };
956 
957   class TimeBucketRegion {
958   public:
959     TimeBucketRegion() : Bucket(nullptr) {}
960     ~TimeBucketRegion() { setBucket(nullptr); }
961 
962     /// Start timing for \p NewBucket.
963     ///
964     /// If there was a bucket already set, it will finish the timing for that
965     /// other bucket.
966     /// \p NewBucket will be timed until the next call to \c setBucket() or
967     /// until the \c TimeBucketRegion is destroyed.
968     /// If \p NewBucket is the same as the currently timed bucket, this call
969     /// does nothing.
970     void setBucket(llvm::TimeRecord *NewBucket) {
971       if (Bucket != NewBucket) {
972         auto Now = llvm::TimeRecord::getCurrentTime(true);
973         if (Bucket)
974           *Bucket += Now;
975         if (NewBucket)
976           *NewBucket -= Now;
977         Bucket = NewBucket;
978       }
979     }
980 
981   private:
982     llvm::TimeRecord *Bucket;
983   };
984 
985   /// Runs all the \p Matchers on \p Node.
986   ///
987   /// Used by \c matchDispatch() below.
988   template <typename T, typename MC>
989   void matchWithoutFilter(const T &Node, const MC &Matchers) {
990     const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
991     TimeBucketRegion Timer;
992     for (const auto &MP : Matchers) {
993       if (EnableCheckProfiling)
994         Timer.setBucket(&TimeByBucket[MP.second->getID()]);
995       BoundNodesTreeBuilder Builder;
996       CurMatchRAII RAII(*this, MP.second, Node);
997       if (MP.first.matches(Node, this, &Builder)) {
998         MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
999         Builder.visitMatches(&Visitor);
1000       }
1001     }
1002   }
1003 
1004   void matchWithFilter(const DynTypedNode &DynNode) {
1005     auto Kind = DynNode.getNodeKind();
1006     auto it = MatcherFiltersMap.find(Kind);
1007     const auto &Filter =
1008         it != MatcherFiltersMap.end() ? it->second : getFilterForKind(Kind);
1009 
1010     if (Filter.empty())
1011       return;
1012 
1013     const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
1014     TimeBucketRegion Timer;
1015     auto &Matchers = this->Matchers->DeclOrStmt;
1016     for (unsigned short I : Filter) {
1017       auto &MP = Matchers[I];
1018       if (EnableCheckProfiling)
1019         Timer.setBucket(&TimeByBucket[MP.second->getID()]);
1020       BoundNodesTreeBuilder Builder;
1021 
1022       {
1023         TraversalKindScope RAII(getASTContext(), MP.first.getTraversalKind());
1024         if (getASTContext().getParentMapContext().traverseIgnored(DynNode) !=
1025             DynNode)
1026           continue;
1027       }
1028 
1029       CurMatchRAII RAII(*this, MP.second, DynNode);
1030       if (MP.first.matches(DynNode, this, &Builder)) {
1031         MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
1032         Builder.visitMatches(&Visitor);
1033       }
1034     }
1035   }
1036 
1037   const std::vector<unsigned short> &getFilterForKind(ASTNodeKind Kind) {
1038     auto &Filter = MatcherFiltersMap[Kind];
1039     auto &Matchers = this->Matchers->DeclOrStmt;
1040     assert((Matchers.size() < USHRT_MAX) && "Too many matchers.");
1041     for (unsigned I = 0, E = Matchers.size(); I != E; ++I) {
1042       if (Matchers[I].first.canMatchNodesOfKind(Kind)) {
1043         Filter.push_back(I);
1044       }
1045     }
1046     return Filter;
1047   }
1048 
1049   /// @{
1050   /// Overloads to pair the different node types to their matchers.
1051   void matchDispatch(const Decl *Node) {
1052     return matchWithFilter(DynTypedNode::create(*Node));
1053   }
1054   void matchDispatch(const Stmt *Node) {
1055     return matchWithFilter(DynTypedNode::create(*Node));
1056   }
1057 
1058   void matchDispatch(const Type *Node) {
1059     matchWithoutFilter(QualType(Node, 0), Matchers->Type);
1060   }
1061   void matchDispatch(const TypeLoc *Node) {
1062     matchWithoutFilter(*Node, Matchers->TypeLoc);
1063   }
1064   void matchDispatch(const QualType *Node) {
1065     matchWithoutFilter(*Node, Matchers->Type);
1066   }
1067   void matchDispatch(const NestedNameSpecifier *Node) {
1068     matchWithoutFilter(*Node, Matchers->NestedNameSpecifier);
1069   }
1070   void matchDispatch(const NestedNameSpecifierLoc *Node) {
1071     matchWithoutFilter(*Node, Matchers->NestedNameSpecifierLoc);
1072   }
1073   void matchDispatch(const CXXCtorInitializer *Node) {
1074     matchWithoutFilter(*Node, Matchers->CtorInit);
1075   }
1076   void matchDispatch(const TemplateArgumentLoc *Node) {
1077     matchWithoutFilter(*Node, Matchers->TemplateArgumentLoc);
1078   }
1079   void matchDispatch(const Attr *Node) {
1080     matchWithoutFilter(*Node, Matchers->Attr);
1081   }
1082   void matchDispatch(const void *) { /* Do nothing. */ }
1083   /// @}
1084 
1085   // Returns whether a direct parent of \p Node matches \p Matcher.
1086   // Unlike matchesAnyAncestorOf there's no memoization: it doesn't save much.
1087   bool matchesParentOf(const DynTypedNode &Node, const DynTypedMatcher &Matcher,
1088                        BoundNodesTreeBuilder *Builder) {
1089     for (const auto &Parent : ActiveASTContext->getParents(Node)) {
1090       BoundNodesTreeBuilder BuilderCopy = *Builder;
1091       if (Matcher.matches(Parent, this, &BuilderCopy)) {
1092         *Builder = std::move(BuilderCopy);
1093         return true;
1094       }
1095     }
1096     return false;
1097   }
1098 
1099   // Returns whether an ancestor of \p Node matches \p Matcher.
1100   //
1101   // The order of matching (which can lead to different nodes being bound in
1102   // case there are multiple matches) is breadth first search.
1103   //
1104   // To allow memoization in the very common case of having deeply nested
1105   // expressions inside a template function, we first walk up the AST, memoizing
1106   // the result of the match along the way, as long as there is only a single
1107   // parent.
1108   //
1109   // Once there are multiple parents, the breadth first search order does not
1110   // allow simple memoization on the ancestors. Thus, we only memoize as long
1111   // as there is a single parent.
1112   //
1113   // We avoid a recursive implementation to prevent excessive stack use on
1114   // very deep ASTs (similarly to RecursiveASTVisitor's data recursion).
1115   bool matchesAnyAncestorOf(DynTypedNode Node, ASTContext &Ctx,
1116                             const DynTypedMatcher &Matcher,
1117                             BoundNodesTreeBuilder *Builder) {
1118 
1119     // Memoization keys that can be updated with the result.
1120     // These are the memoizable nodes in the chain of unique parents, which
1121     // terminates when a node has multiple parents, or matches, or is the root.
1122     std::vector<MatchKey> Keys;
1123     // When returning, update the memoization cache.
1124     auto Finish = [&](bool Matched) {
1125       for (const auto &Key : Keys) {
1126         MemoizedMatchResult &CachedResult = ResultCache[Key];
1127         CachedResult.ResultOfMatch = Matched;
1128         CachedResult.Nodes = *Builder;
1129       }
1130       return Matched;
1131     };
1132 
1133     // Loop while there's a single parent and we want to attempt memoization.
1134     DynTypedNodeList Parents{ArrayRef<DynTypedNode>()}; // after loop: size != 1
1135     for (;;) {
1136       // A cache key only makes sense if memoization is possible.
1137       if (Builder->isComparable()) {
1138         Keys.emplace_back();
1139         Keys.back().MatcherID = Matcher.getID();
1140         Keys.back().Node = Node;
1141         Keys.back().BoundNodes = *Builder;
1142         Keys.back().Traversal = Ctx.getParentMapContext().getTraversalKind();
1143         Keys.back().Type = MatchType::Ancestors;
1144 
1145         // Check the cache.
1146         MemoizationMap::iterator I = ResultCache.find(Keys.back());
1147         if (I != ResultCache.end()) {
1148           Keys.pop_back(); // Don't populate the cache for the matching node!
1149           *Builder = I->second.Nodes;
1150           return Finish(I->second.ResultOfMatch);
1151         }
1152       }
1153 
1154       Parents = ActiveASTContext->getParents(Node);
1155       // Either no parents or multiple parents: leave chain+memoize mode and
1156       // enter bfs+forgetful mode.
1157       if (Parents.size() != 1)
1158         break;
1159 
1160       // Check the next parent.
1161       Node = *Parents.begin();
1162       BoundNodesTreeBuilder BuilderCopy = *Builder;
1163       if (Matcher.matches(Node, this, &BuilderCopy)) {
1164         *Builder = std::move(BuilderCopy);
1165         return Finish(true);
1166       }
1167     }
1168     // We reached the end of the chain.
1169 
1170     if (Parents.empty()) {
1171       // Nodes may have no parents if:
1172       //  a) the node is the TranslationUnitDecl
1173       //  b) we have a limited traversal scope that excludes the parent edges
1174       //  c) there is a bug in the AST, and the node is not reachable
1175       // Usually the traversal scope is the whole AST, which precludes b.
1176       // Bugs are common enough that it's worthwhile asserting when we can.
1177 #ifndef NDEBUG
1178       if (!Node.get<TranslationUnitDecl>() &&
1179           /* Traversal scope is full AST if any of the bounds are the TU */
1180           llvm::any_of(ActiveASTContext->getTraversalScope(), [](Decl *D) {
1181             return D->getKind() == Decl::TranslationUnit;
1182           })) {
1183         llvm::errs() << "Tried to match orphan node:\n";
1184         Node.dump(llvm::errs(), *ActiveASTContext);
1185         llvm_unreachable("Parent map should be complete!");
1186       }
1187 #endif
1188     } else {
1189       assert(Parents.size() > 1);
1190       // BFS starting from the parents not yet considered.
1191       // Memoization of newly visited nodes is not possible (but we still update
1192       // results for the elements in the chain we found above).
1193       std::deque<DynTypedNode> Queue(Parents.begin(), Parents.end());
1194       llvm::DenseSet<const void *> Visited;
1195       while (!Queue.empty()) {
1196         BoundNodesTreeBuilder BuilderCopy = *Builder;
1197         if (Matcher.matches(Queue.front(), this, &BuilderCopy)) {
1198           *Builder = std::move(BuilderCopy);
1199           return Finish(true);
1200         }
1201         for (const auto &Parent : ActiveASTContext->getParents(Queue.front())) {
1202           // Make sure we do not visit the same node twice.
1203           // Otherwise, we'll visit the common ancestors as often as there
1204           // are splits on the way down.
1205           if (Visited.insert(Parent.getMemoizationData()).second)
1206             Queue.push_back(Parent);
1207         }
1208         Queue.pop_front();
1209       }
1210     }
1211     return Finish(false);
1212   }
1213 
1214   // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
1215   // the aggregated bound nodes for each match.
1216   class MatchVisitor : public BoundNodesTreeBuilder::Visitor {
1217     struct CurBoundScope {
1218       CurBoundScope(MatchASTVisitor::CurMatchData &State, const BoundNodes &BN)
1219           : State(State) {
1220         State.SetBoundNodes(BN);
1221       }
1222 
1223       ~CurBoundScope() { State.clearBoundNodes(); }
1224 
1225     private:
1226       MatchASTVisitor::CurMatchData &State;
1227     };
1228 
1229   public:
1230     MatchVisitor(MatchASTVisitor &MV, ASTContext *Context,
1231                  MatchFinder::MatchCallback *Callback)
1232         : State(MV.CurMatchState), Context(Context), Callback(Callback) {}
1233 
1234     void visitMatch(const BoundNodes& BoundNodesView) override {
1235       TraversalKindScope RAII(*Context, Callback->getCheckTraversalKind());
1236       CurBoundScope RAII2(State, BoundNodesView);
1237       Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
1238     }
1239 
1240   private:
1241     MatchASTVisitor::CurMatchData &State;
1242     ASTContext* Context;
1243     MatchFinder::MatchCallback* Callback;
1244   };
1245 
1246   // Returns true if 'TypeNode' has an alias that matches the given matcher.
1247   bool typeHasMatchingAlias(const Type *TypeNode,
1248                             const Matcher<NamedDecl> &Matcher,
1249                             BoundNodesTreeBuilder *Builder) {
1250     const Type *const CanonicalType =
1251       ActiveASTContext->getCanonicalType(TypeNode);
1252     auto Aliases = TypeAliases.find(CanonicalType);
1253     if (Aliases == TypeAliases.end())
1254       return false;
1255     for (const TypedefNameDecl *Alias : Aliases->second) {
1256       BoundNodesTreeBuilder Result(*Builder);
1257       if (Matcher.matches(*Alias, this, &Result)) {
1258         *Builder = std::move(Result);
1259         return true;
1260       }
1261     }
1262     return false;
1263   }
1264 
1265   bool
1266   objcClassHasMatchingCompatibilityAlias(const ObjCInterfaceDecl *InterfaceDecl,
1267                                          const Matcher<NamedDecl> &Matcher,
1268                                          BoundNodesTreeBuilder *Builder) {
1269     auto Aliases = CompatibleAliases.find(InterfaceDecl);
1270     if (Aliases == CompatibleAliases.end())
1271       return false;
1272     for (const ObjCCompatibleAliasDecl *Alias : Aliases->second) {
1273       BoundNodesTreeBuilder Result(*Builder);
1274       if (Matcher.matches(*Alias, this, &Result)) {
1275         *Builder = std::move(Result);
1276         return true;
1277       }
1278     }
1279     return false;
1280   }
1281 
1282   /// Bucket to record map.
1283   ///
1284   /// Used to get the appropriate bucket for each matcher.
1285   llvm::StringMap<llvm::TimeRecord> TimeByBucket;
1286 
1287   const MatchFinder::MatchersByType *Matchers;
1288 
1289   /// Filtered list of matcher indices for each matcher kind.
1290   ///
1291   /// \c Decl and \c Stmt toplevel matchers usually apply to a specific node
1292   /// kind (and derived kinds) so it is a waste to try every matcher on every
1293   /// node.
1294   /// We precalculate a list of matchers that pass the toplevel restrict check.
1295   llvm::DenseMap<ASTNodeKind, std::vector<unsigned short>> MatcherFiltersMap;
1296 
1297   const MatchFinder::MatchFinderOptions &Options;
1298   ASTContext *ActiveASTContext;
1299 
1300   // Maps a canonical type to its TypedefDecls.
1301   llvm::DenseMap<const Type*, std::set<const TypedefNameDecl*> > TypeAliases;
1302 
1303   // Maps an Objective-C interface to its ObjCCompatibleAliasDecls.
1304   llvm::DenseMap<const ObjCInterfaceDecl *,
1305                  llvm::SmallPtrSet<const ObjCCompatibleAliasDecl *, 2>>
1306       CompatibleAliases;
1307 
1308   // Maps (matcher, node) -> the match result for memoization.
1309   typedef std::map<MatchKey, MemoizedMatchResult> MemoizationMap;
1310   MemoizationMap ResultCache;
1311 };
1312 
1313 static CXXRecordDecl *
1314 getAsCXXRecordDeclOrPrimaryTemplate(const Type *TypeNode) {
1315   if (auto *RD = TypeNode->getAsCXXRecordDecl())
1316     return RD;
1317 
1318   // Find the innermost TemplateSpecializationType that isn't an alias template.
1319   auto *TemplateType = TypeNode->getAs<TemplateSpecializationType>();
1320   while (TemplateType && TemplateType->isTypeAlias())
1321     TemplateType =
1322         TemplateType->getAliasedType()->getAs<TemplateSpecializationType>();
1323 
1324   // If this is the name of a (dependent) template specialization, use the
1325   // definition of the template, even though it might be specialized later.
1326   if (TemplateType)
1327     if (auto *ClassTemplate = dyn_cast_or_null<ClassTemplateDecl>(
1328           TemplateType->getTemplateName().getAsTemplateDecl()))
1329       return ClassTemplate->getTemplatedDecl();
1330 
1331   return nullptr;
1332 }
1333 
1334 // Returns true if the given C++ class is directly or indirectly derived
1335 // from a base type with the given name.  A class is not considered to be
1336 // derived from itself.
1337 bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
1338                                          const Matcher<NamedDecl> &Base,
1339                                          BoundNodesTreeBuilder *Builder,
1340                                          bool Directly) {
1341   if (!Declaration->hasDefinition())
1342     return false;
1343   for (const auto &It : Declaration->bases()) {
1344     const Type *TypeNode = It.getType().getTypePtr();
1345 
1346     if (typeHasMatchingAlias(TypeNode, Base, Builder))
1347       return true;
1348 
1349     // FIXME: Going to the primary template here isn't really correct, but
1350     // unfortunately we accept a Decl matcher for the base class not a Type
1351     // matcher, so it's the best thing we can do with our current interface.
1352     CXXRecordDecl *ClassDecl = getAsCXXRecordDeclOrPrimaryTemplate(TypeNode);
1353     if (!ClassDecl)
1354       continue;
1355     if (ClassDecl == Declaration) {
1356       // This can happen for recursive template definitions.
1357       continue;
1358     }
1359     BoundNodesTreeBuilder Result(*Builder);
1360     if (Base.matches(*ClassDecl, this, &Result)) {
1361       *Builder = std::move(Result);
1362       return true;
1363     }
1364     if (!Directly && classIsDerivedFrom(ClassDecl, Base, Builder, Directly))
1365       return true;
1366   }
1367   return false;
1368 }
1369 
1370 // Returns true if the given Objective-C class is directly or indirectly
1371 // derived from a matching base class. A class is not considered to be derived
1372 // from itself.
1373 bool MatchASTVisitor::objcClassIsDerivedFrom(
1374     const ObjCInterfaceDecl *Declaration, const Matcher<NamedDecl> &Base,
1375     BoundNodesTreeBuilder *Builder, bool Directly) {
1376   // Check if any of the superclasses of the class match.
1377   for (const ObjCInterfaceDecl *ClassDecl = Declaration->getSuperClass();
1378        ClassDecl != nullptr; ClassDecl = ClassDecl->getSuperClass()) {
1379     // Check if there are any matching compatibility aliases.
1380     if (objcClassHasMatchingCompatibilityAlias(ClassDecl, Base, Builder))
1381       return true;
1382 
1383     // Check if there are any matching type aliases.
1384     const Type *TypeNode = ClassDecl->getTypeForDecl();
1385     if (typeHasMatchingAlias(TypeNode, Base, Builder))
1386       return true;
1387 
1388     if (Base.matches(*ClassDecl, this, Builder))
1389       return true;
1390 
1391     // Not `return false` as a temporary workaround for PR43879.
1392     if (Directly)
1393       break;
1394   }
1395 
1396   return false;
1397 }
1398 
1399 bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
1400   if (!DeclNode) {
1401     return true;
1402   }
1403 
1404   bool ScopedTraversal =
1405       TraversingASTNodeNotSpelledInSource || DeclNode->isImplicit();
1406   bool ScopedChildren = TraversingASTChildrenNotSpelledInSource;
1407 
1408   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DeclNode)) {
1409     auto SK = CTSD->getSpecializationKind();
1410     if (SK == TSK_ExplicitInstantiationDeclaration ||
1411         SK == TSK_ExplicitInstantiationDefinition)
1412       ScopedChildren = true;
1413   } else if (const auto *FD = dyn_cast<FunctionDecl>(DeclNode)) {
1414     if (FD->isDefaulted())
1415       ScopedChildren = true;
1416     if (FD->isTemplateInstantiation())
1417       ScopedTraversal = true;
1418   } else if (isa<BindingDecl>(DeclNode)) {
1419     ScopedChildren = true;
1420   }
1421 
1422   ASTNodeNotSpelledInSourceScope RAII1(this, ScopedTraversal);
1423   ASTChildrenNotSpelledInSourceScope RAII2(this, ScopedChildren);
1424 
1425   match(*DeclNode);
1426   return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
1427 }
1428 
1429 bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue) {
1430   if (!StmtNode) {
1431     return true;
1432   }
1433   bool ScopedTraversal = TraversingASTNodeNotSpelledInSource ||
1434                          TraversingASTChildrenNotSpelledInSource;
1435 
1436   ASTNodeNotSpelledInSourceScope RAII(this, ScopedTraversal);
1437   match(*StmtNode);
1438   return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode, Queue);
1439 }
1440 
1441 bool MatchASTVisitor::TraverseType(QualType TypeNode) {
1442   match(TypeNode);
1443   return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
1444 }
1445 
1446 bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
1447   // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
1448   // We still want to find those types via matchers, so we match them here. Note
1449   // that the TypeLocs are structurally a shadow-hierarchy to the expressed
1450   // type, so we visit all involved parts of a compound type when matching on
1451   // each TypeLoc.
1452   match(TypeLocNode);
1453   match(TypeLocNode.getType());
1454   return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
1455 }
1456 
1457 bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
1458   match(*NNS);
1459   return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
1460 }
1461 
1462 bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
1463     NestedNameSpecifierLoc NNS) {
1464   if (!NNS)
1465     return true;
1466 
1467   match(NNS);
1468 
1469   // We only match the nested name specifier here (as opposed to traversing it)
1470   // because the traversal is already done in the parallel "Loc"-hierarchy.
1471   if (NNS.hasQualifier())
1472     match(*NNS.getNestedNameSpecifier());
1473   return
1474       RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
1475 }
1476 
1477 bool MatchASTVisitor::TraverseConstructorInitializer(
1478     CXXCtorInitializer *CtorInit) {
1479   if (!CtorInit)
1480     return true;
1481 
1482   bool ScopedTraversal = TraversingASTNodeNotSpelledInSource ||
1483                          TraversingASTChildrenNotSpelledInSource;
1484 
1485   if (!CtorInit->isWritten())
1486     ScopedTraversal = true;
1487 
1488   ASTNodeNotSpelledInSourceScope RAII1(this, ScopedTraversal);
1489 
1490   match(*CtorInit);
1491 
1492   return RecursiveASTVisitor<MatchASTVisitor>::TraverseConstructorInitializer(
1493       CtorInit);
1494 }
1495 
1496 bool MatchASTVisitor::TraverseTemplateArgumentLoc(TemplateArgumentLoc Loc) {
1497   match(Loc);
1498   return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateArgumentLoc(Loc);
1499 }
1500 
1501 bool MatchASTVisitor::TraverseAttr(Attr *AttrNode) {
1502   match(*AttrNode);
1503   return RecursiveASTVisitor<MatchASTVisitor>::TraverseAttr(AttrNode);
1504 }
1505 
1506 class MatchASTConsumer : public ASTConsumer {
1507 public:
1508   MatchASTConsumer(MatchFinder *Finder,
1509                    MatchFinder::ParsingDoneTestCallback *ParsingDone)
1510       : Finder(Finder), ParsingDone(ParsingDone) {}
1511 
1512 private:
1513   void HandleTranslationUnit(ASTContext &Context) override {
1514     if (ParsingDone != nullptr) {
1515       ParsingDone->run();
1516     }
1517     Finder->matchAST(Context);
1518   }
1519 
1520   MatchFinder *Finder;
1521   MatchFinder::ParsingDoneTestCallback *ParsingDone;
1522 };
1523 
1524 } // end namespace
1525 } // end namespace internal
1526 
1527 MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
1528                                       ASTContext *Context)
1529   : Nodes(Nodes), Context(Context),
1530     SourceManager(&Context->getSourceManager()) {}
1531 
1532 MatchFinder::MatchCallback::~MatchCallback() {}
1533 MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
1534 
1535 MatchFinder::MatchFinder(MatchFinderOptions Options)
1536     : Options(std::move(Options)), ParsingDone(nullptr) {}
1537 
1538 MatchFinder::~MatchFinder() {}
1539 
1540 void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
1541                              MatchCallback *Action) {
1542   llvm::Optional<TraversalKind> TK;
1543   if (Action)
1544     TK = Action->getCheckTraversalKind();
1545   if (TK)
1546     Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
1547   else
1548     Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
1549   Matchers.AllCallbacks.insert(Action);
1550 }
1551 
1552 void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
1553                              MatchCallback *Action) {
1554   Matchers.Type.emplace_back(NodeMatch, Action);
1555   Matchers.AllCallbacks.insert(Action);
1556 }
1557 
1558 void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
1559                              MatchCallback *Action) {
1560   llvm::Optional<TraversalKind> TK;
1561   if (Action)
1562     TK = Action->getCheckTraversalKind();
1563   if (TK)
1564     Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
1565   else
1566     Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
1567   Matchers.AllCallbacks.insert(Action);
1568 }
1569 
1570 void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
1571                              MatchCallback *Action) {
1572   Matchers.NestedNameSpecifier.emplace_back(NodeMatch, Action);
1573   Matchers.AllCallbacks.insert(Action);
1574 }
1575 
1576 void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
1577                              MatchCallback *Action) {
1578   Matchers.NestedNameSpecifierLoc.emplace_back(NodeMatch, Action);
1579   Matchers.AllCallbacks.insert(Action);
1580 }
1581 
1582 void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
1583                              MatchCallback *Action) {
1584   Matchers.TypeLoc.emplace_back(NodeMatch, Action);
1585   Matchers.AllCallbacks.insert(Action);
1586 }
1587 
1588 void MatchFinder::addMatcher(const CXXCtorInitializerMatcher &NodeMatch,
1589                              MatchCallback *Action) {
1590   Matchers.CtorInit.emplace_back(NodeMatch, Action);
1591   Matchers.AllCallbacks.insert(Action);
1592 }
1593 
1594 void MatchFinder::addMatcher(const TemplateArgumentLocMatcher &NodeMatch,
1595                              MatchCallback *Action) {
1596   Matchers.TemplateArgumentLoc.emplace_back(NodeMatch, Action);
1597   Matchers.AllCallbacks.insert(Action);
1598 }
1599 
1600 void MatchFinder::addMatcher(const AttrMatcher &AttrMatch,
1601                              MatchCallback *Action) {
1602   Matchers.Attr.emplace_back(AttrMatch, Action);
1603   Matchers.AllCallbacks.insert(Action);
1604 }
1605 
1606 bool MatchFinder::addDynamicMatcher(const internal::DynTypedMatcher &NodeMatch,
1607                                     MatchCallback *Action) {
1608   if (NodeMatch.canConvertTo<Decl>()) {
1609     addMatcher(NodeMatch.convertTo<Decl>(), Action);
1610     return true;
1611   } else if (NodeMatch.canConvertTo<QualType>()) {
1612     addMatcher(NodeMatch.convertTo<QualType>(), Action);
1613     return true;
1614   } else if (NodeMatch.canConvertTo<Stmt>()) {
1615     addMatcher(NodeMatch.convertTo<Stmt>(), Action);
1616     return true;
1617   } else if (NodeMatch.canConvertTo<NestedNameSpecifier>()) {
1618     addMatcher(NodeMatch.convertTo<NestedNameSpecifier>(), Action);
1619     return true;
1620   } else if (NodeMatch.canConvertTo<NestedNameSpecifierLoc>()) {
1621     addMatcher(NodeMatch.convertTo<NestedNameSpecifierLoc>(), Action);
1622     return true;
1623   } else if (NodeMatch.canConvertTo<TypeLoc>()) {
1624     addMatcher(NodeMatch.convertTo<TypeLoc>(), Action);
1625     return true;
1626   } else if (NodeMatch.canConvertTo<CXXCtorInitializer>()) {
1627     addMatcher(NodeMatch.convertTo<CXXCtorInitializer>(), Action);
1628     return true;
1629   } else if (NodeMatch.canConvertTo<TemplateArgumentLoc>()) {
1630     addMatcher(NodeMatch.convertTo<TemplateArgumentLoc>(), Action);
1631     return true;
1632   } else if (NodeMatch.canConvertTo<Attr>()) {
1633     addMatcher(NodeMatch.convertTo<Attr>(), Action);
1634     return true;
1635   }
1636   return false;
1637 }
1638 
1639 std::unique_ptr<ASTConsumer> MatchFinder::newASTConsumer() {
1640   return std::make_unique<internal::MatchASTConsumer>(this, ParsingDone);
1641 }
1642 
1643 void MatchFinder::match(const clang::DynTypedNode &Node, ASTContext &Context) {
1644   internal::MatchASTVisitor Visitor(&Matchers, Options);
1645   Visitor.set_active_ast_context(&Context);
1646   Visitor.match(Node);
1647 }
1648 
1649 void MatchFinder::matchAST(ASTContext &Context) {
1650   internal::MatchASTVisitor Visitor(&Matchers, Options);
1651   internal::MatchASTVisitor::TraceReporter StackTrace(Visitor);
1652   Visitor.set_active_ast_context(&Context);
1653   Visitor.onStartOfTranslationUnit();
1654   Visitor.TraverseAST(Context);
1655   Visitor.onEndOfTranslationUnit();
1656 }
1657 
1658 void MatchFinder::registerTestCallbackAfterParsing(
1659     MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
1660   ParsingDone = NewParsingDone;
1661 }
1662 
1663 StringRef MatchFinder::MatchCallback::getID() const { return "<unknown>"; }
1664 
1665 llvm::Optional<TraversalKind>
1666 MatchFinder::MatchCallback::getCheckTraversalKind() const {
1667   return llvm::None;
1668 }
1669 
1670 } // end namespace ast_matchers
1671 } // end namespace clang
1672