Skip to content

Commit

Permalink
[analyzer] Loop should contain CXXForRangeStmt (#70190)
Browse files Browse the repository at this point in the history
Static analyze can't report diagnose when statement after a
CXXForRangeStmt and enable widen, because
`ExprEngine::processCFGBlockEntrance` lacks of CXXForRangeStmt and when
`AMgr.options.maxBlockVisitOnPath - 1` equals to `blockCount`, it can't
widen. After next iteration, `BlockCount >=
AMgr.options.maxBlockVisitOnPath` holds and generate a sink node. Add
`CXXForRangeStmt` makes it work.

Co-authored-by: huqizhi <836744285@qq.com>
  • Loading branch information
jcsxky committed Oct 26, 2023
1 parent 6282b74 commit 1b6b4d6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
2 changes: 1 addition & 1 deletion clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2509,7 +2509,7 @@ void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
AMgr.options.ShouldWidenLoops) {
const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt();
if (!isa_and_nonnull<ForStmt, WhileStmt, DoStmt>(Term))
if (!isa_and_nonnull<ForStmt, WhileStmt, DoStmt, CXXForRangeStmt>(Term))
return;
// Widen.
const LocationContext *LCtx = Pred->getLocationContext();
Expand Down
4 changes: 3 additions & 1 deletion clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ static const Expr *getLoopCondition(const Stmt *LoopStmt) {
return cast<WhileStmt>(LoopStmt)->getCond();
case Stmt::DoStmtClass:
return cast<DoStmt>(LoopStmt)->getCond();
case Stmt::CXXForRangeStmtClass:
return cast<CXXForRangeStmt>(LoopStmt)->getCond();
}
}

Expand All @@ -45,7 +47,7 @@ ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState,
const LocationContext *LCtx,
unsigned BlockCount, const Stmt *LoopStmt) {

assert((isa<ForStmt, WhileStmt, DoStmt>(LoopStmt)));
assert((isa<ForStmt, WhileStmt, DoStmt, CXXForRangeStmt>(LoopStmt)));

// Invalidate values in the current state.
// TODO Make this more conservative by only invalidating values that might
Expand Down
12 changes: 12 additions & 0 deletions clang/test/Analysis/loop-widening-notes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,15 @@ int test_for_loop() {
return flag_d / num; // no-crash expected-warning {{Division by zero}}
// expected-note@-1 {{Division by zero}}
}

int test_for_range_loop() {
int arr[10] = {0};
for(auto x : arr) { // expected-note {{Assigning value}}
++x;
}
if (arr[0] == 0) // expected-note {{Assuming the condition is true}}
// expected-note@-1 {{Taking true branch}}
return 1/arr[0]; // expected-warning {{Division by zero}}
// expected-note@-1 {{Division by zero}}
return 0;
}

0 comments on commit 1b6b4d6

Please sign in to comment.