1*67e74705SXin Li //===--- ASTMatchFinder.cpp - Structural query framework ------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // Implements an algorithm to efficiently search for matches on AST nodes.
11*67e74705SXin Li // Uses memoization to support recursive matches like HasDescendant.
12*67e74705SXin Li //
13*67e74705SXin Li // The general idea is to visit all AST nodes with a RecursiveASTVisitor,
14*67e74705SXin Li // calling the Matches(...) method of each matcher we are running on each
15*67e74705SXin Li // AST node. The matcher can recurse via the ASTMatchFinder interface.
16*67e74705SXin Li //
17*67e74705SXin Li //===----------------------------------------------------------------------===//
18*67e74705SXin Li
19*67e74705SXin Li #include "clang/ASTMatchers/ASTMatchFinder.h"
20*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
21*67e74705SXin Li #include "clang/AST/ASTContext.h"
22*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
23*67e74705SXin Li #include "llvm/ADT/DenseMap.h"
24*67e74705SXin Li #include "llvm/ADT/StringMap.h"
25*67e74705SXin Li #include "llvm/Support/Timer.h"
26*67e74705SXin Li #include <deque>
27*67e74705SXin Li #include <memory>
28*67e74705SXin Li #include <set>
29*67e74705SXin Li
30*67e74705SXin Li namespace clang {
31*67e74705SXin Li namespace ast_matchers {
32*67e74705SXin Li namespace internal {
33*67e74705SXin Li namespace {
34*67e74705SXin Li
35*67e74705SXin Li typedef MatchFinder::MatchCallback MatchCallback;
36*67e74705SXin Li
37*67e74705SXin Li // The maximum number of memoization entries to store.
38*67e74705SXin Li // 10k has been experimentally found to give a good trade-off
39*67e74705SXin Li // of performance vs. memory consumption by running matcher
40*67e74705SXin Li // that match on every statement over a very large codebase.
41*67e74705SXin Li //
42*67e74705SXin Li // FIXME: Do some performance optimization in general and
43*67e74705SXin Li // revisit this number; also, put up micro-benchmarks that we can
44*67e74705SXin Li // optimize this on.
45*67e74705SXin Li static const unsigned MaxMemoizationEntries = 10000;
46*67e74705SXin Li
47*67e74705SXin Li // We use memoization to avoid running the same matcher on the same
48*67e74705SXin Li // AST node twice. This struct is the key for looking up match
49*67e74705SXin Li // result. It consists of an ID of the MatcherInterface (for
50*67e74705SXin Li // identifying the matcher), a pointer to the AST node and the
51*67e74705SXin Li // bound nodes before the matcher was executed.
52*67e74705SXin Li //
53*67e74705SXin Li // We currently only memoize on nodes whose pointers identify the
54*67e74705SXin Li // nodes (\c Stmt and \c Decl, but not \c QualType or \c TypeLoc).
55*67e74705SXin Li // For \c QualType and \c TypeLoc it is possible to implement
56*67e74705SXin Li // generation of keys for each type.
57*67e74705SXin Li // FIXME: Benchmark whether memoization of non-pointer typed nodes
58*67e74705SXin Li // provides enough benefit for the additional amount of code.
59*67e74705SXin Li struct MatchKey {
60*67e74705SXin Li DynTypedMatcher::MatcherIDType MatcherID;
61*67e74705SXin Li ast_type_traits::DynTypedNode Node;
62*67e74705SXin Li BoundNodesTreeBuilder BoundNodes;
63*67e74705SXin Li
operator <clang::ast_matchers::internal::__anon37a3694d0111::MatchKey64*67e74705SXin Li bool operator<(const MatchKey &Other) const {
65*67e74705SXin Li return std::tie(MatcherID, Node, BoundNodes) <
66*67e74705SXin Li std::tie(Other.MatcherID, Other.Node, Other.BoundNodes);
67*67e74705SXin Li }
68*67e74705SXin Li };
69*67e74705SXin Li
70*67e74705SXin Li // Used to store the result of a match and possibly bound nodes.
71*67e74705SXin Li struct MemoizedMatchResult {
72*67e74705SXin Li bool ResultOfMatch;
73*67e74705SXin Li BoundNodesTreeBuilder Nodes;
74*67e74705SXin Li };
75*67e74705SXin Li
76*67e74705SXin Li // A RecursiveASTVisitor that traverses all children or all descendants of
77*67e74705SXin Li // a node.
78*67e74705SXin Li class MatchChildASTVisitor
79*67e74705SXin Li : public RecursiveASTVisitor<MatchChildASTVisitor> {
80*67e74705SXin Li public:
81*67e74705SXin Li typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase;
82*67e74705SXin Li
83*67e74705SXin Li // Creates an AST visitor that matches 'matcher' on all children or
84*67e74705SXin Li // descendants of a traversed node. max_depth is the maximum depth
85*67e74705SXin Li // to traverse: use 1 for matching the children and INT_MAX for
86*67e74705SXin Li // matching the descendants.
MatchChildASTVisitor(const DynTypedMatcher * Matcher,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder,int MaxDepth,ASTMatchFinder::TraversalKind Traversal,ASTMatchFinder::BindKind Bind)87*67e74705SXin Li MatchChildASTVisitor(const DynTypedMatcher *Matcher,
88*67e74705SXin Li ASTMatchFinder *Finder,
89*67e74705SXin Li BoundNodesTreeBuilder *Builder,
90*67e74705SXin Li int MaxDepth,
91*67e74705SXin Li ASTMatchFinder::TraversalKind Traversal,
92*67e74705SXin Li ASTMatchFinder::BindKind Bind)
93*67e74705SXin Li : Matcher(Matcher),
94*67e74705SXin Li Finder(Finder),
95*67e74705SXin Li Builder(Builder),
96*67e74705SXin Li CurrentDepth(0),
97*67e74705SXin Li MaxDepth(MaxDepth),
98*67e74705SXin Li Traversal(Traversal),
99*67e74705SXin Li Bind(Bind),
100*67e74705SXin Li Matches(false) {}
101*67e74705SXin Li
102*67e74705SXin Li // Returns true if a match is found in the subtree rooted at the
103*67e74705SXin Li // given AST node. This is done via a set of mutually recursive
104*67e74705SXin Li // functions. Here's how the recursion is done (the *wildcard can
105*67e74705SXin Li // actually be Decl, Stmt, or Type):
106*67e74705SXin Li //
107*67e74705SXin Li // - Traverse(node) calls BaseTraverse(node) when it needs
108*67e74705SXin Li // to visit the descendants of node.
109*67e74705SXin Li // - BaseTraverse(node) then calls (via VisitorBase::Traverse*(node))
110*67e74705SXin Li // Traverse*(c) for each child c of 'node'.
111*67e74705SXin Li // - Traverse*(c) in turn calls Traverse(c), completing the
112*67e74705SXin Li // recursion.
findMatch(const ast_type_traits::DynTypedNode & DynNode)113*67e74705SXin Li bool findMatch(const ast_type_traits::DynTypedNode &DynNode) {
114*67e74705SXin Li reset();
115*67e74705SXin Li if (const Decl *D = DynNode.get<Decl>())
116*67e74705SXin Li traverse(*D);
117*67e74705SXin Li else if (const Stmt *S = DynNode.get<Stmt>())
118*67e74705SXin Li traverse(*S);
119*67e74705SXin Li else if (const NestedNameSpecifier *NNS =
120*67e74705SXin Li DynNode.get<NestedNameSpecifier>())
121*67e74705SXin Li traverse(*NNS);
122*67e74705SXin Li else if (const NestedNameSpecifierLoc *NNSLoc =
123*67e74705SXin Li DynNode.get<NestedNameSpecifierLoc>())
124*67e74705SXin Li traverse(*NNSLoc);
125*67e74705SXin Li else if (const QualType *Q = DynNode.get<QualType>())
126*67e74705SXin Li traverse(*Q);
127*67e74705SXin Li else if (const TypeLoc *T = DynNode.get<TypeLoc>())
128*67e74705SXin Li traverse(*T);
129*67e74705SXin Li // FIXME: Add other base types after adding tests.
130*67e74705SXin Li
131*67e74705SXin Li // It's OK to always overwrite the bound nodes, as if there was
132*67e74705SXin Li // no match in this recursive branch, the result set is empty
133*67e74705SXin Li // anyway.
134*67e74705SXin Li *Builder = ResultBindings;
135*67e74705SXin Li
136*67e74705SXin Li return Matches;
137*67e74705SXin Li }
138*67e74705SXin Li
139*67e74705SXin Li // The following are overriding methods from the base visitor class.
140*67e74705SXin Li // They are public only to allow CRTP to work. They are *not *part
141*67e74705SXin Li // of the public API of this class.
TraverseDecl(Decl * DeclNode)142*67e74705SXin Li bool TraverseDecl(Decl *DeclNode) {
143*67e74705SXin Li ScopedIncrement ScopedDepth(&CurrentDepth);
144*67e74705SXin Li return (DeclNode == nullptr) || traverse(*DeclNode);
145*67e74705SXin Li }
TraverseStmt(Stmt * StmtNode)146*67e74705SXin Li bool TraverseStmt(Stmt *StmtNode) {
147*67e74705SXin Li ScopedIncrement ScopedDepth(&CurrentDepth);
148*67e74705SXin Li const Stmt *StmtToTraverse = StmtNode;
149*67e74705SXin Li if (Traversal ==
150*67e74705SXin Li ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses) {
151*67e74705SXin Li const Expr *ExprNode = dyn_cast_or_null<Expr>(StmtNode);
152*67e74705SXin Li if (ExprNode) {
153*67e74705SXin Li StmtToTraverse = ExprNode->IgnoreParenImpCasts();
154*67e74705SXin Li }
155*67e74705SXin Li }
156*67e74705SXin Li return (StmtToTraverse == nullptr) || traverse(*StmtToTraverse);
157*67e74705SXin Li }
158*67e74705SXin Li // We assume that the QualType and the contained type are on the same
159*67e74705SXin Li // hierarchy level. Thus, we try to match either of them.
TraverseType(QualType TypeNode)160*67e74705SXin Li bool TraverseType(QualType TypeNode) {
161*67e74705SXin Li if (TypeNode.isNull())
162*67e74705SXin Li return true;
163*67e74705SXin Li ScopedIncrement ScopedDepth(&CurrentDepth);
164*67e74705SXin Li // Match the Type.
165*67e74705SXin Li if (!match(*TypeNode))
166*67e74705SXin Li return false;
167*67e74705SXin Li // The QualType is matched inside traverse.
168*67e74705SXin Li return traverse(TypeNode);
169*67e74705SXin Li }
170*67e74705SXin Li // We assume that the TypeLoc, contained QualType and contained Type all are
171*67e74705SXin Li // on the same hierarchy level. Thus, we try to match all of them.
TraverseTypeLoc(TypeLoc TypeLocNode)172*67e74705SXin Li bool TraverseTypeLoc(TypeLoc TypeLocNode) {
173*67e74705SXin Li if (TypeLocNode.isNull())
174*67e74705SXin Li return true;
175*67e74705SXin Li ScopedIncrement ScopedDepth(&CurrentDepth);
176*67e74705SXin Li // Match the Type.
177*67e74705SXin Li if (!match(*TypeLocNode.getType()))
178*67e74705SXin Li return false;
179*67e74705SXin Li // Match the QualType.
180*67e74705SXin Li if (!match(TypeLocNode.getType()))
181*67e74705SXin Li return false;
182*67e74705SXin Li // The TypeLoc is matched inside traverse.
183*67e74705SXin Li return traverse(TypeLocNode);
184*67e74705SXin Li }
TraverseNestedNameSpecifier(NestedNameSpecifier * NNS)185*67e74705SXin Li bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
186*67e74705SXin Li ScopedIncrement ScopedDepth(&CurrentDepth);
187*67e74705SXin Li return (NNS == nullptr) || traverse(*NNS);
188*67e74705SXin Li }
TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS)189*67e74705SXin Li bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
190*67e74705SXin Li if (!NNS)
191*67e74705SXin Li return true;
192*67e74705SXin Li ScopedIncrement ScopedDepth(&CurrentDepth);
193*67e74705SXin Li if (!match(*NNS.getNestedNameSpecifier()))
194*67e74705SXin Li return false;
195*67e74705SXin Li return traverse(NNS);
196*67e74705SXin Li }
197*67e74705SXin Li
shouldVisitTemplateInstantiations() const198*67e74705SXin Li bool shouldVisitTemplateInstantiations() const { return true; }
shouldVisitImplicitCode() const199*67e74705SXin Li bool shouldVisitImplicitCode() const { return true; }
200*67e74705SXin Li
201*67e74705SXin Li private:
202*67e74705SXin Li // Used for updating the depth during traversal.
203*67e74705SXin Li struct ScopedIncrement {
ScopedIncrementclang::ast_matchers::internal::__anon37a3694d0111::MatchChildASTVisitor::ScopedIncrement204*67e74705SXin Li explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); }
~ScopedIncrementclang::ast_matchers::internal::__anon37a3694d0111::MatchChildASTVisitor::ScopedIncrement205*67e74705SXin Li ~ScopedIncrement() { --(*Depth); }
206*67e74705SXin Li
207*67e74705SXin Li private:
208*67e74705SXin Li int *Depth;
209*67e74705SXin Li };
210*67e74705SXin Li
211*67e74705SXin Li // Resets the state of this object.
reset()212*67e74705SXin Li void reset() {
213*67e74705SXin Li Matches = false;
214*67e74705SXin Li CurrentDepth = 0;
215*67e74705SXin Li }
216*67e74705SXin Li
217*67e74705SXin Li // Forwards the call to the corresponding Traverse*() method in the
218*67e74705SXin Li // base visitor class.
baseTraverse(const Decl & DeclNode)219*67e74705SXin Li bool baseTraverse(const Decl &DeclNode) {
220*67e74705SXin Li return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
221*67e74705SXin Li }
baseTraverse(const Stmt & StmtNode)222*67e74705SXin Li bool baseTraverse(const Stmt &StmtNode) {
223*67e74705SXin Li return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
224*67e74705SXin Li }
baseTraverse(QualType TypeNode)225*67e74705SXin Li bool baseTraverse(QualType TypeNode) {
226*67e74705SXin Li return VisitorBase::TraverseType(TypeNode);
227*67e74705SXin Li }
baseTraverse(TypeLoc TypeLocNode)228*67e74705SXin Li bool baseTraverse(TypeLoc TypeLocNode) {
229*67e74705SXin Li return VisitorBase::TraverseTypeLoc(TypeLocNode);
230*67e74705SXin Li }
baseTraverse(const NestedNameSpecifier & NNS)231*67e74705SXin Li bool baseTraverse(const NestedNameSpecifier &NNS) {
232*67e74705SXin Li return VisitorBase::TraverseNestedNameSpecifier(
233*67e74705SXin Li const_cast<NestedNameSpecifier*>(&NNS));
234*67e74705SXin Li }
baseTraverse(NestedNameSpecifierLoc NNS)235*67e74705SXin Li bool baseTraverse(NestedNameSpecifierLoc NNS) {
236*67e74705SXin Li return VisitorBase::TraverseNestedNameSpecifierLoc(NNS);
237*67e74705SXin Li }
238*67e74705SXin Li
239*67e74705SXin Li // Sets 'Matched' to true if 'Matcher' matches 'Node' and:
240*67e74705SXin Li // 0 < CurrentDepth <= MaxDepth.
241*67e74705SXin Li //
242*67e74705SXin Li // Returns 'true' if traversal should continue after this function
243*67e74705SXin Li // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
244*67e74705SXin Li template <typename T>
match(const T & Node)245*67e74705SXin Li bool match(const T &Node) {
246*67e74705SXin Li if (CurrentDepth == 0 || CurrentDepth > MaxDepth) {
247*67e74705SXin Li return true;
248*67e74705SXin Li }
249*67e74705SXin Li if (Bind != ASTMatchFinder::BK_All) {
250*67e74705SXin Li BoundNodesTreeBuilder RecursiveBuilder(*Builder);
251*67e74705SXin Li if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node), Finder,
252*67e74705SXin Li &RecursiveBuilder)) {
253*67e74705SXin Li Matches = true;
254*67e74705SXin Li ResultBindings.addMatch(RecursiveBuilder);
255*67e74705SXin Li return false; // Abort as soon as a match is found.
256*67e74705SXin Li }
257*67e74705SXin Li } else {
258*67e74705SXin Li BoundNodesTreeBuilder RecursiveBuilder(*Builder);
259*67e74705SXin Li if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node), Finder,
260*67e74705SXin Li &RecursiveBuilder)) {
261*67e74705SXin Li // After the first match the matcher succeeds.
262*67e74705SXin Li Matches = true;
263*67e74705SXin Li ResultBindings.addMatch(RecursiveBuilder);
264*67e74705SXin Li }
265*67e74705SXin Li }
266*67e74705SXin Li return true;
267*67e74705SXin Li }
268*67e74705SXin Li
269*67e74705SXin Li // Traverses the subtree rooted at 'Node'; returns true if the
270*67e74705SXin Li // traversal should continue after this function returns.
271*67e74705SXin Li template <typename T>
traverse(const T & Node)272*67e74705SXin Li bool traverse(const T &Node) {
273*67e74705SXin Li static_assert(IsBaseType<T>::value,
274*67e74705SXin Li "traverse can only be instantiated with base type");
275*67e74705SXin Li if (!match(Node))
276*67e74705SXin Li return false;
277*67e74705SXin Li return baseTraverse(Node);
278*67e74705SXin Li }
279*67e74705SXin Li
280*67e74705SXin Li const DynTypedMatcher *const Matcher;
281*67e74705SXin Li ASTMatchFinder *const Finder;
282*67e74705SXin Li BoundNodesTreeBuilder *const Builder;
283*67e74705SXin Li BoundNodesTreeBuilder ResultBindings;
284*67e74705SXin Li int CurrentDepth;
285*67e74705SXin Li const int MaxDepth;
286*67e74705SXin Li const ASTMatchFinder::TraversalKind Traversal;
287*67e74705SXin Li const ASTMatchFinder::BindKind Bind;
288*67e74705SXin Li bool Matches;
289*67e74705SXin Li };
290*67e74705SXin Li
291*67e74705SXin Li // Controls the outermost traversal of the AST and allows to match multiple
292*67e74705SXin Li // matchers.
293*67e74705SXin Li class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
294*67e74705SXin Li public ASTMatchFinder {
295*67e74705SXin Li public:
MatchASTVisitor(const MatchFinder::MatchersByType * Matchers,const MatchFinder::MatchFinderOptions & Options)296*67e74705SXin Li MatchASTVisitor(const MatchFinder::MatchersByType *Matchers,
297*67e74705SXin Li const MatchFinder::MatchFinderOptions &Options)
298*67e74705SXin Li : Matchers(Matchers), Options(Options), ActiveASTContext(nullptr) {}
299*67e74705SXin Li
~MatchASTVisitor()300*67e74705SXin Li ~MatchASTVisitor() override {
301*67e74705SXin Li if (Options.CheckProfiling) {
302*67e74705SXin Li Options.CheckProfiling->Records = std::move(TimeByBucket);
303*67e74705SXin Li }
304*67e74705SXin Li }
305*67e74705SXin Li
onStartOfTranslationUnit()306*67e74705SXin Li void onStartOfTranslationUnit() {
307*67e74705SXin Li const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
308*67e74705SXin Li TimeBucketRegion Timer;
309*67e74705SXin Li for (MatchCallback *MC : Matchers->AllCallbacks) {
310*67e74705SXin Li if (EnableCheckProfiling)
311*67e74705SXin Li Timer.setBucket(&TimeByBucket[MC->getID()]);
312*67e74705SXin Li MC->onStartOfTranslationUnit();
313*67e74705SXin Li }
314*67e74705SXin Li }
315*67e74705SXin Li
onEndOfTranslationUnit()316*67e74705SXin Li void onEndOfTranslationUnit() {
317*67e74705SXin Li const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
318*67e74705SXin Li TimeBucketRegion Timer;
319*67e74705SXin Li for (MatchCallback *MC : Matchers->AllCallbacks) {
320*67e74705SXin Li if (EnableCheckProfiling)
321*67e74705SXin Li Timer.setBucket(&TimeByBucket[MC->getID()]);
322*67e74705SXin Li MC->onEndOfTranslationUnit();
323*67e74705SXin Li }
324*67e74705SXin Li }
325*67e74705SXin Li
set_active_ast_context(ASTContext * NewActiveASTContext)326*67e74705SXin Li void set_active_ast_context(ASTContext *NewActiveASTContext) {
327*67e74705SXin Li ActiveASTContext = NewActiveASTContext;
328*67e74705SXin Li }
329*67e74705SXin Li
330*67e74705SXin Li // The following Visit*() and Traverse*() functions "override"
331*67e74705SXin Li // methods in RecursiveASTVisitor.
332*67e74705SXin Li
VisitTypedefNameDecl(TypedefNameDecl * DeclNode)333*67e74705SXin Li bool VisitTypedefNameDecl(TypedefNameDecl *DeclNode) {
334*67e74705SXin Li // When we see 'typedef A B', we add name 'B' to the set of names
335*67e74705SXin Li // A's canonical type maps to. This is necessary for implementing
336*67e74705SXin Li // isDerivedFrom(x) properly, where x can be the name of the base
337*67e74705SXin Li // class or any of its aliases.
338*67e74705SXin Li //
339*67e74705SXin Li // In general, the is-alias-of (as defined by typedefs) relation
340*67e74705SXin Li // is tree-shaped, as you can typedef a type more than once. For
341*67e74705SXin Li // example,
342*67e74705SXin Li //
343*67e74705SXin Li // typedef A B;
344*67e74705SXin Li // typedef A C;
345*67e74705SXin Li // typedef C D;
346*67e74705SXin Li // typedef C E;
347*67e74705SXin Li //
348*67e74705SXin Li // gives you
349*67e74705SXin Li //
350*67e74705SXin Li // A
351*67e74705SXin Li // |- B
352*67e74705SXin Li // `- C
353*67e74705SXin Li // |- D
354*67e74705SXin Li // `- E
355*67e74705SXin Li //
356*67e74705SXin Li // It is wrong to assume that the relation is a chain. A correct
357*67e74705SXin Li // implementation of isDerivedFrom() needs to recognize that B and
358*67e74705SXin Li // E are aliases, even though neither is a typedef of the other.
359*67e74705SXin Li // Therefore, we cannot simply walk through one typedef chain to
360*67e74705SXin Li // find out whether the type name matches.
361*67e74705SXin Li const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
362*67e74705SXin Li const Type *CanonicalType = // root of the typedef tree
363*67e74705SXin Li ActiveASTContext->getCanonicalType(TypeNode);
364*67e74705SXin Li TypeAliases[CanonicalType].insert(DeclNode);
365*67e74705SXin Li return true;
366*67e74705SXin Li }
367*67e74705SXin Li
368*67e74705SXin Li bool TraverseDecl(Decl *DeclNode);
369*67e74705SXin Li bool TraverseStmt(Stmt *StmtNode);
370*67e74705SXin Li bool TraverseType(QualType TypeNode);
371*67e74705SXin Li bool TraverseTypeLoc(TypeLoc TypeNode);
372*67e74705SXin Li bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
373*67e74705SXin Li bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
374*67e74705SXin Li
375*67e74705SXin Li // Matches children or descendants of 'Node' with 'BaseMatcher'.
memoizedMatchesRecursively(const ast_type_traits::DynTypedNode & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,int MaxDepth,TraversalKind Traversal,BindKind Bind)376*67e74705SXin Li bool memoizedMatchesRecursively(const ast_type_traits::DynTypedNode &Node,
377*67e74705SXin Li const DynTypedMatcher &Matcher,
378*67e74705SXin Li BoundNodesTreeBuilder *Builder, int MaxDepth,
379*67e74705SXin Li TraversalKind Traversal, BindKind Bind) {
380*67e74705SXin Li // For AST-nodes that don't have an identity, we can't memoize.
381*67e74705SXin Li if (!Node.getMemoizationData() || !Builder->isComparable())
382*67e74705SXin Li return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal,
383*67e74705SXin Li Bind);
384*67e74705SXin Li
385*67e74705SXin Li MatchKey Key;
386*67e74705SXin Li Key.MatcherID = Matcher.getID();
387*67e74705SXin Li Key.Node = Node;
388*67e74705SXin Li // Note that we key on the bindings *before* the match.
389*67e74705SXin Li Key.BoundNodes = *Builder;
390*67e74705SXin Li
391*67e74705SXin Li MemoizationMap::iterator I = ResultCache.find(Key);
392*67e74705SXin Li if (I != ResultCache.end()) {
393*67e74705SXin Li *Builder = I->second.Nodes;
394*67e74705SXin Li return I->second.ResultOfMatch;
395*67e74705SXin Li }
396*67e74705SXin Li
397*67e74705SXin Li MemoizedMatchResult Result;
398*67e74705SXin Li Result.Nodes = *Builder;
399*67e74705SXin Li Result.ResultOfMatch = matchesRecursively(Node, Matcher, &Result.Nodes,
400*67e74705SXin Li MaxDepth, Traversal, Bind);
401*67e74705SXin Li
402*67e74705SXin Li MemoizedMatchResult &CachedResult = ResultCache[Key];
403*67e74705SXin Li CachedResult = std::move(Result);
404*67e74705SXin Li
405*67e74705SXin Li *Builder = CachedResult.Nodes;
406*67e74705SXin Li return CachedResult.ResultOfMatch;
407*67e74705SXin Li }
408*67e74705SXin Li
409*67e74705SXin Li // Matches children or descendants of 'Node' with 'BaseMatcher'.
matchesRecursively(const ast_type_traits::DynTypedNode & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,int MaxDepth,TraversalKind Traversal,BindKind Bind)410*67e74705SXin Li bool matchesRecursively(const ast_type_traits::DynTypedNode &Node,
411*67e74705SXin Li const DynTypedMatcher &Matcher,
412*67e74705SXin Li BoundNodesTreeBuilder *Builder, int MaxDepth,
413*67e74705SXin Li TraversalKind Traversal, BindKind Bind) {
414*67e74705SXin Li MatchChildASTVisitor Visitor(
415*67e74705SXin Li &Matcher, this, Builder, MaxDepth, Traversal, Bind);
416*67e74705SXin Li return Visitor.findMatch(Node);
417*67e74705SXin Li }
418*67e74705SXin Li
419*67e74705SXin Li bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
420*67e74705SXin Li const Matcher<NamedDecl> &Base,
421*67e74705SXin Li BoundNodesTreeBuilder *Builder) override;
422*67e74705SXin Li
423*67e74705SXin Li // Implements ASTMatchFinder::matchesChildOf.
matchesChildOf(const ast_type_traits::DynTypedNode & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,TraversalKind Traversal,BindKind Bind)424*67e74705SXin Li bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
425*67e74705SXin Li const DynTypedMatcher &Matcher,
426*67e74705SXin Li BoundNodesTreeBuilder *Builder,
427*67e74705SXin Li TraversalKind Traversal,
428*67e74705SXin Li BindKind Bind) override {
429*67e74705SXin Li if (ResultCache.size() > MaxMemoizationEntries)
430*67e74705SXin Li ResultCache.clear();
431*67e74705SXin Li return memoizedMatchesRecursively(Node, Matcher, Builder, 1, Traversal,
432*67e74705SXin Li Bind);
433*67e74705SXin Li }
434*67e74705SXin Li // Implements ASTMatchFinder::matchesDescendantOf.
matchesDescendantOf(const ast_type_traits::DynTypedNode & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,BindKind Bind)435*67e74705SXin Li bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
436*67e74705SXin Li const DynTypedMatcher &Matcher,
437*67e74705SXin Li BoundNodesTreeBuilder *Builder,
438*67e74705SXin Li BindKind Bind) override {
439*67e74705SXin Li if (ResultCache.size() > MaxMemoizationEntries)
440*67e74705SXin Li ResultCache.clear();
441*67e74705SXin Li return memoizedMatchesRecursively(Node, Matcher, Builder, INT_MAX,
442*67e74705SXin Li TK_AsIs, Bind);
443*67e74705SXin Li }
444*67e74705SXin Li // Implements ASTMatchFinder::matchesAncestorOf.
matchesAncestorOf(const ast_type_traits::DynTypedNode & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,AncestorMatchMode MatchMode)445*67e74705SXin Li bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
446*67e74705SXin Li const DynTypedMatcher &Matcher,
447*67e74705SXin Li BoundNodesTreeBuilder *Builder,
448*67e74705SXin Li AncestorMatchMode MatchMode) override {
449*67e74705SXin Li // Reset the cache outside of the recursive call to make sure we
450*67e74705SXin Li // don't invalidate any iterators.
451*67e74705SXin Li if (ResultCache.size() > MaxMemoizationEntries)
452*67e74705SXin Li ResultCache.clear();
453*67e74705SXin Li return memoizedMatchesAncestorOfRecursively(Node, Matcher, Builder,
454*67e74705SXin Li MatchMode);
455*67e74705SXin Li }
456*67e74705SXin Li
457*67e74705SXin Li // Matches all registered matchers on the given node and calls the
458*67e74705SXin Li // result callback for every node that matches.
match(const ast_type_traits::DynTypedNode & Node)459*67e74705SXin Li void match(const ast_type_traits::DynTypedNode &Node) {
460*67e74705SXin Li // FIXME: Improve this with a switch or a visitor pattern.
461*67e74705SXin Li if (auto *N = Node.get<Decl>()) {
462*67e74705SXin Li match(*N);
463*67e74705SXin Li } else if (auto *N = Node.get<Stmt>()) {
464*67e74705SXin Li match(*N);
465*67e74705SXin Li } else if (auto *N = Node.get<Type>()) {
466*67e74705SXin Li match(*N);
467*67e74705SXin Li } else if (auto *N = Node.get<QualType>()) {
468*67e74705SXin Li match(*N);
469*67e74705SXin Li } else if (auto *N = Node.get<NestedNameSpecifier>()) {
470*67e74705SXin Li match(*N);
471*67e74705SXin Li } else if (auto *N = Node.get<NestedNameSpecifierLoc>()) {
472*67e74705SXin Li match(*N);
473*67e74705SXin Li } else if (auto *N = Node.get<TypeLoc>()) {
474*67e74705SXin Li match(*N);
475*67e74705SXin Li }
476*67e74705SXin Li }
477*67e74705SXin Li
match(const T & Node)478*67e74705SXin Li template <typename T> void match(const T &Node) {
479*67e74705SXin Li matchDispatch(&Node);
480*67e74705SXin Li }
481*67e74705SXin Li
482*67e74705SXin Li // Implements ASTMatchFinder::getASTContext.
getASTContext() const483*67e74705SXin Li ASTContext &getASTContext() const override { return *ActiveASTContext; }
484*67e74705SXin Li
shouldVisitTemplateInstantiations() const485*67e74705SXin Li bool shouldVisitTemplateInstantiations() const { return true; }
shouldVisitImplicitCode() const486*67e74705SXin Li bool shouldVisitImplicitCode() const { return true; }
487*67e74705SXin Li
488*67e74705SXin Li private:
489*67e74705SXin Li class TimeBucketRegion {
490*67e74705SXin Li public:
TimeBucketRegion()491*67e74705SXin Li TimeBucketRegion() : Bucket(nullptr) {}
~TimeBucketRegion()492*67e74705SXin Li ~TimeBucketRegion() { setBucket(nullptr); }
493*67e74705SXin Li
494*67e74705SXin Li /// \brief Start timing for \p NewBucket.
495*67e74705SXin Li ///
496*67e74705SXin Li /// If there was a bucket already set, it will finish the timing for that
497*67e74705SXin Li /// other bucket.
498*67e74705SXin Li /// \p NewBucket will be timed until the next call to \c setBucket() or
499*67e74705SXin Li /// until the \c TimeBucketRegion is destroyed.
500*67e74705SXin Li /// If \p NewBucket is the same as the currently timed bucket, this call
501*67e74705SXin Li /// does nothing.
setBucket(llvm::TimeRecord * NewBucket)502*67e74705SXin Li void setBucket(llvm::TimeRecord *NewBucket) {
503*67e74705SXin Li if (Bucket != NewBucket) {
504*67e74705SXin Li auto Now = llvm::TimeRecord::getCurrentTime(true);
505*67e74705SXin Li if (Bucket)
506*67e74705SXin Li *Bucket += Now;
507*67e74705SXin Li if (NewBucket)
508*67e74705SXin Li *NewBucket -= Now;
509*67e74705SXin Li Bucket = NewBucket;
510*67e74705SXin Li }
511*67e74705SXin Li }
512*67e74705SXin Li
513*67e74705SXin Li private:
514*67e74705SXin Li llvm::TimeRecord *Bucket;
515*67e74705SXin Li };
516*67e74705SXin Li
517*67e74705SXin Li /// \brief Runs all the \p Matchers on \p Node.
518*67e74705SXin Li ///
519*67e74705SXin Li /// Used by \c matchDispatch() below.
520*67e74705SXin Li template <typename T, typename MC>
matchWithoutFilter(const T & Node,const MC & Matchers)521*67e74705SXin Li void matchWithoutFilter(const T &Node, const MC &Matchers) {
522*67e74705SXin Li const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
523*67e74705SXin Li TimeBucketRegion Timer;
524*67e74705SXin Li for (const auto &MP : Matchers) {
525*67e74705SXin Li if (EnableCheckProfiling)
526*67e74705SXin Li Timer.setBucket(&TimeByBucket[MP.second->getID()]);
527*67e74705SXin Li BoundNodesTreeBuilder Builder;
528*67e74705SXin Li if (MP.first.matches(Node, this, &Builder)) {
529*67e74705SXin Li MatchVisitor Visitor(ActiveASTContext, MP.second);
530*67e74705SXin Li Builder.visitMatches(&Visitor);
531*67e74705SXin Li }
532*67e74705SXin Li }
533*67e74705SXin Li }
534*67e74705SXin Li
matchWithFilter(const ast_type_traits::DynTypedNode & DynNode)535*67e74705SXin Li void matchWithFilter(const ast_type_traits::DynTypedNode &DynNode) {
536*67e74705SXin Li auto Kind = DynNode.getNodeKind();
537*67e74705SXin Li auto it = MatcherFiltersMap.find(Kind);
538*67e74705SXin Li const auto &Filter =
539*67e74705SXin Li it != MatcherFiltersMap.end() ? it->second : getFilterForKind(Kind);
540*67e74705SXin Li
541*67e74705SXin Li if (Filter.empty())
542*67e74705SXin Li return;
543*67e74705SXin Li
544*67e74705SXin Li const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
545*67e74705SXin Li TimeBucketRegion Timer;
546*67e74705SXin Li auto &Matchers = this->Matchers->DeclOrStmt;
547*67e74705SXin Li for (unsigned short I : Filter) {
548*67e74705SXin Li auto &MP = Matchers[I];
549*67e74705SXin Li if (EnableCheckProfiling)
550*67e74705SXin Li Timer.setBucket(&TimeByBucket[MP.second->getID()]);
551*67e74705SXin Li BoundNodesTreeBuilder Builder;
552*67e74705SXin Li if (MP.first.matchesNoKindCheck(DynNode, this, &Builder)) {
553*67e74705SXin Li MatchVisitor Visitor(ActiveASTContext, MP.second);
554*67e74705SXin Li Builder.visitMatches(&Visitor);
555*67e74705SXin Li }
556*67e74705SXin Li }
557*67e74705SXin Li }
558*67e74705SXin Li
559*67e74705SXin Li const std::vector<unsigned short> &
getFilterForKind(ast_type_traits::ASTNodeKind Kind)560*67e74705SXin Li getFilterForKind(ast_type_traits::ASTNodeKind Kind) {
561*67e74705SXin Li auto &Filter = MatcherFiltersMap[Kind];
562*67e74705SXin Li auto &Matchers = this->Matchers->DeclOrStmt;
563*67e74705SXin Li assert((Matchers.size() < USHRT_MAX) && "Too many matchers.");
564*67e74705SXin Li for (unsigned I = 0, E = Matchers.size(); I != E; ++I) {
565*67e74705SXin Li if (Matchers[I].first.canMatchNodesOfKind(Kind)) {
566*67e74705SXin Li Filter.push_back(I);
567*67e74705SXin Li }
568*67e74705SXin Li }
569*67e74705SXin Li return Filter;
570*67e74705SXin Li }
571*67e74705SXin Li
572*67e74705SXin Li /// @{
573*67e74705SXin Li /// \brief Overloads to pair the different node types to their matchers.
matchDispatch(const Decl * Node)574*67e74705SXin Li void matchDispatch(const Decl *Node) {
575*67e74705SXin Li return matchWithFilter(ast_type_traits::DynTypedNode::create(*Node));
576*67e74705SXin Li }
matchDispatch(const Stmt * Node)577*67e74705SXin Li void matchDispatch(const Stmt *Node) {
578*67e74705SXin Li return matchWithFilter(ast_type_traits::DynTypedNode::create(*Node));
579*67e74705SXin Li }
580*67e74705SXin Li
matchDispatch(const Type * Node)581*67e74705SXin Li void matchDispatch(const Type *Node) {
582*67e74705SXin Li matchWithoutFilter(QualType(Node, 0), Matchers->Type);
583*67e74705SXin Li }
matchDispatch(const TypeLoc * Node)584*67e74705SXin Li void matchDispatch(const TypeLoc *Node) {
585*67e74705SXin Li matchWithoutFilter(*Node, Matchers->TypeLoc);
586*67e74705SXin Li }
matchDispatch(const QualType * Node)587*67e74705SXin Li void matchDispatch(const QualType *Node) {
588*67e74705SXin Li matchWithoutFilter(*Node, Matchers->Type);
589*67e74705SXin Li }
matchDispatch(const NestedNameSpecifier * Node)590*67e74705SXin Li void matchDispatch(const NestedNameSpecifier *Node) {
591*67e74705SXin Li matchWithoutFilter(*Node, Matchers->NestedNameSpecifier);
592*67e74705SXin Li }
matchDispatch(const NestedNameSpecifierLoc * Node)593*67e74705SXin Li void matchDispatch(const NestedNameSpecifierLoc *Node) {
594*67e74705SXin Li matchWithoutFilter(*Node, Matchers->NestedNameSpecifierLoc);
595*67e74705SXin Li }
matchDispatch(const void *)596*67e74705SXin Li void matchDispatch(const void *) { /* Do nothing. */ }
597*67e74705SXin Li /// @}
598*67e74705SXin Li
599*67e74705SXin Li // Returns whether an ancestor of \p Node matches \p Matcher.
600*67e74705SXin Li //
601*67e74705SXin Li // The order of matching ((which can lead to different nodes being bound in
602*67e74705SXin Li // case there are multiple matches) is breadth first search.
603*67e74705SXin Li //
604*67e74705SXin Li // To allow memoization in the very common case of having deeply nested
605*67e74705SXin Li // expressions inside a template function, we first walk up the AST, memoizing
606*67e74705SXin Li // the result of the match along the way, as long as there is only a single
607*67e74705SXin Li // parent.
608*67e74705SXin Li //
609*67e74705SXin Li // Once there are multiple parents, the breadth first search order does not
610*67e74705SXin Li // allow simple memoization on the ancestors. Thus, we only memoize as long
611*67e74705SXin Li // as there is a single parent.
memoizedMatchesAncestorOfRecursively(const ast_type_traits::DynTypedNode & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,AncestorMatchMode MatchMode)612*67e74705SXin Li bool memoizedMatchesAncestorOfRecursively(
613*67e74705SXin Li const ast_type_traits::DynTypedNode &Node, const DynTypedMatcher &Matcher,
614*67e74705SXin Li BoundNodesTreeBuilder *Builder, AncestorMatchMode MatchMode) {
615*67e74705SXin Li if (Node.get<TranslationUnitDecl>() ==
616*67e74705SXin Li ActiveASTContext->getTranslationUnitDecl())
617*67e74705SXin Li return false;
618*67e74705SXin Li
619*67e74705SXin Li // For AST-nodes that don't have an identity, we can't memoize.
620*67e74705SXin Li if (!Builder->isComparable())
621*67e74705SXin Li return matchesAncestorOfRecursively(Node, Matcher, Builder, MatchMode);
622*67e74705SXin Li
623*67e74705SXin Li MatchKey Key;
624*67e74705SXin Li Key.MatcherID = Matcher.getID();
625*67e74705SXin Li Key.Node = Node;
626*67e74705SXin Li Key.BoundNodes = *Builder;
627*67e74705SXin Li
628*67e74705SXin Li // Note that we cannot use insert and reuse the iterator, as recursive
629*67e74705SXin Li // calls to match might invalidate the result cache iterators.
630*67e74705SXin Li MemoizationMap::iterator I = ResultCache.find(Key);
631*67e74705SXin Li if (I != ResultCache.end()) {
632*67e74705SXin Li *Builder = I->second.Nodes;
633*67e74705SXin Li return I->second.ResultOfMatch;
634*67e74705SXin Li }
635*67e74705SXin Li
636*67e74705SXin Li MemoizedMatchResult Result;
637*67e74705SXin Li Result.Nodes = *Builder;
638*67e74705SXin Li Result.ResultOfMatch =
639*67e74705SXin Li matchesAncestorOfRecursively(Node, Matcher, &Result.Nodes, MatchMode);
640*67e74705SXin Li
641*67e74705SXin Li MemoizedMatchResult &CachedResult = ResultCache[Key];
642*67e74705SXin Li CachedResult = std::move(Result);
643*67e74705SXin Li
644*67e74705SXin Li *Builder = CachedResult.Nodes;
645*67e74705SXin Li return CachedResult.ResultOfMatch;
646*67e74705SXin Li }
647*67e74705SXin Li
matchesAncestorOfRecursively(const ast_type_traits::DynTypedNode & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,AncestorMatchMode MatchMode)648*67e74705SXin Li bool matchesAncestorOfRecursively(const ast_type_traits::DynTypedNode &Node,
649*67e74705SXin Li const DynTypedMatcher &Matcher,
650*67e74705SXin Li BoundNodesTreeBuilder *Builder,
651*67e74705SXin Li AncestorMatchMode MatchMode) {
652*67e74705SXin Li const auto &Parents = ActiveASTContext->getParents(Node);
653*67e74705SXin Li assert(!Parents.empty() && "Found node that is not in the parent map.");
654*67e74705SXin Li if (Parents.size() == 1) {
655*67e74705SXin Li // Only one parent - do recursive memoization.
656*67e74705SXin Li const ast_type_traits::DynTypedNode Parent = Parents[0];
657*67e74705SXin Li BoundNodesTreeBuilder BuilderCopy = *Builder;
658*67e74705SXin Li if (Matcher.matches(Parent, this, &BuilderCopy)) {
659*67e74705SXin Li *Builder = std::move(BuilderCopy);
660*67e74705SXin Li return true;
661*67e74705SXin Li }
662*67e74705SXin Li if (MatchMode != ASTMatchFinder::AMM_ParentOnly) {
663*67e74705SXin Li return memoizedMatchesAncestorOfRecursively(Parent, Matcher, Builder,
664*67e74705SXin Li MatchMode);
665*67e74705SXin Li // Once we get back from the recursive call, the result will be the
666*67e74705SXin Li // same as the parent's result.
667*67e74705SXin Li }
668*67e74705SXin Li } else {
669*67e74705SXin Li // Multiple parents - BFS over the rest of the nodes.
670*67e74705SXin Li llvm::DenseSet<const void *> Visited;
671*67e74705SXin Li std::deque<ast_type_traits::DynTypedNode> Queue(Parents.begin(),
672*67e74705SXin Li Parents.end());
673*67e74705SXin Li while (!Queue.empty()) {
674*67e74705SXin Li BoundNodesTreeBuilder BuilderCopy = *Builder;
675*67e74705SXin Li if (Matcher.matches(Queue.front(), this, &BuilderCopy)) {
676*67e74705SXin Li *Builder = std::move(BuilderCopy);
677*67e74705SXin Li return true;
678*67e74705SXin Li }
679*67e74705SXin Li if (MatchMode != ASTMatchFinder::AMM_ParentOnly) {
680*67e74705SXin Li for (const auto &Parent :
681*67e74705SXin Li ActiveASTContext->getParents(Queue.front())) {
682*67e74705SXin Li // Make sure we do not visit the same node twice.
683*67e74705SXin Li // Otherwise, we'll visit the common ancestors as often as there
684*67e74705SXin Li // are splits on the way down.
685*67e74705SXin Li if (Visited.insert(Parent.getMemoizationData()).second)
686*67e74705SXin Li Queue.push_back(Parent);
687*67e74705SXin Li }
688*67e74705SXin Li }
689*67e74705SXin Li Queue.pop_front();
690*67e74705SXin Li }
691*67e74705SXin Li }
692*67e74705SXin Li return false;
693*67e74705SXin Li }
694*67e74705SXin Li
695*67e74705SXin Li // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
696*67e74705SXin Li // the aggregated bound nodes for each match.
697*67e74705SXin Li class MatchVisitor : public BoundNodesTreeBuilder::Visitor {
698*67e74705SXin Li public:
MatchVisitor(ASTContext * Context,MatchFinder::MatchCallback * Callback)699*67e74705SXin Li MatchVisitor(ASTContext* Context,
700*67e74705SXin Li MatchFinder::MatchCallback* Callback)
701*67e74705SXin Li : Context(Context),
702*67e74705SXin Li Callback(Callback) {}
703*67e74705SXin Li
visitMatch(const BoundNodes & BoundNodesView)704*67e74705SXin Li void visitMatch(const BoundNodes& BoundNodesView) override {
705*67e74705SXin Li Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
706*67e74705SXin Li }
707*67e74705SXin Li
708*67e74705SXin Li private:
709*67e74705SXin Li ASTContext* Context;
710*67e74705SXin Li MatchFinder::MatchCallback* Callback;
711*67e74705SXin Li };
712*67e74705SXin Li
713*67e74705SXin Li // Returns true if 'TypeNode' has an alias that matches the given matcher.
typeHasMatchingAlias(const Type * TypeNode,const Matcher<NamedDecl> & Matcher,BoundNodesTreeBuilder * Builder)714*67e74705SXin Li bool typeHasMatchingAlias(const Type *TypeNode,
715*67e74705SXin Li const Matcher<NamedDecl> &Matcher,
716*67e74705SXin Li BoundNodesTreeBuilder *Builder) {
717*67e74705SXin Li const Type *const CanonicalType =
718*67e74705SXin Li ActiveASTContext->getCanonicalType(TypeNode);
719*67e74705SXin Li for (const TypedefNameDecl *Alias : TypeAliases.lookup(CanonicalType)) {
720*67e74705SXin Li BoundNodesTreeBuilder Result(*Builder);
721*67e74705SXin Li if (Matcher.matches(*Alias, this, &Result)) {
722*67e74705SXin Li *Builder = std::move(Result);
723*67e74705SXin Li return true;
724*67e74705SXin Li }
725*67e74705SXin Li }
726*67e74705SXin Li return false;
727*67e74705SXin Li }
728*67e74705SXin Li
729*67e74705SXin Li /// \brief Bucket to record map.
730*67e74705SXin Li ///
731*67e74705SXin Li /// Used to get the appropriate bucket for each matcher.
732*67e74705SXin Li llvm::StringMap<llvm::TimeRecord> TimeByBucket;
733*67e74705SXin Li
734*67e74705SXin Li const MatchFinder::MatchersByType *Matchers;
735*67e74705SXin Li
736*67e74705SXin Li /// \brief Filtered list of matcher indices for each matcher kind.
737*67e74705SXin Li ///
738*67e74705SXin Li /// \c Decl and \c Stmt toplevel matchers usually apply to a specific node
739*67e74705SXin Li /// kind (and derived kinds) so it is a waste to try every matcher on every
740*67e74705SXin Li /// node.
741*67e74705SXin Li /// We precalculate a list of matchers that pass the toplevel restrict check.
742*67e74705SXin Li /// This also allows us to skip the restrict check at matching time. See
743*67e74705SXin Li /// use \c matchesNoKindCheck() above.
744*67e74705SXin Li llvm::DenseMap<ast_type_traits::ASTNodeKind, std::vector<unsigned short>>
745*67e74705SXin Li MatcherFiltersMap;
746*67e74705SXin Li
747*67e74705SXin Li const MatchFinder::MatchFinderOptions &Options;
748*67e74705SXin Li ASTContext *ActiveASTContext;
749*67e74705SXin Li
750*67e74705SXin Li // Maps a canonical type to its TypedefDecls.
751*67e74705SXin Li llvm::DenseMap<const Type*, std::set<const TypedefNameDecl*> > TypeAliases;
752*67e74705SXin Li
753*67e74705SXin Li // Maps (matcher, node) -> the match result for memoization.
754*67e74705SXin Li typedef std::map<MatchKey, MemoizedMatchResult> MemoizationMap;
755*67e74705SXin Li MemoizationMap ResultCache;
756*67e74705SXin Li };
757*67e74705SXin Li
758*67e74705SXin Li static CXXRecordDecl *
getAsCXXRecordDeclOrPrimaryTemplate(const Type * TypeNode)759*67e74705SXin Li getAsCXXRecordDeclOrPrimaryTemplate(const Type *TypeNode) {
760*67e74705SXin Li if (auto *RD = TypeNode->getAsCXXRecordDecl())
761*67e74705SXin Li return RD;
762*67e74705SXin Li
763*67e74705SXin Li // Find the innermost TemplateSpecializationType that isn't an alias template.
764*67e74705SXin Li auto *TemplateType = TypeNode->getAs<TemplateSpecializationType>();
765*67e74705SXin Li while (TemplateType && TemplateType->isTypeAlias())
766*67e74705SXin Li TemplateType =
767*67e74705SXin Li TemplateType->getAliasedType()->getAs<TemplateSpecializationType>();
768*67e74705SXin Li
769*67e74705SXin Li // If this is the name of a (dependent) template specialization, use the
770*67e74705SXin Li // definition of the template, even though it might be specialized later.
771*67e74705SXin Li if (TemplateType)
772*67e74705SXin Li if (auto *ClassTemplate = dyn_cast_or_null<ClassTemplateDecl>(
773*67e74705SXin Li TemplateType->getTemplateName().getAsTemplateDecl()))
774*67e74705SXin Li return ClassTemplate->getTemplatedDecl();
775*67e74705SXin Li
776*67e74705SXin Li return nullptr;
777*67e74705SXin Li }
778*67e74705SXin Li
779*67e74705SXin Li // Returns true if the given class is directly or indirectly derived
780*67e74705SXin Li // from a base type with the given name. A class is not considered to be
781*67e74705SXin Li // derived from itself.
classIsDerivedFrom(const CXXRecordDecl * Declaration,const Matcher<NamedDecl> & Base,BoundNodesTreeBuilder * Builder)782*67e74705SXin Li bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
783*67e74705SXin Li const Matcher<NamedDecl> &Base,
784*67e74705SXin Li BoundNodesTreeBuilder *Builder) {
785*67e74705SXin Li if (!Declaration->hasDefinition())
786*67e74705SXin Li return false;
787*67e74705SXin Li for (const auto &It : Declaration->bases()) {
788*67e74705SXin Li const Type *TypeNode = It.getType().getTypePtr();
789*67e74705SXin Li
790*67e74705SXin Li if (typeHasMatchingAlias(TypeNode, Base, Builder))
791*67e74705SXin Li return true;
792*67e74705SXin Li
793*67e74705SXin Li // FIXME: Going to the primary template here isn't really correct, but
794*67e74705SXin Li // unfortunately we accept a Decl matcher for the base class not a Type
795*67e74705SXin Li // matcher, so it's the best thing we can do with our current interface.
796*67e74705SXin Li CXXRecordDecl *ClassDecl = getAsCXXRecordDeclOrPrimaryTemplate(TypeNode);
797*67e74705SXin Li if (!ClassDecl)
798*67e74705SXin Li continue;
799*67e74705SXin Li if (ClassDecl == Declaration) {
800*67e74705SXin Li // This can happen for recursive template definitions; if the
801*67e74705SXin Li // current declaration did not match, we can safely return false.
802*67e74705SXin Li return false;
803*67e74705SXin Li }
804*67e74705SXin Li BoundNodesTreeBuilder Result(*Builder);
805*67e74705SXin Li if (Base.matches(*ClassDecl, this, &Result)) {
806*67e74705SXin Li *Builder = std::move(Result);
807*67e74705SXin Li return true;
808*67e74705SXin Li }
809*67e74705SXin Li if (classIsDerivedFrom(ClassDecl, Base, Builder))
810*67e74705SXin Li return true;
811*67e74705SXin Li }
812*67e74705SXin Li return false;
813*67e74705SXin Li }
814*67e74705SXin Li
TraverseDecl(Decl * DeclNode)815*67e74705SXin Li bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
816*67e74705SXin Li if (!DeclNode) {
817*67e74705SXin Li return true;
818*67e74705SXin Li }
819*67e74705SXin Li match(*DeclNode);
820*67e74705SXin Li return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
821*67e74705SXin Li }
822*67e74705SXin Li
TraverseStmt(Stmt * StmtNode)823*67e74705SXin Li bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode) {
824*67e74705SXin Li if (!StmtNode) {
825*67e74705SXin Li return true;
826*67e74705SXin Li }
827*67e74705SXin Li match(*StmtNode);
828*67e74705SXin Li return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode);
829*67e74705SXin Li }
830*67e74705SXin Li
TraverseType(QualType TypeNode)831*67e74705SXin Li bool MatchASTVisitor::TraverseType(QualType TypeNode) {
832*67e74705SXin Li match(TypeNode);
833*67e74705SXin Li return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
834*67e74705SXin Li }
835*67e74705SXin Li
TraverseTypeLoc(TypeLoc TypeLocNode)836*67e74705SXin Li bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
837*67e74705SXin Li // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
838*67e74705SXin Li // We still want to find those types via matchers, so we match them here. Note
839*67e74705SXin Li // that the TypeLocs are structurally a shadow-hierarchy to the expressed
840*67e74705SXin Li // type, so we visit all involved parts of a compound type when matching on
841*67e74705SXin Li // each TypeLoc.
842*67e74705SXin Li match(TypeLocNode);
843*67e74705SXin Li match(TypeLocNode.getType());
844*67e74705SXin Li return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
845*67e74705SXin Li }
846*67e74705SXin Li
TraverseNestedNameSpecifier(NestedNameSpecifier * NNS)847*67e74705SXin Li bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
848*67e74705SXin Li match(*NNS);
849*67e74705SXin Li return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
850*67e74705SXin Li }
851*67e74705SXin Li
TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS)852*67e74705SXin Li bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
853*67e74705SXin Li NestedNameSpecifierLoc NNS) {
854*67e74705SXin Li if (!NNS)
855*67e74705SXin Li return true;
856*67e74705SXin Li
857*67e74705SXin Li match(NNS);
858*67e74705SXin Li
859*67e74705SXin Li // We only match the nested name specifier here (as opposed to traversing it)
860*67e74705SXin Li // because the traversal is already done in the parallel "Loc"-hierarchy.
861*67e74705SXin Li if (NNS.hasQualifier())
862*67e74705SXin Li match(*NNS.getNestedNameSpecifier());
863*67e74705SXin Li return
864*67e74705SXin Li RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
865*67e74705SXin Li }
866*67e74705SXin Li
867*67e74705SXin Li class MatchASTConsumer : public ASTConsumer {
868*67e74705SXin Li public:
MatchASTConsumer(MatchFinder * Finder,MatchFinder::ParsingDoneTestCallback * ParsingDone)869*67e74705SXin Li MatchASTConsumer(MatchFinder *Finder,
870*67e74705SXin Li MatchFinder::ParsingDoneTestCallback *ParsingDone)
871*67e74705SXin Li : Finder(Finder), ParsingDone(ParsingDone) {}
872*67e74705SXin Li
873*67e74705SXin Li private:
HandleTranslationUnit(ASTContext & Context)874*67e74705SXin Li void HandleTranslationUnit(ASTContext &Context) override {
875*67e74705SXin Li if (ParsingDone != nullptr) {
876*67e74705SXin Li ParsingDone->run();
877*67e74705SXin Li }
878*67e74705SXin Li Finder->matchAST(Context);
879*67e74705SXin Li }
880*67e74705SXin Li
881*67e74705SXin Li MatchFinder *Finder;
882*67e74705SXin Li MatchFinder::ParsingDoneTestCallback *ParsingDone;
883*67e74705SXin Li };
884*67e74705SXin Li
885*67e74705SXin Li } // end namespace
886*67e74705SXin Li } // end namespace internal
887*67e74705SXin Li
MatchResult(const BoundNodes & Nodes,ASTContext * Context)888*67e74705SXin Li MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
889*67e74705SXin Li ASTContext *Context)
890*67e74705SXin Li : Nodes(Nodes), Context(Context),
891*67e74705SXin Li SourceManager(&Context->getSourceManager()) {}
892*67e74705SXin Li
~MatchCallback()893*67e74705SXin Li MatchFinder::MatchCallback::~MatchCallback() {}
~ParsingDoneTestCallback()894*67e74705SXin Li MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
895*67e74705SXin Li
MatchFinder(MatchFinderOptions Options)896*67e74705SXin Li MatchFinder::MatchFinder(MatchFinderOptions Options)
897*67e74705SXin Li : Options(std::move(Options)), ParsingDone(nullptr) {}
898*67e74705SXin Li
~MatchFinder()899*67e74705SXin Li MatchFinder::~MatchFinder() {}
900*67e74705SXin Li
addMatcher(const DeclarationMatcher & NodeMatch,MatchCallback * Action)901*67e74705SXin Li void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
902*67e74705SXin Li MatchCallback *Action) {
903*67e74705SXin Li Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
904*67e74705SXin Li Matchers.AllCallbacks.insert(Action);
905*67e74705SXin Li }
906*67e74705SXin Li
addMatcher(const TypeMatcher & NodeMatch,MatchCallback * Action)907*67e74705SXin Li void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
908*67e74705SXin Li MatchCallback *Action) {
909*67e74705SXin Li Matchers.Type.emplace_back(NodeMatch, Action);
910*67e74705SXin Li Matchers.AllCallbacks.insert(Action);
911*67e74705SXin Li }
912*67e74705SXin Li
addMatcher(const StatementMatcher & NodeMatch,MatchCallback * Action)913*67e74705SXin Li void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
914*67e74705SXin Li MatchCallback *Action) {
915*67e74705SXin Li Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
916*67e74705SXin Li Matchers.AllCallbacks.insert(Action);
917*67e74705SXin Li }
918*67e74705SXin Li
addMatcher(const NestedNameSpecifierMatcher & NodeMatch,MatchCallback * Action)919*67e74705SXin Li void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
920*67e74705SXin Li MatchCallback *Action) {
921*67e74705SXin Li Matchers.NestedNameSpecifier.emplace_back(NodeMatch, Action);
922*67e74705SXin Li Matchers.AllCallbacks.insert(Action);
923*67e74705SXin Li }
924*67e74705SXin Li
addMatcher(const NestedNameSpecifierLocMatcher & NodeMatch,MatchCallback * Action)925*67e74705SXin Li void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
926*67e74705SXin Li MatchCallback *Action) {
927*67e74705SXin Li Matchers.NestedNameSpecifierLoc.emplace_back(NodeMatch, Action);
928*67e74705SXin Li Matchers.AllCallbacks.insert(Action);
929*67e74705SXin Li }
930*67e74705SXin Li
addMatcher(const TypeLocMatcher & NodeMatch,MatchCallback * Action)931*67e74705SXin Li void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
932*67e74705SXin Li MatchCallback *Action) {
933*67e74705SXin Li Matchers.TypeLoc.emplace_back(NodeMatch, Action);
934*67e74705SXin Li Matchers.AllCallbacks.insert(Action);
935*67e74705SXin Li }
936*67e74705SXin Li
addDynamicMatcher(const internal::DynTypedMatcher & NodeMatch,MatchCallback * Action)937*67e74705SXin Li bool MatchFinder::addDynamicMatcher(const internal::DynTypedMatcher &NodeMatch,
938*67e74705SXin Li MatchCallback *Action) {
939*67e74705SXin Li if (NodeMatch.canConvertTo<Decl>()) {
940*67e74705SXin Li addMatcher(NodeMatch.convertTo<Decl>(), Action);
941*67e74705SXin Li return true;
942*67e74705SXin Li } else if (NodeMatch.canConvertTo<QualType>()) {
943*67e74705SXin Li addMatcher(NodeMatch.convertTo<QualType>(), Action);
944*67e74705SXin Li return true;
945*67e74705SXin Li } else if (NodeMatch.canConvertTo<Stmt>()) {
946*67e74705SXin Li addMatcher(NodeMatch.convertTo<Stmt>(), Action);
947*67e74705SXin Li return true;
948*67e74705SXin Li } else if (NodeMatch.canConvertTo<NestedNameSpecifier>()) {
949*67e74705SXin Li addMatcher(NodeMatch.convertTo<NestedNameSpecifier>(), Action);
950*67e74705SXin Li return true;
951*67e74705SXin Li } else if (NodeMatch.canConvertTo<NestedNameSpecifierLoc>()) {
952*67e74705SXin Li addMatcher(NodeMatch.convertTo<NestedNameSpecifierLoc>(), Action);
953*67e74705SXin Li return true;
954*67e74705SXin Li } else if (NodeMatch.canConvertTo<TypeLoc>()) {
955*67e74705SXin Li addMatcher(NodeMatch.convertTo<TypeLoc>(), Action);
956*67e74705SXin Li return true;
957*67e74705SXin Li }
958*67e74705SXin Li return false;
959*67e74705SXin Li }
960*67e74705SXin Li
newASTConsumer()961*67e74705SXin Li std::unique_ptr<ASTConsumer> MatchFinder::newASTConsumer() {
962*67e74705SXin Li return llvm::make_unique<internal::MatchASTConsumer>(this, ParsingDone);
963*67e74705SXin Li }
964*67e74705SXin Li
match(const clang::ast_type_traits::DynTypedNode & Node,ASTContext & Context)965*67e74705SXin Li void MatchFinder::match(const clang::ast_type_traits::DynTypedNode &Node,
966*67e74705SXin Li ASTContext &Context) {
967*67e74705SXin Li internal::MatchASTVisitor Visitor(&Matchers, Options);
968*67e74705SXin Li Visitor.set_active_ast_context(&Context);
969*67e74705SXin Li Visitor.match(Node);
970*67e74705SXin Li }
971*67e74705SXin Li
matchAST(ASTContext & Context)972*67e74705SXin Li void MatchFinder::matchAST(ASTContext &Context) {
973*67e74705SXin Li internal::MatchASTVisitor Visitor(&Matchers, Options);
974*67e74705SXin Li Visitor.set_active_ast_context(&Context);
975*67e74705SXin Li Visitor.onStartOfTranslationUnit();
976*67e74705SXin Li Visitor.TraverseDecl(Context.getTranslationUnitDecl());
977*67e74705SXin Li Visitor.onEndOfTranslationUnit();
978*67e74705SXin Li }
979*67e74705SXin Li
registerTestCallbackAfterParsing(MatchFinder::ParsingDoneTestCallback * NewParsingDone)980*67e74705SXin Li void MatchFinder::registerTestCallbackAfterParsing(
981*67e74705SXin Li MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
982*67e74705SXin Li ParsingDone = NewParsingDone;
983*67e74705SXin Li }
984*67e74705SXin Li
getID() const985*67e74705SXin Li StringRef MatchFinder::MatchCallback::getID() const { return "<unknown>"; }
986*67e74705SXin Li
987*67e74705SXin Li } // end namespace ast_matchers
988*67e74705SXin Li } // end namespace clang
989