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