clang-tools 22.0.0git
InfiniteLoopCheck.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
9#include "InfiniteLoopCheck.h"
10#include "../utils/Aliasing.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
14#include "clang/Analysis/CallGraph.h"
15#include "llvm/ADT/SCCIterator.h"
16
17using namespace clang::ast_matchers;
18using clang::ast_matchers::internal::Matcher;
20
21namespace clang::tidy::bugprone {
22
23namespace {
24/// matches a Decl if it has a "no return" attribute of any kind
25AST_MATCHER(Decl, declHasNoReturnAttr) {
26 return Node.hasAttr<NoReturnAttr>() || Node.hasAttr<CXX11NoReturnAttr>() ||
27 Node.hasAttr<C11NoReturnAttr>();
28}
29
30/// matches a FunctionType if the type includes the GNU no return attribute
31AST_MATCHER(FunctionType, typeHasNoReturnAttr) {
32 return Node.getNoReturnAttr();
33}
34} // namespace
35
36static Matcher<Stmt> loopEndingStmt(Matcher<Stmt> Internal) {
37 const Matcher<QualType> IsNoReturnFunType =
38 ignoringParens(functionType(typeHasNoReturnAttr()));
39 Matcher<Decl> IsNoReturnDecl =
40 anyOf(declHasNoReturnAttr(), functionDecl(hasType(IsNoReturnFunType)),
41 varDecl(hasType(blockPointerType(pointee(IsNoReturnFunType)))));
42
43 return stmt(anyOf(
44 mapAnyOf(breakStmt, returnStmt, gotoStmt, cxxThrowExpr).with(Internal),
45 callExpr(Internal,
46 callee(mapAnyOf(functionDecl, /* block callee */ varDecl)
47 .with(IsNoReturnDecl))),
48 objcMessageExpr(Internal, callee(IsNoReturnDecl))));
49}
50
51/// Return whether `Var` was changed in `LoopStmt`.
52static bool isChanged(const Stmt *LoopStmt, const ValueDecl *Var,
53 ASTContext *Context) {
54 if (const auto *ForLoop = dyn_cast<ForStmt>(LoopStmt))
55 return (ForLoop->getInc() &&
56 ExprMutationAnalyzer(*ForLoop->getInc(), *Context)
57 .isMutated(Var)) ||
58 (ForLoop->getBody() &&
59 ExprMutationAnalyzer(*ForLoop->getBody(), *Context)
60 .isMutated(Var)) ||
61 (ForLoop->getCond() &&
62 ExprMutationAnalyzer(*ForLoop->getCond(), *Context).isMutated(Var));
63
64 return ExprMutationAnalyzer(*LoopStmt, *Context).isMutated(Var);
65}
66
67static bool isVarPossiblyChanged(const Decl *Func, const Stmt *LoopStmt,
68 const ValueDecl *VD, ASTContext *Context) {
69 const VarDecl *Var = nullptr;
70 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
71 Var = VarD;
72 } else if (const auto *BD = dyn_cast<BindingDecl>(VD)) {
73 if (const auto *DD = dyn_cast<DecompositionDecl>(BD->getDecomposedDecl()))
74 Var = DD;
75 }
76
77 if (!Var)
78 return false;
79
80 if (!Var->isLocalVarDeclOrParm() || Var->getType().isVolatileQualified())
81 return true;
82
83 if (!VD->getType().getTypePtr()->isIntegerType())
84 return true;
85
86 return hasPtrOrReferenceInFunc(Func, VD) || isChanged(LoopStmt, VD, Context);
87 // FIXME: Track references.
88}
89
90/// Return whether `Cond` is a variable that is possibly changed in `LoopStmt`.
91static bool isVarThatIsPossiblyChanged(const Decl *Func, const Stmt *LoopStmt,
92 const Stmt *Cond, ASTContext *Context) {
93 if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
94 if (const auto *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
95 return isVarPossiblyChanged(Func, LoopStmt, VD, Context);
96 } else if (isa<MemberExpr, CallExpr, ObjCIvarRefExpr, ObjCPropertyRefExpr,
97 ObjCMessageExpr>(Cond)) {
98 // FIXME: Handle MemberExpr.
99 return true;
100 } else if (const auto *CE = dyn_cast<CastExpr>(Cond)) {
101 QualType T = CE->getType();
102 while (true) {
103 if (T.isVolatileQualified())
104 return true;
105
106 if (!T->isAnyPointerType() && !T->isReferenceType())
107 break;
108
109 T = T->getPointeeType();
110 }
111 }
112
113 return false;
114}
115
116/// Return whether at least one variable of `Cond` changed in `LoopStmt`.
117static bool isAtLeastOneCondVarChanged(const Decl *Func, const Stmt *LoopStmt,
118 const Stmt *Cond, ASTContext *Context) {
119 if (isVarThatIsPossiblyChanged(Func, LoopStmt, Cond, Context))
120 return true;
121
122 return llvm::any_of(Cond->children(), [&](const Stmt *Child) {
123 return Child && isAtLeastOneCondVarChanged(Func, LoopStmt, Child, Context);
124 });
125}
126
127/// Return the variable names in `Cond`.
128static std::string getCondVarNames(const Stmt *Cond) {
129 if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
130 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl()))
131 return std::string(Var->getName());
132
133 if (const auto *BD = dyn_cast<BindingDecl>(DRE->getDecl())) {
134 return std::string(BD->getName());
135 }
136 }
137
138 std::string Result;
139 for (const Stmt *Child : Cond->children()) {
140 if (!Child)
141 continue;
142
143 const std::string NewNames = getCondVarNames(Child);
144 if (!Result.empty() && !NewNames.empty())
145 Result += ", ";
146 Result += NewNames;
147 }
148 return Result;
149}
150
151static bool isKnownToHaveValue(const Expr &Cond, const ASTContext &Ctx,
152 bool ExpectedValue) {
153 if (Cond.isValueDependent()) {
154 if (const auto *BinOp = dyn_cast<BinaryOperator>(&Cond)) {
155 // Conjunctions (disjunctions) can still be handled if at least one
156 // conjunct (disjunct) is known to be false (true).
157 if (!ExpectedValue && BinOp->getOpcode() == BO_LAnd)
158 return isKnownToHaveValue(*BinOp->getLHS(), Ctx, false) ||
159 isKnownToHaveValue(*BinOp->getRHS(), Ctx, false);
160 if (ExpectedValue && BinOp->getOpcode() == BO_LOr)
161 return isKnownToHaveValue(*BinOp->getLHS(), Ctx, true) ||
162 isKnownToHaveValue(*BinOp->getRHS(), Ctx, true);
163 if (BinOp->getOpcode() == BO_Comma)
164 return isKnownToHaveValue(*BinOp->getRHS(), Ctx, ExpectedValue);
165 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(&Cond)) {
166 if (UnOp->getOpcode() == UO_LNot)
167 return isKnownToHaveValue(*UnOp->getSubExpr(), Ctx, !ExpectedValue);
168 } else if (const auto *Paren = dyn_cast<ParenExpr>(&Cond))
169 return isKnownToHaveValue(*Paren->getSubExpr(), Ctx, ExpectedValue);
170 else if (const auto *ImplCast = dyn_cast<ImplicitCastExpr>(&Cond))
171 return isKnownToHaveValue(*ImplCast->getSubExpr(), Ctx, ExpectedValue);
172 return false;
173 }
174 bool Result = false;
175 if (Cond.EvaluateAsBooleanCondition(Result, Ctx))
176 return Result == ExpectedValue;
177 return false;
178}
179
180/// populates the set `Callees` with all function (and objc method) declarations
181/// called in `StmtNode` if all visited call sites have resolved call targets.
182///
183/// \return true iff all `CallExprs` visited have callees; false otherwise
184/// indicating there is an unresolved indirect call.
185static bool populateCallees(const Stmt *StmtNode,
186 llvm::SmallPtrSet<const Decl *, 16> &Callees) {
187 if (const auto *Call = dyn_cast<CallExpr>(StmtNode)) {
188 const Decl *Callee = Call->getDirectCallee();
189
190 if (!Callee)
191 return false; // unresolved call
192 Callees.insert(Callee->getCanonicalDecl());
193 }
194 if (const auto *Call = dyn_cast<ObjCMessageExpr>(StmtNode)) {
195 const Decl *Callee = Call->getMethodDecl();
196
197 if (!Callee)
198 return false; // unresolved call
199 Callees.insert(Callee->getCanonicalDecl());
200 }
201 for (const Stmt *Child : StmtNode->children())
202 if (Child && !populateCallees(Child, Callees))
203 return false;
204 return true;
205}
206
207/// returns true iff `SCC` contains `Func` and its' function set overlaps with
208/// `Callees`
209static bool overlap(ArrayRef<CallGraphNode *> SCC,
210 const llvm::SmallPtrSet<const Decl *, 16> &Callees,
211 const Decl *Func) {
212 bool ContainsFunc = false, Overlap = false;
213
214 for (const CallGraphNode *GNode : SCC) {
215 const Decl *CanDecl = GNode->getDecl()->getCanonicalDecl();
216
217 ContainsFunc = ContainsFunc || (CanDecl == Func);
218 Overlap = Overlap || Callees.contains(CanDecl);
219 if (ContainsFunc && Overlap)
220 return true;
221 }
222 return false;
223}
224
225/// returns true iff `Cond` involves at least one static local variable.
226static bool hasStaticLocalVariable(const Stmt *Cond) {
227 if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
228 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
229 if (VD->isStaticLocal())
230 return true;
231
232 if (const auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
233 if (const auto *DD = dyn_cast<DecompositionDecl>(BD->getDecomposedDecl()))
234 if (DD->isStaticLocal())
235 return true;
236 }
237
238 return llvm::any_of(Cond->children(), [](const Stmt *Child) {
239 return Child && hasStaticLocalVariable(Child);
240 });
241}
242
243/// Tests if the loop condition `Cond` involves static local variables and
244/// the enclosing function `Func` is recursive.
245///
246/// \code
247/// void f() {
248/// static int i = 10;
249/// i--;
250/// while (i >= 0) f();
251/// }
252/// \endcode
253/// The example above is NOT an infinite loop.
254static bool hasRecursionOverStaticLoopCondVariables(const Expr *Cond,
255 const Stmt *LoopStmt,
256 const Decl *Func,
257 const ASTContext *Ctx) {
258 if (!hasStaticLocalVariable(Cond))
259 return false;
260
261 llvm::SmallPtrSet<const Decl *, 16> CalleesInLoop;
262
263 if (!populateCallees(LoopStmt, CalleesInLoop)) {
264 // If there are unresolved indirect calls, we assume there could
265 // be recursion so to avoid false alarm.
266 return true;
267 }
268 if (CalleesInLoop.empty())
269 return false;
270
271 TranslationUnitDecl *TUDecl = Ctx->getTranslationUnitDecl();
272 CallGraph CG;
273
274 CG.addToCallGraph(TUDecl);
275 // For each `SCC` containing `Func`, if functions in the `SCC`
276 // overlap with `CalleesInLoop`, there is a recursive call in `LoopStmt`.
277 for (llvm::scc_iterator<CallGraph *> SCCI = llvm::scc_begin(&CG),
278 SCCE = llvm::scc_end(&CG);
279 SCCI != SCCE; ++SCCI) {
280 if (!SCCI.hasCycle()) // We only care about cycles, not standalone nodes.
281 continue;
282 // `SCC`s are mutually disjoint, so there will be no redundancy in
283 // comparing `SCC` with the callee set one by one.
284 if (overlap(*SCCI, CalleesInLoop, Func->getCanonicalDecl()))
285 return true;
286 }
287 return false;
288}
289
290void InfiniteLoopCheck::registerMatchers(MatchFinder *Finder) {
291 const auto LoopCondition = allOf(
292 hasCondition(expr(forCallable(decl().bind("func"))).bind("condition")),
293 unless(hasBody(hasDescendant(
294 loopEndingStmt(forCallable(equalsBoundNode("func")))))));
295
296 Finder->addMatcher(mapAnyOf(whileStmt, doStmt, forStmt)
297 .with(LoopCondition)
298 .bind("loop-stmt"),
299 this);
300}
301
302void InfiniteLoopCheck::check(const MatchFinder::MatchResult &Result) {
303 const auto *Cond = Result.Nodes.getNodeAs<Expr>("condition");
304 const auto *LoopStmt = Result.Nodes.getNodeAs<Stmt>("loop-stmt");
305 const auto *Func = Result.Nodes.getNodeAs<Decl>("func");
306
307 if (isKnownToHaveValue(*Cond, *Result.Context, false))
308 return;
309
310 bool ShouldHaveConditionVariables = true;
311 if (const auto *While = dyn_cast<WhileStmt>(LoopStmt)) {
312 if (const VarDecl *LoopVarDecl = While->getConditionVariable()) {
313 if (const Expr *Init = LoopVarDecl->getInit()) {
314 ShouldHaveConditionVariables = false;
315 Cond = Init;
316 }
317 }
318 }
319
320 if (ExprMutationAnalyzer::isUnevaluated(LoopStmt, *Result.Context))
321 return;
322
323 if (isAtLeastOneCondVarChanged(Func, LoopStmt, Cond, Result.Context))
324 return;
325 if (hasRecursionOverStaticLoopCondVariables(Cond, LoopStmt, Func,
326 Result.Context))
327 return;
328
329 const std::string CondVarNames = getCondVarNames(Cond);
330 if (ShouldHaveConditionVariables && CondVarNames.empty())
331 return;
332
333 if (CondVarNames.empty()) {
334 diag(LoopStmt->getBeginLoc(),
335 "this loop is infinite; it does not check any variables in the"
336 " condition");
337 } else {
338 diag(LoopStmt->getBeginLoc(),
339 "this loop is infinite; none of its condition variables (%0)"
340 " are updated in the loop body")
341 << CondVarNames;
342 }
343}
344
345} // namespace clang::tidy::bugprone
bool hasPtrOrReferenceInFunc(const Decl *Func, const ValueDecl *Var)
Returns whether Var has a pointer or reference in Func.
Definition Aliasing.cpp:86
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static bool isChanged(const Stmt *LoopStmt, const ValueDecl *Var, ASTContext *Context)
Return whether Var was changed in LoopStmt.
static Matcher< Stmt > loopEndingStmt(Matcher< Stmt > Internal)
static bool isKnownToHaveValue(const Expr &Cond, const ASTContext &Ctx, bool ExpectedValue)
static bool hasStaticLocalVariable(const Stmt *Cond)
returns true iff Cond involves at least one static local variable.
static bool isVarThatIsPossiblyChanged(const Decl *Func, const Stmt *LoopStmt, const Stmt *Cond, ASTContext *Context)
Return whether Cond is a variable that is possibly changed in LoopStmt.
static bool hasRecursionOverStaticLoopCondVariables(const Expr *Cond, const Stmt *LoopStmt, const Decl *Func, const ASTContext *Ctx)
Tests if the loop condition Cond involves static local variables and the enclosing function Func is r...
static bool overlap(ArrayRef< CallGraphNode * > SCC, const llvm::SmallPtrSet< const Decl *, 16 > &Callees, const Decl *Func)
returns true iff SCC contains Func and its' function set overlaps with Callees
static std::string getCondVarNames(const Stmt *Cond)
Return the variable names in Cond.
static bool populateCallees(const Stmt *StmtNode, llvm::SmallPtrSet< const Decl *, 16 > &Callees)
populates the set Callees with all function (and objc method) declarations called in StmtNode if all ...
static bool isVarPossiblyChanged(const Decl *Func, const Stmt *LoopStmt, const ValueDecl *VD, ASTContext *Context)
static bool isAtLeastOneCondVarChanged(const Decl *Func, const Stmt *LoopStmt, const Stmt *Cond, ASTContext *Context)
Return whether at least one variable of Cond changed in LoopStmt.
AST_MATCHER(BinaryOperator, isRelationalOperator)
bool hasPtrOrReferenceInFunc(const Decl *Func, const ValueDecl *Var)
Returns whether Var has a pointer or reference in Func.
Definition Aliasing.cpp:86