31#define GEN_PASS_DEF_CONVERTSCFTOOPENMPPASS
32#include "mlir/Conversion/Passes.h.inc"
43template <
typename... OpTy>
45 if (block.
empty() || llvm::hasSingleElement(block) ||
46 std::next(block.
begin(), 2) != block.
end())
56 if (!reducedVal || !isa<BlockArgument>(reducedVal) || combinerOps.size() != 1)
59 return isa<OpTy...>(combinerOps[0]) &&
60 isa<scf::ReduceReturnOp>(block.
back()) &&
76 typename CompareOpTy,
typename SelectOpTy,
77 typename Predicate =
decltype(std::declval<CompareOpTy>().getPredicate())>
82 llvm::is_one_of<SelectOpTy, arith::SelectOp, LLVM::SelectOp>::value,
83 "only arithmetic and llvm select ops are supported");
86 if (block.
empty() || llvm::hasSingleElement(block) ||
87 std::next(block.
begin(), 2) == block.
end() ||
88 std::next(block.
begin(), 3) != block.
end())
92 auto compare = dyn_cast<CompareOpTy>(block.
front());
93 auto select = dyn_cast<SelectOpTy>(block.
front().getNextNode());
94 auto terminator = dyn_cast<scf::ReduceReturnOp>(block.
back());
95 if (!compare || !select || !terminator)
104 if (llvm::is_contained(lessThanPredicates, compare.getPredicate())) {
106 }
else if (llvm::is_contained(greaterThanPredicates,
107 compare.getPredicate())) {
113 if (select.getCondition() != compare.getResult())
121 constexpr unsigned kTrueValue = 1;
122 constexpr unsigned kFalseValue = 2;
123 bool sameOperands = select.getOperand(kTrueValue) == compare.getLhs() &&
124 select.getOperand(kFalseValue) == compare.getRhs();
125 bool swappedOperands = select.getOperand(kTrueValue) == compare.getRhs() &&
126 select.getOperand(kFalseValue) == compare.getLhs();
127 if (!sameOperands && !swappedOperands)
130 if (select.getResult() != terminator.getResult())
135 isMin = (isLess && sameOperands) || (!isLess && swappedOperands);
136 return isMin || (isLess & swappedOperands) || (!isLess && sameOperands);
142 return llvm::APFloat::IEEEhalf();
144 return llvm::APFloat::IEEEsingle();
146 return llvm::APFloat::IEEEdouble();
148 return llvm::APFloat::IEEEquad();
150 return llvm::APFloat::BFloat();
152 return llvm::APFloat::x87DoubleExtended();
153 llvm_unreachable(
"unknown float type");
159 if (
auto vecType = dyn_cast<VectorType>(type))
168 auto fltType = cast<FloatType>(elType);
179 auto intType = cast<IntegerType>(elType);
180 unsigned bitwidth = intType.getWidth();
181 auto val =
min ? llvm::APInt::getSignedMinValue(bitwidth)
182 : llvm::APInt::getSignedMaxValue(bitwidth);
192 auto intType = cast<IntegerType>(elType);
193 unsigned bitwidth = intType.getWidth();
195 min ? llvm::APInt::getZero(bitwidth) : llvm::APInt::getAllOnes(bitwidth);
204static omp::DeclareReductionOp
208 Type type =
reduce.getOperands()[reductionIndex].getType();
209 auto decl = omp::DeclareReductionOp::create(builder,
reduce.getLoc(),
216 decl.getInitializerRegion().end(), {type},
217 {reduce.getOperands()[reductionIndex].getLoc()});
220 LLVM::ConstantOp::create(builder,
reduce.getLoc(), type, initValue);
221 omp::YieldOp::create(builder,
reduce.getLoc(), init);
224 &
reduce.getReductions()[reductionIndex].front().back();
225 assert(isa<scf::ReduceReturnOp>(terminator) &&
226 "expected reduce op to be terminated by reduce return");
231 decl.getReductionRegion(),
232 decl.getReductionRegion().end());
239 LLVM::AtomicBinOp atomicKind,
240 omp::DeclareReductionOp decl,
244 auto ptrType = LLVM::LLVMPointerType::get(builder.
getContext());
245 Location reduceOperandLoc =
reduce.getOperands()[reductionIndex].getLoc();
246 builder.
createBlock(&decl.getAtomicReductionRegion(),
247 decl.getAtomicReductionRegion().end(), {ptrType, ptrType},
248 {reduceOperandLoc, reduceOperandLoc});
249 Block *atomicBlock = &decl.getAtomicReductionRegion().
back();
251 Value loaded = LLVM::LoadOp::create(builder,
reduce.getLoc(), decl.getType(),
253 LLVM::AtomicRMWOp::create(builder,
reduce.getLoc(), atomicKind,
255 LLVM::AtomicOrdering::monotonic);
283 assert(llvm::hasSingleElement(
reduce.getReductions()[reductionIndex]) &&
284 "expected reduction region to have a single element");
287 Type type =
reduce.getOperands()[reductionIndex].getType();
288 Block &reduction =
reduce.getReductions()[reductionIndex].front();
296 builder, symbolTable,
reduce, reductionIndex,
299 decl,
reduce, reductionIndex)
304 builder, symbolTable,
reduce, reductionIndex,
307 decl,
reduce, reductionIndex)
312 builder, symbolTable,
reduce, reductionIndex,
315 decl,
reduce, reductionIndex)
320 builder, symbolTable,
reduce, reductionIndex,
323 decl,
reduce, reductionIndex)
329 builder, symbolTable,
reduce, reductionIndex,
332 decl,
reduce, reductionIndex)
341 builder, symbolTable,
reduce, reductionIndex,
347 builder, symbolTable,
reduce, reductionIndex,
355 arith::CmpFPredicate>(
356 reduction, {arith::CmpFPredicate::OLT, arith::CmpFPredicate::OLE},
357 {arith::CmpFPredicate::OGT, arith::CmpFPredicate::OGE}, isMin) ||
359 arith::CmpFPredicate>(
360 reduction, {arith::CmpFPredicate::OGT, arith::CmpFPredicate::OGE},
361 {arith::CmpFPredicate::OLT, arith::CmpFPredicate::OLE}, isMin)) {
368 arith::CmpIPredicate>(
369 reduction, {arith::CmpIPredicate::slt, arith::CmpIPredicate::sle},
370 {arith::CmpIPredicate::sgt, arith::CmpIPredicate::sge}, isMin) ||
372 arith::CmpIPredicate>(
373 reduction, {arith::CmpIPredicate::sgt, arith::CmpIPredicate::sge},
374 {arith::CmpIPredicate::slt, arith::CmpIPredicate::sle}, isMin)) {
375 omp::DeclareReductionOp decl =
379 isMin ? LLVM::AtomicBinOp::min
380 : LLVM::AtomicBinOp::max,
381 decl,
reduce, reductionIndex)
387 arith::CmpIPredicate>(
388 reduction, {arith::CmpIPredicate::ult, arith::CmpIPredicate::ule},
389 {arith::CmpIPredicate::ugt, arith::CmpIPredicate::uge}, isMin) ||
391 arith::CmpIPredicate>(
392 reduction, {arith::CmpIPredicate::ugt, arith::CmpIPredicate::uge},
393 {arith::CmpIPredicate::ult, arith::CmpIPredicate::ule}, isMin)) {
394 omp::DeclareReductionOp decl =
398 isMin ? LLVM::AtomicBinOp::umin
399 : LLVM::AtomicBinOp::umax,
400 decl,
reduce, reductionIndex)
410 static constexpr unsigned kUseOpenMPDefaultNumThreads = 0;
414 unsigned numThreads = kUseOpenMPDefaultNumThreads)
417 LogicalResult matchAndRewrite(scf::ParallelOp parallelOp,
419 if (parallelOp.getUnsignedCmp())
421 parallelOp,
"unsigned loop bounds are not supported");
425 for (
Value init : parallelOp.getInitVals()) {
427 !isa<LLVM::PointerElementTypeInterface>(init.getType()))
429 parallelOp,
"reduction init type is not an LLVM-compatible type");
437 auto reduce = cast<scf::ReduceOp>(parallelOp.getBody()->getTerminator());
438 for (
int64_t i = 0, e = parallelOp.getNumReductions(); i < e; ++i) {
440 ompReductionDecls.push_back(decl);
443 reductionSyms.push_back(
444 SymbolRefAttr::get(rewriter.
getContext(), decl.getSymName()));
451 LLVM::ConstantOp::create(rewriter, loc, rewriter.
getIntegerType(64),
454 reductionVariables.reserve(parallelOp.getNumReductions());
455 auto ptrType = LLVM::LLVMPointerType::get(parallelOp.getContext());
456 for (
Value init : parallelOp.getInitVals()) {
457 Value storage = LLVM::AllocaOp::create(rewriter, loc, ptrType,
458 init.getType(), one, 0);
459 LLVM::StoreOp::create(rewriter, loc, init, storage);
460 reductionVariables.push_back(storage);
466 for (
auto [x, y, rD] : llvm::zip_equal(
467 reductionVariables,
reduce.getOperands(), ompReductionDecls)) {
470 Region &redRegion = rD.getReductionRegion();
476 "expect reduction region to have one block");
477 Value pvtRedVar = parallelOp.getRegion().addArgument(x.getType(), loc);
478 Value pvtRedVal = LLVM::LoadOp::create(rewriter,
reduce.getLoc(),
479 rD.getType(), pvtRedVar);
482 builder.setInsertionPoint(
reduce);
485 "expect reduction region to have two arguments");
488 for (
auto &op : redRegion.
getOps()) {
490 if (
auto yieldOp = dyn_cast<omp::YieldOp>(*cloneOp)) {
491 assert(yieldOp && yieldOp.getResults().size() == 1 &&
492 "expect YieldOp in reduction region to return one result");
493 Value redVal = yieldOp.getResults()[0];
494 LLVM::StoreOp::create(rewriter, loc, redVal, pvtRedVar);
503 if (numThreads > 0) {
504 Value numThreadsVar = LLVM::ConstantOp::create(
506 numThreadsVars.push_back(numThreadsVar);
509 auto ompParallel = omp::ParallelOp::create(
520 omp::ClauseProcBindKindAttr{},
534 auto wsloopOp = omp::WsloopOp::create(rewriter, parallelOp.getLoc());
535 if (!reductionVariables.empty()) {
536 wsloopOp.setReductionSymsAttr(
537 ArrayAttr::get(rewriter.
getContext(), reductionSyms));
538 wsloopOp.getReductionVarsMutable().append(reductionVariables);
542 reductionByRef.resize(reductionVariables.size(),
false);
543 wsloopOp.setReductionByref(
546 omp::TerminatorOp::create(rewriter, loc);
551 reductionTypes.reserve(reductionVariables.size());
552 llvm::transform(reductionVariables, std::back_inserter(reductionTypes),
555 &wsloopOp.getRegion(), {}, reductionTypes,
557 parallelOp.getLoc()));
560 auto loopOp = omp::LoopNestOp::create(
561 rewriter, parallelOp.getLoc(), parallelOp.getLowerBound().size(),
562 parallelOp.getLowerBound(), parallelOp.getUpperBound(),
563 parallelOp.getStep(),
false,
567 loopOp.getRegion().begin());
572 unsigned numLoops = parallelOp.getNumLoops();
575 wsloopOp.getRegion().getArguments());
583 auto scope = memref::AllocaScopeOp::create(
584 rewriter, parallelOp.getLoc(),
TypeRange());
585 omp::YieldOp::create(rewriter, loc,
ValueRange());
589 memref::AllocaScopeReturnOp::create(rewriter, loc,
ValueRange());
595 results.reserve(reductionVariables.size());
596 for (
auto [variable, type] :
597 llvm::zip(reductionVariables, parallelOp.getResultTypes())) {
598 Value res = LLVM::LoadOp::create(rewriter, loc, type, variable);
599 results.push_back(res);
608static LogicalResult
applyPatterns(ModuleOp module,
unsigned numThreads) {
610 patterns.add<ParallelOpLowering>(module.getContext(), numThreads);
613 auto status =
module.walk([](Operation *op) {
614 if (isa<scf::ReduceOp, scf::ReduceReturnOp, scf::ParallelOp>(op)) {
615 op->emitError("unconverted operation found");
620 return failure(status.wasInterrupted());
624struct SCFToOpenMPPass
625 :
public impl::ConvertSCFToOpenMPPassBase<SCFToOpenMPPass> {
630 void runOnOperation()
override {
static Value reduce(OpBuilder &builder, Location loc, Value input, Value output, int64_t dim)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static void applyPatterns(Region ®ion, const FrozenRewritePatternSet &patterns, ArrayRef< ReductionNode::Range > rangeToKeep, bool eraseOpNotInRange)
We implicitly number each operation in the region and if an operation's number falls into rangeToKeep...
static Attribute minMaxValueForFloat(Type type, bool min)
Returns an attribute with the minimum (if min is set) or the maximum value (otherwise) for the given ...
static omp::DeclareReductionOp addAtomicRMW(OpBuilder &builder, LLVM::AtomicBinOp atomicKind, omp::DeclareReductionOp decl, scf::ReduceOp reduce, int64_t reductionIndex)
Adds an atomic reduction combiner to the given OpenMP reduction declaration using llvm....
static bool matchSimpleReduction(Block &block)
Matches a block containing a "simple" reduction.
static const llvm::fltSemantics & fltSemanticsForType(FloatType type)
Returns the float semantics for the given float type.
static Attribute getSplatOrScalarAttr(Type type, Attribute val)
Helper to create a splat attribute for vector types, or return the scalar attribute for scalar types.
static bool supportsAtomic(Type type)
Returns true if the type is supported by llvm.atomicrmw.
static omp::DeclareReductionOp declareReduction(PatternRewriter &builder, scf::ReduceOp reduce, int64_t reductionIndex)
Creates an OpenMP reduction declaration that corresponds to the given SCF reduction and returns it.
static bool matchSelectReduction(Block &block, ArrayRef< Predicate > lessThanPredicates, ArrayRef< Predicate > greaterThanPredicates, bool &isMin)
Matches a block containing a select-based min/max reduction.
static omp::DeclareReductionOp createDecl(PatternRewriter &builder, SymbolTable &symbolTable, scf::ReduceOp reduce, int64_t reductionIndex, Attribute initValue)
Creates an OpenMP reduction declaration and inserts it into the provided symbol table.
static Attribute minMaxValueForSignedInt(Type type, bool min)
Returns an attribute with the signed integer minimum (if min is set) or the maximum value (otherwise)...
static Attribute minMaxValueForUnsignedInt(Type type, bool min)
Returns an attribute with the unsigned integer minimum (if min is set) or the maximum value (otherwis...
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
void eraseArguments(unsigned start, unsigned num)
Erases 'num' arguments from the index 'start'.
BlockArgListType getArguments()
IntegerAttr getI32IntegerAttr(int32_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
FloatAttr getFloatAttr(Type type, double value)
IntegerAttr getI64IntegerAttr(int64_t value)
IntegerType getIntegerType(unsigned width)
MLIRContext * getContext() const
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
This class represents a frozen set of patterns that can be processed by a pattern applicator.
This is a utility class for mapping one set of IR entities to another.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Operation is the basic unit of execution within MLIR.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
operand_range getOperands()
Returns an iterator on the underlying Value's.
Operation * clone(IRMapping &mapper, const CloneOptions &options=CloneOptions::all())
Create a deep copy of this operation, remapping any operands that use values outside of the operation...
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
iterator_range< OpIterator > getOps()
unsigned getNumArguments()
BlockArgument getArgument(unsigned i)
bool hasOneBlock()
Return true if this region has exactly one block.
Block * splitBlock(Block *block, Block::iterator before)
Split the operations starting at "before" (inclusive) out of the given block into a new block,...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void inlineRegionBefore(Region ®ion, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
StringAttr insert(Operation *symbol, Block::iterator insertPt={})
Insert a new symbol into the table, and rename it as necessary to avoid collisions.
static Operation * getNearestSymbolTable(Operation *from)
Returns the nearest symbol table from a given operation from.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
static WalkResult advance()
static WalkResult interrupt()
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< bool > content)
bool isCompatibleType(Type type)
Returns true if the given type is compatible with the LLVM dialect.
Include the generated interface declarations.
Value matchReduction(ArrayRef< BlockArgument > iterCarriedArgs, unsigned redPos, SmallVectorImpl< Operation * > &combinerOps)
Utility to match a generic reduction given a list of iteration-carried arguments, iterCarriedArgs and...
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
void walkAndApplyPatterns(Operation *op, const FrozenRewritePatternSet &patterns, RewriterBase::Listener *listener=nullptr)
A fast walk-based pattern rewrite driver.
detail::DenseArrayAttrImpl< bool > DenseBoolArrayAttr
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...