diff --git a/flang/lib/Lower/ConvertExpr.cpp b/flang/lib/Lower/ConvertExpr.cpp --- a/flang/lib/Lower/ConvertExpr.cpp +++ b/flang/lib/Lower/ConvertExpr.cpp @@ -1301,10 +1301,20 @@ // to "0xE2 0x82 0xAC" : UTF-8. mlir::Value bufferSize = boxchar.getLen(); auto kindMap = builder.getKindMap(); - auto fromBits = kindMap.getCharacterBitsize( - fir::unwrapRefType(boxchar.getAddr().getType()) - .cast() - .getFKind()); + mlir::Value boxCharAddr = boxchar.getAddr(); + auto fromTy = boxCharAddr.getType(); + if (auto charTy = fromTy.dyn_cast()) { + // boxchar is a value, not a variable. Turn it into a temporary. + // As a value, it ought to have a constant LEN value. + assert(charTy.hasConstantLen() && "must have constant length"); + mlir::Value tmp = builder.createTemporary(loc, charTy); + builder.create(loc, boxCharAddr, tmp); + boxCharAddr = tmp; + } + auto fromBits = + kindMap.getCharacterBitsize(fir::unwrapRefType(fromTy) + .cast() + .getFKind()); auto toBits = kindMap.getCharacterBitsize( ty.cast().getFKind()); if (toBits < fromBits) { @@ -1316,7 +1326,7 @@ } auto dest = builder.create( loc, ty, mlir::ValueRange{bufferSize}); - builder.create(loc, boxchar.getAddr(), + builder.create(loc, boxCharAddr, boxchar.getLen(), dest); return fir::CharBoxValue{dest, boxchar.getLen()}; } else { diff --git a/flang/test/Fir/achar.f90 b/flang/test/Fir/achar.f90 new file mode 100644 --- /dev/null +++ b/flang/test/Fir/achar.f90 @@ -0,0 +1,24 @@ +! RUN: bbc -emit-fir %s -o - | FileCheck %s + +! Tests ACHAR lowering (converting an INTEGER to a CHARACTER (singleton, LEN=1) +! along with conversion of CHARACTER to another KIND. +subroutine achar_test1(a) + integer, parameter :: ckind = 2 + integer, intent(in) :: a + character(kind=ckind, len=1) :: ch + + ch = achar(a) + call achar_test1_foo(ch) +end subroutine achar_test1 + +! CHECK-LABEL: func @_QPachar_test1( +! CHECK-SAME: %[[arg:.*]]: !fir.ref {fir.bindc_name = "a"}) { +! CHECK: %[[VAL_0:.*]] = fir.alloca !fir.char<1> +! CHECK: %[[VAL_1:.*]] = fir.alloca !fir.char<2> {bindc_name = "ch", uniq_name = "_QFachar_test1Ech"} +! CHECK: %[[VAL_2:.*]] = fir.load %[[arg]] : !fir.ref +! CHECK: %[[VAL_5:.*]] = fir.undefined !fir.char<1> +! CHECK: %[[VAL_6:.*]] = fir.insert_value %[[VAL_5]], %{{.*}}, [0 : index] : (!fir.char<1>, i8) -> !fir.char<1> +! CHECK: fir.store %[[VAL_6]] to %[[VAL_0]] : !fir.ref> +! CHECK: %[[VAL_7:.*]] = fir.alloca !fir.char<2,?>(%{{.*}} : index) +! CHECK: fir.char_convert %[[VAL_0]] for %{{.*}} to %[[VAL_7]] : !fir.ref>, index, !fir.ref> +! CHECK: fir.call @_QPachar_test1_foo(%{{.*}}) : (!fir.boxchar<2>) -> ()