1 //===- Detensorize.cpp - Linalg transformations as 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 #include "PassDetail.h" 10 #include "mlir/Dialect/Linalg/IR/Linalg.h" 11 #include "mlir/Dialect/Linalg/Passes.h" 12 #include "mlir/Dialect/StandardOps/Transforms/FuncConversions.h" 13 #include "mlir/Dialect/Tensor/IR/Tensor.h" 14 #include "mlir/IR/OpDefinition.h" 15 #include "mlir/Transforms/DialectConversion.h" 16 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 17 #include <iterator> 18 #include <memory> 19 #include <utility> 20 21 using namespace mlir; 22 using namespace mlir::linalg; 23 24 static Value sourceMaterializationCallback(OpBuilder &builder, Type type, 25 ValueRange inputs, Location loc) { 26 assert(inputs.size() == 1); 27 auto inputType = inputs[0].getType(); 28 if (inputType.isa<TensorType>()) 29 return nullptr; 30 31 // A detensored value is converted back by creating a new tensor from its 32 // element(s). 33 return builder.create<tensor::FromElementsOp>( 34 loc, RankedTensorType::get({}, inputType), inputs[0]); 35 } 36 37 namespace { 38 /// Defines the criteria a TensorType must follow in order to be considered 39 /// "detensorable". 40 /// 41 /// NOTE: For now, only 0-D tensors are supported. 42 /// 43 /// Returns true if tensorType can be detensored. 44 bool canBeDetensored(TensorType tensorType) { 45 return tensorType.hasRank() && tensorType.getRank() == 0; 46 } 47 48 bool shouldBeDetensored(Operation *op, TypeConverter typeConverter) { 49 GenericOp genericOp = dyn_cast_or_null<GenericOp>(op); 50 return genericOp && 51 llvm::all_of( 52 genericOp.getInputAndOutputOperands(), [&](OpOperand *opOperand) { 53 return !typeConverter.isLegal(opOperand->get().getType()); 54 }); 55 } 56 57 /// A conversion patttern for detensoring `linalg.generic` ops. 58 class DetensorizeGenericOp : public OpConversionPattern<GenericOp> { 59 public: 60 using OpConversionPattern::OpConversionPattern; 61 LogicalResult 62 matchAndRewrite(GenericOp op, OpAdaptor adaptor, 63 ConversionPatternRewriter &rewriter) const override { 64 Block *originalBlock = op->getBlock(); 65 66 // Gather some information about the op before inling its region. 67 Block *opEntryBlock = &*op.region().begin(); 68 YieldOp yieldOp = dyn_cast<YieldOp>(op.region().back().getTerminator()); 69 70 // Split the op's region before the op. This way, we have a clear insertion 71 // point in which the op can be inlined. 72 Block *newBlock = rewriter.splitBlock(originalBlock, Block::iterator(op)); 73 rewriter.inlineRegionBefore(op.region(), newBlock); 74 // Now that op's region is inlined, the operands of its YieldOp are mapped 75 // to the materialized target values. Therefore, we can replace the op's 76 // uses with those of its YielOp's operands. 77 rewriter.replaceOp(op, yieldOp->getOperands()); 78 79 // No need for these intermediate blocks, merge them into 1. 80 rewriter.mergeBlocks(opEntryBlock, originalBlock, adaptor.getOperands()); 81 rewriter.mergeBlocks(newBlock, originalBlock, {}); 82 83 rewriter.eraseOp(&*Block::iterator(yieldOp)); 84 85 return success(); 86 } 87 }; 88 89 /// A conversion pattern for detensoring internal (non-entry) blocks within a 90 /// function. 91 struct FunctionNonEntryBlockConversion : public ConversionPattern { 92 FunctionNonEntryBlockConversion(MLIRContext *ctx, TypeConverter &converter, 93 DenseSet<BlockArgument> blockArgsToDetensor) 94 : ConversionPattern(converter, MatchTraitOpTypeTag(), 95 TypeID::get<OpTrait::FunctionLike>(), /*benefit=*/1, 96 ctx), 97 blockArgsToDetensor(std::move(blockArgsToDetensor)) {} 98 99 LogicalResult 100 matchAndRewrite(Operation *op, ArrayRef<Value> operands, 101 ConversionPatternRewriter &rewriter) const override { 102 rewriter.startRootUpdate(op); 103 Region ®ion = function_like_impl::getFunctionBody(op); 104 SmallVector<TypeConverter::SignatureConversion, 2> conversions; 105 106 for (Block &block : llvm::drop_begin(region, 1)) { 107 conversions.emplace_back(block.getNumArguments()); 108 TypeConverter::SignatureConversion &back = conversions.back(); 109 110 for (BlockArgument blockArgument : block.getArguments()) { 111 int idx = blockArgument.getArgNumber(); 112 113 if (blockArgsToDetensor.count(blockArgument)) 114 back.addInputs(idx, {getTypeConverter()->convertType( 115 block.getArgumentTypes()[idx])}); 116 else 117 back.addInputs(idx, {block.getArgumentTypes()[idx]}); 118 } 119 } 120 121 if (failed(rewriter.convertNonEntryRegionTypes(®ion, *typeConverter, 122 conversions))) { 123 rewriter.cancelRootUpdate(op); 124 return failure(); 125 } 126 127 rewriter.finalizeRootUpdate(op); 128 return success(); 129 } 130 131 private: 132 const DenseSet<BlockArgument> blockArgsToDetensor; 133 }; 134 135 class DetensorizeTypeConverter : public TypeConverter { 136 public: 137 DetensorizeTypeConverter() { 138 addConversion([](Type type) { return type; }); 139 140 // A TensorType that can be detensored, is converted to the underlying 141 // element type. 142 addConversion([](TensorType tensorType) -> Type { 143 if (canBeDetensored(tensorType)) 144 return tensorType.getElementType(); 145 146 return tensorType; 147 }); 148 149 // A tensor value is detensoried by extracting its element(s). 150 addTargetMaterialization([](OpBuilder &builder, Type type, 151 ValueRange inputs, Location loc) -> Value { 152 return builder.create<tensor::ExtractOp>(loc, inputs[0], ValueRange{}); 153 }); 154 155 addSourceMaterialization(sourceMaterializationCallback); 156 addArgumentMaterialization(sourceMaterializationCallback); 157 } 158 }; 159 160 /// @see LinalgDetensorize in Linalg/Passes.td for more details. 161 struct LinalgDetensorize : public LinalgDetensorizeBase<LinalgDetensorize> { 162 LinalgDetensorize() = default; 163 164 class CostModel { 165 public: 166 virtual ~CostModel() = default; 167 168 /// A cost model algorithm computes the following outputs: 169 /// 170 /// - opsToDetensor: the list of linalg ops that should be 171 /// detensored. 172 /// 173 /// - blockArgsToDetensor: since the operands and results of detensored 174 /// linalg ops can cross the BB boundary (e.g. a linalg op's input can come 175 /// from a BB argument and a linalg op's output can be passed to successor 176 /// BBs), we need to maintain the sub-set of arguments that should be 177 /// detensored (i.e. converted by typeConverter) for each affected BB. 178 /// 179 /// Example: 180 /// 181 /// For the following snippet: 182 /// ... 183 /// ^bb1(%6: tensor<i32>, %9: tensor<i32>): 184 /// %7 = linalg.init_tensor [] : tensor<i32> 185 /// %8 = linalg.generic #attrs 186 /// ins(%6, %6 : tensor<i32>, tensor<i32>) 187 /// outs(%7 : tensor<i32>) { 188 /// ^bb0(%arg0: i32, %arg1: i32, %arg2: i32): 189 /// %9 = arith.addi %arg0, %arg1 : i32 190 /// linalg.yield %9 : i32 191 /// } -> tensor<i32> 192 /// %10 = "some.op"(%9) 193 /// br ^bb2(%8 : tensor<i32>) 194 /// ... 195 /// 196 /// if the cost model decides that the linalg.generic op should be 197 /// detensored, then: 198 /// - opsToDetensor should be = {linalg.generic{add}}. 199 /// - blockArgsToDetensor should be = {bb1 -> {0}, bb2 -> {0}}. 200 virtual void compute(Operation *func, 201 DetensorizeTypeConverter typeConverter, 202 DenseSet<Operation *> &opsToDetensor, 203 DenseSet<BlockArgument> &blockArgsToDetensor) = 0; 204 205 /// From the blockArgsToDetensor set computed by a CostModel 206 /// implementation, this method computes the corresponding branch op 207 /// detensoring. The result is a map from a branch op to a subset of indices 208 /// of its operands. The indices specify which of the branch op's operands 209 /// should be detensored. 210 /// 211 /// For the previous example, this method would compute: {bb2 -> {0}}. 212 static DenseMap<Operation *, DenseSet<int>> computeBranchOpDetensoring( 213 const DenseSet<BlockArgument> &blockArgsToDetensor) { 214 DenseMap<Operation *, DenseSet<int>> detensorableBranchOps; 215 216 for (auto blockArgumentElem : blockArgsToDetensor) { 217 Block *block = blockArgumentElem.getOwner(); 218 219 for (PredecessorIterator pred = block->pred_begin(); 220 pred != block->pred_end(); ++pred) { 221 BranchOpInterface terminator = 222 dyn_cast<BranchOpInterface>((*pred)->getTerminator()); 223 auto blockOperands = 224 terminator.getSuccessorOperands(pred.getSuccessorIndex()); 225 226 if (!blockOperands || blockOperands->empty()) 227 continue; 228 229 detensorableBranchOps[terminator].insert( 230 blockOperands->getBeginOperandIndex() + 231 blockArgumentElem.getArgNumber()); 232 } 233 } 234 235 return detensorableBranchOps; 236 } 237 }; 238 239 /// Detensorize linalg ops involved in control-flow within a function. 240 /// 241 /// This model starts from BranchOps and CondBranchOps within a function. For 242 /// each such branch, the model then walks the use-def chain for the branch's 243 /// condition backwards in order to understand where the condition's value 244 /// comes from. If the condition value is (indirectly) computed by a linalg op 245 /// that can be detensored, the model then continues walking the use-def chain 246 /// in order to understand where the linalg op's operands come from. This 247 /// leads to discovering a "detensoring component". A detensoring component is 248 /// the set of operations + block arguments that are involved in control-flow 249 /// AND can be detensored. 250 class ControlFlowDetectionModel : public CostModel { 251 public: 252 void compute(Operation *func, DetensorizeTypeConverter typeConverter, 253 DenseSet<Operation *> &opsToDetensor, 254 DenseSet<BlockArgument> &blockArgsToDetensor) override { 255 SmallVector<Value> workList; 256 257 func->walk([&](CondBranchOp condBr) { 258 for (auto operand : condBr.getOperands()) { 259 workList.push_back(operand); 260 } 261 }); 262 263 func->walk([&](BranchOp br) { 264 for (auto operand : br.getOperands()) { 265 workList.push_back(operand); 266 } 267 }); 268 269 DenseSet<Value> visitedValues; 270 DenseSet<Operation *> visitedOps; 271 272 // For a (to-be-detesored) value, check if it "escapes" the block by being 273 // passed to terminator. If it does, then workList is updated with the 274 // corresponding argument to the successor block. 275 auto updateWorkListWithSuccessorArguments = 276 [&](Value value, BranchOpInterface terminator) { 277 if (!terminator) 278 return; 279 280 for (auto operandIdx : 281 llvm::seq<unsigned>(0, terminator->getOperands().size())) { 282 Value operand = terminator->getOperand(operandIdx); 283 284 if (operand == value) { 285 auto succBlockArg = 286 terminator.getSuccessorBlockArgument(operandIdx); 287 288 if (succBlockArg && !blockArgsToDetensor.count(*succBlockArg)) 289 workList.push_back(*succBlockArg); 290 } 291 } 292 }; 293 294 while (!workList.empty()) { 295 Value currentItem = workList.pop_back_val(); 296 297 if (!visitedValues.insert(currentItem).second) 298 continue; 299 300 // 1 - Look forward: 301 // 1.1 - If currentItem escapes to one or more successors, add 302 // the corresponding successor arguments to workList. 303 updateWorkListWithSuccessorArguments( 304 currentItem, dyn_cast<BranchOpInterface>( 305 currentItem.getParentBlock()->getTerminator())); 306 307 // 1.2 - For each user of currentItem, add the defined values to 308 // workList. This way, the user ops can be inspected later if they are 309 // detensorable and if so, their operands will be added to workList to 310 // potentially discover other parts of the detensorable component. 311 for (auto *user : currentItem.getUsers()) 312 for (Value result : user->getResults()) 313 workList.push_back(result); 314 315 // 2 - Look backward: 316 // 2.1 - The current item is defined by a block argument. If the owner 317 // block is a non-entry one, then: 318 // * Add the argument to blockArgsToDetensor. 319 // * Walk the use-def chain backwards to add each predecessor's 320 // terminator-operands corresponding to currentItem to workList. 321 if (currentItem.dyn_cast<BlockArgument>()) { 322 BlockArgument currentItemBlockArgument = 323 currentItem.cast<BlockArgument>(); 324 Block *ownerBlock = currentItemBlockArgument.getOwner(); 325 326 // Function arguments are not detensored/converted. 327 if (&*ownerBlock->getParent()->begin() == ownerBlock) 328 continue; 329 330 // This inner-block argument is involved in control-flow, it should be 331 // detensored. 332 blockArgsToDetensor.insert(currentItemBlockArgument); 333 334 for (PredecessorIterator pred = ownerBlock->pred_begin(); 335 pred != ownerBlock->pred_end(); ++pred) { 336 BranchOpInterface predTerminator = 337 dyn_cast<BranchOpInterface>((*pred)->getTerminator()); 338 339 // TODO: For now, we give up if any of the control-flow components 340 // in a function is not detensorable. Fix that. 341 if (!predTerminator) { 342 opsToDetensor.clear(); 343 blockArgsToDetensor.clear(); 344 return; 345 } 346 347 auto ownerBlockOperands = 348 predTerminator.getSuccessorOperands(pred.getSuccessorIndex()); 349 350 if (!ownerBlockOperands || ownerBlockOperands->empty()) 351 continue; 352 353 // For each predecessor, add the value it passes to that argument to 354 // workList to find out how it's computed. 355 workList.push_back( 356 ownerBlockOperands 357 .getValue()[currentItemBlockArgument.getArgNumber()]); 358 } 359 360 continue; 361 } 362 363 Operation *currentItemDefiningOp = currentItem.getDefiningOp(); 364 365 if (!visitedOps.insert(currentItemDefiningOp).second) 366 continue; 367 368 // 2.2 - The current item is computed by a GenericOp. If the op should 369 // be detensored, then: 370 // * Add it to opsToDetensor. 371 // * Add its operands to workList to discover other parts of the 372 // potentially detensorable component. 373 if (auto genericOp = dyn_cast<GenericOp>(currentItemDefiningOp)) { 374 // The op was encountered already, no need to inspect it again. 375 if (opsToDetensor.count(genericOp)) 376 continue; 377 378 // The op should not be detensored, give up on it but continue with 379 // discovering the rest of the control-flow component. 380 if (!shouldBeDetensored(genericOp, typeConverter)) { 381 continue; 382 } 383 384 opsToDetensor.insert(genericOp); 385 386 for (Value genericOpOperand : genericOp.inputs()) 387 workList.push_back(genericOpOperand); 388 389 continue; 390 } 391 392 // 2.3 - The current item is the result of a FromElementsOp, it will be 393 // trivially detensored later as part of canonicalization patterns 394 // applied at the end of detensoring. 395 // 396 // Note: No need to check whether the result type of this op is 397 // detensorable since if it wasn't we wouldn't reach that point in the 398 // work list. 399 if (dyn_cast<tensor::FromElementsOp>(currentItemDefiningOp)) 400 continue; 401 402 // 2.4 - The current item is the result of a scalar op, add all its 403 // operands to the work list. 404 if (llvm::all_of( 405 currentItemDefiningOp->getResultTypes(), 406 [&](Type resultType) { return resultType.isIntOrFloat(); })) 407 for (Value scalarOpOperand : currentItemDefiningOp->getOperands()) 408 workList.push_back(scalarOpOperand); 409 } 410 411 // Since the cost model gives up on some ops (see the details of step 2.2 412 // above), block arguments that correspond to the values produced by those 413 // ops should not be detensored as well. 414 415 DenseSet<BlockArgument> blockArgsToRemove; 416 417 for (auto &blockArg : blockArgsToDetensor) { 418 Block *block = blockArg.getParentBlock(); 419 420 // For the potentially detensorable block argument, find the 421 // correpsonding operands in predecessor blocks. 422 for (PredecessorIterator pred = block->pred_begin(); 423 pred != block->pred_end(); ++pred) { 424 BranchOpInterface terminator = 425 dyn_cast<BranchOpInterface>((*pred)->getTerminator()); 426 auto blockOperands = 427 terminator.getSuccessorOperands(pred.getSuccessorIndex()); 428 429 if (!blockOperands || blockOperands->empty()) 430 continue; 431 432 Operation *definingOp = 433 terminator 434 ->getOperand(blockOperands->getBeginOperandIndex() + 435 blockArg.getArgNumber()) 436 .getDefiningOp(); 437 438 // If the operand is defined by a GenericOp that will not be 439 // detensored, then do not detensor the corresponding block argument. 440 if (dyn_cast_or_null<GenericOp>(definingOp) && 441 opsToDetensor.count(definingOp) == 0) { 442 blockArgsToRemove.insert(blockArg); 443 break; 444 } 445 } 446 } 447 448 for (auto &blockArg : blockArgsToRemove) { 449 blockArgsToDetensor.erase(blockArg); 450 } 451 } 452 }; 453 454 /// Detensorize everything that can detensored. 455 class AggressiveDetensoringModel : public CostModel { 456 public: 457 void compute(Operation *func, DetensorizeTypeConverter typeConverter, 458 DenseSet<Operation *> &opsToDetensor, 459 DenseSet<BlockArgument> &blockArgsToDetensor) override { 460 func->walk([&](GenericOp genericOp) { 461 if (shouldBeDetensored(genericOp, typeConverter)) 462 opsToDetensor.insert(genericOp); 463 }); 464 465 for (Block &block : 466 llvm::drop_begin(function_like_impl::getFunctionBody(func), 1)) 467 for (BlockArgument blockArgument : block.getArguments()) 468 blockArgsToDetensor.insert(blockArgument); 469 } 470 }; 471 472 void runOnOperation() override { 473 assert(getOperation()->hasTrait<OpTrait::FunctionLike>() && 474 "DetensorizePass can only be run on FunctionLike operations"); 475 MLIRContext *context = &getContext(); 476 DetensorizeTypeConverter typeConverter; 477 RewritePatternSet patterns(context); 478 ConversionTarget target(*context); 479 DenseSet<Operation *> opsToDetensor; 480 DenseMap<Operation *, DenseSet<int>> detensorableBranchOps; 481 DenseSet<BlockArgument> blockArgsToDetensor; 482 483 if (aggressiveMode.getValue()) { 484 AggressiveDetensoringModel costModel; 485 costModel.compute(getOperation(), typeConverter, opsToDetensor, 486 blockArgsToDetensor); 487 488 } else { 489 ControlFlowDetectionModel costModel; 490 costModel.compute(getOperation(), typeConverter, opsToDetensor, 491 blockArgsToDetensor); 492 } 493 494 detensorableBranchOps = 495 CostModel::computeBranchOpDetensoring(blockArgsToDetensor); 496 497 target.addDynamicallyLegalOp<GenericOp>( 498 [&](GenericOp op) { return !opsToDetensor.count(op); }); 499 500 target.markUnknownOpDynamicallyLegal([&](Operation *op) { 501 // A function is legal if all of its non-entry blocks are legal. We 502 // don't legalize the entry block (i.e. the function's signature) 503 // since detensoring can't happen along external calling convention 504 // boundaries, which we conservatively approximate as all function 505 // signatures. 506 if (op->hasTrait<OpTrait::FunctionLike>()) { 507 auto &body = function_like_impl::getFunctionBody(op); 508 return llvm::all_of(llvm::drop_begin(body, 1), [&](Block &block) { 509 return !llvm::any_of( 510 blockArgsToDetensor, [&](BlockArgument blockArgument) { 511 return blockArgument.getOwner() == &block && 512 !typeConverter.isLegal(blockArgument.getType()); 513 }); 514 }); 515 } 516 517 if (isNotBranchOpInterfaceOrReturnLikeOp(op) || 518 isLegalForReturnOpTypeConversionPattern(op, typeConverter, 519 /*returnOpAlwaysLegal*/ true)) 520 return true; 521 522 if (auto branchOp = dyn_cast<BranchOpInterface>(op)) { 523 if (!detensorableBranchOps.count(branchOp)) 524 return true; 525 526 for (auto operandIdx : detensorableBranchOps[branchOp]) 527 if (!typeConverter.isLegal( 528 branchOp->getOperand(operandIdx).getType())) 529 return false; 530 531 return true; 532 } 533 534 return false; 535 }); 536 537 patterns.insert<DetensorizeGenericOp>(typeConverter, context); 538 patterns.insert<FunctionNonEntryBlockConversion>(context, typeConverter, 539 blockArgsToDetensor); 540 // Since non-entry block arguments get detensorized, we also need to 541 // update the control flow inside the function to reflect the correct 542 // types. 543 auto shouldConvertBranchOperand = [&](BranchOpInterface branchOp, 544 int operandIdx) -> bool { 545 return detensorableBranchOps.count(branchOp) && 546 detensorableBranchOps[branchOp].count(operandIdx); 547 }; 548 549 populateBranchOpInterfaceTypeConversionPattern(patterns, typeConverter, 550 shouldConvertBranchOperand); 551 552 if (failed( 553 applyFullConversion(getOperation(), target, std::move(patterns)))) 554 signalPassFailure(); 555 556 RewritePatternSet canonPatterns(context); 557 tensor::FromElementsOp::getCanonicalizationPatterns(canonPatterns, context); 558 if (failed(applyPatternsAndFoldGreedily(getOperation(), 559 std::move(canonPatterns)))) 560 signalPassFailure(); 561 } 562 }; 563 } // namespace 564 565 std::unique_ptr<Pass> mlir::createLinalgDetensorizePass() { 566 return std::make_unique<LinalgDetensorize>(); 567 } 568