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