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(converter, 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 111 class WhileOpConversion final : public SCFToSPIRVPattern<scf::WhileOp> { 112 public: 113 using SCFToSPIRVPattern<scf::WhileOp>::SCFToSPIRVPattern; 114 115 LogicalResult 116 matchAndRewrite(scf::WhileOp forOp, OpAdaptor adaptor, 117 ConversionPatternRewriter &rewriter) const override; 118 }; 119 } // namespace 120 121 /// Helper function to replaces SCF op outputs with SPIR-V variable loads. 122 /// We create VariableOp to handle the results value of the control flow region. 123 /// spv.mlir.loop/spv.mlir.selection currently don't yield value. Right after 124 /// the loop we load the value from the allocation and use it as the SCF op 125 /// result. 126 template <typename ScfOp, typename OpTy> 127 static void replaceSCFOutputValue(ScfOp scfOp, OpTy newOp, 128 ConversionPatternRewriter &rewriter, 129 ScfToSPIRVContextImpl *scfToSPIRVContext, 130 ArrayRef<Type> returnTypes) { 131 132 Location loc = scfOp.getLoc(); 133 auto &allocas = scfToSPIRVContext->outputVars[newOp]; 134 // Clearing the allocas is necessary in case a dialect conversion path failed 135 // previously, and this is the second attempt of this conversion. 136 allocas.clear(); 137 SmallVector<Value, 8> resultValue; 138 for (Type convertedType : returnTypes) { 139 auto pointerType = 140 spirv::PointerType::get(convertedType, spirv::StorageClass::Function); 141 rewriter.setInsertionPoint(newOp); 142 auto alloc = rewriter.create<spirv::VariableOp>( 143 loc, pointerType, spirv::StorageClass::Function, 144 /*initializer=*/nullptr); 145 allocas.push_back(alloc); 146 rewriter.setInsertionPointAfter(newOp); 147 Value loadResult = rewriter.create<spirv::LoadOp>(loc, alloc); 148 resultValue.push_back(loadResult); 149 } 150 rewriter.replaceOp(scfOp, resultValue); 151 } 152 153 static Region::iterator getBlockIt(Region ®ion, unsigned index) { 154 return std::next(region.begin(), index); 155 } 156 157 //===----------------------------------------------------------------------===// 158 // scf::ForOp 159 //===----------------------------------------------------------------------===// 160 161 LogicalResult 162 ForOpConversion::matchAndRewrite(scf::ForOp forOp, OpAdaptor adaptor, 163 ConversionPatternRewriter &rewriter) const { 164 // scf::ForOp can be lowered to the structured control flow represented by 165 // spirv::LoopOp by making the continue block of the spirv::LoopOp the loop 166 // latch and the merge block the exit block. The resulting spirv::LoopOp has a 167 // single back edge from the continue to header block, and a single exit from 168 // header to merge. 169 auto loc = forOp.getLoc(); 170 auto loopOp = rewriter.create<spirv::LoopOp>(loc, spirv::LoopControl::None); 171 loopOp.addEntryAndMergeBlock(); 172 173 OpBuilder::InsertionGuard guard(rewriter); 174 // Create the block for the header. 175 auto *header = new Block(); 176 // Insert the header. 177 loopOp.body().getBlocks().insert(getBlockIt(loopOp.body(), 1), header); 178 179 // Create the new induction variable to use. 180 BlockArgument newIndVar = header->addArgument(adaptor.lowerBound().getType()); 181 for (Value arg : adaptor.initArgs()) 182 header->addArgument(arg.getType()); 183 Block *body = forOp.getBody(); 184 185 // Apply signature conversion to the body of the forOp. It has a single block, 186 // with argument which is the induction variable. That has to be replaced with 187 // the new induction variable. 188 TypeConverter::SignatureConversion signatureConverter( 189 body->getNumArguments()); 190 signatureConverter.remapInput(0, newIndVar); 191 for (unsigned i = 1, e = body->getNumArguments(); i < e; i++) 192 signatureConverter.remapInput(i, header->getArgument(i)); 193 body = rewriter.applySignatureConversion(&forOp.getLoopBody(), 194 signatureConverter); 195 196 // Move the blocks from the forOp into the loopOp. This is the body of the 197 // loopOp. 198 rewriter.inlineRegionBefore(forOp->getRegion(0), loopOp.body(), 199 getBlockIt(loopOp.body(), 2)); 200 201 SmallVector<Value, 8> args(1, adaptor.lowerBound()); 202 args.append(adaptor.initArgs().begin(), adaptor.initArgs().end()); 203 // Branch into it from the entry. 204 rewriter.setInsertionPointToEnd(&(loopOp.body().front())); 205 rewriter.create<spirv::BranchOp>(loc, header, args); 206 207 // Generate the rest of the loop header. 208 rewriter.setInsertionPointToEnd(header); 209 auto *mergeBlock = loopOp.getMergeBlock(); 210 auto cmpOp = rewriter.create<spirv::SLessThanOp>( 211 loc, rewriter.getI1Type(), newIndVar, adaptor.upperBound()); 212 213 rewriter.create<spirv::BranchConditionalOp>( 214 loc, cmpOp, body, ArrayRef<Value>(), mergeBlock, ArrayRef<Value>()); 215 216 // Generate instructions to increment the step of the induction variable and 217 // branch to the header. 218 Block *continueBlock = loopOp.getContinueBlock(); 219 rewriter.setInsertionPointToEnd(continueBlock); 220 221 // Add the step to the induction variable and branch to the header. 222 Value updatedIndVar = rewriter.create<spirv::IAddOp>( 223 loc, newIndVar.getType(), newIndVar, adaptor.step()); 224 rewriter.create<spirv::BranchOp>(loc, header, updatedIndVar); 225 226 // Infer the return types from the init operands. Vector type may get 227 // converted to CooperativeMatrix or to Vector type, to avoid having complex 228 // extra logic to figure out the right type we just infer it from the Init 229 // operands. 230 SmallVector<Type, 8> initTypes; 231 for (auto arg : adaptor.initArgs()) 232 initTypes.push_back(arg.getType()); 233 replaceSCFOutputValue(forOp, loopOp, rewriter, scfToSPIRVContext, initTypes); 234 return success(); 235 } 236 237 //===----------------------------------------------------------------------===// 238 // scf::IfOp 239 //===----------------------------------------------------------------------===// 240 241 LogicalResult 242 IfOpConversion::matchAndRewrite(scf::IfOp ifOp, OpAdaptor adaptor, 243 ConversionPatternRewriter &rewriter) const { 244 // When lowering `scf::IfOp` we explicitly create a selection header block 245 // before the control flow diverges and a merge block where control flow 246 // subsequently converges. 247 auto loc = ifOp.getLoc(); 248 249 // Create `spv.selection` operation, selection header block and merge block. 250 auto selectionOp = 251 rewriter.create<spirv::SelectionOp>(loc, spirv::SelectionControl::None); 252 auto *mergeBlock = 253 rewriter.createBlock(&selectionOp.body(), selectionOp.body().end()); 254 rewriter.create<spirv::MergeOp>(loc); 255 256 OpBuilder::InsertionGuard guard(rewriter); 257 auto *selectionHeaderBlock = 258 rewriter.createBlock(&selectionOp.body().front()); 259 260 // Inline `then` region before the merge block and branch to it. 261 auto &thenRegion = ifOp.thenRegion(); 262 auto *thenBlock = &thenRegion.front(); 263 rewriter.setInsertionPointToEnd(&thenRegion.back()); 264 rewriter.create<spirv::BranchOp>(loc, mergeBlock); 265 rewriter.inlineRegionBefore(thenRegion, mergeBlock); 266 267 auto *elseBlock = mergeBlock; 268 // If `else` region is not empty, inline that region before the merge block 269 // and branch to it. 270 if (!ifOp.elseRegion().empty()) { 271 auto &elseRegion = ifOp.elseRegion(); 272 elseBlock = &elseRegion.front(); 273 rewriter.setInsertionPointToEnd(&elseRegion.back()); 274 rewriter.create<spirv::BranchOp>(loc, mergeBlock); 275 rewriter.inlineRegionBefore(elseRegion, mergeBlock); 276 } 277 278 // Create a `spv.BranchConditional` operation for selection header block. 279 rewriter.setInsertionPointToEnd(selectionHeaderBlock); 280 rewriter.create<spirv::BranchConditionalOp>(loc, adaptor.condition(), 281 thenBlock, ArrayRef<Value>(), 282 elseBlock, ArrayRef<Value>()); 283 284 SmallVector<Type, 8> returnTypes; 285 for (auto result : ifOp.results()) { 286 auto convertedType = typeConverter.convertType(result.getType()); 287 returnTypes.push_back(convertedType); 288 } 289 replaceSCFOutputValue(ifOp, selectionOp, rewriter, scfToSPIRVContext, 290 returnTypes); 291 return success(); 292 } 293 294 //===----------------------------------------------------------------------===// 295 // scf::YieldOp 296 //===----------------------------------------------------------------------===// 297 298 /// Yield is lowered to stores to the VariableOp created during lowering of the 299 /// parent region. For loops we also need to update the branch looping back to 300 /// the header with the loop carried values. 301 LogicalResult TerminatorOpConversion::matchAndRewrite( 302 scf::YieldOp terminatorOp, OpAdaptor adaptor, 303 ConversionPatternRewriter &rewriter) const { 304 ValueRange operands = adaptor.getOperands(); 305 306 // If the region is return values, store each value into the associated 307 // VariableOp created during lowering of the parent region. 308 if (!operands.empty()) { 309 auto &allocas = scfToSPIRVContext->outputVars[terminatorOp->getParentOp()]; 310 if (allocas.size() != operands.size()) 311 return failure(); 312 313 auto loc = terminatorOp.getLoc(); 314 for (unsigned i = 0, e = operands.size(); i < e; i++) 315 rewriter.create<spirv::StoreOp>(loc, allocas[i], operands[i]); 316 if (isa<spirv::LoopOp>(terminatorOp->getParentOp())) { 317 // For loops we also need to update the branch jumping back to the header. 318 auto br = 319 cast<spirv::BranchOp>(rewriter.getInsertionBlock()->getTerminator()); 320 SmallVector<Value, 8> args(br.getBlockArguments()); 321 args.append(operands.begin(), operands.end()); 322 rewriter.setInsertionPoint(br); 323 rewriter.create<spirv::BranchOp>(terminatorOp.getLoc(), br.getTarget(), 324 args); 325 rewriter.eraseOp(br); 326 } 327 } 328 rewriter.eraseOp(terminatorOp); 329 return success(); 330 } 331 332 //===----------------------------------------------------------------------===// 333 // scf::WhileOp 334 //===----------------------------------------------------------------------===// 335 336 LogicalResult 337 WhileOpConversion::matchAndRewrite(scf::WhileOp whileOp, OpAdaptor adaptor, 338 ConversionPatternRewriter &rewriter) const { 339 auto loc = whileOp.getLoc(); 340 auto loopOp = rewriter.create<spirv::LoopOp>(loc, spirv::LoopControl::None); 341 loopOp.addEntryAndMergeBlock(); 342 343 OpBuilder::InsertionGuard guard(rewriter); 344 345 Region &beforeRegion = whileOp.before(); 346 Region &afterRegion = whileOp.after(); 347 348 Block &entryBlock = *loopOp.getEntryBlock(); 349 Block &beforeBlock = beforeRegion.front(); 350 Block &afterBlock = afterRegion.front(); 351 Block &mergeBlock = *loopOp.getMergeBlock(); 352 353 auto cond = cast<scf::ConditionOp>(beforeBlock.getTerminator()); 354 SmallVector<Value> condArgs; 355 if (failed(rewriter.getRemappedValues(cond.args(), condArgs))) 356 return failure(); 357 358 Value conditionVal = rewriter.getRemappedValue(cond.condition()); 359 if (!conditionVal) 360 return failure(); 361 362 auto yield = cast<scf::YieldOp>(afterBlock.getTerminator()); 363 SmallVector<Value> yieldArgs; 364 if (failed(rewriter.getRemappedValues(yield.results(), yieldArgs))) 365 return failure(); 366 367 // Move the while before block as the initial loop header block. 368 rewriter.inlineRegionBefore(beforeRegion, loopOp.body(), 369 getBlockIt(loopOp.body(), 1)); 370 371 // Move the while after block as the initial loop body block. 372 rewriter.inlineRegionBefore(afterRegion, loopOp.body(), 373 getBlockIt(loopOp.body(), 2)); 374 375 // Jump from the loop entry block to the loop header block. 376 rewriter.setInsertionPointToEnd(&entryBlock); 377 rewriter.create<spirv::BranchOp>(loc, &beforeBlock, adaptor.inits()); 378 379 auto condLoc = cond.getLoc(); 380 381 SmallVector<Value> resultValues(condArgs.size()); 382 383 // For other SCF ops, the scf.yield op yields the value for the whole SCF op. 384 // So we use the scf.yield op as the anchor to create/load/store SPIR-V local 385 // variables. But for the scf.while op, the scf.yield op yields a value for 386 // the before region, which may not matching the whole op's result. Instead, 387 // the scf.condition op returns values matching the whole op's results. So we 388 // need to create/load/store variables according to that. 389 for (auto it : llvm::enumerate(condArgs)) { 390 auto res = it.value(); 391 auto i = it.index(); 392 auto pointerType = 393 spirv::PointerType::get(res.getType(), spirv::StorageClass::Function); 394 395 // Create local variables before the scf.while op. 396 rewriter.setInsertionPoint(loopOp); 397 auto alloc = rewriter.create<spirv::VariableOp>( 398 condLoc, pointerType, spirv::StorageClass::Function, 399 /*initializer=*/nullptr); 400 401 // Load the final result values after the scf.while op. 402 rewriter.setInsertionPointAfter(loopOp); 403 auto loadResult = rewriter.create<spirv::LoadOp>(condLoc, alloc); 404 resultValues[i] = loadResult; 405 406 // Store the current iteration's result value. 407 rewriter.setInsertionPointToEnd(&beforeBlock); 408 rewriter.create<spirv::StoreOp>(condLoc, alloc, res); 409 } 410 411 rewriter.setInsertionPointToEnd(&beforeBlock); 412 rewriter.replaceOpWithNewOp<spirv::BranchConditionalOp>( 413 cond, conditionVal, &afterBlock, condArgs, &mergeBlock, llvm::None); 414 415 // Convert the scf.yield op to a branch back to the header block. 416 rewriter.setInsertionPointToEnd(&afterBlock); 417 rewriter.replaceOpWithNewOp<spirv::BranchOp>(yield, &beforeBlock, yieldArgs); 418 419 rewriter.replaceOp(whileOp, resultValues); 420 return success(); 421 } 422 423 //===----------------------------------------------------------------------===// 424 // Hooks 425 //===----------------------------------------------------------------------===// 426 427 void mlir::populateSCFToSPIRVPatterns(SPIRVTypeConverter &typeConverter, 428 ScfToSPIRVContext &scfToSPIRVContext, 429 RewritePatternSet &patterns) { 430 patterns.add<ForOpConversion, IfOpConversion, TerminatorOpConversion, 431 WhileOpConversion>(patterns.getContext(), typeConverter, 432 scfToSPIRVContext.getImpl()); 433 } 434