[flang-commits] [flang] [flang][acc] Fix cache directive lowering for derived type designators (PR #176022)
via flang-commits
flang-commits at lists.llvm.org
Wed Jan 14 12:11:27 PST 2026
https://github.com/khaki3 updated https://github.com/llvm/llvm-project/pull/176022
>From d93dae26e52898ad5adca9c0c70acaba9597fc76 Mon Sep 17 00:00:00 2001
From: Kazuaki Matsumura <kmatsumura at nvidia.com>
Date: Wed, 14 Jan 2026 12:06:16 -0800
Subject: [PATCH 1/2] [flang][OpenACC] Fix cache directive for derived type
designators
The cache directive was failing for derived type designators (e.g.,
data%array(i-4:i+4)) because it incorrectly assumed the symbol would
always map to an hlfir::DeclareOp.
This patch:
- Uses gatherDataOperandAddrAndBounds to properly handle all designator
types including derived type components
- Adds fallback logic for base address resolution
- Uses function-level StatementContext to ensure operations persist
- Adds component override for derived type members so subsequent
accesses use the cached value
- Extracts common component extraction logic into a helper function
Fixes assertion failure when caching derived type array members.
---
flang/lib/Lower/OpenACC.cpp | 111 +++++++++++++++++--------
flang/test/Lower/OpenACC/acc-cache.f90 | 77 +++++++++++++++++
2 files changed, 155 insertions(+), 33 deletions(-)
diff --git a/flang/lib/Lower/OpenACC.cpp b/flang/lib/Lower/OpenACC.cpp
index cfbcf06c4b39e..75c4a4e561b7b 100644
--- a/flang/lib/Lower/OpenACC.cpp
+++ b/flang/lib/Lower/OpenACC.cpp
@@ -750,6 +750,31 @@ class AccDataMap {
};
} // namespace
+/// Extract the component reference from a designator expression, if any.
+/// For `data%array(i)`, this returns the Component for `data%array`.
+static std::optional<Fortran::evaluate::Component>
+extractComponentFromDesignator(
+ const Fortran::semantics::MaybeExpr &designator) {
+ if (!designator)
+ return std::nullopt;
+ std::optional<Fortran::evaluate::Component> componentRef;
+ if (std::optional<Fortran::evaluate::DataRef> dataRef =
+ Fortran::evaluate::ExtractDataRef(*designator)) {
+ Fortran::common::visit(
+ Fortran::common::visitors{
+ [&](const Fortran::evaluate::Component &component) {
+ componentRef = component;
+ },
+ [&](const Fortran::evaluate::ArrayRef &arrayRef) {
+ if (auto *comp = arrayRef.base().UnwrapComponent())
+ componentRef = *comp;
+ },
+ [](const auto &) {}},
+ dataRef->u);
+ }
+ return componentRef;
+}
+
template <typename Op>
static void
genDataOperandOperations(const Fortran::parser::AccObjectList &objectList,
@@ -773,23 +798,10 @@ genDataOperandOperations(const Fortran::parser::AccObjectList &objectList,
Fortran::semantics::Symbol &symbol = getSymbolFromAccObject(accObject);
- std::optional<Fortran::evaluate::Component> componentRef;
Fortran::semantics::MaybeExpr designator = Fortran::common::visit(
[&](auto &&s) { return ea.Analyze(s); }, accObject.u);
- if (std::optional<Fortran::evaluate::DataRef> dataRef =
- Fortran::evaluate::ExtractDataRef(designator)) {
- Fortran::common::visit(
- Fortran::common::visitors{
- [&](const Fortran::evaluate::Component &component) {
- componentRef = component;
- },
- [&](const Fortran::evaluate::ArrayRef &arrayRef) {
- if (auto *comp = arrayRef.base().UnwrapComponent())
- componentRef = *comp;
- },
- [](const auto &) {}},
- dataRef->u);
- }
+ std::optional<Fortran::evaluate::Component> componentRef =
+ extractComponentFromDesignator(designator);
fir::factory::AddrAndBoundsInfo info =
Fortran::lower::gatherDataOperandAddrAndBounds<
@@ -4856,12 +4868,11 @@ genACC(Fortran::lower::AbstractConverter &converter,
modifier &&
(*modifier).v == Fortran::parser::AccDataModifier::Modifier::ReadOnly;
- Fortran::lower::StatementContext stmtCtx;
+ Fortran::lower::StatementContext &stmtCtx = converter.getFctCtx();
for (const auto &accObject : accObjectList.v) {
mlir::Location operandLocation = genOperandLocation(converter, accObject);
Fortran::semantics::Symbol &symbol = getSymbolFromAccObject(accObject);
-
std::stringstream asFortran;
Fortran::evaluate::ExpressionAnalyzer ea{semanticsContext};
@@ -4869,19 +4880,22 @@ genACC(Fortran::lower::AbstractConverter &converter,
[&](auto &&s) { return ea.Analyze(s); }, accObject.u);
llvm::SmallVector<mlir::Value> bounds;
- Fortran::lower::gatherDataOperandAddrAndBounds<mlir::acc::DataBoundsOp,
- mlir::acc::DataBoundsType>(
- converter, builder, semanticsContext, stmtCtx, symbol, designator,
- operandLocation, asFortran, bounds,
- /*treatIndexAsSection=*/true, /*unwrapFirBox=*/false,
- /*genDefaultBounds=*/false, /*strideIncludeLowerExtent=*/false,
- /*loadAllocatableAndPointerComponent=*/false);
-
- std::optional<fir::FortranVariableOpInterface> varDef =
- converter.getSymbolMap().lookupVariableDefinition(symbol);
- assert(varDef.has_value() && llvm::isa<hlfir::DeclareOp>(*varDef) &&
- "expected symbol to be mapped to hlfir.declare");
- mlir::Value base = varDef->getBase();
+ fir::factory::AddrAndBoundsInfo info =
+ Fortran::lower::gatherDataOperandAddrAndBounds<
+ mlir::acc::DataBoundsOp, mlir::acc::DataBoundsType>(
+ converter, builder, semanticsContext, stmtCtx, symbol, designator,
+ operandLocation, asFortran, bounds,
+ /*treatIndexAsSection=*/true, /*unwrapFirBox=*/false,
+ /*genDefaultBounds=*/false, /*strideIncludeLowerExtent=*/false,
+ /*loadAllocatableAndPointerComponent=*/false);
+
+ mlir::Value base = info.addr ? info.addr : info.rawInput;
+ if (!base && designator)
+ base = fir::getBase(
+ converter.genExprAddr(operandLocation, *designator, stmtCtx));
+
+ if (!base)
+ continue;
mlir::acc::CacheOp cacheOp = createDataEntryOp<mlir::acc::CacheOp>(
builder, operandLocation, base, asFortran, bounds,
@@ -4892,9 +4906,40 @@ genACC(Fortran::lower::AbstractConverter &converter,
isReadonly ? mlir::acc::DataClauseModifier::readonly
: mlir::acc::DataClauseModifier::none);
- fir::ExtendedValue hostExv = converter.getSymbolExtendedValue(symbol);
- fir::ExtendedValue cacheExv = fir::substBase(hostExv, cacheOp.getAccVar());
- converter.bindSymbol(symbol, cacheExv);
+ // Rebind the symbol so subsequent references use the cached value.
+ if (Fortran::lower::SymbolBox symBox =
+ converter.getSymbolMap().lookupSymbol(symbol)) {
+ // For simple variables, rebind the symbol directly.
+ fir::ExtendedValue hostExv = converter.getSymbolExtendedValue(symbol);
+ fir::ExtendedValue cacheExv =
+ fir::substBase(hostExv, cacheOp.getAccVar());
+ converter.bindSymbol(symbol, cacheExv);
+ } else if (designator) {
+ // For derived type components, extract the component reference and
+ // add a component override so subsequent accesses use the cached value.
+ std::optional<Fortran::evaluate::Component> componentRef =
+ extractComponentFromDesignator(designator);
+ if (componentRef) {
+ // Create an hlfir.declare for the cache result and add component
+ // override so subsequent accesses use the cached value.
+ llvm::SmallVector<mlir::Value> lenParams;
+ mlir::Value shape;
+ fir::FortranVariableFlagsAttr attrs;
+ // Try to get shape/typeparams from the defining designate op.
+ if (auto designate = base.getDefiningOp<hlfir::DesignateOp>()) {
+ shape = designate.getShape();
+ lenParams = llvm::SmallVector<mlir::Value>(
+ designate.getTypeparams().begin(),
+ designate.getTypeparams().end());
+ attrs = designate.getFortranAttrsAttr();
+ }
+ auto declareOp = hlfir::DeclareOp::create(
+ builder, operandLocation, cacheOp.getAccVar(), asFortran.str(),
+ shape, lenParams, /*dummyScope=*/nullptr, /*storage=*/nullptr,
+ /*storageOffset=*/0, attrs);
+ converter.getSymbolMap().addComponentOverride(*componentRef, declareOp);
+ }
+ }
}
}
diff --git a/flang/test/Lower/OpenACC/acc-cache.f90 b/flang/test/Lower/OpenACC/acc-cache.f90
index 1cfe064993160..3fe5131364679 100644
--- a/flang/test/Lower/OpenACC/acc-cache.f90
+++ b/flang/test/Lower/OpenACC/acc-cache.f90
@@ -560,3 +560,80 @@ subroutine test_cache_in_nested_do()
! CHECK: fir.do_loop
! CHECK: hlfir.designate %[[B_VAR]]#0
end subroutine
+
+! CHECK-LABEL: func.func @_QPtest_cache_derived_type()
+subroutine test_cache_derived_type()
+ type :: dt
+ real :: array(100)
+ end type
+
+ integer, parameter :: n = 100
+ type(dt) :: data
+ real :: a(n)
+ integer :: i
+
+ !$acc loop
+ do i = 5, n - 4
+ !$acc cache(data%array(i-4:i+4))
+ a(i) = data%array(i)
+ end do
+
+! CHECK: acc.loop
+! CHECK: %[[ARRAY_COORD:.*]] = hlfir.designate %{{.*}}{"array"} shape %{{.*}} : (!fir.ref<!fir.type<_QFtest_cache_derived_typeTdt{array:!fir.array<100xf32>}>>, !fir.shape<1>) -> !fir.ref<!fir.array<100xf32>>
+! CHECK: %[[BOUND:.*]] = acc.bounds lowerbound(%{{.*}} : index) upperbound(%{{.*}} : index) extent(%{{.*}} : index) stride(%{{.*}} : index) startIdx(%{{.*}} : index)
+! CHECK: %[[CACHE:.*]] = acc.cache varPtr(%[[ARRAY_COORD]] : !fir.ref<!fir.array<100xf32>>) bounds(%[[BOUND]]) -> !fir.ref<!fir.array<100xf32>> {name = "data%array(i-4_4:i+4_4)", structured = false}
+! CHECK: acc.yield
+end subroutine
+
+! CHECK-LABEL: func.func @_QPtest_cache_derived_type_readonly()
+subroutine test_cache_derived_type_readonly()
+ type :: dt
+ real :: array(100)
+ end type
+
+ integer, parameter :: n = 100
+ type(dt) :: data
+ real :: a(n)
+ integer :: i
+
+ !$acc loop
+ do i = 5, n - 4
+ !$acc cache(readonly: data%array(i-4:i+4))
+ a(i) = data%array(i)
+ end do
+
+! CHECK: acc.loop
+! CHECK: %[[ARRAY_COORD:.*]] = hlfir.designate %{{.*}}{"array"} shape %{{.*}} : (!fir.ref<!fir.type<_QFtest_cache_derived_type_readonlyTdt{array:!fir.array<100xf32>}>>, !fir.shape<1>) -> !fir.ref<!fir.array<100xf32>>
+! CHECK: %[[BOUND:.*]] = acc.bounds lowerbound(%{{.*}} : index) upperbound(%{{.*}} : index) extent(%{{.*}} : index) stride(%{{.*}} : index) startIdx(%{{.*}} : index)
+! CHECK: %[[CACHE:.*]] = acc.cache varPtr(%[[ARRAY_COORD]] : !fir.ref<!fir.array<100xf32>>) bounds(%[[BOUND]]) -> !fir.ref<!fir.array<100xf32>> {modifiers = #acc<data_clause_modifier readonly>, name = "data%array(i-4_4:i+4_4)", structured = false}
+! CHECK: acc.yield
+end subroutine
+
+! CHECK-LABEL: func.func @_QPtest_cache_nested_derived_type()
+subroutine test_cache_nested_derived_type()
+ type :: inner
+ real :: arr(50)
+ end type
+
+ type :: outer
+ type(inner) :: in
+ end type
+
+ integer, parameter :: n = 50
+ type(outer) :: obj
+ real :: a(n)
+ integer :: i
+
+ !$acc loop
+ do i = 1, n
+ !$acc cache(obj%in%arr(i))
+ a(i) = obj%in%arr(i)
+ end do
+
+! CHECK: acc.loop
+! CHECK: %[[IN_COORD:.*]] = hlfir.designate %{{.*}}{"in"} : (!fir.ref<!fir.type<_QFtest_cache_nested_derived_typeTouter{in:!fir.type<_QFtest_cache_nested_derived_typeTinner{arr:!fir.array<50xf32>}>}>>) -> !fir.ref<!fir.type<_QFtest_cache_nested_derived_typeTinner{arr:!fir.array<50xf32>}>>
+! CHECK: %[[ARR_COORD:.*]] = hlfir.designate %[[IN_COORD]]{"arr"} shape %{{.*}} : (!fir.ref<!fir.type<_QFtest_cache_nested_derived_typeTinner{arr:!fir.array<50xf32>}>>, !fir.shape<1>) -> !fir.ref<!fir.array<50xf32>>
+! CHECK: %[[BOUND:.*]] = acc.bounds lowerbound(%{{.*}} : index) upperbound(%{{.*}} : index) extent(%{{.*}} : index) stride(%{{.*}} : index) startIdx(%{{.*}} : index)
+! CHECK: %[[CACHE:.*]] = acc.cache varPtr(%[[ARR_COORD]] : !fir.ref<!fir.array<50xf32>>) bounds(%[[BOUND]]) -> !fir.ref<!fir.array<50xf32>> {name = "obj%in%arr(i)", structured = false}
+! CHECK: acc.yield
+end subroutine
>From ce8ccee28750494d31e3883967f676c6c3a8d8af Mon Sep 17 00:00:00 2001
From: Kazuaki Matsumura <kmatsumura at nvidia.com>
Date: Wed, 14 Jan 2026 12:11:12 -0800
Subject: [PATCH 2/2] format
---
flang/lib/Lower/OpenACC.cpp | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/flang/lib/Lower/OpenACC.cpp b/flang/lib/Lower/OpenACC.cpp
index 75c4a4e561b7b..7c2fea2a0abb2 100644
--- a/flang/lib/Lower/OpenACC.cpp
+++ b/flang/lib/Lower/OpenACC.cpp
@@ -4928,9 +4928,9 @@ genACC(Fortran::lower::AbstractConverter &converter,
// Try to get shape/typeparams from the defining designate op.
if (auto designate = base.getDefiningOp<hlfir::DesignateOp>()) {
shape = designate.getShape();
- lenParams = llvm::SmallVector<mlir::Value>(
- designate.getTypeparams().begin(),
- designate.getTypeparams().end());
+ lenParams =
+ llvm::SmallVector<mlir::Value>(designate.getTypeparams().begin(),
+ designate.getTypeparams().end());
attrs = designate.getFortranAttrsAttr();
}
auto declareOp = hlfir::DeclareOp::create(
More information about the flang-commits
mailing list