This PR is one of 3 in a PR stack, this is the primary change set which seeks to extend the current derived type explicit member mapping support to handle descriptor member mapping at arbitrary levels of nesting. The PR stack seems to do this reasonably (from testing so far) but as you can create quite complex mappings with derived types (in particular when adding allocatable derived types or arrays of allocatable derived types) I imagine there will be hiccups, which I am more than happy to address. There will also be further extensions to this work to handle the implicit auto-magical mapping of descriptor members in derived types and a few other changes planned for the future (with some ideas on optimizing things). The changes in this PR primarily occur in the OpenMP lowering and the OMPMapInfoFinalization pass. In the OpenMP lowering several utility functions were added or extended to support the generation of appropriate intermediate member mappings which are currently required when the parent (or multiple parents) of a mapped member are descriptor types. We need to map the entirety of these types or do a "deep copy" for lack of a better term, where we map both the base address and the descriptor as without the copying of both of these we lack the information in the case of the descriptor to access the member or attach the pointers data to the pointer and in the latter case we require the base address to map the chunk of data. Currently we do not segment descriptor based derived types as we do with regular non-descriptor derived types, we effectively map their entirety in all cases at the moment, I hope to address this at some point in the future as it adds a fair bit of a performance penalty to having nestings of allocatable derived types as an example. The process of mapping all intermediate descriptor members in a members path only occurs if a member has an allocatable or object parent in its symbol path or the member itself is a member or allocatable. This occurs in the createParentSymAndGenIntermediateMaps function, which will also generate the appropriate address for the allocatable member within the derived type to use as a the varPtr field of the map (for intermediate allocatable maps and final allocatable mappings). In this case it's necessary as we can't utilise the usual Fortran::lower functionality such as gatherDataOperandAddrAndBounds without causing issues later in the lowering due to extra allocas being spawned which seem to affect the pointer attachment (at least this is my current assumption, it results in memory access errors on the device due to incorrect map information generation). This is similar to why we do not use the MLIR value generated for this and utilise the original symbol provided when mapping descriptor types external to derived types. Hopefully this can be rectified in the future so this function can be simplified and more closely aligned to the other type mappings. We also make use of fir::CoordinateOp as opposed to the HLFIR version as the HLFIR version doesn't support the appropriate lowering to FIR necessary at the moment, we also cannot use a single CoordinateOp (similarly to a single GEP) as when we index through a descriptor operation (BoxType) we encounter issues later in the lowering, however in either case we need access to intermediate descriptors so individual CoordinateOp's aid this (although, being able to compress them into a smaller amount of CoordinateOp's may simplify the IR and perhaps result in a better end product, something to consider for the future). The other large change area was in the OMPMapInfoFinalization pass, where the pass had to be extended to support the expansion of box types (or multiple nestings of box types) within derived types, or box type derived types. This requires expanding each BoxType mapping from one into two maps and then modifying all of the existing member indices of the overarching parent mapping to account for the addition of these new members alongside adjusting the existing member indices to support the addition of these new maps which extend the original member indices (as a base address of a box type is currently considered a member of the box type at a position of 0 as when lowered to LLVM-IR it's a pointer contained at this position in the descriptor type, however, this means extending mapped children of this expanded descriptor type to additionally incorporate the new member index in the correct location in its own index list). I believe there is a reasonable amount of comments that should aid in understanding this better, alongside the test alterations for the pass. A subset of the changes were also aimed at making some of the utilities for packing and unpacking the DenseIntElementsAttr containing the member indices shareable across the lowering and OMPMapInfoFinalization, this required moving some functions to the Lower/Support/Utils.h header, and transforming the lowering structure containing the member index data into something more similar to the version used in OMPMapInfoFinalization. There we also some other attempts at tidying things up in relation to the member index data generation in the lowering, some of which required creating a logical operator for the OpenMP ID class so it can be utilised as a map key (it simply utilises the symbol address for the moment as ordering isn't particularly important). Otherwise I have added a set of new tests encompassing some of the mappings currently supported by this PR (unfortunately as you can have arbitrary nestings of all shapes and types it's not very feasible to cover them all).
157 lines
6.7 KiB
C++
157 lines
6.7 KiB
C++
//===- MapsForPrivatizedSymbols.cpp
|
|
//-----------------------------------------===//
|
|
//
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
/// \file
|
|
/// An OpenMP dialect related pass for FIR/HLFIR which creates MapInfoOp
|
|
/// instances for certain privatized symbols.
|
|
/// For example, if an allocatable variable is used in a private clause attached
|
|
/// to a omp.target op, then the allocatable variable's descriptor will be
|
|
/// needed on the device (e.g. GPU). This descriptor needs to be separately
|
|
/// mapped onto the device. This pass creates the necessary omp.map.info ops for
|
|
/// this.
|
|
//===----------------------------------------------------------------------===//
|
|
// TODO:
|
|
// 1. Before adding omp.map.info, check if we already have an omp.map.info for
|
|
// the variable in question.
|
|
// 2. Generalize this for more than just omp.target ops.
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
#include "flang/Optimizer/Builder/FIRBuilder.h"
|
|
#include "flang/Optimizer/Dialect/FIRType.h"
|
|
#include "flang/Optimizer/Dialect/Support/KindMapping.h"
|
|
#include "flang/Optimizer/HLFIR/HLFIROps.h"
|
|
#include "flang/Optimizer/OpenMP/Passes.h"
|
|
#include "mlir/Dialect/Func/IR/FuncOps.h"
|
|
#include "mlir/Dialect/OpenMP/OpenMPDialect.h"
|
|
#include "mlir/IR/BuiltinAttributes.h"
|
|
#include "mlir/IR/SymbolTable.h"
|
|
#include "mlir/Pass/Pass.h"
|
|
#include "llvm/Frontend/OpenMP/OMPConstants.h"
|
|
#include "llvm/Support/Debug.h"
|
|
#include <type_traits>
|
|
|
|
#define DEBUG_TYPE "omp-maps-for-privatized-symbols"
|
|
|
|
namespace flangomp {
|
|
#define GEN_PASS_DEF_MAPSFORPRIVATIZEDSYMBOLSPASS
|
|
#include "flang/Optimizer/OpenMP/Passes.h.inc"
|
|
} // namespace flangomp
|
|
using namespace mlir;
|
|
namespace {
|
|
class MapsForPrivatizedSymbolsPass
|
|
: public flangomp::impl::MapsForPrivatizedSymbolsPassBase<
|
|
MapsForPrivatizedSymbolsPass> {
|
|
|
|
bool privatizerNeedsMap(omp::PrivateClauseOp &privatizer) {
|
|
Region &allocRegion = privatizer.getAllocRegion();
|
|
Value blockArg0 = allocRegion.getArgument(0);
|
|
if (blockArg0.use_empty())
|
|
return false;
|
|
return true;
|
|
}
|
|
omp::MapInfoOp createMapInfo(Location loc, Value var,
|
|
fir::FirOpBuilder &builder) {
|
|
uint64_t mapTypeTo = static_cast<
|
|
std::underlying_type_t<llvm::omp::OpenMPOffloadMappingFlags>>(
|
|
llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TO);
|
|
Operation *definingOp = var.getDefiningOp();
|
|
auto declOp = llvm::dyn_cast_or_null<hlfir::DeclareOp>(definingOp);
|
|
assert(declOp &&
|
|
"Expected defining Op of privatized var to be hlfir.declare");
|
|
|
|
// We want the first result of the hlfir.declare op because our goal
|
|
// is to map the descriptor (fir.box or fir.boxchar) and the first
|
|
// result for hlfir.declare is the descriptor if a the symbol being
|
|
// decalred needs a descriptor.
|
|
Value varPtr = declOp.getBase();
|
|
|
|
// If we do not have a reference to descritor, but the descriptor itself
|
|
// then we need to store that on the stack so that we can map the
|
|
// address of the descriptor.
|
|
if (mlir::isa<fir::BaseBoxType>(varPtr.getType()) ||
|
|
mlir::isa<fir::BoxCharType>(varPtr.getType())) {
|
|
OpBuilder::InsertPoint savedInsPoint = builder.saveInsertionPoint();
|
|
mlir::Block *allocaBlock = builder.getAllocaBlock();
|
|
assert(allocaBlock && "No allocablock found for a funcOp");
|
|
builder.setInsertionPointToStart(allocaBlock);
|
|
auto alloca = builder.create<fir::AllocaOp>(loc, varPtr.getType());
|
|
builder.restoreInsertionPoint(savedInsPoint);
|
|
builder.create<fir::StoreOp>(loc, varPtr, alloca);
|
|
varPtr = alloca;
|
|
}
|
|
return builder.create<omp::MapInfoOp>(
|
|
loc, varPtr.getType(), varPtr,
|
|
TypeAttr::get(llvm::cast<omp::PointerLikeType>(varPtr.getType())
|
|
.getElementType()),
|
|
/*varPtrPtr=*/Value{},
|
|
/*members=*/SmallVector<Value>{},
|
|
/*member_index=*/mlir::ArrayAttr{},
|
|
/*bounds=*/ValueRange{},
|
|
builder.getIntegerAttr(builder.getIntegerType(64, /*isSigned=*/false),
|
|
mapTypeTo),
|
|
builder.getAttr<omp::VariableCaptureKindAttr>(
|
|
omp::VariableCaptureKind::ByRef),
|
|
StringAttr(), builder.getBoolAttr(false));
|
|
}
|
|
void addMapInfoOp(omp::TargetOp targetOp, omp::MapInfoOp mapInfoOp) {
|
|
auto argIface = llvm::cast<omp::BlockArgOpenMPOpInterface>(*targetOp);
|
|
unsigned insertIndex =
|
|
argIface.getMapBlockArgsStart() + argIface.numMapBlockArgs();
|
|
targetOp.getMapVarsMutable().append(ValueRange{mapInfoOp});
|
|
targetOp.getRegion().insertArgument(insertIndex, mapInfoOp.getType(),
|
|
mapInfoOp.getLoc());
|
|
}
|
|
void addMapInfoOps(omp::TargetOp targetOp,
|
|
llvm::SmallVectorImpl<omp::MapInfoOp> &mapInfoOps) {
|
|
for (auto mapInfoOp : mapInfoOps)
|
|
addMapInfoOp(targetOp, mapInfoOp);
|
|
}
|
|
void runOnOperation() override {
|
|
ModuleOp module = getOperation()->getParentOfType<ModuleOp>();
|
|
fir::KindMapping kindMap = fir::getKindMapping(module);
|
|
fir::FirOpBuilder builder{module, std::move(kindMap)};
|
|
llvm::DenseMap<Operation *, llvm::SmallVector<omp::MapInfoOp, 4>>
|
|
mapInfoOpsForTarget;
|
|
|
|
getOperation()->walk([&](omp::TargetOp targetOp) {
|
|
if (targetOp.getPrivateVars().empty())
|
|
return;
|
|
OperandRange privVars = targetOp.getPrivateVars();
|
|
std::optional<ArrayAttr> privSyms = targetOp.getPrivateSyms();
|
|
SmallVector<omp::MapInfoOp, 4> mapInfoOps;
|
|
for (auto [privVar, privSym] : llvm::zip_equal(privVars, *privSyms)) {
|
|
|
|
SymbolRefAttr privatizerName = llvm::cast<SymbolRefAttr>(privSym);
|
|
omp::PrivateClauseOp privatizer =
|
|
SymbolTable::lookupNearestSymbolFrom<omp::PrivateClauseOp>(
|
|
targetOp, privatizerName);
|
|
if (!privatizerNeedsMap(privatizer)) {
|
|
continue;
|
|
}
|
|
builder.setInsertionPoint(targetOp);
|
|
Location loc = targetOp.getLoc();
|
|
omp::MapInfoOp mapInfoOp = createMapInfo(loc, privVar, builder);
|
|
mapInfoOps.push_back(mapInfoOp);
|
|
LLVM_DEBUG(llvm::dbgs() << "MapsForPrivatizedSymbolsPass created ->\n");
|
|
LLVM_DEBUG(mapInfoOp.dump());
|
|
}
|
|
if (!mapInfoOps.empty()) {
|
|
mapInfoOpsForTarget.insert({targetOp.getOperation(), mapInfoOps});
|
|
}
|
|
});
|
|
if (!mapInfoOpsForTarget.empty()) {
|
|
for (auto &[targetOp, mapInfoOps] : mapInfoOpsForTarget) {
|
|
addMapInfoOps(static_cast<omp::TargetOp>(targetOp), mapInfoOps);
|
|
}
|
|
}
|
|
}
|
|
};
|
|
} // namespace
|