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