1 //===- SCFToSPIRV.cpp - SCF to SPIR-V Patterns ----------------------------===//
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 patterns to convert SCF dialect to SPIR-V dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Conversion/SCFToSPIRV/SCFToSPIRV.h"
14 #include "mlir/Dialect/SCF/SCF.h"
15 #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
16 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
17 #include "mlir/Dialect/SPIRV/Transforms/SPIRVConversion.h"
18 #include "mlir/IR/BuiltinOps.h"
19 #include "mlir/Transforms/DialectConversion.h"
20 
21 using namespace mlir;
22 
23 //===----------------------------------------------------------------------===//
24 // Context
25 //===----------------------------------------------------------------------===//
26 
27 namespace mlir {
28 struct ScfToSPIRVContextImpl {
29   // Map between the spirv region control flow operation (spv.mlir.loop or
30   // spv.mlir.selection) to the VariableOp created to store the region results.
31   // The order of the VariableOp matches the order of the results.
32   DenseMap<Operation *, SmallVector<spirv::VariableOp, 8>> outputVars;
33 };
34 } // namespace mlir
35 
36 /// We use ScfToSPIRVContext to store information about the lowering of the scf
37 /// region that need to be used later on. When we lower scf.for/scf.if we create
38 /// VariableOp to store the results. We need to keep track of the VariableOp
39 /// created as we need to insert stores into them when lowering Yield. Those
40 /// StoreOp cannot be created earlier as they may use a different type than
41 /// yield operands.
42 ScfToSPIRVContext::ScfToSPIRVContext() {
43   impl = std::make_unique<ScfToSPIRVContextImpl>();
44 }
45 
46 ScfToSPIRVContext::~ScfToSPIRVContext() = default;
47 
48 //===----------------------------------------------------------------------===//
49 // Pattern Declarations
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53 /// Common class for all vector to GPU patterns.
54 template <typename OpTy>
55 class SCFToSPIRVPattern : public OpConversionPattern<OpTy> {
56 public:
57   SCFToSPIRVPattern<OpTy>(MLIRContext *context, SPIRVTypeConverter &converter,
58                           ScfToSPIRVContextImpl *scfToSPIRVContext)
59       : OpConversionPattern<OpTy>::OpConversionPattern(context),
60         scfToSPIRVContext(scfToSPIRVContext), typeConverter(converter) {}
61 
62 protected:
63   ScfToSPIRVContextImpl *scfToSPIRVContext;
64   // FIXME: We explicitly keep a reference of the type converter here instead of
65   // passing it to OpConversionPattern during construction. This effectively
66   // bypasses the conversion framework's automation on type conversion. This is
67   // needed right now because the conversion framework will unconditionally
68   // legalize all types used by SCF ops upon discovering them, for example, the
69   // types of loop carried values. We use SPIR-V variables for those loop
70   // carried values. Depending on the available capabilities, the SPIR-V
71   // variable can be different, for example, cooperative matrix or normal
72   // variable. We'd like to detach the conversion of the loop carried values
73   // from the SCF ops (which is mainly a region). So we need to "mark" types
74   // used by SCF ops as legal, if to use the conversion framework for type
75   // conversion. There isn't a straightforward way to do that yet, as when
76   // converting types, ops aren't taken into consideration. Therefore, we just
77   // bypass the framework's type conversion for now.
78   SPIRVTypeConverter &typeConverter;
79 };
80 
81 /// Pattern to convert a scf::ForOp within kernel functions into spirv::LoopOp.
82 class ForOpConversion final : public SCFToSPIRVPattern<scf::ForOp> {
83 public:
84   using SCFToSPIRVPattern<scf::ForOp>::SCFToSPIRVPattern;
85 
86   LogicalResult
87   matchAndRewrite(scf::ForOp forOp, OpAdaptor adaptor,
88                   ConversionPatternRewriter &rewriter) const override;
89 };
90 
91 /// Pattern to convert a scf::IfOp within kernel functions into
92 /// spirv::SelectionOp.
93 class IfOpConversion final : public SCFToSPIRVPattern<scf::IfOp> {
94 public:
95   using SCFToSPIRVPattern<scf::IfOp>::SCFToSPIRVPattern;
96 
97   LogicalResult
98   matchAndRewrite(scf::IfOp ifOp, OpAdaptor adaptor,
99                   ConversionPatternRewriter &rewriter) const override;
100 };
101 
102 class TerminatorOpConversion final : public SCFToSPIRVPattern<scf::YieldOp> {
103 public:
104   using SCFToSPIRVPattern<scf::YieldOp>::SCFToSPIRVPattern;
105 
106   LogicalResult
107   matchAndRewrite(scf::YieldOp terminatorOp, OpAdaptor adaptor,
108                   ConversionPatternRewriter &rewriter) const override;
109 };
110 } // namespace
111 
112 /// Helper function to replaces SCF op outputs with SPIR-V variable loads.
113 /// We create VariableOp to handle the results value of the control flow region.
114 /// spv.mlir.loop/spv.mlir.selection currently don't yield value. Right after
115 /// the loop we load the value from the allocation and use it as the SCF op
116 /// result.
117 template <typename ScfOp, typename OpTy>
118 static void replaceSCFOutputValue(ScfOp scfOp, OpTy newOp,
119                                   ConversionPatternRewriter &rewriter,
120                                   ScfToSPIRVContextImpl *scfToSPIRVContext,
121                                   ArrayRef<Type> returnTypes) {
122 
123   Location loc = scfOp.getLoc();
124   auto &allocas = scfToSPIRVContext->outputVars[newOp];
125   // Clearing the allocas is necessary in case a dialect conversion path failed
126   // previously, and this is the second attempt of this conversion.
127   allocas.clear();
128   SmallVector<Value, 8> resultValue;
129   for (Type convertedType : returnTypes) {
130     auto pointerType =
131         spirv::PointerType::get(convertedType, spirv::StorageClass::Function);
132     rewriter.setInsertionPoint(newOp);
133     auto alloc = rewriter.create<spirv::VariableOp>(
134         loc, pointerType, spirv::StorageClass::Function,
135         /*initializer=*/nullptr);
136     allocas.push_back(alloc);
137     rewriter.setInsertionPointAfter(newOp);
138     Value loadResult = rewriter.create<spirv::LoadOp>(loc, alloc);
139     resultValue.push_back(loadResult);
140   }
141   rewriter.replaceOp(scfOp, resultValue);
142 }
143 
144 //===----------------------------------------------------------------------===//
145 // scf::ForOp
146 //===----------------------------------------------------------------------===//
147 
148 LogicalResult
149 ForOpConversion::matchAndRewrite(scf::ForOp forOp, OpAdaptor adaptor,
150                                  ConversionPatternRewriter &rewriter) const {
151   // scf::ForOp can be lowered to the structured control flow represented by
152   // spirv::LoopOp by making the continue block of the spirv::LoopOp the loop
153   // latch and the merge block the exit block. The resulting spirv::LoopOp has a
154   // single back edge from the continue to header block, and a single exit from
155   // header to merge.
156   auto loc = forOp.getLoc();
157   auto loopOp = rewriter.create<spirv::LoopOp>(loc, spirv::LoopControl::None);
158   loopOp.addEntryAndMergeBlock();
159 
160   OpBuilder::InsertionGuard guard(rewriter);
161   // Create the block for the header.
162   auto *header = new Block();
163   // Insert the header.
164   loopOp.body().getBlocks().insert(std::next(loopOp.body().begin(), 1), header);
165 
166   // Create the new induction variable to use.
167   BlockArgument newIndVar = header->addArgument(adaptor.lowerBound().getType());
168   for (Value arg : adaptor.initArgs())
169     header->addArgument(arg.getType());
170   Block *body = forOp.getBody();
171 
172   // Apply signature conversion to the body of the forOp. It has a single block,
173   // with argument which is the induction variable. That has to be replaced with
174   // the new induction variable.
175   TypeConverter::SignatureConversion signatureConverter(
176       body->getNumArguments());
177   signatureConverter.remapInput(0, newIndVar);
178   for (unsigned i = 1, e = body->getNumArguments(); i < e; i++)
179     signatureConverter.remapInput(i, header->getArgument(i));
180   body = rewriter.applySignatureConversion(&forOp.getLoopBody(),
181                                            signatureConverter);
182 
183   // Move the blocks from the forOp into the loopOp. This is the body of the
184   // loopOp.
185   rewriter.inlineRegionBefore(forOp->getRegion(0), loopOp.body(),
186                               std::next(loopOp.body().begin(), 2));
187 
188   SmallVector<Value, 8> args(1, adaptor.lowerBound());
189   args.append(adaptor.initArgs().begin(), adaptor.initArgs().end());
190   // Branch into it from the entry.
191   rewriter.setInsertionPointToEnd(&(loopOp.body().front()));
192   rewriter.create<spirv::BranchOp>(loc, header, args);
193 
194   // Generate the rest of the loop header.
195   rewriter.setInsertionPointToEnd(header);
196   auto *mergeBlock = loopOp.getMergeBlock();
197   auto cmpOp = rewriter.create<spirv::SLessThanOp>(
198       loc, rewriter.getI1Type(), newIndVar, adaptor.upperBound());
199 
200   rewriter.create<spirv::BranchConditionalOp>(
201       loc, cmpOp, body, ArrayRef<Value>(), mergeBlock, ArrayRef<Value>());
202 
203   // Generate instructions to increment the step of the induction variable and
204   // branch to the header.
205   Block *continueBlock = loopOp.getContinueBlock();
206   rewriter.setInsertionPointToEnd(continueBlock);
207 
208   // Add the step to the induction variable and branch to the header.
209   Value updatedIndVar = rewriter.create<spirv::IAddOp>(
210       loc, newIndVar.getType(), newIndVar, adaptor.step());
211   rewriter.create<spirv::BranchOp>(loc, header, updatedIndVar);
212 
213   // Infer the return types from the init operands. Vector type may get
214   // converted to CooperativeMatrix or to Vector type, to avoid having complex
215   // extra logic to figure out the right type we just infer it from the Init
216   // operands.
217   SmallVector<Type, 8> initTypes;
218   for (auto arg : adaptor.initArgs())
219     initTypes.push_back(arg.getType());
220   replaceSCFOutputValue(forOp, loopOp, rewriter, scfToSPIRVContext, initTypes);
221   return success();
222 }
223 
224 //===----------------------------------------------------------------------===//
225 // scf::IfOp
226 //===----------------------------------------------------------------------===//
227 
228 LogicalResult
229 IfOpConversion::matchAndRewrite(scf::IfOp ifOp, OpAdaptor adaptor,
230                                 ConversionPatternRewriter &rewriter) const {
231   // When lowering `scf::IfOp` we explicitly create a selection header block
232   // before the control flow diverges and a merge block where control flow
233   // subsequently converges.
234   auto loc = ifOp.getLoc();
235 
236   // Create `spv.selection` operation, selection header block and merge block.
237   auto selectionOp =
238       rewriter.create<spirv::SelectionOp>(loc, spirv::SelectionControl::None);
239   auto *mergeBlock =
240       rewriter.createBlock(&selectionOp.body(), selectionOp.body().end());
241   rewriter.create<spirv::MergeOp>(loc);
242 
243   OpBuilder::InsertionGuard guard(rewriter);
244   auto *selectionHeaderBlock =
245       rewriter.createBlock(&selectionOp.body().front());
246 
247   // Inline `then` region before the merge block and branch to it.
248   auto &thenRegion = ifOp.thenRegion();
249   auto *thenBlock = &thenRegion.front();
250   rewriter.setInsertionPointToEnd(&thenRegion.back());
251   rewriter.create<spirv::BranchOp>(loc, mergeBlock);
252   rewriter.inlineRegionBefore(thenRegion, mergeBlock);
253 
254   auto *elseBlock = mergeBlock;
255   // If `else` region is not empty, inline that region before the merge block
256   // and branch to it.
257   if (!ifOp.elseRegion().empty()) {
258     auto &elseRegion = ifOp.elseRegion();
259     elseBlock = &elseRegion.front();
260     rewriter.setInsertionPointToEnd(&elseRegion.back());
261     rewriter.create<spirv::BranchOp>(loc, mergeBlock);
262     rewriter.inlineRegionBefore(elseRegion, mergeBlock);
263   }
264 
265   // Create a `spv.BranchConditional` operation for selection header block.
266   rewriter.setInsertionPointToEnd(selectionHeaderBlock);
267   rewriter.create<spirv::BranchConditionalOp>(loc, adaptor.condition(),
268                                               thenBlock, ArrayRef<Value>(),
269                                               elseBlock, ArrayRef<Value>());
270 
271   SmallVector<Type, 8> returnTypes;
272   for (auto result : ifOp.results()) {
273     auto convertedType = typeConverter.convertType(result.getType());
274     returnTypes.push_back(convertedType);
275   }
276   replaceSCFOutputValue(ifOp, selectionOp, rewriter, scfToSPIRVContext,
277                         returnTypes);
278   return success();
279 }
280 
281 //===----------------------------------------------------------------------===//
282 // scf::YieldOp
283 //===----------------------------------------------------------------------===//
284 
285 /// Yield is lowered to stores to the VariableOp created during lowering of the
286 /// parent region. For loops we also need to update the branch looping back to
287 /// the header with the loop carried values.
288 LogicalResult TerminatorOpConversion::matchAndRewrite(
289     scf::YieldOp terminatorOp, OpAdaptor adaptor,
290     ConversionPatternRewriter &rewriter) const {
291   ValueRange operands = adaptor.getOperands();
292 
293   // If the region is return values, store each value into the associated
294   // VariableOp created during lowering of the parent region.
295   if (!operands.empty()) {
296     auto loc = terminatorOp.getLoc();
297     auto &allocas = scfToSPIRVContext->outputVars[terminatorOp->getParentOp()];
298     assert(allocas.size() == operands.size());
299     for (unsigned i = 0, e = operands.size(); i < e; i++)
300       rewriter.create<spirv::StoreOp>(loc, allocas[i], operands[i]);
301     if (isa<spirv::LoopOp>(terminatorOp->getParentOp())) {
302       // For loops we also need to update the branch jumping back to the header.
303       auto br =
304           cast<spirv::BranchOp>(rewriter.getInsertionBlock()->getTerminator());
305       SmallVector<Value, 8> args(br.getBlockArguments());
306       args.append(operands.begin(), operands.end());
307       rewriter.setInsertionPoint(br);
308       rewriter.create<spirv::BranchOp>(terminatorOp.getLoc(), br.getTarget(),
309                                        args);
310       rewriter.eraseOp(br);
311     }
312   }
313   rewriter.eraseOp(terminatorOp);
314   return success();
315 }
316 
317 //===----------------------------------------------------------------------===//
318 // Hooks
319 //===----------------------------------------------------------------------===//
320 
321 void mlir::populateSCFToSPIRVPatterns(SPIRVTypeConverter &typeConverter,
322                                       ScfToSPIRVContext &scfToSPIRVContext,
323                                       RewritePatternSet &patterns) {
324   patterns.add<ForOpConversion, IfOpConversion, TerminatorOpConversion>(
325       patterns.getContext(), typeConverter, scfToSPIRVContext.getImpl());
326 }
327