clang-tools 24.0.0git
InefficientAlgorithmCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Lex/Lexer.h"
13
14using namespace clang::ast_matchers;
15
17
18static bool areTypesCompatible(QualType Left, QualType Right) {
19 if (const auto *LeftRefType = Left->getAs<ReferenceType>())
20 Left = LeftRefType->getPointeeType();
21 if (const auto *RightRefType = Right->getAs<ReferenceType>())
22 Right = RightRefType->getPointeeType();
23 return Left->getCanonicalTypeUnqualified() ==
24 Right->getCanonicalTypeUnqualified();
25}
26
28 const auto Algorithms =
29 hasAnyName("::std::find", "::std::count", "::std::equal_range",
30 "::std::lower_bound", "::std::upper_bound");
31 const auto ContainerMatcher = classTemplateSpecializationDecl(hasAnyName(
32 "::std::set", "::std::map", "::std::multiset", "::std::multimap",
33 "::std::unordered_set", "::std::unordered_map",
34 "::std::unordered_multiset", "::std::unordered_multimap"));
35
36 const auto Matcher =
37 callExpr(
38 callee(functionDecl(Algorithms)), argumentCountAtLeast(3),
39 hasArgument(
40 0, cxxMemberCallExpr(
41 callee(cxxMethodDecl(hasName("begin"))),
42 on(declRefExpr(
43 hasDeclaration(decl().bind("IneffContObj")),
44 anyOf(hasType(ContainerMatcher.bind("IneffCont")),
45 hasType(pointsTo(
46 ContainerMatcher.bind("IneffContPtr")))))
47 .bind("IneffContExpr")))),
48 hasArgument(
49 1, cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end"))),
50 on(declRefExpr(hasDeclaration(
51 equalsBoundNode("IneffContObj")))))))
52 .bind("IneffAlg");
53
54 Finder->addMatcher(Matcher, this);
55}
56
57void InefficientAlgorithmCheck::check(const MatchFinder::MatchResult &Result) {
58 const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>("IneffAlg");
59 const auto *IneffCont =
60 Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("IneffCont");
61 bool PtrToContainer = false;
62 if (!IneffCont) {
63 IneffCont =
64 Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("IneffContPtr");
65 PtrToContainer = true;
66 }
67 const StringRef IneffContName = IneffCont->getName();
68 const bool Unordered = IneffContName.contains("unordered");
69 const bool Maplike = IneffContName.contains("map");
70
71 // Store if the key type of the container is compatible with the value
72 // that is searched for.
73 const QualType ValueType = AlgCall->getArg(2)->getType();
74 const QualType KeyType =
75 IneffCont->getTemplateArgs()[0].getAsType().getCanonicalType();
76 const bool CompatibleTypes = areTypesCompatible(KeyType, ValueType);
77
78 // Check if the comparison type for the algorithm and the container matches.
79 if (AlgCall->getNumArgs() == 4 && !Unordered) {
80 const Expr *Arg = AlgCall->getArg(3);
81 const QualType AlgCmp =
82 Arg->getType().getUnqualifiedType().getCanonicalType();
83 const unsigned CmpPosition = IneffContName.contains("map") ? 2 : 1;
84 const QualType ContainerCmp = IneffCont->getTemplateArgs()[CmpPosition]
85 .getAsType()
86 .getUnqualifiedType()
87 .getCanonicalType();
88 if (AlgCmp != ContainerCmp) {
89 diag(Arg->getBeginLoc(),
90 "different comparers used in the algorithm and the container");
91 return;
92 }
93 }
94
95 const auto *AlgDecl = AlgCall->getDirectCallee();
96 if (!AlgDecl)
97 return;
98
99 if (Unordered && AlgDecl->getName().contains("bound"))
100 return;
101
102 const auto *IneffContExpr = Result.Nodes.getNodeAs<Expr>("IneffContExpr");
103 FixItHint Hint;
104
105 const SourceManager &SM = *Result.SourceManager;
106 const LangOptions LangOpts = getLangOpts();
107
108 CharSourceRange CallRange =
109 CharSourceRange::getTokenRange(AlgCall->getSourceRange());
110
111 // FIXME: Create a common utility to extract a file range that the given token
112 // sequence is exactly spelled at (without macro argument expansions etc.).
113 // We can't use Lexer::makeFileCharRange here, because for
114 //
115 // #define F(x) x
116 // x(a b c);
117 //
118 // it will return "x(a b c)", when given the range "a"-"c". It makes sense for
119 // removals, but not for replacements.
120 //
121 // This code is over-simplified, but works for many real cases.
122 if (SM.isMacroArgExpansion(CallRange.getBegin()) &&
123 SM.isMacroArgExpansion(CallRange.getEnd())) {
124 CallRange.setBegin(SM.getSpellingLoc(CallRange.getBegin()));
125 CallRange.setEnd(SM.getSpellingLoc(CallRange.getEnd()));
126 }
127
128 if (!CallRange.getBegin().isMacroID() && !Maplike && CompatibleTypes) {
129 const StringRef ContainerText = Lexer::getSourceText(
130 CharSourceRange::getTokenRange(IneffContExpr->getSourceRange()), SM,
131 LangOpts);
132 const StringRef ParamText = Lexer::getSourceText(
133 CharSourceRange::getTokenRange(AlgCall->getArg(2)->getSourceRange()),
134 SM, LangOpts);
135 // There is no source text for an expression that covers only part of a
136 // macro expansion. Building the replacement from an empty string would
137 // incorrectly drop the container or the value.
138 if (!ContainerText.empty() && !ParamText.empty()) {
139 const std::string ReplacementText =
140 (llvm::Twine(ContainerText) + (PtrToContainer ? "->" : ".") +
141 AlgDecl->getName() + "(" + ParamText + ")")
142 .str();
143 Hint = FixItHint::CreateReplacement(CallRange, ReplacementText);
144 }
145 }
146
147 diag(AlgCall->getBeginLoc(),
148 "this STL algorithm call should be replaced with a container method")
149 << Hint;
150}
151
152} // namespace clang::tidy::performance
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static bool areTypesCompatible(QualType Left, QualType Right)