Issue 239226
Summary [flang] SELECT CASE on INTEGER(16): case values outside the INTEGER(8) range are lowered incorrectly
Labels miscompilation, flang:fir-hlfir
Assignees
Reporter eugeneepshteyn
    Lowering of `SELECT CASE` converts each integer case value with `evaluate::ToInt64` and passes it to `fir::FirOpBuilder::createIntegerConstant`, which takes an `int64_t` (`flang/lib/Lower/Bridge.cpp`, the `addValue` lambda in the `SelectCaseStmt` lowering). For an INTEGER(16) selector, a case value that is negative or does not fit in 64 bits is not lowered correctly.

A negative case value:

```fortran
program p
  implicit none
  integer(16) :: i
 i = -3
  select case (i)
  case (-3_16)
    print *, 'matched -3'
  case default
    print *, 'no match'
  end select
end program
```

With assertions enabled, `flang t.f90` aborts:

```console
flang/lib/Optimizer/Builder/FIRBuilder.cpp:155: mlir::Value fir::FirOpBuilder::createIntegerConstant(mlir::Location, mlir::Type, std::int64_t): Assertion `(cst >= 0 || mlir::isa<mlir::IndexType>(ty) || mlir::cast<mlir::IntegerType>(ty).getWidth() <= 64) && "must use APint"' failed.
```

Without assertions (flang 21.1.5) it compiles, and the program prints `no match` instead of `matched -3`.

A case value larger than `HUGE(0_8)` gives wrong code with or without assertions:

```fortran
program p
  implicit none
  integer(16) :: i
 i = 2_16**70
  select case (i)
  case (2_16**70)
    print *, 'matched 2**70'
  case default
    print *, 'no match'
  end select
end program
```

This prints `no match`. `flang -fc1 -emit-hlfir` shows that the case value became zero:

```
fir.select_case %3 : i128 [#fir.point, %c0_i128, ^bb1, unit, ^bb2]
```

Expected output: `matched -3` and `matched 2**70`. Reproduced on x86_64 Linux with main at 1087db09497370a892a0586ffa1e5827ab9b1c4f and with flang 21.1.5.

(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