[PATCH] D71503: New warning on for-loops that never run because condition is false on the first iteration

Richard Trieu via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Fri Dec 13 19:04:45 PST 2019


rtrieu created this revision.

This is a proposed warning to be added to -Wfor-loop-analysis, which is part of -Wall.  This warning will catch instances where the condition will be false on the first iteration and the loop body will never be run.  The warning will be emitted when:

1. The for-loop initializes or sets the value of a single variable to a constant value
2. The condition is a simple comparison between the variable and another constant value
3. If the initial value of the variable substituted into the comparison would cause the comparison to be false

In order to make step 3 work, the constant value from step 1 may need to be casted to a different type.  The casts can be extracted from the comparison operand.  This allows the warning to work with both integer and floating point types, as well as mixing types.

Two exceptions to this warning.

1. Parentheses around the condition will silence this warning.  This is suggested in a note.
2. If the variable is used as an array index in the body, and the condition is less than a value the same as the array size.

Example:
https://reviews.llvm.org/D48498
This warning would have caught the issue that lebedev.ri brought up about the loop not running.


https://reviews.llvm.org/D71503

Files:
  clang/include/clang/AST/Expr.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Sema/SemaStmt.cpp

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D71503.233898.patch
Type: text/x-patch
Size: 15224 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20191214/a61d775b/attachment-0001.bin>


More information about the cfe-commits mailing list