18bfedb3cSKazuaki Ishizaki //===- KernelOutlining.cpp - Implementation of GPU kernel outlining -------===// 260965b46SAlex Zinenko // 330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information. 556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 660965b46SAlex Zinenko // 756222a06SMehdi Amini //===----------------------------------------------------------------------===// 860965b46SAlex Zinenko // 960965b46SAlex Zinenko // This file implements the GPU dialect kernel outlining pass. 1060965b46SAlex Zinenko // 1160965b46SAlex Zinenko //===----------------------------------------------------------------------===// 1260965b46SAlex Zinenko 131834ad4aSRiver Riddle #include "PassDetail.h" 1460965b46SAlex Zinenko #include "mlir/Dialect/GPU/GPUDialect.h" 1560965b46SAlex Zinenko #include "mlir/Dialect/GPU/Passes.h" 163f44495dSMaheshRavishankar #include "mlir/Dialect/GPU/Utils.h" 1769d757c0SRob Suderman #include "mlir/Dialect/StandardOps/IR/Ops.h" 1860965b46SAlex Zinenko #include "mlir/IR/BlockAndValueMapping.h" 1960965b46SAlex Zinenko #include "mlir/IR/Builders.h" 20b8cd0c14STres Popp #include "mlir/IR/SymbolTable.h" 21283b5e73SStephan Herhut #include "mlir/Transforms/RegionUtils.h" 2260965b46SAlex Zinenko 2360965b46SAlex Zinenko using namespace mlir; 2460965b46SAlex Zinenko 2560965b46SAlex Zinenko template <typename OpTy> 2660965b46SAlex Zinenko static void createForAllDimensions(OpBuilder &builder, Location loc, 27e62a6956SRiver Riddle SmallVectorImpl<Value> &values) { 2860965b46SAlex Zinenko for (StringRef dim : {"x", "y", "z"}) { 29e62a6956SRiver Riddle Value v = builder.create<OpTy>(loc, builder.getIndexType(), 3060965b46SAlex Zinenko builder.getStringAttr(dim)); 3160965b46SAlex Zinenko values.push_back(v); 3260965b46SAlex Zinenko } 3360965b46SAlex Zinenko } 3460965b46SAlex Zinenko 356273fa0cSAlex Zinenko // Add operations generating block/thread ids and grid/block dimensions at the 363f44495dSMaheshRavishankar // beginning of the `launchFuncOpBody` region. Add mapping from argument in 373f44495dSMaheshRavishankar // entry block of `launchOpBody`, to the corresponding result value of the added 383f44495dSMaheshRavishankar // operations. 393f44495dSMaheshRavishankar static void injectGpuIndexOperations(Location loc, Region &launchFuncOpBody, 403f44495dSMaheshRavishankar Region &launchOpBody, 413f44495dSMaheshRavishankar BlockAndValueMapping &map) { 426273fa0cSAlex Zinenko OpBuilder builder(loc->getContext()); 433f44495dSMaheshRavishankar Block &firstBlock = launchOpBody.front(); 443f44495dSMaheshRavishankar builder.setInsertionPointToStart(&launchFuncOpBody.front()); 45e62a6956SRiver Riddle SmallVector<Value, 12> indexOps; 466273fa0cSAlex Zinenko createForAllDimensions<gpu::BlockIdOp>(builder, loc, indexOps); 476273fa0cSAlex Zinenko createForAllDimensions<gpu::ThreadIdOp>(builder, loc, indexOps); 486273fa0cSAlex Zinenko createForAllDimensions<gpu::GridDimOp>(builder, loc, indexOps); 496273fa0cSAlex Zinenko createForAllDimensions<gpu::BlockDimOp>(builder, loc, indexOps); 5060965b46SAlex Zinenko // Replace the leading 12 function args with the respective thread/block index 5160965b46SAlex Zinenko // operations. Iterate backwards since args are erased and indices change. 523f44495dSMaheshRavishankar for (auto indexOp : enumerate(indexOps)) 533f44495dSMaheshRavishankar map.map(firstBlock.getArgument(indexOp.index()), indexOp.value()); 5460965b46SAlex Zinenko } 5560965b46SAlex Zinenko 563f44495dSMaheshRavishankar static bool isSinkingBeneficiary(Operation *op) { 57abb62668SStephan Herhut return isa<ConstantOp>(op) || isa<DimOp>(op); 58abb62668SStephan Herhut } 59abb62668SStephan Herhut 603f44495dSMaheshRavishankar LogicalResult mlir::sinkOperationsIntoLaunchOp(gpu::LaunchOp launchOp) { 613f44495dSMaheshRavishankar Region &launchOpBody = launchOp.body(); 62318ff019SStephan Herhut 633f44495dSMaheshRavishankar // Identify uses from values defined outside of the scope of the launch 643f44495dSMaheshRavishankar // operation. 653f44495dSMaheshRavishankar llvm::SetVector<Value> sinkCandidates; 663f44495dSMaheshRavishankar getUsedValuesDefinedAbove(launchOpBody, sinkCandidates); 673f44495dSMaheshRavishankar 683f44495dSMaheshRavishankar llvm::SetVector<Value> sunkValues; 693f44495dSMaheshRavishankar llvm::SetVector<Operation *> sunkOperations; 703f44495dSMaheshRavishankar for (Value operand : sinkCandidates) { 713f44495dSMaheshRavishankar Operation *operandOp = operand.getDefiningOp(); 723f44495dSMaheshRavishankar if (!operandOp || !isSinkingBeneficiary(operandOp)) 733f44495dSMaheshRavishankar continue; 743f44495dSMaheshRavishankar // Only sink operations that do not create new sinkCandidates. 753f44495dSMaheshRavishankar if (!llvm::all_of(operandOp->getOperands(), [&sinkCandidates](Value value) { 763f44495dSMaheshRavishankar return sinkCandidates.count(value); 773f44495dSMaheshRavishankar })) 783f44495dSMaheshRavishankar continue; 793f44495dSMaheshRavishankar sunkValues.insert(operand); 803f44495dSMaheshRavishankar sunkOperations.insert(operandOp); 81dfd06af5SStephan Herhut } 823f44495dSMaheshRavishankar 833f44495dSMaheshRavishankar // Insert operations so that the defs get cloned before uses. 843f44495dSMaheshRavishankar BlockAndValueMapping map; 853f44495dSMaheshRavishankar OpBuilder builder(launchOpBody); 863f44495dSMaheshRavishankar DenseSet<Operation *> processed; 873f44495dSMaheshRavishankar SmallVector<Operation *, 2> clonedOps; 883f44495dSMaheshRavishankar while (processed.size() != sunkOperations.size()) { 893f44495dSMaheshRavishankar auto startSize = processed.size(); 903f44495dSMaheshRavishankar for (Operation *sunkOperation : sunkOperations) { 913f44495dSMaheshRavishankar if (processed.count(sunkOperation)) 923f44495dSMaheshRavishankar continue; 933f44495dSMaheshRavishankar 943f44495dSMaheshRavishankar // Operation cant be cloned yet if any of its operands is also being sunk, 953f44495dSMaheshRavishankar // but isnt cloned yet. 963f44495dSMaheshRavishankar if (llvm::any_of( 973f44495dSMaheshRavishankar sunkOperation->getOperands(), [&sunkValues, &map](Value value) { 983f44495dSMaheshRavishankar return sunkValues.count(value) && !map.lookupOrNull(value); 993f44495dSMaheshRavishankar })) 1003f44495dSMaheshRavishankar continue; 1013f44495dSMaheshRavishankar 1023f44495dSMaheshRavishankar Operation *clonedOp = builder.clone(*sunkOperation, map); 1033f44495dSMaheshRavishankar // Only replace uses within the launch op. 1043f44495dSMaheshRavishankar for (auto result : llvm::enumerate(sunkOperation->getResults())) { 1053f44495dSMaheshRavishankar auto replacement = clonedOp->getResult(result.index()); 1063f44495dSMaheshRavishankar for (auto &use : llvm::make_early_inc_range(result.value().getUses())) 1073f44495dSMaheshRavishankar if (use.getOwner()->getParentOfType<gpu::LaunchOp>() == launchOp) 1083f44495dSMaheshRavishankar use.set(replacement); 1093f44495dSMaheshRavishankar } 1103f44495dSMaheshRavishankar processed.insert(sunkOperation); 1113f44495dSMaheshRavishankar } 1123f44495dSMaheshRavishankar if (startSize == processed.size()) 1133f44495dSMaheshRavishankar return launchOp.emitError( 1143f44495dSMaheshRavishankar "found illegal cyclic dependency between operations while sinking"); 1153f44495dSMaheshRavishankar } 1163f44495dSMaheshRavishankar return success(); 117dfd06af5SStephan Herhut } 118dfd06af5SStephan Herhut 11960965b46SAlex Zinenko // Outline the `gpu.launch` operation body into a kernel function. Replace 12026927518SStephan Herhut // `gpu.terminator` operations by `gpu.return` in the generated function. 1213f44495dSMaheshRavishankar static gpu::GPUFuncOp outlineKernelFuncImpl(gpu::LaunchOp launchOp, 1223f44495dSMaheshRavishankar StringRef kernelFnName, 123283b5e73SStephan Herhut llvm::SetVector<Value> &operands) { 12460965b46SAlex Zinenko Location loc = launchOp.getLoc(); 1256273fa0cSAlex Zinenko // Create a builder with no insertion point, insertion will happen separately 1266273fa0cSAlex Zinenko // due to symbol table manipulation. 1276273fa0cSAlex Zinenko OpBuilder builder(launchOp.getContext()); 1283f44495dSMaheshRavishankar Region &launchOpBody = launchOp.body(); 1296273fa0cSAlex Zinenko 130283b5e73SStephan Herhut // Identify uses from values defined outside of the scope of the launch 131283b5e73SStephan Herhut // operation. 1323f44495dSMaheshRavishankar getUsedValuesDefinedAbove(launchOpBody, operands); 133283b5e73SStephan Herhut 1343f44495dSMaheshRavishankar // Create the gpu.func operation. 135283b5e73SStephan Herhut SmallVector<Type, 4> kernelOperandTypes; 136283b5e73SStephan Herhut kernelOperandTypes.reserve(operands.size()); 137283b5e73SStephan Herhut for (Value operand : operands) { 138283b5e73SStephan Herhut kernelOperandTypes.push_back(operand.getType()); 139283b5e73SStephan Herhut } 14060965b46SAlex Zinenko FunctionType type = 14160965b46SAlex Zinenko FunctionType::get(kernelOperandTypes, {}, launchOp.getContext()); 1423f44495dSMaheshRavishankar auto outlinedFunc = builder.create<gpu::GPUFuncOp>(loc, kernelFnName, type); 14360965b46SAlex Zinenko outlinedFunc.setAttr(gpu::GPUDialect::getKernelFuncAttrName(), 14460965b46SAlex Zinenko builder.getUnitAttr()); 1453f44495dSMaheshRavishankar BlockAndValueMapping map; 1463f44495dSMaheshRavishankar 1473f44495dSMaheshRavishankar // Map the arguments corresponding to the launch parameters like blockIdx, 1483f44495dSMaheshRavishankar // threadIdx, etc. 1493f44495dSMaheshRavishankar Region &outlinedFuncBody = outlinedFunc.body(); 1503f44495dSMaheshRavishankar injectGpuIndexOperations(loc, outlinedFuncBody, launchOpBody, map); 1513f44495dSMaheshRavishankar 1523f44495dSMaheshRavishankar // Map arguments from gpu.launch region to the arguments of the gpu.func 1533f44495dSMaheshRavishankar // operation. 1543f44495dSMaheshRavishankar Block &entryBlock = outlinedFuncBody.front(); 1553f44495dSMaheshRavishankar for (auto operand : enumerate(operands)) 1563f44495dSMaheshRavishankar map.map(operand.value(), entryBlock.getArgument(operand.index())); 1573f44495dSMaheshRavishankar 1583f44495dSMaheshRavishankar // Clone the region of the gpu.launch operation into the gpu.func operation. 1593f44495dSMaheshRavishankar // TODO(ravishankarm): If cloneInto can be modified such that if a mapping for 1603f44495dSMaheshRavishankar // a block exists, that block will be used to clone operations into (at the 1613f44495dSMaheshRavishankar // end of the block), instead of creating a new block, this would be much 1623f44495dSMaheshRavishankar // cleaner. 1633f44495dSMaheshRavishankar launchOpBody.cloneInto(&outlinedFuncBody, map); 1643f44495dSMaheshRavishankar 1655aacce3dSKazuaki Ishizaki // Branch from entry of the gpu.func operation to the block that is cloned 1665aacce3dSKazuaki Ishizaki // from the entry block of the gpu.launch operation. 1673f44495dSMaheshRavishankar Block &launchOpEntry = launchOpBody.front(); 1683f44495dSMaheshRavishankar Block *clonedLaunchOpEntry = map.lookup(&launchOpEntry); 1693f44495dSMaheshRavishankar builder.setInsertionPointToEnd(&entryBlock); 1703f44495dSMaheshRavishankar builder.create<BranchOp>(loc, clonedLaunchOpEntry); 1713f44495dSMaheshRavishankar 17226927518SStephan Herhut outlinedFunc.walk([](gpu::TerminatorOp op) { 17326927518SStephan Herhut OpBuilder replacer(op); 17426927518SStephan Herhut replacer.create<gpu::ReturnOp>(op.getLoc()); 17526927518SStephan Herhut op.erase(); 17626927518SStephan Herhut }); 17760965b46SAlex Zinenko return outlinedFunc; 17860965b46SAlex Zinenko } 17960965b46SAlex Zinenko 1803f44495dSMaheshRavishankar gpu::GPUFuncOp mlir::outlineKernelFunc(gpu::LaunchOp launchOp, 1813f44495dSMaheshRavishankar StringRef kernelFnName, 1823f44495dSMaheshRavishankar llvm::SmallVectorImpl<Value> &operands) { 1833f44495dSMaheshRavishankar DenseSet<Value> inputOperandSet; 1843f44495dSMaheshRavishankar inputOperandSet.insert(operands.begin(), operands.end()); 1853f44495dSMaheshRavishankar llvm::SetVector<Value> operandSet(operands.begin(), operands.end()); 1863f44495dSMaheshRavishankar auto funcOp = outlineKernelFuncImpl(launchOp, kernelFnName, operandSet); 1873f44495dSMaheshRavishankar for (auto operand : operandSet) { 1883f44495dSMaheshRavishankar if (!inputOperandSet.count(operand)) 1893f44495dSMaheshRavishankar operands.push_back(operand); 1903f44495dSMaheshRavishankar } 1913f44495dSMaheshRavishankar return funcOp; 1923f44495dSMaheshRavishankar } 1933f44495dSMaheshRavishankar 19460965b46SAlex Zinenko // Replace `gpu.launch` operations with an `gpu.launch_func` operation launching 195dfd06af5SStephan Herhut // `kernelFunc`. The kernel func contains the body of the `gpu.launch` with 196dfd06af5SStephan Herhut // constant region arguments inlined. 1973f44495dSMaheshRavishankar static void convertToLaunchFuncOp(gpu::LaunchOp launchOp, 198283b5e73SStephan Herhut gpu::GPUFuncOp kernelFunc, 199283b5e73SStephan Herhut ValueRange operands) { 20060965b46SAlex Zinenko OpBuilder builder(launchOp); 2013f44495dSMaheshRavishankar builder.create<gpu::LaunchFuncOp>( 20260965b46SAlex Zinenko launchOp.getLoc(), kernelFunc, launchOp.getGridSizeOperandValues(), 203283b5e73SStephan Herhut launchOp.getBlockSizeOperandValues(), operands); 20460965b46SAlex Zinenko launchOp.erase(); 20560965b46SAlex Zinenko } 20660965b46SAlex Zinenko 20760965b46SAlex Zinenko namespace { 208b8676da1SChristian Sigg /// Pass that moves the kernel of each LaunchOp into its separate nested module. 209b8676da1SChristian Sigg /// 210b8676da1SChristian Sigg /// This pass moves the kernel code of each LaunchOp into a function created 211b8676da1SChristian Sigg /// inside a nested module. It also creates an external function of the same 212b8676da1SChristian Sigg /// name in the parent module. 213b8676da1SChristian Sigg /// 2149a52ea5cSTres Popp /// The gpu.modules are intended to be compiled to a cubin blob independently in 2159a52ea5cSTres Popp /// a separate pass. The external functions can then be annotated with the 216b8676da1SChristian Sigg /// symbol of the cubin accessor function. 217722f909fSRiver Riddle class GpuKernelOutliningPass 2181834ad4aSRiver Riddle : public GpuKernelOutliningBase<GpuKernelOutliningPass> { 21960965b46SAlex Zinenko public: 220722f909fSRiver Riddle void runOnOperation() override { 221722f909fSRiver Riddle SymbolTable symbolTable(getOperation()); 22290d65d32SAlex Zinenko bool modified = false; 223722f909fSRiver Riddle for (auto func : getOperation().getOps<FuncOp>()) { 224b8676da1SChristian Sigg // Insert just after the function. 225b8676da1SChristian Sigg Block::iterator insertPt(func.getOperation()->getNextNode()); 2263f44495dSMaheshRavishankar auto funcWalkResult = func.walk([&](gpu::LaunchOp op) { 227283b5e73SStephan Herhut llvm::SetVector<Value> operands; 2283f44495dSMaheshRavishankar std::string kernelFnName = 2293f44495dSMaheshRavishankar Twine(op.getParentOfType<FuncOp>().getName(), "_kernel").str(); 2303f44495dSMaheshRavishankar 2313f44495dSMaheshRavishankar // Pull in instructions that can be sunk 2323f44495dSMaheshRavishankar if (failed(sinkOperationsIntoLaunchOp(op))) 2333f44495dSMaheshRavishankar return WalkResult::interrupt(); 2343f44495dSMaheshRavishankar gpu::GPUFuncOp outlinedFunc = 2353f44495dSMaheshRavishankar outlineKernelFuncImpl(op, kernelFnName, operands); 236b8676da1SChristian Sigg 23790d65d32SAlex Zinenko // Create nested module and insert outlinedFunc. The module will 23890d65d32SAlex Zinenko // originally get the same name as the function, but may be renamed on 23990d65d32SAlex Zinenko // insertion into the parent module. 240b8cd0c14STres Popp auto kernelModule = createKernelModule(outlinedFunc, symbolTable); 241b8cd0c14STres Popp symbolTable.insert(kernelModule, insertPt); 242b8676da1SChristian Sigg 243b8676da1SChristian Sigg // Potentially changes signature, pulling in constants. 244283b5e73SStephan Herhut convertToLaunchFuncOp(op, outlinedFunc, operands.getArrayRef()); 24590d65d32SAlex Zinenko modified = true; 2463f44495dSMaheshRavishankar return WalkResult::advance(); 24760965b46SAlex Zinenko }); 2483f44495dSMaheshRavishankar if (funcWalkResult.wasInterrupted()) 2493f44495dSMaheshRavishankar return signalPassFailure(); 25060965b46SAlex Zinenko } 25190d65d32SAlex Zinenko 25290d65d32SAlex Zinenko // If any new module was inserted in this module, annotate this module as 25390d65d32SAlex Zinenko // a container module. 25490d65d32SAlex Zinenko if (modified) 255722f909fSRiver Riddle getOperation().setAttr(gpu::GPUDialect::getContainerModuleAttrName(), 25690d65d32SAlex Zinenko UnitAttr::get(&getContext())); 25760965b46SAlex Zinenko } 25874cdbf59SChristian Sigg 25974cdbf59SChristian Sigg private: 2609a52ea5cSTres Popp // Returns a gpu.module containing kernelFunc and all callees (recursive). 2619a52ea5cSTres Popp gpu::GPUModuleOp createKernelModule(gpu::GPUFuncOp kernelFunc, 262b8cd0c14STres Popp const SymbolTable &parentSymbolTable) { 2639a52ea5cSTres Popp // TODO: This code cannot use an OpBuilder because it must be inserted into 2649a52ea5cSTres Popp // a SymbolTable by the caller. SymbolTable needs to be refactored to 2659a52ea5cSTres Popp // prevent manual building of Ops with symbols in code using SymbolTables 2669a52ea5cSTres Popp // and then this needs to use the OpBuilder. 267722f909fSRiver Riddle auto context = getOperation().getContext(); 268*bb1d976fSAlex Zinenko OpBuilder builder(context); 2699a52ea5cSTres Popp OperationState state(kernelFunc.getLoc(), 2709a52ea5cSTres Popp gpu::GPUModuleOp::getOperationName()); 271*bb1d976fSAlex Zinenko gpu::GPUModuleOp::build(builder, state, kernelFunc.getName()); 2729a52ea5cSTres Popp auto kernelModule = cast<gpu::GPUModuleOp>(Operation::create(state)); 273b8cd0c14STres Popp SymbolTable symbolTable(kernelModule); 274b8cd0c14STres Popp symbolTable.insert(kernelFunc); 27574cdbf59SChristian Sigg 2764562e389SRiver Riddle SmallVector<Operation *, 8> symbolDefWorklist = {kernelFunc}; 2779fbf52e3SMLIR Team while (!symbolDefWorklist.empty()) { 2789fbf52e3SMLIR Team if (Optional<SymbolTable::UseRange> symbolUses = 2799fbf52e3SMLIR Team SymbolTable::getSymbolUses(symbolDefWorklist.pop_back_val())) { 2809fbf52e3SMLIR Team for (SymbolTable::SymbolUse symbolUse : *symbolUses) { 2819b9c647cSRiver Riddle StringRef symbolName = 2829b9c647cSRiver Riddle symbolUse.getSymbolRef().cast<FlatSymbolRefAttr>().getValue(); 283b8cd0c14STres Popp if (symbolTable.lookup(symbolName)) 2849fbf52e3SMLIR Team continue; 28574cdbf59SChristian Sigg 2869fbf52e3SMLIR Team Operation *symbolDefClone = 287b8cd0c14STres Popp parentSymbolTable.lookup(symbolName)->clone(); 2889fbf52e3SMLIR Team symbolDefWorklist.push_back(symbolDefClone); 289b8cd0c14STres Popp symbolTable.insert(symbolDefClone); 2909fbf52e3SMLIR Team } 2919fbf52e3SMLIR Team } 29274cdbf59SChristian Sigg } 29374cdbf59SChristian Sigg 29474cdbf59SChristian Sigg return kernelModule; 29574cdbf59SChristian Sigg } 29660965b46SAlex Zinenko }; 29760965b46SAlex Zinenko 29860965b46SAlex Zinenko } // namespace 29960965b46SAlex Zinenko 30080aca1eaSRiver Riddle std::unique_ptr<OperationPass<ModuleOp>> mlir::createGpuKernelOutliningPass() { 30179f53b0cSJacques Pienaar return std::make_unique<GpuKernelOutliningPass>(); 30260965b46SAlex Zinenko } 303