clang-tools 22.0.0git
NonConstParameterCheck.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
13using namespace clang::ast_matchers;
14
16
18 // Add parameters to Parameters.
19 Finder->addMatcher(parmVarDecl().bind("Parm"), this);
20
21 // C++ constructor.
22 Finder->addMatcher(cxxConstructorDecl().bind("Ctor"), this);
23
24 // Track unused parameters, there is Wunused-parameter about unused
25 // parameters.
26 Finder->addMatcher(declRefExpr().bind("Ref"), this);
27
28 // Analyse parameter usage in function.
29 Finder->addMatcher(stmt(anyOf(unaryOperator(hasAnyOperatorName("++", "--")),
30 binaryOperator(), callExpr(), returnStmt(),
31 cxxConstructExpr()))
32 .bind("Mark"),
33 this);
34 Finder->addMatcher(varDecl(hasInitializer(anything())).bind("Mark"), this);
35}
36
37void NonConstParameterCheck::check(const MatchFinder::MatchResult &Result) {
38 if (const auto *Parm = Result.Nodes.getNodeAs<ParmVarDecl>("Parm")) {
39 if (const DeclContext *D = Parm->getParentFunctionOrMethod()) {
40 if (const auto *M = dyn_cast<CXXMethodDecl>(D)) {
41 if (M->isVirtual() || M->size_overridden_methods() != 0)
42 return;
43 }
44 }
45 addParm(Parm);
46 } else if (const auto *Ctor =
47 Result.Nodes.getNodeAs<CXXConstructorDecl>("Ctor")) {
48 for (const auto *Parm : Ctor->parameters())
49 addParm(Parm);
50 for (const auto *Init : Ctor->inits())
51 markCanNotBeConst(Init->getInit(), true);
52 } else if (const auto *Ref = Result.Nodes.getNodeAs<DeclRefExpr>("Ref")) {
53 setReferenced(Ref);
54 } else if (const auto *S = Result.Nodes.getNodeAs<Stmt>("Mark")) {
55 if (const auto *B = dyn_cast<BinaryOperator>(S)) {
56 if (B->isAssignmentOp())
57 markCanNotBeConst(B, false);
58 } else if (const auto *CE = dyn_cast<CallExpr>(S)) {
59 // Typically, if a parameter is const then it is fine to make the data
60 // const. But sometimes the data is written even though the parameter
61 // is const. Mark all data passed by address to the function.
62 for (const auto *Arg : CE->arguments())
63 markCanNotBeConst(Arg->IgnoreParenCasts(), true);
64
65 // Data passed by nonconst reference should not be made const.
66 if (const FunctionDecl *FD = CE->getDirectCallee()) {
67 unsigned ArgNr = 0U;
68 for (const auto *Par : FD->parameters()) {
69 if (ArgNr >= CE->getNumArgs())
70 break;
71 const Expr *Arg = CE->getArg(ArgNr++);
72 // Is this a non constant reference parameter?
73 const Type *ParType = Par->getType().getTypePtr();
74 if (!ParType->isReferenceType() || Par->getType().isConstQualified())
75 continue;
76 markCanNotBeConst(Arg->IgnoreParenCasts(), false);
77 }
78 }
79 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(S)) {
80 for (const auto *Arg : CE->arguments())
81 markCanNotBeConst(Arg->IgnoreParenCasts(), true);
82 // Data passed by nonconst reference should not be made const.
83 unsigned ArgNr = 0U;
84 if (const auto *CD = CE->getConstructor()) {
85 for (const auto *Par : CD->parameters()) {
86 if (ArgNr >= CE->getNumArgs())
87 break;
88 const Expr *Arg = CE->getArg(ArgNr++);
89 // Is this a non constant reference parameter?
90 const Type *ParType = Par->getType().getTypePtr();
91 if (!ParType->isReferenceType() || Par->getType().isConstQualified())
92 continue;
93 markCanNotBeConst(Arg->IgnoreParenCasts(), false);
94 }
95 }
96 } else if (const auto *R = dyn_cast<ReturnStmt>(S)) {
97 markCanNotBeConst(R->getRetValue(), true);
98 } else if (const auto *U = dyn_cast<UnaryOperator>(S)) {
99 markCanNotBeConst(U, true);
100 }
101 } else if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("Mark")) {
102 const QualType T = VD->getType();
103 if ((T->isPointerType() && !T->getPointeeType().isConstQualified()) ||
104 T->isArrayType() || T->isRecordType())
105 markCanNotBeConst(VD->getInit(), true);
106 else if (T->isLValueReferenceType() &&
107 !T->getPointeeType().isConstQualified())
108 markCanNotBeConst(VD->getInit(), false);
109 }
110}
111
112void NonConstParameterCheck::addParm(const ParmVarDecl *Parm) {
113 // Only add nonconst integer/float pointer parameters.
114 const QualType T = Parm->getType();
115 if (!T->isPointerType() || T->getPointeeType().isConstQualified() ||
116 !(T->getPointeeType()->isIntegerType() ||
117 T->getPointeeType()->isFloatingType()))
118 return;
119
120 auto [It, Inserted] = Parameters.try_emplace(Parm);
121 if (!Inserted)
122 return;
123
124 It->second.IsReferenced = false;
125 It->second.CanBeConst = true;
126}
127
128void NonConstParameterCheck::setReferenced(const DeclRefExpr *Ref) {
129 auto It = Parameters.find(dyn_cast<ParmVarDecl>(Ref->getDecl()));
130 if (It != Parameters.end())
131 It->second.IsReferenced = true;
132}
133
135 diagnoseNonConstParameters();
136}
137
138void NonConstParameterCheck::diagnoseNonConstParameters() {
139 for (const auto &It : Parameters) {
140 const ParmVarDecl *Par = It.first;
141 const ParmInfo &ParamInfo = It.second;
142
143 // Unused parameter => there are other warnings about this.
144 if (!ParamInfo.IsReferenced)
145 continue;
146
147 // Parameter can't be const.
148 if (!ParamInfo.CanBeConst)
149 continue;
150
151 SmallVector<FixItHint, 8> Fixes;
152 auto *Function =
153 dyn_cast_or_null<const FunctionDecl>(Par->getParentFunctionOrMethod());
154 if (!Function)
155 continue;
156 const unsigned Index = Par->getFunctionScopeIndex();
157 for (FunctionDecl *FnDecl : Function->redecls()) {
158 if (FnDecl->getNumParams() <= Index)
159 continue;
160 Fixes.push_back(FixItHint::CreateInsertion(
161 FnDecl->getParamDecl(Index)->getBeginLoc(), "const "));
162 }
163
164 diag(Par->getLocation(), "pointer parameter '%0' can be pointer to const")
165 << Par->getName() << Fixes;
166 }
167}
168
169void NonConstParameterCheck::markCanNotBeConst(const Expr *E,
170 bool CanNotBeConst) {
171 if (!E)
172 return;
173
174 if (const auto *Cast = dyn_cast<ImplicitCastExpr>(E)) {
175 // If expression is const then ignore usage.
176 const QualType T = Cast->getType();
177 if (T->isPointerType() && T->getPointeeType().isConstQualified())
178 return;
179 }
180
181 E = E->IgnoreParenCasts();
182
183 if (const auto *B = dyn_cast<BinaryOperator>(E)) {
184 if (B->isAdditiveOp()) {
185 // p + 2
186 markCanNotBeConst(B->getLHS(), CanNotBeConst);
187 markCanNotBeConst(B->getRHS(), CanNotBeConst);
188 } else if (B->isAssignmentOp()) {
189 markCanNotBeConst(B->getLHS(), false);
190
191 // If LHS is not const then RHS can't be const.
192 const QualType T = B->getLHS()->getType();
193 if (T->isPointerType() && !T->getPointeeType().isConstQualified())
194 markCanNotBeConst(B->getRHS(), true);
195 }
196 } else if (const auto *C = dyn_cast<ConditionalOperator>(E)) {
197 markCanNotBeConst(C->getTrueExpr(), CanNotBeConst);
198 markCanNotBeConst(C->getFalseExpr(), CanNotBeConst);
199 } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
200 if (U->getOpcode() == UO_PreInc || U->getOpcode() == UO_PreDec ||
201 U->getOpcode() == UO_PostInc || U->getOpcode() == UO_PostDec) {
202 if (const auto *SubU =
203 dyn_cast<UnaryOperator>(U->getSubExpr()->IgnoreParenCasts()))
204 markCanNotBeConst(SubU->getSubExpr(), true);
205 markCanNotBeConst(U->getSubExpr(), CanNotBeConst);
206 } else if (U->getOpcode() == UO_Deref) {
207 if (!CanNotBeConst)
208 markCanNotBeConst(U->getSubExpr(), true);
209 } else {
210 markCanNotBeConst(U->getSubExpr(), CanNotBeConst);
211 }
212 } else if (const auto *A = dyn_cast<ArraySubscriptExpr>(E)) {
213 markCanNotBeConst(A->getBase(), true);
214 } else if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(E)) {
215 markCanNotBeConst(CLE->getInitializer(), true);
216 } else if (const auto *Constr = dyn_cast<CXXConstructExpr>(E)) {
217 for (const auto *Arg : Constr->arguments())
218 if (const auto *M = dyn_cast<MaterializeTemporaryExpr>(Arg))
219 markCanNotBeConst(cast<Expr>(M->getSubExpr()), CanNotBeConst);
220 } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
221 for (unsigned I = 0U; I < ILE->getNumInits(); ++I)
222 markCanNotBeConst(ILE->getInit(I), true);
223 } else if (CanNotBeConst) {
224 // Referencing parameter.
225 if (const auto *D = dyn_cast<DeclRefExpr>(E)) {
226 auto It = Parameters.find(dyn_cast<ParmVarDecl>(D->getDecl()));
227 if (It != Parameters.end())
228 It->second.CanBeConst = false;
229 }
230 }
231}
232
233} // namespace clang::tidy::readability
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override