Skip to content

Commit 113f019

Browse files
committed
[clang-tidy] Fix minor bug in bugprone-too-small-loop-variable
Correct issue when incorrectly matched bitfield loop variable would still be considered valid and equal to base type, because check didnt compare size of bitfield. Fixes issue introduced in: D142587 Reviewed By: carlosgalvezp Differential Revision: https://reviews.llvm.org/D145958
1 parent 7ba9c06 commit 113f019

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ struct MagnitudeBits {
3434
bool operator<(const MagnitudeBits &Other) const noexcept {
3535
return WidthWithoutSignBit < Other.WidthWithoutSignBit;
3636
}
37+
38+
bool operator!=(const MagnitudeBits &Other) const noexcept {
39+
return WidthWithoutSignBit != Other.WidthWithoutSignBit ||
40+
BitFieldWidth != Other.BitFieldWidth;
41+
}
3742
};
3843

3944
} // namespace
@@ -184,13 +189,19 @@ void TooSmallLoopVariableCheck::check(const MatchFinder::MatchResult &Result) {
184189
if (LoopVar->getType() != LoopIncrement->getType())
185190
return;
186191

187-
const QualType LoopVarType = LoopVar->getType();
188-
const QualType UpperBoundType = UpperBound->getType();
189-
190192
ASTContext &Context = *Result.Context;
191193

194+
const QualType LoopVarType = LoopVar->getType();
192195
const MagnitudeBits LoopVarMagnitudeBits =
193196
calcMagnitudeBits(Context, LoopVarType, LoopVar);
197+
198+
const MagnitudeBits LoopIncrementMagnitudeBits =
199+
calcMagnitudeBits(Context, LoopIncrement->getType(), LoopIncrement);
200+
// We matched the loop variable incorrectly.
201+
if (LoopIncrementMagnitudeBits != LoopVarMagnitudeBits)
202+
return;
203+
204+
const QualType UpperBoundType = UpperBound->getType();
194205
const MagnitudeBits UpperBoundMagnitudeBits =
195206
calcUpperBoundMagnitudeBits(Context, UpperBound, UpperBoundType);
196207

clang-tools-extra/test/clang-tidy/checkers/bugprone/too-small-loop-variable.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,3 +373,20 @@ void badForLoopWithBitfieldOnLoopVarAndUpperBoundOnPtr() {
373373
}
374374
}
375375

376+
void goodForLoopWithBitfieldOnUpperBoundOnly() {
377+
struct S {
378+
int x : 4;
379+
} s;
380+
381+
for (int i = 10; i > s.x; --i) {
382+
}
383+
}
384+
385+
void goodForLoopWithIntegersOnUpperBoundOnly() {
386+
struct S {
387+
short x;
388+
} s;
389+
390+
for (int i = 10; i > s.x; --i) {
391+
}
392+
}

0 commit comments

Comments
 (0)