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"
21*edeff6e6SStephan Herhut #include "mlir/Support/LLVM.h"
22283b5e73SStephan Herhut #include "mlir/Transforms/RegionUtils.h"
2360965b46SAlex Zinenko 
2460965b46SAlex Zinenko using namespace mlir;
2560965b46SAlex Zinenko 
2660965b46SAlex Zinenko template <typename OpTy>
2760965b46SAlex Zinenko static void createForAllDimensions(OpBuilder &builder, Location loc,
28e62a6956SRiver Riddle                                    SmallVectorImpl<Value> &values) {
2960965b46SAlex Zinenko   for (StringRef dim : {"x", "y", "z"}) {
30e62a6956SRiver Riddle     Value v = builder.create<OpTy>(loc, builder.getIndexType(),
3160965b46SAlex Zinenko                                    builder.getStringAttr(dim));
3260965b46SAlex Zinenko     values.push_back(v);
3360965b46SAlex Zinenko   }
3460965b46SAlex Zinenko }
3560965b46SAlex Zinenko 
36*edeff6e6SStephan Herhut /// Adds operations generating block/thread ids and grid/block dimensions at the
37*edeff6e6SStephan Herhut /// beginning of the `launchFuncOpBody` region. Add mapping from argument in
38*edeff6e6SStephan Herhut /// entry block of `launchOpBody`, to the corresponding result value of the
39*edeff6e6SStephan Herhut /// added operations.
403f44495dSMaheshRavishankar static void injectGpuIndexOperations(Location loc, Region &launchFuncOpBody,
413f44495dSMaheshRavishankar                                      Region &launchOpBody,
423f44495dSMaheshRavishankar                                      BlockAndValueMapping &map) {
436273fa0cSAlex Zinenko   OpBuilder builder(loc->getContext());
443f44495dSMaheshRavishankar   Block &firstBlock = launchOpBody.front();
453f44495dSMaheshRavishankar   builder.setInsertionPointToStart(&launchFuncOpBody.front());
46e62a6956SRiver Riddle   SmallVector<Value, 12> indexOps;
476273fa0cSAlex Zinenko   createForAllDimensions<gpu::BlockIdOp>(builder, loc, indexOps);
486273fa0cSAlex Zinenko   createForAllDimensions<gpu::ThreadIdOp>(builder, loc, indexOps);
496273fa0cSAlex Zinenko   createForAllDimensions<gpu::GridDimOp>(builder, loc, indexOps);
506273fa0cSAlex Zinenko   createForAllDimensions<gpu::BlockDimOp>(builder, loc, indexOps);
5160965b46SAlex Zinenko   // Replace the leading 12 function args with the respective thread/block index
5260965b46SAlex Zinenko   // operations. Iterate backwards since args are erased and indices change.
533f44495dSMaheshRavishankar   for (auto indexOp : enumerate(indexOps))
543f44495dSMaheshRavishankar     map.map(firstBlock.getArgument(indexOp.index()), indexOp.value());
5560965b46SAlex Zinenko }
5660965b46SAlex Zinenko 
57*edeff6e6SStephan Herhut /// Identifies operations that are beneficial to sink into kernels. These
58*edeff6e6SStephan Herhut /// operations may not have side-effects, as otherwise sinking (and hence
59*edeff6e6SStephan Herhut /// duplicating them) is not legal.
603f44495dSMaheshRavishankar static bool isSinkingBeneficiary(Operation *op) {
61*edeff6e6SStephan Herhut   return isa<ConstantOp, DimOp, SelectOp, CmpIOp>(op);
62*edeff6e6SStephan Herhut }
63*edeff6e6SStephan Herhut 
64*edeff6e6SStephan Herhut /// For a given operation `op`, computes whether it is beneficial to sink the
65*edeff6e6SStephan Herhut /// operation into the kernel. An operation can be sunk if doing so does not
66*edeff6e6SStephan Herhut /// introduce new kernel arguments. Whether a value is already available in the
67*edeff6e6SStephan Herhut /// kernel (and hence does not introduce new arguments) is checked by
68*edeff6e6SStephan Herhut /// querying `availableValues`.
69*edeff6e6SStephan Herhut /// If an operand is not yet available, we recursively check whether it can be
70*edeff6e6SStephan Herhut /// made available by siking its defining op.
71*edeff6e6SStephan Herhut /// Operations that are indentified for sinking are added to `beneficiaryOps` in
72*edeff6e6SStephan Herhut /// the order the should appear in the kernel. Furthermore, `availableValues` is
73*edeff6e6SStephan Herhut /// updated with results that will be available after sinking the identified
74*edeff6e6SStephan Herhut /// ops.
75*edeff6e6SStephan Herhut static bool extractBeneficiaryOps(Operation *op,
76*edeff6e6SStephan Herhut                                   llvm::SetVector<Operation *> &beneficiaryOps,
77*edeff6e6SStephan Herhut                                   llvm::SetVector<Value> &availableValues) {
78*edeff6e6SStephan Herhut   if (beneficiaryOps.count(op))
79*edeff6e6SStephan Herhut     return true;
80*edeff6e6SStephan Herhut 
81*edeff6e6SStephan Herhut   if (!isSinkingBeneficiary(op))
82*edeff6e6SStephan Herhut     return false;
83*edeff6e6SStephan Herhut 
84*edeff6e6SStephan Herhut   for (Value operand : op->getOperands()) {
85*edeff6e6SStephan Herhut     // It is already visisble in the kernel, keep going.
86*edeff6e6SStephan Herhut     if (availableValues.count(operand))
87*edeff6e6SStephan Herhut       continue;
88*edeff6e6SStephan Herhut     // Else check whether it can be made available via sinking.
89*edeff6e6SStephan Herhut     Operation *definingOp = operand.getDefiningOp();
90*edeff6e6SStephan Herhut     if (!definingOp ||
91*edeff6e6SStephan Herhut         !extractBeneficiaryOps(definingOp, beneficiaryOps, availableValues))
92*edeff6e6SStephan Herhut       return false;
93*edeff6e6SStephan Herhut   }
94*edeff6e6SStephan Herhut   // We will sink the operation, mark its results as now available.
95*edeff6e6SStephan Herhut   beneficiaryOps.insert(op);
96*edeff6e6SStephan Herhut   for (Value result : op->getResults())
97*edeff6e6SStephan Herhut     availableValues.insert(result);
98*edeff6e6SStephan Herhut   return true;
99abb62668SStephan Herhut }
100abb62668SStephan Herhut 
1013f44495dSMaheshRavishankar LogicalResult mlir::sinkOperationsIntoLaunchOp(gpu::LaunchOp launchOp) {
1023f44495dSMaheshRavishankar   Region &launchOpBody = launchOp.body();
103318ff019SStephan Herhut 
1043f44495dSMaheshRavishankar   // Identify uses from values defined outside of the scope of the launch
1053f44495dSMaheshRavishankar   // operation.
1063f44495dSMaheshRavishankar   llvm::SetVector<Value> sinkCandidates;
1073f44495dSMaheshRavishankar   getUsedValuesDefinedAbove(launchOpBody, sinkCandidates);
1083f44495dSMaheshRavishankar 
109*edeff6e6SStephan Herhut   SmallVector<Value, 4> worklist(sinkCandidates.begin(), sinkCandidates.end());
110*edeff6e6SStephan Herhut   llvm::SetVector<Operation *> toBeSunk;
111*edeff6e6SStephan Herhut   for (Value operand : worklist) {
1123f44495dSMaheshRavishankar     Operation *operandOp = operand.getDefiningOp();
113*edeff6e6SStephan Herhut     if (!operandOp)
1143f44495dSMaheshRavishankar       continue;
115*edeff6e6SStephan Herhut     extractBeneficiaryOps(operandOp, toBeSunk, sinkCandidates);
116dfd06af5SStephan Herhut   }
1173f44495dSMaheshRavishankar 
1183f44495dSMaheshRavishankar   // Insert operations so that the defs get cloned before uses.
1193f44495dSMaheshRavishankar   BlockAndValueMapping map;
1203f44495dSMaheshRavishankar   OpBuilder builder(launchOpBody);
121*edeff6e6SStephan Herhut   for (Operation *op : toBeSunk) {
122*edeff6e6SStephan Herhut     Operation *clonedOp = builder.clone(*op, map);
1233f44495dSMaheshRavishankar     // Only replace uses within the launch op.
124*edeff6e6SStephan Herhut     for (auto pair : llvm::zip(op->getResults(), clonedOp->getResults()))
125*edeff6e6SStephan Herhut       replaceAllUsesInRegionWith(std::get<0>(pair), std::get<1>(pair),
126*edeff6e6SStephan Herhut                                  launchOp.body());
1273f44495dSMaheshRavishankar   }
1283f44495dSMaheshRavishankar   return success();
129dfd06af5SStephan Herhut }
130dfd06af5SStephan Herhut 
131*edeff6e6SStephan Herhut /// Outline the `gpu.launch` operation body into a kernel function. Replace
132*edeff6e6SStephan Herhut /// `gpu.terminator` operations by `gpu.return` in the generated function.
1333f44495dSMaheshRavishankar static gpu::GPUFuncOp outlineKernelFuncImpl(gpu::LaunchOp launchOp,
1343f44495dSMaheshRavishankar                                             StringRef kernelFnName,
135283b5e73SStephan Herhut                                             llvm::SetVector<Value> &operands) {
13660965b46SAlex Zinenko   Location loc = launchOp.getLoc();
1376273fa0cSAlex Zinenko   // Create a builder with no insertion point, insertion will happen separately
1386273fa0cSAlex Zinenko   // due to symbol table manipulation.
1396273fa0cSAlex Zinenko   OpBuilder builder(launchOp.getContext());
1403f44495dSMaheshRavishankar   Region &launchOpBody = launchOp.body();
1416273fa0cSAlex Zinenko 
142283b5e73SStephan Herhut   // Identify uses from values defined outside of the scope of the launch
143283b5e73SStephan Herhut   // operation.
1443f44495dSMaheshRavishankar   getUsedValuesDefinedAbove(launchOpBody, operands);
145283b5e73SStephan Herhut 
1463f44495dSMaheshRavishankar   // Create the gpu.func operation.
147283b5e73SStephan Herhut   SmallVector<Type, 4> kernelOperandTypes;
148283b5e73SStephan Herhut   kernelOperandTypes.reserve(operands.size());
149283b5e73SStephan Herhut   for (Value operand : operands) {
150283b5e73SStephan Herhut     kernelOperandTypes.push_back(operand.getType());
151283b5e73SStephan Herhut   }
15260965b46SAlex Zinenko   FunctionType type =
15360965b46SAlex Zinenko       FunctionType::get(kernelOperandTypes, {}, launchOp.getContext());
1543f44495dSMaheshRavishankar   auto outlinedFunc = builder.create<gpu::GPUFuncOp>(loc, kernelFnName, type);
15560965b46SAlex Zinenko   outlinedFunc.setAttr(gpu::GPUDialect::getKernelFuncAttrName(),
15660965b46SAlex Zinenko                        builder.getUnitAttr());
1573f44495dSMaheshRavishankar   BlockAndValueMapping map;
1583f44495dSMaheshRavishankar 
1593f44495dSMaheshRavishankar   // Map the arguments corresponding to the launch parameters like blockIdx,
1603f44495dSMaheshRavishankar   // threadIdx, etc.
1613f44495dSMaheshRavishankar   Region &outlinedFuncBody = outlinedFunc.body();
1623f44495dSMaheshRavishankar   injectGpuIndexOperations(loc, outlinedFuncBody, launchOpBody, map);
1633f44495dSMaheshRavishankar 
1643f44495dSMaheshRavishankar   // Map arguments from gpu.launch region to the arguments of the gpu.func
1653f44495dSMaheshRavishankar   // operation.
1663f44495dSMaheshRavishankar   Block &entryBlock = outlinedFuncBody.front();
1673f44495dSMaheshRavishankar   for (auto operand : enumerate(operands))
1683f44495dSMaheshRavishankar     map.map(operand.value(), entryBlock.getArgument(operand.index()));
1693f44495dSMaheshRavishankar 
1703f44495dSMaheshRavishankar   // Clone the region of the gpu.launch operation into the gpu.func operation.
1719db53a18SRiver Riddle   // TODO: If cloneInto can be modified such that if a mapping for
1723f44495dSMaheshRavishankar   // a block exists, that block will be used to clone operations into (at the
1733f44495dSMaheshRavishankar   // end of the block), instead of creating a new block, this would be much
1743f44495dSMaheshRavishankar   // cleaner.
1753f44495dSMaheshRavishankar   launchOpBody.cloneInto(&outlinedFuncBody, map);
1763f44495dSMaheshRavishankar 
1775aacce3dSKazuaki Ishizaki   // Branch from entry of the gpu.func operation to the block that is cloned
1785aacce3dSKazuaki Ishizaki   // from the entry block of the gpu.launch operation.
1793f44495dSMaheshRavishankar   Block &launchOpEntry = launchOpBody.front();
1803f44495dSMaheshRavishankar   Block *clonedLaunchOpEntry = map.lookup(&launchOpEntry);
1813f44495dSMaheshRavishankar   builder.setInsertionPointToEnd(&entryBlock);
1823f44495dSMaheshRavishankar   builder.create<BranchOp>(loc, clonedLaunchOpEntry);
1833f44495dSMaheshRavishankar 
18426927518SStephan Herhut   outlinedFunc.walk([](gpu::TerminatorOp op) {
18526927518SStephan Herhut     OpBuilder replacer(op);
18626927518SStephan Herhut     replacer.create<gpu::ReturnOp>(op.getLoc());
18726927518SStephan Herhut     op.erase();
18826927518SStephan Herhut   });
18960965b46SAlex Zinenko   return outlinedFunc;
19060965b46SAlex Zinenko }
19160965b46SAlex Zinenko 
1923f44495dSMaheshRavishankar gpu::GPUFuncOp mlir::outlineKernelFunc(gpu::LaunchOp launchOp,
1933f44495dSMaheshRavishankar                                        StringRef kernelFnName,
1943f44495dSMaheshRavishankar                                        llvm::SmallVectorImpl<Value> &operands) {
1953f44495dSMaheshRavishankar   DenseSet<Value> inputOperandSet;
1963f44495dSMaheshRavishankar   inputOperandSet.insert(operands.begin(), operands.end());
1973f44495dSMaheshRavishankar   llvm::SetVector<Value> operandSet(operands.begin(), operands.end());
1983f44495dSMaheshRavishankar   auto funcOp = outlineKernelFuncImpl(launchOp, kernelFnName, operandSet);
1993f44495dSMaheshRavishankar   for (auto operand : operandSet) {
2003f44495dSMaheshRavishankar     if (!inputOperandSet.count(operand))
2013f44495dSMaheshRavishankar       operands.push_back(operand);
2023f44495dSMaheshRavishankar   }
2033f44495dSMaheshRavishankar   return funcOp;
2043f44495dSMaheshRavishankar }
2053f44495dSMaheshRavishankar 
206*edeff6e6SStephan Herhut /// Replace `gpu.launch` operations with an `gpu.launch_func` operation
207*edeff6e6SStephan Herhut /// launching `kernelFunc`. The kernel func contains the body of the
208*edeff6e6SStephan Herhut /// `gpu.launch` with constant region arguments inlined.
2093f44495dSMaheshRavishankar static void convertToLaunchFuncOp(gpu::LaunchOp launchOp,
210283b5e73SStephan Herhut                                   gpu::GPUFuncOp kernelFunc,
211283b5e73SStephan Herhut                                   ValueRange operands) {
21260965b46SAlex Zinenko   OpBuilder builder(launchOp);
2133f44495dSMaheshRavishankar   builder.create<gpu::LaunchFuncOp>(
21460965b46SAlex Zinenko       launchOp.getLoc(), kernelFunc, launchOp.getGridSizeOperandValues(),
215283b5e73SStephan Herhut       launchOp.getBlockSizeOperandValues(), operands);
21660965b46SAlex Zinenko   launchOp.erase();
21760965b46SAlex Zinenko }
21860965b46SAlex Zinenko 
21960965b46SAlex Zinenko namespace {
220b8676da1SChristian Sigg /// Pass that moves the kernel of each LaunchOp into its separate nested module.
221b8676da1SChristian Sigg ///
222b8676da1SChristian Sigg /// This pass moves the kernel code of each LaunchOp into a function created
223b8676da1SChristian Sigg /// inside a nested module. It also creates an external function of the same
224b8676da1SChristian Sigg /// name in the parent module.
225b8676da1SChristian Sigg ///
2269a52ea5cSTres Popp /// The gpu.modules are intended to be compiled to a cubin blob independently in
2279a52ea5cSTres Popp /// a separate pass. The external functions can then be annotated with the
228b8676da1SChristian Sigg /// symbol of the cubin accessor function.
229722f909fSRiver Riddle class GpuKernelOutliningPass
2301834ad4aSRiver Riddle     : public GpuKernelOutliningBase<GpuKernelOutliningPass> {
23160965b46SAlex Zinenko public:
232722f909fSRiver Riddle   void runOnOperation() override {
233722f909fSRiver Riddle     SymbolTable symbolTable(getOperation());
23490d65d32SAlex Zinenko     bool modified = false;
235722f909fSRiver Riddle     for (auto func : getOperation().getOps<FuncOp>()) {
236b8676da1SChristian Sigg       // Insert just after the function.
237b8676da1SChristian Sigg       Block::iterator insertPt(func.getOperation()->getNextNode());
2383f44495dSMaheshRavishankar       auto funcWalkResult = func.walk([&](gpu::LaunchOp op) {
239283b5e73SStephan Herhut         llvm::SetVector<Value> operands;
2403f44495dSMaheshRavishankar         std::string kernelFnName =
2413f44495dSMaheshRavishankar             Twine(op.getParentOfType<FuncOp>().getName(), "_kernel").str();
2423f44495dSMaheshRavishankar 
2433f44495dSMaheshRavishankar         // Pull in instructions that can be sunk
2443f44495dSMaheshRavishankar         if (failed(sinkOperationsIntoLaunchOp(op)))
2453f44495dSMaheshRavishankar           return WalkResult::interrupt();
2463f44495dSMaheshRavishankar         gpu::GPUFuncOp outlinedFunc =
2473f44495dSMaheshRavishankar             outlineKernelFuncImpl(op, kernelFnName, operands);
248b8676da1SChristian Sigg 
24990d65d32SAlex Zinenko         // Create nested module and insert outlinedFunc. The module will
25090d65d32SAlex Zinenko         // originally get the same name as the function, but may be renamed on
25190d65d32SAlex Zinenko         // insertion into the parent module.
252b8cd0c14STres Popp         auto kernelModule = createKernelModule(outlinedFunc, symbolTable);
253b8cd0c14STres Popp         symbolTable.insert(kernelModule, insertPt);
254b8676da1SChristian Sigg 
255b8676da1SChristian Sigg         // Potentially changes signature, pulling in constants.
256283b5e73SStephan Herhut         convertToLaunchFuncOp(op, outlinedFunc, operands.getArrayRef());
25790d65d32SAlex Zinenko         modified = true;
2583f44495dSMaheshRavishankar         return WalkResult::advance();
25960965b46SAlex Zinenko       });
2603f44495dSMaheshRavishankar       if (funcWalkResult.wasInterrupted())
2613f44495dSMaheshRavishankar         return signalPassFailure();
26260965b46SAlex Zinenko     }
26390d65d32SAlex Zinenko 
26490d65d32SAlex Zinenko     // If any new module was inserted in this module, annotate this module as
26590d65d32SAlex Zinenko     // a container module.
26690d65d32SAlex Zinenko     if (modified)
267722f909fSRiver Riddle       getOperation().setAttr(gpu::GPUDialect::getContainerModuleAttrName(),
26890d65d32SAlex Zinenko                              UnitAttr::get(&getContext()));
26960965b46SAlex Zinenko   }
27074cdbf59SChristian Sigg 
27174cdbf59SChristian Sigg private:
272*edeff6e6SStephan Herhut   /// Returns a gpu.module containing kernelFunc and all callees (recursive).
2739a52ea5cSTres Popp   gpu::GPUModuleOp createKernelModule(gpu::GPUFuncOp kernelFunc,
274b8cd0c14STres Popp                                       const SymbolTable &parentSymbolTable) {
2759a52ea5cSTres Popp     // TODO: This code cannot use an OpBuilder because it must be inserted into
2769a52ea5cSTres Popp     // a SymbolTable by the caller. SymbolTable needs to be refactored to
2779a52ea5cSTres Popp     // prevent manual building of Ops with symbols in code using SymbolTables
2789a52ea5cSTres Popp     // and then this needs to use the OpBuilder.
279722f909fSRiver Riddle     auto context = getOperation().getContext();
280bb1d976fSAlex Zinenko     OpBuilder builder(context);
2819a52ea5cSTres Popp     OperationState state(kernelFunc.getLoc(),
2829a52ea5cSTres Popp                          gpu::GPUModuleOp::getOperationName());
283bb1d976fSAlex Zinenko     gpu::GPUModuleOp::build(builder, state, kernelFunc.getName());
2849a52ea5cSTres Popp     auto kernelModule = cast<gpu::GPUModuleOp>(Operation::create(state));
285b8cd0c14STres Popp     SymbolTable symbolTable(kernelModule);
286b8cd0c14STres Popp     symbolTable.insert(kernelFunc);
28774cdbf59SChristian Sigg 
2884562e389SRiver Riddle     SmallVector<Operation *, 8> symbolDefWorklist = {kernelFunc};
2899fbf52e3SMLIR Team     while (!symbolDefWorklist.empty()) {
2909fbf52e3SMLIR Team       if (Optional<SymbolTable::UseRange> symbolUses =
2919fbf52e3SMLIR Team               SymbolTable::getSymbolUses(symbolDefWorklist.pop_back_val())) {
2929fbf52e3SMLIR Team         for (SymbolTable::SymbolUse symbolUse : *symbolUses) {
2939b9c647cSRiver Riddle           StringRef symbolName =
2949b9c647cSRiver Riddle               symbolUse.getSymbolRef().cast<FlatSymbolRefAttr>().getValue();
295b8cd0c14STres Popp           if (symbolTable.lookup(symbolName))
2969fbf52e3SMLIR Team             continue;
29774cdbf59SChristian Sigg 
2989fbf52e3SMLIR Team           Operation *symbolDefClone =
299b8cd0c14STres Popp               parentSymbolTable.lookup(symbolName)->clone();
3009fbf52e3SMLIR Team           symbolDefWorklist.push_back(symbolDefClone);
301b8cd0c14STres Popp           symbolTable.insert(symbolDefClone);
3029fbf52e3SMLIR Team         }
3039fbf52e3SMLIR Team       }
30474cdbf59SChristian Sigg     }
30574cdbf59SChristian Sigg 
30674cdbf59SChristian Sigg     return kernelModule;
30774cdbf59SChristian Sigg   }
30860965b46SAlex Zinenko };
30960965b46SAlex Zinenko 
31060965b46SAlex Zinenko } // namespace
31160965b46SAlex Zinenko 
31280aca1eaSRiver Riddle std::unique_ptr<OperationPass<ModuleOp>> mlir::createGpuKernelOutliningPass() {
31379f53b0cSJacques Pienaar   return std::make_unique<GpuKernelOutliningPass>();
31460965b46SAlex Zinenko }
315