1 //===- SCFToOpenMP.cpp - Structured Control Flow to OpenMP conversion -----===// 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 // 9 // This file implements a pass to convert scf.parallel operations into OpenMP 10 // parallel loops. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Conversion/SCFToOpenMP/SCFToOpenMP.h" 15 #include "../PassDetail.h" 16 #include "mlir/Analysis/LoopAnalysis.h" 17 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 18 #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 19 #include "mlir/Dialect/SCF/SCF.h" 20 #include "mlir/Dialect/StandardOps/IR/Ops.h" 21 #include "mlir/IR/ImplicitLocOpBuilder.h" 22 #include "mlir/IR/SymbolTable.h" 23 #include "mlir/Transforms/DialectConversion.h" 24 25 using namespace mlir; 26 27 /// Matches a block containing a "simple" reduction. The expected shape of the 28 /// block is as follows. 29 /// 30 /// ^bb(%arg0, %arg1): 31 /// %0 = OpTy(%arg0, %arg1) 32 /// scf.reduce.return %0 33 template <typename... OpTy> 34 static bool matchSimpleReduction(Block &block) { 35 if (block.empty() || llvm::hasSingleElement(block) || 36 std::next(block.begin(), 2) != block.end()) 37 return false; 38 39 if (block.getNumArguments() != 2) 40 return false; 41 42 SmallVector<Operation *, 4> combinerOps; 43 Value reducedVal = matchReduction({block.getArguments()[1]}, 44 /*redPos=*/0, combinerOps); 45 46 if (!reducedVal || !reducedVal.isa<BlockArgument>() || 47 combinerOps.size() != 1) 48 return false; 49 50 return isa<OpTy...>(combinerOps[0]) && 51 isa<scf::ReduceReturnOp>(block.back()) && 52 block.front().getOperands() == block.getArguments(); 53 } 54 55 /// Matches a block containing a select-based min/max reduction. The types of 56 /// select and compare operations are provided as template arguments. The 57 /// comparison predicates suitable for min and max are provided as function 58 /// arguments. If a reduction is matched, `ifMin` will be set if the reduction 59 /// compute the minimum and unset if it computes the maximum, otherwise it 60 /// remains unmodified. The expected shape of the block is as follows. 61 /// 62 /// ^bb(%arg0, %arg1): 63 /// %0 = CompareOpTy(<one-of-predicates>, %arg0, %arg1) 64 /// %1 = SelectOpTy(%0, %arg0, %arg1) // %arg0, %arg1 may be swapped here. 65 /// scf.reduce.return %1 66 template < 67 typename CompareOpTy, typename SelectOpTy, 68 typename Predicate = decltype(std::declval<CompareOpTy>().predicate())> 69 static bool 70 matchSelectReduction(Block &block, ArrayRef<Predicate> lessThanPredicates, 71 ArrayRef<Predicate> greaterThanPredicates, bool &isMin) { 72 static_assert(llvm::is_one_of<SelectOpTy, SelectOp, LLVM::SelectOp>::value, 73 "only std and llvm select ops are supported"); 74 75 // Expect exactly three operations in the block. 76 if (block.empty() || llvm::hasSingleElement(block) || 77 std::next(block.begin(), 2) == block.end() || 78 std::next(block.begin(), 3) != block.end()) 79 return false; 80 81 // Check op kinds. 82 auto compare = dyn_cast<CompareOpTy>(block.front()); 83 auto select = dyn_cast<SelectOpTy>(block.front().getNextNode()); 84 auto terminator = dyn_cast<scf::ReduceReturnOp>(block.back()); 85 if (!compare || !select || !terminator) 86 return false; 87 88 // Block arguments must be compared. 89 if (compare->getOperands() != block.getArguments()) 90 return false; 91 92 // Detect whether the comparison is less-than or greater-than, otherwise bail. 93 bool isLess; 94 if (llvm::find(lessThanPredicates, compare.predicate()) != 95 lessThanPredicates.end()) { 96 isLess = true; 97 } else if (llvm::find(greaterThanPredicates, compare.predicate()) != 98 greaterThanPredicates.end()) { 99 isLess = false; 100 } else { 101 return false; 102 } 103 104 if (select.condition() != compare.getResult()) 105 return false; 106 107 // Detect if the operands are swapped between cmpf and select. Match the 108 // comparison type with the requested type or with the opposite of the 109 // requested type if the operands are swapped. Use generic accessors because 110 // std and LLVM versions of select have different operand names but identical 111 // positions. 112 constexpr unsigned kTrueValue = 1; 113 constexpr unsigned kFalseValue = 2; 114 bool sameOperands = select.getOperand(kTrueValue) == compare.lhs() && 115 select.getOperand(kFalseValue) == compare.rhs(); 116 bool swappedOperands = select.getOperand(kTrueValue) == compare.rhs() && 117 select.getOperand(kFalseValue) == compare.lhs(); 118 if (!sameOperands && !swappedOperands) 119 return false; 120 121 if (select.getResult() != terminator.result()) 122 return false; 123 124 // The reduction is a min if it uses less-than predicates with same operands 125 // or greather-than predicates with swapped operands. Similarly for max. 126 isMin = (isLess && sameOperands) || (!isLess && swappedOperands); 127 return isMin || (isLess & swappedOperands) || (!isLess && sameOperands); 128 } 129 130 /// Returns the float semantics for the given float type. 131 static const llvm::fltSemantics &fltSemanticsForType(FloatType type) { 132 if (type.isF16()) 133 return llvm::APFloat::IEEEhalf(); 134 if (type.isF32()) 135 return llvm::APFloat::IEEEsingle(); 136 if (type.isF64()) 137 return llvm::APFloat::IEEEdouble(); 138 if (type.isF128()) 139 return llvm::APFloat::IEEEquad(); 140 if (type.isBF16()) 141 return llvm::APFloat::BFloat(); 142 if (type.isF80()) 143 return llvm::APFloat::x87DoubleExtended(); 144 llvm_unreachable("unknown float type"); 145 } 146 147 /// Returns an attribute with the minimum (if `min` is set) or the maximum value 148 /// (otherwise) for the given float type. 149 static Attribute minMaxValueForFloat(Type type, bool min) { 150 auto fltType = type.cast<FloatType>(); 151 return FloatAttr::get( 152 type, llvm::APFloat::getLargest(fltSemanticsForType(fltType), min)); 153 } 154 155 /// Returns an attribute with the signed integer minimum (if `min` is set) or 156 /// the maximum value (otherwise) for the given integer type, regardless of its 157 /// signedness semantics (only the width is considered). 158 static Attribute minMaxValueForSignedInt(Type type, bool min) { 159 auto intType = type.cast<IntegerType>(); 160 unsigned bitwidth = intType.getWidth(); 161 return IntegerAttr::get(type, min ? llvm::APInt::getSignedMinValue(bitwidth) 162 : llvm::APInt::getSignedMaxValue(bitwidth)); 163 } 164 165 /// Returns an attribute with the unsigned integer minimum (if `min` is set) or 166 /// the maximum value (otherwise) for the given integer type, regardless of its 167 /// signedness semantics (only the width is considered). 168 static Attribute minMaxValueForUnsignedInt(Type type, bool min) { 169 auto intType = type.cast<IntegerType>(); 170 unsigned bitwidth = intType.getWidth(); 171 return IntegerAttr::get(type, min ? llvm::APInt::getNullValue(bitwidth) 172 : llvm::APInt::getAllOnesValue(bitwidth)); 173 } 174 175 /// Creates an OpenMP reduction declaration and inserts it into the provided 176 /// symbol table. The declaration has a constant initializer with the neutral 177 /// value `initValue`, and the reduction combiner carried over from `reduce`. 178 static omp::ReductionDeclareOp createDecl(PatternRewriter &builder, 179 SymbolTable &symbolTable, 180 scf::ReduceOp reduce, 181 Attribute initValue) { 182 OpBuilder::InsertionGuard guard(builder); 183 auto decl = builder.create<omp::ReductionDeclareOp>( 184 reduce.getLoc(), "__scf_reduction", reduce.operand().getType()); 185 symbolTable.insert(decl); 186 187 Type type = reduce.operand().getType(); 188 builder.createBlock(&decl.initializerRegion(), decl.initializerRegion().end(), 189 {type}); 190 builder.setInsertionPointToEnd(&decl.initializerRegion().back()); 191 Value init = 192 builder.create<LLVM::ConstantOp>(reduce.getLoc(), type, initValue); 193 builder.create<omp::YieldOp>(reduce.getLoc(), init); 194 195 Operation *terminator = &reduce.getRegion().front().back(); 196 assert(isa<scf::ReduceReturnOp>(terminator) && 197 "expected reduce op to be terminated by redure return"); 198 builder.setInsertionPoint(terminator); 199 builder.replaceOpWithNewOp<omp::YieldOp>(terminator, 200 terminator->getOperands()); 201 builder.inlineRegionBefore(reduce.getRegion(), decl.reductionRegion(), 202 decl.reductionRegion().end()); 203 return decl; 204 } 205 206 /// Adds an atomic reduction combiner to the given OpenMP reduction declaration 207 /// using llvm.atomicrmw of the given kind. 208 static omp::ReductionDeclareOp addAtomicRMW(OpBuilder &builder, 209 LLVM::AtomicBinOp atomicKind, 210 omp::ReductionDeclareOp decl, 211 scf::ReduceOp reduce) { 212 OpBuilder::InsertionGuard guard(builder); 213 Type type = reduce.operand().getType(); 214 Type ptrType = LLVM::LLVMPointerType::get(type); 215 builder.createBlock(&decl.atomicReductionRegion(), 216 decl.atomicReductionRegion().end(), {ptrType, ptrType}); 217 Block *atomicBlock = &decl.atomicReductionRegion().back(); 218 builder.setInsertionPointToEnd(atomicBlock); 219 Value loaded = builder.create<LLVM::LoadOp>(reduce.getLoc(), 220 atomicBlock->getArgument(1)); 221 builder.create<LLVM::AtomicRMWOp>(reduce.getLoc(), type, atomicKind, 222 atomicBlock->getArgument(0), loaded, 223 LLVM::AtomicOrdering::monotonic); 224 builder.create<omp::YieldOp>(reduce.getLoc(), ArrayRef<Value>()); 225 return decl; 226 } 227 228 /// Creates an OpenMP reduction declaration that corresponds to the given SCF 229 /// reduction and returns it. Recognizes common reductions in order to identify 230 /// the neutral value, necessary for the OpenMP declaration. If the reduction 231 /// cannot be recognized, returns null. 232 static omp::ReductionDeclareOp declareReduction(PatternRewriter &builder, 233 scf::ReduceOp reduce) { 234 Operation *container = SymbolTable::getNearestSymbolTable(reduce); 235 SymbolTable symbolTable(container); 236 237 // Insert reduction declarations in the symbol-table ancestor before the 238 // ancestor of the current insertion point. 239 Operation *insertionPoint = reduce; 240 while (insertionPoint->getParentOp() != container) 241 insertionPoint = insertionPoint->getParentOp(); 242 OpBuilder::InsertionGuard guard(builder); 243 builder.setInsertionPoint(insertionPoint); 244 245 assert(llvm::hasSingleElement(reduce.getRegion()) && 246 "expected reduction region to have a single element"); 247 248 // Match simple binary reductions that can be expressed with atomicrmw. 249 Type type = reduce.operand().getType(); 250 Block &reduction = reduce.getRegion().front(); 251 if (matchSimpleReduction<AddFOp, LLVM::FAddOp>(reduction)) { 252 omp::ReductionDeclareOp decl = createDecl(builder, symbolTable, reduce, 253 builder.getFloatAttr(type, 0.0)); 254 return addAtomicRMW(builder, LLVM::AtomicBinOp::fadd, decl, reduce); 255 } 256 if (matchSimpleReduction<AddIOp, LLVM::AddOp>(reduction)) { 257 omp::ReductionDeclareOp decl = createDecl(builder, symbolTable, reduce, 258 builder.getIntegerAttr(type, 0)); 259 return addAtomicRMW(builder, LLVM::AtomicBinOp::add, decl, reduce); 260 } 261 if (matchSimpleReduction<OrOp, LLVM::OrOp>(reduction)) { 262 omp::ReductionDeclareOp decl = createDecl(builder, symbolTable, reduce, 263 builder.getIntegerAttr(type, 0)); 264 return addAtomicRMW(builder, LLVM::AtomicBinOp::_or, decl, reduce); 265 } 266 if (matchSimpleReduction<XOrOp, LLVM::XOrOp>(reduction)) { 267 omp::ReductionDeclareOp decl = createDecl(builder, symbolTable, reduce, 268 builder.getIntegerAttr(type, 0)); 269 return addAtomicRMW(builder, LLVM::AtomicBinOp::_xor, decl, reduce); 270 } 271 if (matchSimpleReduction<AndOp, LLVM::AndOp>(reduction)) { 272 omp::ReductionDeclareOp decl = createDecl( 273 builder, symbolTable, reduce, 274 builder.getIntegerAttr( 275 type, llvm::APInt::getAllOnesValue(type.getIntOrFloatBitWidth()))); 276 return addAtomicRMW(builder, LLVM::AtomicBinOp::_and, decl, reduce); 277 } 278 279 // Match simple binary reductions that cannot be expressed with atomicrmw. 280 // TODO: add atomic region using cmpxchg (which needs atomic load to be 281 // available as an op). 282 if (matchSimpleReduction<MulFOp, LLVM::FMulOp>(reduction)) { 283 return createDecl(builder, symbolTable, reduce, 284 builder.getFloatAttr(type, 1.0)); 285 } 286 287 // Match select-based min/max reductions. 288 bool isMin; 289 if (matchSelectReduction<CmpFOp, SelectOp>( 290 reduction, {CmpFPredicate::OLT, CmpFPredicate::OLE}, 291 {CmpFPredicate::OGT, CmpFPredicate::OGE}, isMin) || 292 matchSelectReduction<LLVM::FCmpOp, LLVM::SelectOp>( 293 reduction, {LLVM::FCmpPredicate::olt, LLVM::FCmpPredicate::ole}, 294 {LLVM::FCmpPredicate::ogt, LLVM::FCmpPredicate::oge}, isMin)) { 295 return createDecl(builder, symbolTable, reduce, 296 minMaxValueForFloat(type, !isMin)); 297 } 298 if (matchSelectReduction<CmpIOp, SelectOp>( 299 reduction, {CmpIPredicate::slt, CmpIPredicate::sle}, 300 {CmpIPredicate::sgt, CmpIPredicate::sge}, isMin) || 301 matchSelectReduction<LLVM::ICmpOp, LLVM::SelectOp>( 302 reduction, {LLVM::ICmpPredicate::slt, LLVM::ICmpPredicate::sle}, 303 {LLVM::ICmpPredicate::sgt, LLVM::ICmpPredicate::sge}, isMin)) { 304 omp::ReductionDeclareOp decl = createDecl( 305 builder, symbolTable, reduce, minMaxValueForSignedInt(type, !isMin)); 306 return addAtomicRMW(builder, 307 isMin ? LLVM::AtomicBinOp::min : LLVM::AtomicBinOp::max, 308 decl, reduce); 309 } 310 if (matchSelectReduction<CmpIOp, SelectOp>( 311 reduction, {CmpIPredicate::ult, CmpIPredicate::ule}, 312 {CmpIPredicate::ugt, CmpIPredicate::uge}, isMin) || 313 matchSelectReduction<LLVM::ICmpOp, LLVM::SelectOp>( 314 reduction, {LLVM::ICmpPredicate::ugt, LLVM::ICmpPredicate::ule}, 315 {LLVM::ICmpPredicate::ugt, LLVM::ICmpPredicate::uge}, isMin)) { 316 omp::ReductionDeclareOp decl = createDecl( 317 builder, symbolTable, reduce, minMaxValueForUnsignedInt(type, !isMin)); 318 return addAtomicRMW( 319 builder, isMin ? LLVM::AtomicBinOp::umin : LLVM::AtomicBinOp::umax, 320 decl, reduce); 321 } 322 323 return nullptr; 324 } 325 326 namespace { 327 328 struct ParallelOpLowering : public OpRewritePattern<scf::ParallelOp> { 329 using OpRewritePattern<scf::ParallelOp>::OpRewritePattern; 330 331 LogicalResult matchAndRewrite(scf::ParallelOp parallelOp, 332 PatternRewriter &rewriter) const override { 333 // Replace SCF yield with OpenMP yield. 334 { 335 OpBuilder::InsertionGuard guard(rewriter); 336 rewriter.setInsertionPointToEnd(parallelOp.getBody()); 337 assert(llvm::hasSingleElement(parallelOp.region()) && 338 "expected scf.parallel to have one block"); 339 rewriter.replaceOpWithNewOp<omp::YieldOp>( 340 parallelOp.getBody()->getTerminator(), ValueRange()); 341 } 342 343 // Declare reductions. 344 // TODO: consider checking it here is already a compatible reduction 345 // declaration and use it instead of redeclaring. 346 SmallVector<Attribute> reductionDeclSymbols; 347 for (auto reduce : parallelOp.getOps<scf::ReduceOp>()) { 348 omp::ReductionDeclareOp decl = declareReduction(rewriter, reduce); 349 if (!decl) 350 return failure(); 351 reductionDeclSymbols.push_back( 352 SymbolRefAttr::get(rewriter.getContext(), decl.sym_name())); 353 } 354 355 // Allocate reduction variables. Make sure the we don't overflow the stack 356 // with local `alloca`s by saving and restoring the stack pointer. 357 Location loc = parallelOp.getLoc(); 358 Value one = rewriter.create<LLVM::ConstantOp>( 359 loc, rewriter.getIntegerType(64), rewriter.getI64IntegerAttr(1)); 360 SmallVector<Value> reductionVariables; 361 reductionVariables.reserve(parallelOp.getNumReductions()); 362 Value token = rewriter.create<LLVM::StackSaveOp>( 363 loc, LLVM::LLVMPointerType::get(rewriter.getIntegerType(8))); 364 for (Value init : parallelOp.initVals()) { 365 assert((LLVM::isCompatibleType(init.getType()) || 366 init.getType().isa<LLVM::PointerElementTypeInterface>()) && 367 "cannot create a reduction variable if the type is not an LLVM " 368 "pointer element"); 369 Value storage = rewriter.create<LLVM::AllocaOp>( 370 loc, LLVM::LLVMPointerType::get(init.getType()), one, 0); 371 rewriter.create<LLVM::StoreOp>(loc, init, storage); 372 reductionVariables.push_back(storage); 373 } 374 375 // Replace the reduction operations contained in this loop. Must be done 376 // here rather than in a separate pattern to have access to the list of 377 // reduction variables. 378 for (auto pair : 379 llvm::zip(parallelOp.getOps<scf::ReduceOp>(), reductionVariables)) { 380 OpBuilder::InsertionGuard guard(rewriter); 381 scf::ReduceOp reduceOp = std::get<0>(pair); 382 rewriter.setInsertionPoint(reduceOp); 383 rewriter.replaceOpWithNewOp<omp::ReductionOp>( 384 reduceOp, reduceOp.operand(), std::get<1>(pair)); 385 } 386 387 // Create the parallel wrapper. 388 auto ompParallel = rewriter.create<omp::ParallelOp>(loc); 389 { 390 OpBuilder::InsertionGuard guard(rewriter); 391 rewriter.createBlock(&ompParallel.region()); 392 393 // Replace SCF yield with OpenMP yield. 394 { 395 OpBuilder::InsertionGuard innerGuard(rewriter); 396 rewriter.setInsertionPointToEnd(parallelOp.getBody()); 397 assert(llvm::hasSingleElement(parallelOp.region()) && 398 "expected scf.parallel to have one block"); 399 rewriter.replaceOpWithNewOp<omp::YieldOp>( 400 parallelOp.getBody()->getTerminator(), ValueRange()); 401 } 402 403 // Replace the loop. 404 auto loop = rewriter.create<omp::WsLoopOp>( 405 parallelOp.getLoc(), parallelOp.lowerBound(), parallelOp.upperBound(), 406 parallelOp.step()); 407 rewriter.create<omp::TerminatorOp>(loc); 408 409 rewriter.inlineRegionBefore(parallelOp.region(), loop.region(), 410 loop.region().begin()); 411 if (!reductionVariables.empty()) { 412 loop.reductionsAttr( 413 ArrayAttr::get(rewriter.getContext(), reductionDeclSymbols)); 414 loop.reduction_varsMutable().append(reductionVariables); 415 } 416 } 417 418 // Load loop results. 419 SmallVector<Value> results; 420 results.reserve(reductionVariables.size()); 421 for (Value variable : reductionVariables) { 422 Value res = rewriter.create<LLVM::LoadOp>(loc, variable); 423 results.push_back(res); 424 } 425 rewriter.replaceOp(parallelOp, results); 426 427 rewriter.create<LLVM::StackRestoreOp>(loc, token); 428 return success(); 429 } 430 }; 431 432 /// Applies the conversion patterns in the given function. 433 static LogicalResult applyPatterns(ModuleOp module) { 434 ConversionTarget target(*module.getContext()); 435 target.addIllegalOp<scf::ReduceOp, scf::ReduceReturnOp, scf::ParallelOp>(); 436 target.addLegalDialect<omp::OpenMPDialect, LLVM::LLVMDialect>(); 437 438 RewritePatternSet patterns(module.getContext()); 439 patterns.add<ParallelOpLowering>(module.getContext()); 440 FrozenRewritePatternSet frozen(std::move(patterns)); 441 return applyPartialConversion(module, target, frozen); 442 } 443 444 /// A pass converting SCF operations to OpenMP operations. 445 struct SCFToOpenMPPass : public ConvertSCFToOpenMPBase<SCFToOpenMPPass> { 446 /// Pass entry point. 447 void runOnOperation() override { 448 if (failed(applyPatterns(getOperation()))) 449 signalPassFailure(); 450 } 451 }; 452 453 } // end namespace 454 455 std::unique_ptr<OperationPass<ModuleOp>> mlir::createConvertSCFToOpenMPPass() { 456 return std::make_unique<SCFToOpenMPPass>(); 457 } 458