Index: flang/lib/Evaluate/shape.cpp =================================================================== --- flang/lib/Evaluate/shape.cpp +++ flang/lib/Evaluate/shape.cpp @@ -811,13 +811,24 @@ if (auto chars{characteristics::Procedure::FromActuals( call.proc(), call.arguments(), *context_)}) { std::size_t j{0}; + std::size_t anyArrayArgRank{0}; for (const auto &arg : call.arguments()) { - if (arg && arg->Rank() > 0 && j < chars->dummyArguments.size() && - !chars->dummyArguments[j].IsOptional()) { - return (*this)(*arg); + if (arg && arg->Rank() > 0 && j < chars->dummyArguments.size()) { + anyArrayArgRank = arg->Rank(); + if (!chars->dummyArguments[j].IsOptional()) { + return (*this)(*arg); + } } ++j; } + if (anyArrayArgRank) { + // All dummy array arguments of the procedure are OPTIONAL. + // We cannot take the shape from just any array argument, + // because all of them might be OPTIONAL dummy arguments + // of the caller. Return unknown shape ranked according + // to the last actual array argument. + return Shape(anyArrayArgRank, MaybeExtentExpr{}); + } } } return ScalarShape(); Index: flang/test/Lower/shape-of-elemental-with-optional-arg.f90 =================================================================== --- /dev/null +++ flang/test/Lower/shape-of-elemental-with-optional-arg.f90 @@ -0,0 +1,19 @@ +! Test that the shape of the elemental call is properly +! computed as being rank 1, even though the only dummy +! argument is optional. + +! RUN: bbc -emit-fir %s -o - | FileCheck %s +! RUN: bbc -emit-hlfir %s -o - | FileCheck %s + +subroutine test + interface + elemental function callee(arg1) + integer, intent(in), optional :: arg1 + integer :: fun + end function callee + end interface + integer :: arr(2) + print *, callee(arr) +end subroutine test +! The PRINT statement must be lowered into a ranked print: +! CHECK: fir.call @_FortranAioOutputDescriptor