Issue 242874
Summary [flang] -Wunused-variable: values referenced in IF conditions, DO bounds, SELECT CASE and I/O specifiers are not counted as uses
Labels flang
Assignees
Reporter eugeneepshteyn
    flang version 24.0.0git (https://github.com/llvm/llvm-project fe077b6e4150de8d5712e7a6a6507bdd397a7877)

```fortran
program scalar_context_initialized
  implicit none
  integer :: k = 1, n = 3, c = 2, i
  logical :: flag = .true.
  if (k > 0) print *, 'k'
  do i = 1, n
 end do
  select case (c)
  case (2)
    print *, 'two'
  end select
  if (flag) print *, 'flag'
end program
```

```console
$ flang -fsyntax-only -pedantic t.f90
t.f90:3:14: warning: Value of local variable 'k' is never used [-Wunused-variable]
t.f90:3:21: warning: Value of local variable 'n' is never used [-Wunused-variable]
t.f90:3:28: warning: Value of local variable 'c' is never used [-Wunused-variable]
t.f90:4:14: warning: Value of local variable 'flag' is never used [-Wunused-variable]
```

All four values are used. The same happens for an initialized variable that appears only in `OPEN(..., RECL=recl)`, and probably in every other context that the parse tree wraps as `Scalar<...>` (STOP codes, I/O unit numbers and specifiers, and so on).

For a variable that is never defined, the warning is still issued, but with the wrong text. With `integer :: k, n, c, s` and the same references (plus `stop s`), each variable gets "Value of local variable '...' is never used" instead of "Value of uninitialized local variable '...' is used but never defined".

Cause: `ExprChecker` in `flang/include/flang/Semantics/_expression_.h` routes `parser::Scalar<A>`, `Integer<A>`, `Logical<A>`, `Constant<A>` and `DefaultChar<A>` to `AnalyzeAndNoteUses(x)`. That function notes uses only when `parser::HasTypedExpr<A>` (or `HasTypedCall`/`HasTypedAssignment`) is true for the node type itself. The wrapper templates have no `typedExpr` member, so for them the call only analyzes the _expression_ and notes nothing. The code has had this shape since the warnings were added (173504).

A possible fix: in `AnalyzeAndNoteUses`, unwrap the wrapper to the `parser::Expr` it contains (`parser::Unwrap<parser::Expr>`, or `semantics::GetExpr`) and note the uses of its typed _expression_. Wrappers around a `parser::Variable` (`ScalarIntVariable`, `ScalarLogicalVariable`, ...) occur only in definition contexts (I/O specifier variables, STAT=, ...), so they should keep noting nothing. Note that once these uses are counted, a variable whose value is referenced only in such a context is reported as "used but never defined" unless something records its definition. The IOLENGTH= variable is one such case (issue 242873), so that fix should land first or together with this one.

(This issue was filed with the help of AI)

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to