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"
14a54f4eaeSMogball #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
15*32fe1a8aSDiego Caballero #include "mlir/Dialect/DLTI/DLTI.h"
1660965b46SAlex Zinenko #include "mlir/Dialect/GPU/GPUDialect.h"
1760965b46SAlex Zinenko #include "mlir/Dialect/GPU/Passes.h"
183f44495dSMaheshRavishankar #include "mlir/Dialect/GPU/Utils.h"
19e2310704SJulian Gross #include "mlir/Dialect/MemRef/IR/MemRef.h"
2069d757c0SRob Suderman #include "mlir/Dialect/StandardOps/IR/Ops.h"
2160965b46SAlex Zinenko #include "mlir/IR/BlockAndValueMapping.h"
2260965b46SAlex Zinenko #include "mlir/IR/Builders.h"
23b8cd0c14STres Popp #include "mlir/IR/SymbolTable.h"
24*32fe1a8aSDiego Caballero #include "mlir/Parser.h"
25edeff6e6SStephan Herhut #include "mlir/Support/LLVM.h"
26283b5e73SStephan Herhut #include "mlir/Transforms/RegionUtils.h"
2760965b46SAlex Zinenko 
2860965b46SAlex Zinenko using namespace mlir;
2960965b46SAlex Zinenko 
3060965b46SAlex Zinenko template <typename OpTy>
3160965b46SAlex Zinenko static void createForAllDimensions(OpBuilder &builder, Location loc,
32e62a6956SRiver Riddle                                    SmallVectorImpl<Value> &values) {
3360965b46SAlex Zinenko   for (StringRef dim : {"x", "y", "z"}) {
34e62a6956SRiver Riddle     Value v = builder.create<OpTy>(loc, builder.getIndexType(),
3560965b46SAlex Zinenko                                    builder.getStringAttr(dim));
3660965b46SAlex Zinenko     values.push_back(v);
3760965b46SAlex Zinenko   }
3860965b46SAlex Zinenko }
3960965b46SAlex Zinenko 
40edeff6e6SStephan Herhut /// Adds operations generating block/thread ids and grid/block dimensions at the
41edeff6e6SStephan Herhut /// beginning of the `launchFuncOpBody` region. Add mapping from argument in
42edeff6e6SStephan Herhut /// entry block of `launchOpBody`, to the corresponding result value of the
43edeff6e6SStephan Herhut /// added operations.
443f44495dSMaheshRavishankar static void injectGpuIndexOperations(Location loc, Region &launchFuncOpBody,
453f44495dSMaheshRavishankar                                      Region &launchOpBody,
463f44495dSMaheshRavishankar                                      BlockAndValueMapping &map) {
476273fa0cSAlex Zinenko   OpBuilder builder(loc->getContext());
483f44495dSMaheshRavishankar   Block &firstBlock = launchOpBody.front();
493f44495dSMaheshRavishankar   builder.setInsertionPointToStart(&launchFuncOpBody.front());
50e62a6956SRiver Riddle   SmallVector<Value, 12> indexOps;
516273fa0cSAlex Zinenko   createForAllDimensions<gpu::BlockIdOp>(builder, loc, indexOps);
526273fa0cSAlex Zinenko   createForAllDimensions<gpu::ThreadIdOp>(builder, loc, indexOps);
536273fa0cSAlex Zinenko   createForAllDimensions<gpu::GridDimOp>(builder, loc, indexOps);
546273fa0cSAlex Zinenko   createForAllDimensions<gpu::BlockDimOp>(builder, loc, indexOps);
5560965b46SAlex Zinenko   // Replace the leading 12 function args with the respective thread/block index
5660965b46SAlex Zinenko   // operations. Iterate backwards since args are erased and indices change.
573f44495dSMaheshRavishankar   for (auto indexOp : enumerate(indexOps))
583f44495dSMaheshRavishankar     map.map(firstBlock.getArgument(indexOp.index()), indexOp.value());
5960965b46SAlex Zinenko }
6060965b46SAlex Zinenko 
61edeff6e6SStephan Herhut /// Identifies operations that are beneficial to sink into kernels. These
62edeff6e6SStephan Herhut /// operations may not have side-effects, as otherwise sinking (and hence
63edeff6e6SStephan Herhut /// duplicating them) is not legal.
643f44495dSMaheshRavishankar static bool isSinkingBeneficiary(Operation *op) {
65a54f4eaeSMogball   return isa<arith::ConstantOp, ConstantOp, memref::DimOp, SelectOp,
66a54f4eaeSMogball              arith::CmpIOp>(op);
67edeff6e6SStephan Herhut }
68edeff6e6SStephan Herhut 
69edeff6e6SStephan Herhut /// For a given operation `op`, computes whether it is beneficial to sink the
70edeff6e6SStephan Herhut /// operation into the kernel. An operation can be sunk if doing so does not
71edeff6e6SStephan Herhut /// introduce new kernel arguments. Whether a value is already available in the
72edeff6e6SStephan Herhut /// kernel (and hence does not introduce new arguments) is checked by
73366d8435SStephan Herhut /// querying `existingDependencies` and `availableValues`.
74edeff6e6SStephan Herhut /// If an operand is not yet available, we recursively check whether it can be
75edeff6e6SStephan Herhut /// made available by siking its defining op.
76edeff6e6SStephan Herhut /// Operations that are indentified for sinking are added to `beneficiaryOps` in
77366d8435SStephan Herhut /// the order they should appear in the kernel. Furthermore, `availableValues`
78366d8435SStephan Herhut /// is updated with results that will be available after sinking the identified
79edeff6e6SStephan Herhut /// ops.
80366d8435SStephan Herhut static bool
814efb7754SRiver Riddle extractBeneficiaryOps(Operation *op, SetVector<Value> existingDependencies,
824efb7754SRiver Riddle                       SetVector<Operation *> &beneficiaryOps,
83366d8435SStephan Herhut                       llvm::SmallPtrSetImpl<Value> &availableValues) {
84edeff6e6SStephan Herhut   if (beneficiaryOps.count(op))
85edeff6e6SStephan Herhut     return true;
86edeff6e6SStephan Herhut 
87edeff6e6SStephan Herhut   if (!isSinkingBeneficiary(op))
88edeff6e6SStephan Herhut     return false;
89edeff6e6SStephan Herhut 
90edeff6e6SStephan Herhut   for (Value operand : op->getOperands()) {
9141b09f4eSKazuaki Ishizaki     // It is already visible in the kernel, keep going.
92edeff6e6SStephan Herhut     if (availableValues.count(operand))
93edeff6e6SStephan Herhut       continue;
94366d8435SStephan Herhut     // Else check whether it can be made available via sinking or already is a
95366d8435SStephan Herhut     // dependency.
96edeff6e6SStephan Herhut     Operation *definingOp = operand.getDefiningOp();
97366d8435SStephan Herhut     if ((!definingOp ||
98366d8435SStephan Herhut          !extractBeneficiaryOps(definingOp, existingDependencies,
99366d8435SStephan Herhut                                 beneficiaryOps, availableValues)) &&
100366d8435SStephan Herhut         !existingDependencies.count(operand))
101edeff6e6SStephan Herhut       return false;
102edeff6e6SStephan Herhut   }
103edeff6e6SStephan Herhut   // We will sink the operation, mark its results as now available.
104edeff6e6SStephan Herhut   beneficiaryOps.insert(op);
105edeff6e6SStephan Herhut   for (Value result : op->getResults())
106edeff6e6SStephan Herhut     availableValues.insert(result);
107edeff6e6SStephan Herhut   return true;
108abb62668SStephan Herhut }
109abb62668SStephan Herhut 
1103f44495dSMaheshRavishankar LogicalResult mlir::sinkOperationsIntoLaunchOp(gpu::LaunchOp launchOp) {
1113f44495dSMaheshRavishankar   Region &launchOpBody = launchOp.body();
112318ff019SStephan Herhut 
1133f44495dSMaheshRavishankar   // Identify uses from values defined outside of the scope of the launch
1143f44495dSMaheshRavishankar   // operation.
1154efb7754SRiver Riddle   SetVector<Value> sinkCandidates;
1163f44495dSMaheshRavishankar   getUsedValuesDefinedAbove(launchOpBody, sinkCandidates);
1173f44495dSMaheshRavishankar 
1184efb7754SRiver Riddle   SetVector<Operation *> toBeSunk;
119366d8435SStephan Herhut   llvm::SmallPtrSet<Value, 4> availableValues;
120366d8435SStephan Herhut   for (Value operand : sinkCandidates) {
1213f44495dSMaheshRavishankar     Operation *operandOp = operand.getDefiningOp();
122edeff6e6SStephan Herhut     if (!operandOp)
1233f44495dSMaheshRavishankar       continue;
124366d8435SStephan Herhut     extractBeneficiaryOps(operandOp, sinkCandidates, toBeSunk, availableValues);
125dfd06af5SStephan Herhut   }
1263f44495dSMaheshRavishankar 
1273f44495dSMaheshRavishankar   // Insert operations so that the defs get cloned before uses.
1283f44495dSMaheshRavishankar   BlockAndValueMapping map;
1293f44495dSMaheshRavishankar   OpBuilder builder(launchOpBody);
130edeff6e6SStephan Herhut   for (Operation *op : toBeSunk) {
131edeff6e6SStephan Herhut     Operation *clonedOp = builder.clone(*op, map);
1323f44495dSMaheshRavishankar     // Only replace uses within the launch op.
133edeff6e6SStephan Herhut     for (auto pair : llvm::zip(op->getResults(), clonedOp->getResults()))
134edeff6e6SStephan Herhut       replaceAllUsesInRegionWith(std::get<0>(pair), std::get<1>(pair),
135edeff6e6SStephan Herhut                                  launchOp.body());
1363f44495dSMaheshRavishankar   }
1373f44495dSMaheshRavishankar   return success();
138dfd06af5SStephan Herhut }
139dfd06af5SStephan Herhut 
140edeff6e6SStephan Herhut /// Outline the `gpu.launch` operation body into a kernel function. Replace
141edeff6e6SStephan Herhut /// `gpu.terminator` operations by `gpu.return` in the generated function.
1423f44495dSMaheshRavishankar static gpu::GPUFuncOp outlineKernelFuncImpl(gpu::LaunchOp launchOp,
1433f44495dSMaheshRavishankar                                             StringRef kernelFnName,
1444efb7754SRiver Riddle                                             SetVector<Value> &operands) {
14560965b46SAlex Zinenko   Location loc = launchOp.getLoc();
1466273fa0cSAlex Zinenko   // Create a builder with no insertion point, insertion will happen separately
1476273fa0cSAlex Zinenko   // due to symbol table manipulation.
1486273fa0cSAlex Zinenko   OpBuilder builder(launchOp.getContext());
1493f44495dSMaheshRavishankar   Region &launchOpBody = launchOp.body();
1506273fa0cSAlex Zinenko 
151283b5e73SStephan Herhut   // Identify uses from values defined outside of the scope of the launch
152283b5e73SStephan Herhut   // operation.
1533f44495dSMaheshRavishankar   getUsedValuesDefinedAbove(launchOpBody, operands);
154283b5e73SStephan Herhut 
1553f44495dSMaheshRavishankar   // Create the gpu.func operation.
156283b5e73SStephan Herhut   SmallVector<Type, 4> kernelOperandTypes;
157283b5e73SStephan Herhut   kernelOperandTypes.reserve(operands.size());
158283b5e73SStephan Herhut   for (Value operand : operands) {
159283b5e73SStephan Herhut     kernelOperandTypes.push_back(operand.getType());
160283b5e73SStephan Herhut   }
16160965b46SAlex Zinenko   FunctionType type =
1621b97cdf8SRiver Riddle       FunctionType::get(launchOp.getContext(), kernelOperandTypes, {});
1633f44495dSMaheshRavishankar   auto outlinedFunc = builder.create<gpu::GPUFuncOp>(loc, kernelFnName, type);
1641ffc1aaaSChristian Sigg   outlinedFunc->setAttr(gpu::GPUDialect::getKernelFuncAttrName(),
16560965b46SAlex Zinenko                         builder.getUnitAttr());
1663f44495dSMaheshRavishankar   BlockAndValueMapping map;
1673f44495dSMaheshRavishankar 
1683f44495dSMaheshRavishankar   // Map the arguments corresponding to the launch parameters like blockIdx,
1693f44495dSMaheshRavishankar   // threadIdx, etc.
1703f44495dSMaheshRavishankar   Region &outlinedFuncBody = outlinedFunc.body();
1713f44495dSMaheshRavishankar   injectGpuIndexOperations(loc, outlinedFuncBody, launchOpBody, map);
1723f44495dSMaheshRavishankar 
1733f44495dSMaheshRavishankar   // Map arguments from gpu.launch region to the arguments of the gpu.func
1743f44495dSMaheshRavishankar   // operation.
1753f44495dSMaheshRavishankar   Block &entryBlock = outlinedFuncBody.front();
1763f44495dSMaheshRavishankar   for (auto operand : enumerate(operands))
1773f44495dSMaheshRavishankar     map.map(operand.value(), entryBlock.getArgument(operand.index()));
1783f44495dSMaheshRavishankar 
1793f44495dSMaheshRavishankar   // Clone the region of the gpu.launch operation into the gpu.func operation.
1809db53a18SRiver Riddle   // TODO: If cloneInto can be modified such that if a mapping for
1813f44495dSMaheshRavishankar   // a block exists, that block will be used to clone operations into (at the
1823f44495dSMaheshRavishankar   // end of the block), instead of creating a new block, this would be much
1833f44495dSMaheshRavishankar   // cleaner.
1843f44495dSMaheshRavishankar   launchOpBody.cloneInto(&outlinedFuncBody, map);
1853f44495dSMaheshRavishankar 
1865aacce3dSKazuaki Ishizaki   // Branch from entry of the gpu.func operation to the block that is cloned
1875aacce3dSKazuaki Ishizaki   // from the entry block of the gpu.launch operation.
1883f44495dSMaheshRavishankar   Block &launchOpEntry = launchOpBody.front();
1893f44495dSMaheshRavishankar   Block *clonedLaunchOpEntry = map.lookup(&launchOpEntry);
1903f44495dSMaheshRavishankar   builder.setInsertionPointToEnd(&entryBlock);
1913f44495dSMaheshRavishankar   builder.create<BranchOp>(loc, clonedLaunchOpEntry);
1923f44495dSMaheshRavishankar 
19326927518SStephan Herhut   outlinedFunc.walk([](gpu::TerminatorOp op) {
19426927518SStephan Herhut     OpBuilder replacer(op);
19526927518SStephan Herhut     replacer.create<gpu::ReturnOp>(op.getLoc());
19626927518SStephan Herhut     op.erase();
19726927518SStephan Herhut   });
19860965b46SAlex Zinenko   return outlinedFunc;
19960965b46SAlex Zinenko }
20060965b46SAlex Zinenko 
2013f44495dSMaheshRavishankar gpu::GPUFuncOp mlir::outlineKernelFunc(gpu::LaunchOp launchOp,
2023f44495dSMaheshRavishankar                                        StringRef kernelFnName,
2033f44495dSMaheshRavishankar                                        llvm::SmallVectorImpl<Value> &operands) {
2043f44495dSMaheshRavishankar   DenseSet<Value> inputOperandSet;
2053f44495dSMaheshRavishankar   inputOperandSet.insert(operands.begin(), operands.end());
2064efb7754SRiver Riddle   SetVector<Value> operandSet(operands.begin(), operands.end());
2073f44495dSMaheshRavishankar   auto funcOp = outlineKernelFuncImpl(launchOp, kernelFnName, operandSet);
2083f44495dSMaheshRavishankar   for (auto operand : operandSet) {
2093f44495dSMaheshRavishankar     if (!inputOperandSet.count(operand))
2103f44495dSMaheshRavishankar       operands.push_back(operand);
2113f44495dSMaheshRavishankar   }
2123f44495dSMaheshRavishankar   return funcOp;
2133f44495dSMaheshRavishankar }
2143f44495dSMaheshRavishankar 
215edeff6e6SStephan Herhut /// Replace `gpu.launch` operations with an `gpu.launch_func` operation
216edeff6e6SStephan Herhut /// launching `kernelFunc`. The kernel func contains the body of the
217edeff6e6SStephan Herhut /// `gpu.launch` with constant region arguments inlined.
2183f44495dSMaheshRavishankar static void convertToLaunchFuncOp(gpu::LaunchOp launchOp,
219283b5e73SStephan Herhut                                   gpu::GPUFuncOp kernelFunc,
220283b5e73SStephan Herhut                                   ValueRange operands) {
22160965b46SAlex Zinenko   OpBuilder builder(launchOp);
22208b63db8SUday Bondhugula   // The launch op has an optional dynamic shared memory size. If it doesn't
22308b63db8SUday Bondhugula   // exist, we use zero.
2243f44495dSMaheshRavishankar   builder.create<gpu::LaunchFuncOp>(
22560965b46SAlex Zinenko       launchOp.getLoc(), kernelFunc, launchOp.getGridSizeOperandValues(),
22608b63db8SUday Bondhugula       launchOp.getBlockSizeOperandValues(), launchOp.dynamicSharedMemorySize(),
22708b63db8SUday Bondhugula       operands);
22860965b46SAlex Zinenko   launchOp.erase();
22960965b46SAlex Zinenko }
23060965b46SAlex Zinenko 
23160965b46SAlex Zinenko namespace {
232b8676da1SChristian Sigg /// Pass that moves the kernel of each LaunchOp into its separate nested module.
233b8676da1SChristian Sigg ///
234b8676da1SChristian Sigg /// This pass moves the kernel code of each LaunchOp into a function created
235b8676da1SChristian Sigg /// inside a nested module. It also creates an external function of the same
236b8676da1SChristian Sigg /// name in the parent module.
237b8676da1SChristian Sigg ///
2389a52ea5cSTres Popp /// The gpu.modules are intended to be compiled to a cubin blob independently in
2399a52ea5cSTres Popp /// a separate pass. The external functions can then be annotated with the
240b8676da1SChristian Sigg /// symbol of the cubin accessor function.
241722f909fSRiver Riddle class GpuKernelOutliningPass
2421834ad4aSRiver Riddle     : public GpuKernelOutliningBase<GpuKernelOutliningPass> {
24360965b46SAlex Zinenko public:
244*32fe1a8aSDiego Caballero   GpuKernelOutliningPass(StringRef dlStr) {
245*32fe1a8aSDiego Caballero     if (!dlStr.empty() && !dataLayoutStr.hasValue())
246*32fe1a8aSDiego Caballero       dataLayoutStr = dlStr.str();
247*32fe1a8aSDiego Caballero   }
248*32fe1a8aSDiego Caballero 
249*32fe1a8aSDiego Caballero   GpuKernelOutliningPass(const GpuKernelOutliningPass &other)
250*32fe1a8aSDiego Caballero       : dataLayoutSpec(other.dataLayoutSpec) {
251*32fe1a8aSDiego Caballero     dataLayoutStr = other.dataLayoutStr;
252*32fe1a8aSDiego Caballero   }
253*32fe1a8aSDiego Caballero 
254*32fe1a8aSDiego Caballero   LogicalResult initialize(MLIRContext *context) override {
255*32fe1a8aSDiego Caballero     // Initialize the data layout specification from the data layout string.
256*32fe1a8aSDiego Caballero     if (!dataLayoutStr.empty()) {
257*32fe1a8aSDiego Caballero       Attribute resultAttr = mlir::parseAttribute(dataLayoutStr, context);
258*32fe1a8aSDiego Caballero       if (!resultAttr)
259*32fe1a8aSDiego Caballero         return failure();
260*32fe1a8aSDiego Caballero 
261*32fe1a8aSDiego Caballero       dataLayoutSpec = resultAttr.dyn_cast<DataLayoutSpecInterface>();
262*32fe1a8aSDiego Caballero       if (!dataLayoutSpec)
263*32fe1a8aSDiego Caballero         return failure();
264*32fe1a8aSDiego Caballero     }
265*32fe1a8aSDiego Caballero 
266*32fe1a8aSDiego Caballero     return success();
267*32fe1a8aSDiego Caballero   }
268*32fe1a8aSDiego Caballero 
269722f909fSRiver Riddle   void runOnOperation() override {
270722f909fSRiver Riddle     SymbolTable symbolTable(getOperation());
27190d65d32SAlex Zinenko     bool modified = false;
272722f909fSRiver Riddle     for (auto func : getOperation().getOps<FuncOp>()) {
273b8676da1SChristian Sigg       // Insert just after the function.
274c4a04059SChristian Sigg       Block::iterator insertPt(func->getNextNode());
2753f44495dSMaheshRavishankar       auto funcWalkResult = func.walk([&](gpu::LaunchOp op) {
2764efb7754SRiver Riddle         SetVector<Value> operands;
2773f44495dSMaheshRavishankar         std::string kernelFnName =
2780bf4a82aSChristian Sigg             Twine(op->getParentOfType<FuncOp>().getName(), "_kernel").str();
2793f44495dSMaheshRavishankar 
2803f44495dSMaheshRavishankar         // Pull in instructions that can be sunk
2813f44495dSMaheshRavishankar         if (failed(sinkOperationsIntoLaunchOp(op)))
2823f44495dSMaheshRavishankar           return WalkResult::interrupt();
2833f44495dSMaheshRavishankar         gpu::GPUFuncOp outlinedFunc =
2843f44495dSMaheshRavishankar             outlineKernelFuncImpl(op, kernelFnName, operands);
285b8676da1SChristian Sigg 
28690d65d32SAlex Zinenko         // Create nested module and insert outlinedFunc. The module will
28790d65d32SAlex Zinenko         // originally get the same name as the function, but may be renamed on
28890d65d32SAlex Zinenko         // insertion into the parent module.
289b8cd0c14STres Popp         auto kernelModule = createKernelModule(outlinedFunc, symbolTable);
290b8cd0c14STres Popp         symbolTable.insert(kernelModule, insertPt);
291b8676da1SChristian Sigg 
292b8676da1SChristian Sigg         // Potentially changes signature, pulling in constants.
293283b5e73SStephan Herhut         convertToLaunchFuncOp(op, outlinedFunc, operands.getArrayRef());
29490d65d32SAlex Zinenko         modified = true;
2953f44495dSMaheshRavishankar         return WalkResult::advance();
29660965b46SAlex Zinenko       });
2973f44495dSMaheshRavishankar       if (funcWalkResult.wasInterrupted())
2983f44495dSMaheshRavishankar         return signalPassFailure();
29960965b46SAlex Zinenko     }
30090d65d32SAlex Zinenko 
30190d65d32SAlex Zinenko     // If any new module was inserted in this module, annotate this module as
30290d65d32SAlex Zinenko     // a container module.
30390d65d32SAlex Zinenko     if (modified)
3041ffc1aaaSChristian Sigg       getOperation()->setAttr(gpu::GPUDialect::getContainerModuleAttrName(),
30590d65d32SAlex Zinenko                               UnitAttr::get(&getContext()));
30660965b46SAlex Zinenko   }
30774cdbf59SChristian Sigg 
30874cdbf59SChristian Sigg private:
309edeff6e6SStephan Herhut   /// Returns a gpu.module containing kernelFunc and all callees (recursive).
3109a52ea5cSTres Popp   gpu::GPUModuleOp createKernelModule(gpu::GPUFuncOp kernelFunc,
311b8cd0c14STres Popp                                       const SymbolTable &parentSymbolTable) {
3129a52ea5cSTres Popp     // TODO: This code cannot use an OpBuilder because it must be inserted into
3139a52ea5cSTres Popp     // a SymbolTable by the caller. SymbolTable needs to be refactored to
3149a52ea5cSTres Popp     // prevent manual building of Ops with symbols in code using SymbolTables
3159a52ea5cSTres Popp     // and then this needs to use the OpBuilder.
316722f909fSRiver Riddle     auto context = getOperation().getContext();
317bb1d976fSAlex Zinenko     OpBuilder builder(context);
318e1364f10SMehdi Amini     auto kernelModule = builder.create<gpu::GPUModuleOp>(kernelFunc.getLoc(),
319e1364f10SMehdi Amini                                                          kernelFunc.getName());
320*32fe1a8aSDiego Caballero 
321*32fe1a8aSDiego Caballero     // If a valid data layout spec was provided, attach it to the kernel module.
322*32fe1a8aSDiego Caballero     // Otherwise, the default data layout will be used.
323*32fe1a8aSDiego Caballero     if (dataLayoutSpec)
324*32fe1a8aSDiego Caballero       kernelModule->setAttr("dlspec", dataLayoutSpec);
325*32fe1a8aSDiego Caballero 
326b8cd0c14STres Popp     SymbolTable symbolTable(kernelModule);
327b8cd0c14STres Popp     symbolTable.insert(kernelFunc);
32874cdbf59SChristian Sigg 
3294562e389SRiver Riddle     SmallVector<Operation *, 8> symbolDefWorklist = {kernelFunc};
3309fbf52e3SMLIR Team     while (!symbolDefWorklist.empty()) {
3319fbf52e3SMLIR Team       if (Optional<SymbolTable::UseRange> symbolUses =
3329fbf52e3SMLIR Team               SymbolTable::getSymbolUses(symbolDefWorklist.pop_back_val())) {
3339fbf52e3SMLIR Team         for (SymbolTable::SymbolUse symbolUse : *symbolUses) {
3349b9c647cSRiver Riddle           StringRef symbolName =
3359b9c647cSRiver Riddle               symbolUse.getSymbolRef().cast<FlatSymbolRefAttr>().getValue();
336b8cd0c14STres Popp           if (symbolTable.lookup(symbolName))
3379fbf52e3SMLIR Team             continue;
33874cdbf59SChristian Sigg 
3399fbf52e3SMLIR Team           Operation *symbolDefClone =
340b8cd0c14STres Popp               parentSymbolTable.lookup(symbolName)->clone();
3419fbf52e3SMLIR Team           symbolDefWorklist.push_back(symbolDefClone);
342b8cd0c14STres Popp           symbolTable.insert(symbolDefClone);
3439fbf52e3SMLIR Team         }
3449fbf52e3SMLIR Team       }
34574cdbf59SChristian Sigg     }
34674cdbf59SChristian Sigg 
34774cdbf59SChristian Sigg     return kernelModule;
34874cdbf59SChristian Sigg   }
349*32fe1a8aSDiego Caballero 
350*32fe1a8aSDiego Caballero   Option<std::string> dataLayoutStr{
351*32fe1a8aSDiego Caballero       *this, "data-layout-str",
352*32fe1a8aSDiego Caballero       llvm::cl::desc("String containing the data layout specification to be "
353*32fe1a8aSDiego Caballero                      "attached to the GPU kernel module")};
354*32fe1a8aSDiego Caballero 
355*32fe1a8aSDiego Caballero   DataLayoutSpecInterface dataLayoutSpec;
35660965b46SAlex Zinenko };
35760965b46SAlex Zinenko 
35860965b46SAlex Zinenko } // namespace
35960965b46SAlex Zinenko 
360*32fe1a8aSDiego Caballero std::unique_ptr<OperationPass<ModuleOp>>
361*32fe1a8aSDiego Caballero mlir::createGpuKernelOutliningPass(StringRef dataLayoutStr) {
362*32fe1a8aSDiego Caballero   return std::make_unique<GpuKernelOutliningPass>(dataLayoutStr);
36360965b46SAlex Zinenko }
364