| 1 |
//===- BufferizeHLFIR.cpp - Bufferize HLFIR ------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
// This file defines a pass that bufferize hlfir.expr. It translates operations |
| 9 |
// producing or consuming hlfir.expr into operations operating on memory. |
| 10 |
// An hlfir.expr is translated to a tuple<variable address, cleanupflag> |
| 11 |
// where cleanupflag is set to true if storage for the expression was allocated |
| 12 |
// on the heap. |
| 13 |
//===----------------------------------------------------------------------===// |
| 14 |
|
| 15 |
#include "flang/Optimizer/Builder/Character.h" |
| 16 |
#include "flang/Optimizer/Builder/FIRBuilder.h" |
| 17 |
#include "flang/Optimizer/Builder/HLFIRTools.h" |
| 18 |
#include "flang/Optimizer/Builder/MutableBox.h" |
| 19 |
#include "flang/Optimizer/Builder/Runtime/Assign.h" |
| 20 |
#include "flang/Optimizer/Builder/Todo.h" |
| 21 |
#include "flang/Optimizer/Dialect/FIRDialect.h" |
| 22 |
#include "flang/Optimizer/Dialect/FIROps.h" |
| 23 |
#include "flang/Optimizer/Dialect/FIRType.h" |
| 24 |
#include "flang/Optimizer/HLFIR/HLFIROps.h" |
| 25 |
#include "flang/Optimizer/HLFIR/Passes.h" |
| 26 |
#include "flang/Optimizer/Support/FIRContext.h" |
| 27 |
#include "mlir/IR/PatternMatch.h" |
| 28 |
#include "mlir/Pass/Pass.h" |
| 29 |
#include "mlir/Pass/PassManager.h" |
| 30 |
#include "mlir/Transforms/DialectConversion.h" |
| 31 |
#include <optional> |
| 32 |
|
| 33 |
namespace hlfir { |
| 34 |
#define GEN_PASS_DEF_BUFFERIZEHLFIR |
| 35 |
#include "flang/Optimizer/HLFIR/Passes.h.inc" |
| 36 |
} // namespace hlfir |
| 37 |
|
| 38 |
namespace { |
| 39 |
|
| 40 |
/// Helper to create tuple from a bufferized expr storage and clean up |
| 41 |
/// instruction flag. |
| 42 |
static mlir::Value packageBufferizedExpr(mlir::Location loc, |
| 43 |
fir::FirOpBuilder &builder, |
| 44 |
mlir::Value storage, |
| 45 |
mlir::Value mustFree) { |
| 46 |
auto tupleType = mlir::TupleType::get( |
| 47 |
builder.getContext(), |
| 48 |
mlir::TypeRange{storage.getType(), mustFree.getType()}); |
| 49 |
auto undef = builder.create<fir::UndefOp>(loc, tupleType); |
| 50 |
auto insert = builder.create<fir::InsertValueOp>( |
| 51 |
loc, tupleType, undef, mustFree, |
| 52 |
builder.getArrayAttr( |
| 53 |
{builder.getIntegerAttr(builder.getIndexType(), 1)})); |
| 54 |
return builder.create<fir::InsertValueOp>( |
| 55 |
loc, tupleType, insert, storage, |
| 56 |
builder.getArrayAttr( |
| 57 |
{builder.getIntegerAttr(builder.getIndexType(), 0)})); |
| 58 |
} |
| 59 |
|
| 60 |
/// Helper to create tuple from a bufferized expr storage and constant |
| 61 |
/// boolean clean-up flag. |
| 62 |
static mlir::Value packageBufferizedExpr(mlir::Location loc, |
| 63 |
fir::FirOpBuilder &builder, |
| 64 |
mlir::Value storage, bool mustFree) { |
| 65 |
mlir::Value mustFreeValue = builder.createBool(loc, mustFree); |
| 66 |
return packageBufferizedExpr(loc, builder, storage, mustFreeValue); |
| 67 |
} |
| 68 |
|
| 69 |
/// Helper to extract the storage from a tuple created by packageBufferizedExpr. |
| 70 |
/// It assumes no tuples are used as HLFIR operation operands, which is |
| 71 |
/// currently enforced by the verifiers that only accept HLFIR value or |
| 72 |
/// variable types which do not include tuples. |
| 73 |
static mlir::Value getBufferizedExprStorage(mlir::Value bufferizedExpr) { |
| 74 |
auto tupleType = bufferizedExpr.getType().dyn_cast<mlir::TupleType>(); |
| 75 |
if (!tupleType) |
| 76 |
return bufferizedExpr; |
| 77 |
assert(tupleType.size() == 2 && "unexpected tuple type"); |
| 78 |
if (auto insert = bufferizedExpr.getDefiningOp<fir::InsertValueOp>()) |
| 79 |
if (insert.getVal().getType() == tupleType.getType(0)) |
| 80 |
return insert.getVal(); |
| 81 |
TODO(bufferizedExpr.getLoc(), "general extract storage case"); |
| 82 |
} |
| 83 |
|
| 84 |
/// Helper to extract the clean-up flag from a tuple created by |
| 85 |
/// packageBufferizedExpr. |
| 86 |
static mlir::Value getBufferizedExprMustFreeFlag(mlir::Value bufferizedExpr) { |
| 87 |
auto tupleType = bufferizedExpr.getType().dyn_cast<mlir::TupleType>(); |
| 88 |
if (!tupleType) |
| 89 |
return bufferizedExpr; |
| 90 |
assert(tupleType.size() == 2 && "unexpected tuple type"); |
| 91 |
if (auto insert = bufferizedExpr.getDefiningOp<fir::InsertValueOp>()) |
| 92 |
if (auto insert0 = insert.getAdt().getDefiningOp<fir::InsertValueOp>()) |
| 93 |
if (insert0.getVal().getType() == tupleType.getType(1)) |
| 94 |
return insert0.getVal(); |
| 95 |
TODO(bufferizedExpr.getLoc(), "general extract storage case"); |
| 96 |
} |
| 97 |
|
| 98 |
static std::pair<hlfir::Entity, mlir::Value> |
| 99 |
createTempFromMold(mlir::Location loc, fir::FirOpBuilder &builder, |
| 100 |
hlfir::Entity mold) { |
| 101 |
llvm::SmallVector<mlir::Value> lenParams; |
| 102 |
hlfir::genLengthParameters(loc, builder, mold, lenParams); |
| 103 |
llvm::StringRef tmpName{".tmp"}; |
| 104 |
mlir::Value alloc; |
| 105 |
mlir::Value isHeapAlloc; |
| 106 |
mlir::Value shape{}; |
| 107 |
if (mold.isArray()) { |
| 108 |
mlir::Type sequenceType = |
| 109 |
hlfir::getFortranElementOrSequenceType(mold.getType()); |
| 110 |
shape = hlfir::genShape(loc, builder, mold); |
| 111 |
auto extents = hlfir::getIndexExtents(loc, builder, shape); |
| 112 |
alloc = builder.createHeapTemporary(loc, sequenceType, tmpName, extents, |
| 113 |
lenParams); |
| 114 |
isHeapAlloc = builder.createBool(loc, true); |
| 115 |
} else { |
| 116 |
alloc = builder.createTemporary(loc, mold.getFortranElementType(), tmpName, |
| 117 |
/*shape*/ std::nullopt, lenParams); |
| 118 |
isHeapAlloc = builder.createBool(loc, false); |
| 119 |
} |
| 120 |
auto declareOp = builder.create<hlfir::DeclareOp>( |
| 121 |
loc, alloc, tmpName, shape, lenParams, fir::FortranVariableFlagsAttr{}); |
| 122 |
return {hlfir::Entity{declareOp.getBase()}, isHeapAlloc}; |
| 123 |
} |
| 124 |
|
| 125 |
static std::pair<hlfir::Entity, mlir::Value> |
| 126 |
createArrayTemp(mlir::Location loc, fir::FirOpBuilder &builder, |
| 127 |
mlir::Type exprType, mlir::Value shape, |
| 128 |
mlir::ValueRange extents, mlir::ValueRange lenParams) { |
| 129 |
mlir::Type sequenceType = hlfir::getFortranElementOrSequenceType(exprType); |
| 130 |
llvm::StringRef tmpName{".tmp.array"}; |
| 131 |
mlir::Value allocmem = builder.createHeapTemporary(loc, sequenceType, tmpName, |
| 132 |
extents, lenParams); |
| 133 |
auto declareOp = |
| 134 |
builder.create<hlfir::DeclareOp>(loc, allocmem, tmpName, shape, lenParams, |
| 135 |
fir::FortranVariableFlagsAttr{}); |
| 136 |
mlir::Value trueVal = builder.createBool(loc, true); |
| 137 |
return {hlfir::Entity{declareOp.getBase()}, trueVal}; |
| 138 |
} |
| 139 |
|
| 140 |
struct AsExprOpConversion : public mlir::OpConversionPattern<hlfir::AsExprOp> { |
| 141 |
using mlir::OpConversionPattern<hlfir::AsExprOp>::OpConversionPattern; |
| 142 |
explicit AsExprOpConversion(mlir::MLIRContext *ctx) |
| 143 |
: mlir::OpConversionPattern<hlfir::AsExprOp>{ctx} {} |
| 144 |
mlir::LogicalResult |
| 145 |
matchAndRewrite(hlfir::AsExprOp asExpr, OpAdaptor adaptor, |
| 146 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 147 |
mlir::Location loc = asExpr->getLoc(); |
| 148 |
auto module = asExpr->getParentOfType<mlir::ModuleOp>(); |
| 149 |
fir::FirOpBuilder builder(rewriter, fir::getKindMapping(module)); |
| 150 |
if (asExpr.isMove()) { |
| 151 |
// Move variable storage for the hlfir.expr buffer. |
| 152 |
mlir::Value bufferizedExpr = packageBufferizedExpr( |
| 153 |
loc, builder, adaptor.getVar(), adaptor.getMustFree()); |
| 154 |
rewriter.replaceOp(asExpr, bufferizedExpr); |
| 155 |
return mlir::success(); |
| 156 |
} |
| 157 |
// Otherwise, create a copy in a new buffer. |
| 158 |
hlfir::Entity source = hlfir::Entity{adaptor.getVar()}; |
| 159 |
auto [temp, cleanup] = createTempFromMold(loc, builder, source); |
| 160 |
builder.create<hlfir::AssignOp>(loc, source, temp); |
| 161 |
mlir::Value bufferizedExpr = |
| 162 |
packageBufferizedExpr(loc, builder, temp, cleanup); |
| 163 |
rewriter.replaceOp(asExpr, bufferizedExpr); |
| 164 |
return mlir::success(); |
| 165 |
} |
| 166 |
}; |
| 167 |
|
| 168 |
struct ApplyOpConversion : public mlir::OpConversionPattern<hlfir::ApplyOp> { |
| 169 |
using mlir::OpConversionPattern<hlfir::ApplyOp>::OpConversionPattern; |
| 170 |
explicit ApplyOpConversion(mlir::MLIRContext *ctx) |
| 171 |
: mlir::OpConversionPattern<hlfir::ApplyOp>{ctx} {} |
| 172 |
mlir::LogicalResult |
| 173 |
matchAndRewrite(hlfir::ApplyOp apply, OpAdaptor adaptor, |
| 174 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 175 |
mlir::Location loc = apply->getLoc(); |
| 176 |
hlfir::Entity bufferizedExpr{getBufferizedExprStorage(adaptor.getExpr())}; |
| 177 |
mlir::Type resultType = hlfir::getVariableElementType(bufferizedExpr); |
| 178 |
mlir::Value result = rewriter.create<hlfir::DesignateOp>( |
| 179 |
loc, resultType, bufferizedExpr, adaptor.getIndices(), |
| 180 |
adaptor.getTypeparams()); |
| 181 |
if (fir::isa_trivial(apply.getType())) |
| 182 |
result = rewriter.create<fir::LoadOp>(loc, result); |
| 183 |
rewriter.replaceOp(apply, result); |
| 184 |
return mlir::success(); |
| 185 |
} |
| 186 |
}; |
| 187 |
|
| 188 |
struct AssignOpConversion : public mlir::OpConversionPattern<hlfir::AssignOp> { |
| 189 |
using mlir::OpConversionPattern<hlfir::AssignOp>::OpConversionPattern; |
| 190 |
explicit AssignOpConversion(mlir::MLIRContext *ctx) |
| 191 |
: mlir::OpConversionPattern<hlfir::AssignOp>{ctx} {} |
| 192 |
mlir::LogicalResult |
| 193 |
matchAndRewrite(hlfir::AssignOp assign, OpAdaptor adaptor, |
| 194 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 195 |
rewriter.replaceOpWithNewOp<hlfir::AssignOp>( |
| 196 |
assign, getBufferizedExprStorage(adaptor.getOperands()[0]), |
| 197 |
getBufferizedExprStorage(adaptor.getOperands()[1])); |
| 198 |
return mlir::success(); |
| 199 |
} |
| 200 |
}; |
| 201 |
|
| 202 |
struct ConcatOpConversion : public mlir::OpConversionPattern<hlfir::ConcatOp> { |
| 203 |
using mlir::OpConversionPattern<hlfir::ConcatOp>::OpConversionPattern; |
| 204 |
explicit ConcatOpConversion(mlir::MLIRContext *ctx) |
| 205 |
: mlir::OpConversionPattern<hlfir::ConcatOp>{ctx} {} |
| 206 |
mlir::LogicalResult |
| 207 |
matchAndRewrite(hlfir::ConcatOp concat, OpAdaptor adaptor, |
| 208 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 209 |
mlir::Location loc = concat->getLoc(); |
| 210 |
auto module = concat->getParentOfType<mlir::ModuleOp>(); |
| 211 |
fir::FirOpBuilder builder(rewriter, fir::getKindMapping(module)); |
| 212 |
assert(adaptor.getStrings().size() >= 2 && |
| 213 |
"must have at least two strings operands"); |
| 214 |
if (adaptor.getStrings().size() > 2) |
| 215 |
TODO(loc, "codegen of optimized chained concatenation of more than two " |
| 216 |
"strings"); |
| 217 |
hlfir::Entity lhs{getBufferizedExprStorage(adaptor.getStrings()[0])}; |
| 218 |
hlfir::Entity rhs{getBufferizedExprStorage(adaptor.getStrings()[1])}; |
| 219 |
auto [lhsExv, c1] = hlfir::translateToExtendedValue(loc, builder, lhs); |
| 220 |
auto [rhsExv, c2] = hlfir::translateToExtendedValue(loc, builder, rhs); |
| 221 |
assert(!c1 && !c2 && "expected variables"); |
| 222 |
fir::ExtendedValue res = |
| 223 |
fir::factory::CharacterExprHelper{builder, loc}.createConcatenate( |
| 224 |
*lhsExv.getCharBox(), *rhsExv.getCharBox()); |
| 225 |
// Ensure the memory type is the same as the result type. |
| 226 |
mlir::Type addrType = fir::ReferenceType::get( |
| 227 |
hlfir::getFortranElementType(concat.getResult().getType())); |
| 228 |
mlir::Value cast = builder.createConvert(loc, addrType, fir::getBase(res)); |
| 229 |
res = fir::substBase(res, cast); |
| 230 |
auto hlfirTempRes = hlfir::genDeclare(loc, builder, res, "tmp", |
| 231 |
fir::FortranVariableFlagsAttr{}) |
| 232 |
.getBase(); |
| 233 |
mlir::Value bufferizedExpr = |
| 234 |
packageBufferizedExpr(loc, builder, hlfirTempRes, false); |
| 235 |
rewriter.replaceOp(concat, bufferizedExpr); |
| 236 |
return mlir::success(); |
| 237 |
} |
| 238 |
}; |
| 239 |
|
| 240 |
struct SetLengthOpConversion |
| 241 |
: public mlir::OpConversionPattern<hlfir::SetLengthOp> { |
| 242 |
using mlir::OpConversionPattern<hlfir::SetLengthOp>::OpConversionPattern; |
| 243 |
explicit SetLengthOpConversion(mlir::MLIRContext *ctx) |
| 244 |
: mlir::OpConversionPattern<hlfir::SetLengthOp>{ctx} {} |
| 245 |
mlir::LogicalResult |
| 246 |
matchAndRewrite(hlfir::SetLengthOp setLength, OpAdaptor adaptor, |
| 247 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 248 |
mlir::Location loc = setLength->getLoc(); |
| 249 |
auto module = setLength->getParentOfType<mlir::ModuleOp>(); |
| 250 |
fir::FirOpBuilder builder(rewriter, fir::getKindMapping(module)); |
| 251 |
// Create a temp with the new length. |
| 252 |
hlfir::Entity string{getBufferizedExprStorage(adaptor.getString())}; |
| 253 |
auto charType = hlfir::getFortranElementType(setLength.getType()); |
| 254 |
llvm::StringRef tmpName{".tmp"}; |
| 255 |
llvm::SmallVector<mlir::Value, 1> lenParams{adaptor.getLength()}; |
| 256 |
auto alloca = builder.createTemporary(loc, charType, tmpName, |
| 257 |
/*shape=*/std::nullopt, lenParams); |
| 258 |
auto declareOp = builder.create<hlfir::DeclareOp>( |
| 259 |
loc, alloca, tmpName, /*shape=*/mlir::Value{}, lenParams, |
| 260 |
fir::FortranVariableFlagsAttr{}); |
| 261 |
// Assign string value to the created temp. |
| 262 |
builder.create<hlfir::AssignOp>(loc, string, declareOp.getBase()); |
| 263 |
mlir::Value bufferizedExpr = |
| 264 |
packageBufferizedExpr(loc, builder, alloca, false); |
| 265 |
rewriter.replaceOp(setLength, bufferizedExpr); |
| 266 |
return mlir::success(); |
| 267 |
} |
| 268 |
}; |
| 269 |
|
| 270 |
static bool allOtherUsesAreDestroys(mlir::Value value, |
| 271 |
mlir::Operation *currentUse) { |
| 272 |
for (mlir::Operation *useOp : value.getUsers()) |
| 273 |
if (!mlir::isa<hlfir::DestroyOp>(useOp) && useOp != currentUse) |
| 274 |
return false; |
| 275 |
return true; |
| 276 |
} |
| 277 |
|
| 278 |
static void eraseAllUsesInDestroys(mlir::Value value, |
| 279 |
mlir::ConversionPatternRewriter &rewriter) { |
| 280 |
for (mlir::Operation *useOp : value.getUsers()) |
| 281 |
if (mlir::isa<hlfir::DestroyOp>(useOp)) |
| 282 |
rewriter.eraseOp(useOp); |
| 283 |
} |
| 284 |
|
| 285 |
struct AssociateOpConversion |
| 286 |
: public mlir::OpConversionPattern<hlfir::AssociateOp> { |
| 287 |
using mlir::OpConversionPattern<hlfir::AssociateOp>::OpConversionPattern; |
| 288 |
explicit AssociateOpConversion(mlir::MLIRContext *ctx) |
| 289 |
: mlir::OpConversionPattern<hlfir::AssociateOp>{ctx} {} |
| 290 |
mlir::LogicalResult |
| 291 |
matchAndRewrite(hlfir::AssociateOp associate, OpAdaptor adaptor, |
| 292 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 293 |
mlir::Location loc = associate->getLoc(); |
| 294 |
// If this is the last use of the expression value and this is an hlfir.expr |
| 295 |
// that was bufferized, re-use the storage. |
| 296 |
// Otherwise, create a temp and assign the storage to it. |
| 297 |
mlir::Value bufferizedExpr = getBufferizedExprStorage(adaptor.getSource()); |
| 298 |
const bool isTrivialValue = fir::isa_trivial(bufferizedExpr.getType()); |
| 299 |
|
| 300 |
auto replaceWith = [&](mlir::Value hlfirVar, mlir::Value firVar, |
| 301 |
mlir::Value flag) { |
| 302 |
associate.getResult(0).replaceAllUsesWith(hlfirVar); |
| 303 |
associate.getResult(1).replaceAllUsesWith(firVar); |
| 304 |
associate.getResult(2).replaceAllUsesWith(flag); |
| 305 |
rewriter.replaceOp(associate, {hlfirVar, firVar, flag}); |
| 306 |
}; |
| 307 |
|
| 308 |
if (!isTrivialValue && allOtherUsesAreDestroys(associate.getSource(), |
| 309 |
associate.getOperation())) { |
| 310 |
// Re-use hlfir.expr buffer if this is the only use of the hlfir.expr |
| 311 |
// outside of the hlfir.destroy. Take on the cleaning-up responsibility |
| 312 |
// for the related hlfir.end_associate, and erase the hlfir.destroy (if |
| 313 |
// any). |
| 314 |
mlir::Value mustFree = getBufferizedExprMustFreeFlag(adaptor.getSource()); |
| 315 |
mlir::Value firBase = hlfir::Entity{bufferizedExpr}.getFirBase(); |
| 316 |
replaceWith(bufferizedExpr, firBase, mustFree); |
| 317 |
eraseAllUsesInDestroys(associate.getSource(), rewriter); |
| 318 |
return mlir::success(); |
| 319 |
} |
| 320 |
if (isTrivialValue) { |
| 321 |
auto module = associate->getParentOfType<mlir::ModuleOp>(); |
| 322 |
fir::FirOpBuilder builder(rewriter, fir::getKindMapping(module)); |
| 323 |
auto temp = builder.createTemporary(loc, bufferizedExpr.getType(), |
| 324 |
associate.getUniqName()); |
| 325 |
builder.create<fir::StoreOp>(loc, bufferizedExpr, temp); |
| 326 |
mlir::Value mustFree = builder.createBool(loc, false); |
| 327 |
replaceWith(temp, temp, mustFree); |
| 328 |
return mlir::success(); |
| 329 |
} |
| 330 |
TODO(loc, "hlfir.associate of hlfir.expr with more than one use"); |
| 331 |
} |
| 332 |
}; |
| 333 |
|
| 334 |
static void genFreeIfMustFree(mlir::Location loc, |
| 335 |
mlir::ConversionPatternRewriter &rewriter, |
| 336 |
mlir::Value var, mlir::Value mustFree) { |
| 337 |
auto genFree = [&]() { |
| 338 |
if (var.getType().isa<fir::BaseBoxType>()) |
| 339 |
TODO(loc, "unbox"); |
| 340 |
if (!var.getType().isa<fir::HeapType>()) |
| 341 |
var = rewriter.create<fir::ConvertOp>( |
| 342 |
loc, fir::HeapType::get(fir::unwrapRefType(var.getType())), var); |
| 343 |
rewriter.create<fir::FreeMemOp>(loc, var); |
| 344 |
}; |
| 345 |
if (auto cstMustFree = fir::getIntIfConstant(mustFree)) { |
| 346 |
if (*cstMustFree != 0) |
| 347 |
genFree(); |
| 348 |
// else, nothing to do. |
| 349 |
return; |
| 350 |
} |
| 351 |
TODO(loc, "conditional free"); |
| 352 |
} |
| 353 |
|
| 354 |
struct EndAssociateOpConversion |
| 355 |
: public mlir::OpConversionPattern<hlfir::EndAssociateOp> { |
| 356 |
using mlir::OpConversionPattern<hlfir::EndAssociateOp>::OpConversionPattern; |
| 357 |
explicit EndAssociateOpConversion(mlir::MLIRContext *ctx) |
| 358 |
: mlir::OpConversionPattern<hlfir::EndAssociateOp>{ctx} {} |
| 359 |
mlir::LogicalResult |
| 360 |
matchAndRewrite(hlfir::EndAssociateOp endAssociate, OpAdaptor adaptor, |
| 361 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 362 |
mlir::Location loc = endAssociate->getLoc(); |
| 363 |
genFreeIfMustFree(loc, rewriter, adaptor.getVar(), adaptor.getMustFree()); |
| 364 |
rewriter.eraseOp(endAssociate); |
| 365 |
return mlir::success(); |
| 366 |
} |
| 367 |
}; |
| 368 |
|
| 369 |
struct DestroyOpConversion |
| 370 |
: public mlir::OpConversionPattern<hlfir::DestroyOp> { |
| 371 |
using mlir::OpConversionPattern<hlfir::DestroyOp>::OpConversionPattern; |
| 372 |
explicit DestroyOpConversion(mlir::MLIRContext *ctx) |
| 373 |
: mlir::OpConversionPattern<hlfir::DestroyOp>{ctx} {} |
| 374 |
mlir::LogicalResult |
| 375 |
matchAndRewrite(hlfir::DestroyOp destroy, OpAdaptor adaptor, |
| 376 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 377 |
// If expr was bufferized on the heap, now is time to deallocate the buffer. |
| 378 |
mlir::Location loc = destroy->getLoc(); |
| 379 |
mlir::Value bufferizedExpr = getBufferizedExprStorage(adaptor.getExpr()); |
| 380 |
if (!fir::isa_trivial(bufferizedExpr.getType())) { |
| 381 |
mlir::Value mustFree = getBufferizedExprMustFreeFlag(adaptor.getExpr()); |
| 382 |
mlir::Value firBase = hlfir::Entity(bufferizedExpr).getFirBase(); |
| 383 |
genFreeIfMustFree(loc, rewriter, firBase, mustFree); |
| 384 |
} |
| 385 |
rewriter.eraseOp(destroy); |
| 386 |
return mlir::success(); |
| 387 |
} |
| 388 |
}; |
| 389 |
|
| 390 |
struct NoReassocOpConversion |
| 391 |
: public mlir::OpConversionPattern<hlfir::NoReassocOp> { |
| 392 |
using mlir::OpConversionPattern<hlfir::NoReassocOp>::OpConversionPattern; |
| 393 |
explicit NoReassocOpConversion(mlir::MLIRContext *ctx) |
| 394 |
: mlir::OpConversionPattern<hlfir::NoReassocOp>{ctx} {} |
| 395 |
mlir::LogicalResult |
| 396 |
matchAndRewrite(hlfir::NoReassocOp noreassoc, OpAdaptor adaptor, |
| 397 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 398 |
rewriter.replaceOpWithNewOp<hlfir::NoReassocOp>( |
| 399 |
noreassoc, getBufferizedExprStorage(adaptor.getVal())); |
| 400 |
return mlir::success(); |
| 401 |
} |
| 402 |
}; |
| 403 |
|
| 404 |
/// Was \p value created in the mlir block where \p builder is currently set ? |
| 405 |
static bool wasCreatedInCurrentBlock(mlir::Value value, |
| 406 |
fir::FirOpBuilder &builder) { |
| 407 |
if (mlir::Operation *op = value.getDefiningOp()) |
| 408 |
return op->getBlock() == builder.getBlock(); |
| 409 |
return false; |
| 410 |
} |
| 411 |
|
| 412 |
/// This Listener allows setting both the builder and the rewriter as |
| 413 |
/// listeners. This is required when a pattern uses a firBuilder helper that |
| 414 |
/// may create illegal operations that will need to be translated and requires |
| 415 |
/// notifying the rewriter. |
| 416 |
struct HLFIRListener : public mlir::OpBuilder::Listener { |
| 417 |
HLFIRListener(fir::FirOpBuilder &builder, |
| 418 |
mlir::ConversionPatternRewriter &rewriter) |
| 419 |
: builder{builder}, rewriter{rewriter} {} |
| 420 |
void notifyOperationInserted(mlir::Operation *op) override { |
| 421 |
builder.notifyOperationInserted(op); |
| 422 |
rewriter.notifyOperationInserted(op); |
| 423 |
} |
| 424 |
virtual void notifyBlockCreated(mlir::Block *block) override { |
| 425 |
builder.notifyBlockCreated(block); |
| 426 |
rewriter.notifyBlockCreated(block); |
| 427 |
} |
| 428 |
fir::FirOpBuilder &builder; |
| 429 |
mlir::ConversionPatternRewriter &rewriter; |
| 430 |
}; |
| 431 |
|
| 432 |
struct ElementalOpConversion |
| 433 |
: public mlir::OpConversionPattern<hlfir::ElementalOp> { |
| 434 |
using mlir::OpConversionPattern<hlfir::ElementalOp>::OpConversionPattern; |
| 435 |
explicit ElementalOpConversion(mlir::MLIRContext *ctx) |
| 436 |
: mlir::OpConversionPattern<hlfir::ElementalOp>{ctx} {} |
| 437 |
mlir::LogicalResult |
| 438 |
matchAndRewrite(hlfir::ElementalOp elemental, OpAdaptor adaptor, |
| 439 |
mlir::ConversionPatternRewriter &rewriter) const override { |
| 440 |
mlir::Location loc = elemental->getLoc(); |
| 441 |
auto module = elemental->getParentOfType<mlir::ModuleOp>(); |
| 442 |
fir::FirOpBuilder builder(rewriter, fir::getKindMapping(module)); |
| 443 |
// The body of the elemental op may contain operation that will require |
| 444 |
// to be translated. Notify the rewriter about the cloned operations. |
| 445 |
HLFIRListener listener{builder, rewriter}; |
| 446 |
builder.setListener(&listener); |
| 447 |
|
| 448 |
mlir::Value shape = adaptor.getShape(); |
| 449 |
auto extents = hlfir::getIndexExtents(loc, builder, shape); |
| 450 |
auto [temp, cleanup] = |
| 451 |
createArrayTemp(loc, builder, elemental.getType(), shape, extents, |
| 452 |
adaptor.getTypeparams()); |
| 453 |
// Generate a loop nest looping around the fir.elemental shape and clone |
| 454 |
// fir.elemental region inside the inner loop. |
| 455 |
auto [innerLoop, oneBasedLoopIndices] = |
| 456 |
hlfir::genLoopNest(loc, builder, extents); |
| 457 |
auto insPt = builder.saveInsertionPoint(); |
| 458 |
builder.setInsertionPointToStart(innerLoop.getBody()); |
| 459 |
auto yield = |
| 460 |
hlfir::inlineElementalOp(loc, builder, elemental, oneBasedLoopIndices); |
| 461 |
hlfir::Entity elementValue(yield.getElementValue()); |
| 462 |
// Skip final AsExpr if any. It would create an element temporary, |
| 463 |
// which is no needed since the element will be assigned right away in |
| 464 |
// the array temporary. An hlfir.as_expr may have been added if the |
| 465 |
// elemental is a "view" over a variable (e.g parentheses or transpose). |
| 466 |
if (auto asExpr = elementValue.getDefiningOp<hlfir::AsExprOp>()) { |
| 467 |
if (asExpr->hasOneUse() && !asExpr.isMove()) { |
| 468 |
elementValue = hlfir::Entity{asExpr.getVar()}; |
| 469 |
rewriter.eraseOp(asExpr); |
| 470 |
} |
| 471 |
} |
| 472 |
rewriter.eraseOp(yield); |
| 473 |
// Assign the element value to the temp element for this iteration. |
| 474 |
auto tempElement = |
| 475 |
hlfir::getElementAt(loc, builder, temp, oneBasedLoopIndices); |
| 476 |
builder.create<hlfir::AssignOp>(loc, elementValue, tempElement); |
| 477 |
// hlfir.yield_element implicitly marks the end-of-life its operand if |
| 478 |
// it is an expression created in the hlfir.elemental (since it is its |
| 479 |
// last use and an hlfir.destroy could not be created afterwards) |
| 480 |
// Now that this node has been removed and the expression has been used in |
| 481 |
// the assign, insert an hlfir.destroy to mark the expression end-of-life. |
| 482 |
// If the expression creation allocated a buffer on the heap inside the |
| 483 |
// loop, this will ensure the buffer properly deallocated. |
| 484 |
if (elementValue.getType().isa<hlfir::ExprType>() && |
| 485 |
wasCreatedInCurrentBlock(elementValue, builder)) |
| 486 |
builder.create<hlfir::DestroyOp>(loc, elementValue); |
| 487 |
builder.restoreInsertionPoint(insPt); |
| 488 |
|
| 489 |
mlir::Value bufferizedExpr = |
| 490 |
packageBufferizedExpr(loc, builder, temp, cleanup); |
| 491 |
rewriter.replaceOp(elemental, bufferizedExpr); |
| 492 |
return mlir::success(); |
| 493 |
} |
| 494 |
}; |
| 495 |
|
| 496 |
class BufferizeHLFIR : public hlfir::impl::BufferizeHLFIRBase<BufferizeHLFIR> { |
| 497 |
public: |
| 498 |
void runOnOperation() override { |
| 499 |
// TODO: make this a pass operating on FuncOp. The issue is that |
| 500 |
// FirOpBuilder helpers may generate new FuncOp because of runtime/llvm |
| 501 |
// intrinsics calls creation. This may create race conflict if the pass is |
| 502 |
// scheduled on FuncOp. A solution could be to provide an optional mutex |
| 503 |
// when building a FirOpBuilder and locking around FuncOp and GlobalOp |
| 504 |
// creation, but this needs a bit more thinking, so at this point the pass |
| 505 |
// is scheduled on the moduleOp. |
| 506 |
auto module = this->getOperation(); |
| 507 |
auto *context = &getContext(); |
| 508 |
mlir::RewritePatternSet patterns(context); |
| 509 |
patterns |
| 510 |
.insert<ApplyOpConversion, AsExprOpConversion, AssignOpConversion, |
| 511 |
AssociateOpConversion, ConcatOpConversion, DestroyOpConversion, |
| 512 |
ElementalOpConversion, EndAssociateOpConversion, |
| 513 |
NoReassocOpConversion, SetLengthOpConversion>(context); |
| 514 |
mlir::ConversionTarget target(*context); |
| 515 |
target.addIllegalOp<hlfir::ApplyOp, hlfir::AssociateOp, hlfir::ElementalOp, |
| 516 |
hlfir::EndAssociateOp, hlfir::SetLengthOp, |
| 517 |
hlfir::YieldElementOp>(); |
| 518 |
target.markUnknownOpDynamicallyLegal([](mlir::Operation *op) { |
| 519 |
return llvm::all_of( |
| 520 |
op->getResultTypes(), |
| 521 |
[](mlir::Type ty) { return !ty.isa<hlfir::ExprType>(); }) && |
| 522 |
llvm::all_of(op->getOperandTypes(), [](mlir::Type ty) { |
| 523 |
return !ty.isa<hlfir::ExprType>(); |
| 524 |
}); |
| 525 |
}); |
| 526 |
if (mlir::failed( |
| 527 |
mlir::applyFullConversion(module, target, std::move(patterns)))) { |
| 528 |
mlir::emitError(mlir::UnknownLoc::get(context), |
| 529 |
"failure in HLFIR bufferization pass"); |
| 530 |
signalPassFailure(); |
| 531 |
} |
| 532 |
} |
| 533 |
}; |
| 534 |
} // namespace |
| 535 |
|
| 536 |
std::unique_ptr<mlir::Pass> hlfir::createBufferizeHLFIRPass() { |
| 537 |
return std::make_unique<BufferizeHLFIR>(); |
| 538 |
} |