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