MLIR 24.0.0git
HostOpFiltering.cpp
Go to the documentation of this file.
1//===- HostOpFiltering.cpp ------------------------------------------------===//
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 transforms to swap stack allocations on the target
10// device with device shared memory where applicable.
11//
12//===----------------------------------------------------------------------===//
13
15
20
21namespace mlir {
22namespace omp {
23#define GEN_PASS_DEF_HOSTOPFILTERINGPASS
24#include "mlir/Dialect/OpenMP/Transforms/Passes.h.inc"
25} // namespace omp
26} // namespace mlir
27
28using namespace mlir;
29
30/// Some host operations, like \c llvm.mlir.addressof and constants, must remain
31/// in the device module because they impact how device code is generated when
32/// attached to an \c omp.target operation.
33///
34/// This function identifies the operations that need this special handling.
35/// This includes cast-style operations to avoid losing information about the
36/// original source of an operand.
37static bool keepHostOpInDevice(Operation &op) {
38 return isPure(&op) &&
39 op.getDialect() ==
40 op.getContext()->getLoadedDialect<LLVM::LLVMDialect>();
41}
42
43/// Add an \c omp.map.info operation and all its members recursively to the
44/// output set to be later rewritten.
45///
46/// Dependencies across \c omp.map.info are maintained by ensuring dependencies
47/// are added to the output sets before operations based on them.
48static void collectRewrite(omp::MapInfoOp mapOp,
50 for (Value member : mapOp.getMembers())
51 collectRewrite(cast<omp::MapInfoOp>(member.getDefiningOp()), rewrites);
52
53 rewrites.insert(mapOp);
54}
55
56/// Add the given value to a sorted set if it should be replaced by a
57/// placeholder when used as an operand that must remain for the device.
58///
59/// Values that are block arguments of function operations are skipped, since
60/// they will still be available after all rewrites are completed, and operands
61/// of operations that need to remain on the host are recursively collected.
62static void collectRewrite(Value value, llvm::SetVector<Value> &rewrites) {
63 if ((isa<BlockArgument>(value) &&
64 isa<FunctionOpInterface>(
65 cast<BlockArgument>(value).getOwner()->getParentOp())) ||
66 rewrites.contains(value))
67 return;
68
69 Operation *op = value.getDefiningOp();
70 if (op && keepHostOpInDevice(*op))
71 for (Value operand : op->getOperands())
72 collectRewrite(operand, rewrites);
73
74 rewrites.insert(value);
75}
76
77/// Provide the \c device_type of an \c omp.declare_target attribute, if
78/// defined.
79static std::optional<omp::DeclareTargetDeviceType>
81 auto declareTargetOp = dyn_cast<omp::DeclareTargetInterface>(op);
82 omp::DeclareTargetAttr declareTargetAttr =
83 declareTargetOp ? declareTargetOp.getDeclareTarget() : nullptr;
84 if (declareTargetAttr)
85 return declareTargetAttr.getDeviceType();
86 return std::nullopt;
87}
88
89namespace {
90class HostOpFilteringPass
91 : public omp::impl::HostOpFilteringPassBase<HostOpFilteringPass> {
92public:
93 HostOpFilteringPass() = default;
94
95 void runOnOperation() override {
96 auto op = dyn_cast<omp::OffloadModuleInterface>(getOperation());
97 if (!op || !op.getIsTargetDevice())
98 return;
99
100 op->walk<WalkOrder::PreOrder>([&](LLVM::LLVMFuncOp funcOp) {
101 omp::DeclareTargetDeviceType declareType =
102 getDeclareTargetDevice(*funcOp.getOperation())
103 .value_or(omp::DeclareTargetDeviceType::host);
104
105 // Only process host function definitions.
106 if (funcOp.isExternal() ||
107 declareType != omp::DeclareTargetDeviceType::host)
108 return WalkResult::advance();
109
110 if (failed(rewriteHostFunction(funcOp))) {
111 funcOp.emitOpError() << "could not filter host-only operations";
112 return WalkResult::interrupt();
113 }
114 return WalkResult::advance();
115 });
116
117 // Make non-declare target globals internal for the device. They cannot be
118 // deleted, because they are needed in order to properly lower map clauses.
119 // However, no uses will remain in the device module, so we make them
120 // internal to prevent link time redefinitions.
121 op->walk([&](LLVM::GlobalOp globalOp) {
122 if (!getDeclareTargetDevice(*globalOp.getOperation()).has_value())
123 globalOp.setLinkage(LLVM::Linkage::Internal);
124 });
125 }
126
127private:
128 /// Rewrite the given host device function containing \c omp.target
129 /// operations, to remove host-only operations that are not used by device
130 /// codegen.
131 ///
132 /// It is based on the expected form of an MLIR module lowered to where it can
133 /// be directly translated to LLVM IR and it performs the following mutations:
134 /// - Removes all returned values from the function.
135 /// - \c omp.target operations are moved to the end of the function. If they
136 /// are nested inside of any other operations, they are hoisted out of
137 /// them.
138 /// - \c depend, \c device, \c dyn_groupprivate, \c if and \c in_reduction
139 /// clauses are removed from these target functions. Values used to
140 /// initialize other clauses are replaced by placeholders as follows:
141 /// - Values defined by block arguments are replaced by placeholders only
142 /// if they are not attached to the parent function. In that case, they
143 /// are passed unmodified.
144 /// - Pure operations of the LLVM dialect are maintained, and any value
145 /// operands they might have are also replaced by placeholders following
146 /// the same rules.
147 /// - Other values are replaced by new function arguments.
148 /// - \c omp.map.info operations associated to these target regions are
149 /// preserved. These are moved above all \c omp.target and sorted to
150 /// satisfy dependencies among them.
151 /// - \c bounds arguments are removed from \c omp.map.info operations.
152 /// - \c var_ptr and \c var_ptr_ptr arguments of \c omp.map.info are
153 /// replaced by placeholders as described above.
154 /// - Every other operation not located inside of an \c omp.target is
155 /// removed.
156 LogicalResult rewriteHostFunction(LLVM::LLVMFuncOp funcOp) {
157 Region &region = funcOp.getFunctionBody();
158 LLVM::LLVMFunctionType functionType = funcOp.getFunctionType();
159
160 // Collect target operations inside of the function.
162 region.walk<WalkOrder::PreOrder>([&](Operation *op) {
163 // Skip the inside of omp.target regions, since these contain device code.
164 if (auto targetOp = dyn_cast<omp::TargetOp>(op)) {
165 targetOps.push_back(targetOp);
166 return WalkResult::skip();
167 }
168
169 // Replace omp.target_data entry block argument uses with the value used
170 // to initialize the associated omp.map.info operation. This way,
171 // references are still valid once the omp.target operation has been
172 // extracted out of the omp.target_data region.
173 if (auto targetDataOp = dyn_cast<omp::TargetDataOp>(op)) {
175 cast<omp::BlockArgOpenMPOpInterface>(*targetDataOp)
176 .getBlockArgsPairs(argPairs);
177 for (auto [operand, blockArg] : argPairs) {
178 auto mapInfo = cast<omp::MapInfoOp>(operand.getDefiningOp());
179 blockArg.replaceAllUsesWith(mapInfo.getVarPtr());
180 }
181 }
182 return WalkResult::advance();
183 });
184
185 // Make a temporary clone of the parent function with an empty region,
186 // and update all references to entry block arguments to those of the new
187 // region. Users of these arguments will later either be moved to the new
188 // region or deleted when the original region is replaced by the new.
189 OpBuilder builder(&getContext());
190 builder.setInsertionPointAfter(funcOp);
191 Operation *newFuncOp = builder.cloneWithoutRegions(funcOp);
192 Block &block = newFuncOp->getRegion(0).emplaceBlock();
193
195 locs.reserve(region.getNumArguments());
196 llvm::transform(region.getArguments(), std::back_inserter(locs),
197 [](const BlockArgument &arg) { return arg.getLoc(); });
198 block.addArguments(region.getArgumentTypes(), locs);
199
200 for (auto [oldArg, newArg] :
201 llvm::zip_equal(region.getArguments(), block.getArguments()))
202 oldArg.replaceAllUsesWith(newArg);
203
204 // Collect omp.map.info ops while satisfying interdependencies and remove
205 // operands that aren't used by target device codegen.
206 //
207 // This logic must be updated whenever operands to omp.target change.
208 llvm::SetVector<Value> rewriteValues;
210 for (omp::TargetOp targetOp : targetOps) {
211 assert(targetOp.getHostEvalVars().empty() &&
212 "unexpected host_eval in target device module");
213
214 // Variables unused by the device.
215 targetOp.getDependVarsMutable().clear();
216 targetOp.setDependKindsAttr(nullptr);
217 targetOp.getDependIteratedMutable().clear();
218 targetOp.setDependIteratedKindsAttr(nullptr);
219 targetOp.getDeviceMutable().clear();
220 targetOp.getDynGroupprivateSizeMutable().clear();
221 targetOp.setDynGroupprivateAccessGroupAttr(nullptr);
222 targetOp.setDynGroupprivateFallbackAttr(nullptr);
223 targetOp.getIfExprMutable().clear();
224 targetOp.getInReductionVarsMutable().clear();
225 targetOp.setInReductionByrefAttr(nullptr);
226 targetOp.setInReductionSymsAttr(nullptr);
227
228 // TODO: Clear some of these operands rather than rewriting them,
229 // depending on whether they are needed by device codegen once support for
230 // them is fully implemented.
231 for (Value allocVar : targetOp.getAllocateVars())
232 collectRewrite(allocVar, rewriteValues);
233 for (Value allocVar : targetOp.getAllocatorVars())
234 collectRewrite(allocVar, rewriteValues);
235 for (Value isDevPtr : targetOp.getIsDevicePtrVars())
236 collectRewrite(isDevPtr, rewriteValues);
237 for (Value mapVar : targetOp.getHasDeviceAddrVars())
238 collectRewrite(cast<omp::MapInfoOp>(mapVar.getDefiningOp()), mapInfos);
239 for (Value mapVar : targetOp.getMapVars())
240 collectRewrite(cast<omp::MapInfoOp>(mapVar.getDefiningOp()), mapInfos);
241 for (Value privateVar : targetOp.getPrivateVars())
242 collectRewrite(privateVar, rewriteValues);
243 for (Value threadLimit : targetOp.getThreadLimitVars())
244 collectRewrite(threadLimit, rewriteValues);
245 }
246
247 // Move omp.map.info ops to the new block and collect dependencies.
248 for (omp::MapInfoOp mapOp : mapInfos) {
249 collectRewrite(mapOp.getVarPtr(), rewriteValues);
250
251 if (Value varPtrPtr = mapOp.getVarPtrPtr())
252 collectRewrite(varPtrPtr, rewriteValues);
253
254 // Bounds are not used during target device codegen.
255 mapOp.getBoundsMutable().clear();
256 mapOp->moveBefore(&block, block.end());
257 }
258
259 builder.setInsertionPointToStart(&block);
260
261 // We don't actually need the proper initialization for all operands, but
262 // rather just to maintain the basic form of omp.target operations. We
263 // create new function arguments as placeholders for rewritten values.
264 llvm::SmallVector<Type> newFnArgTypes(functionType.getParams());
265 for (Value value : rewriteValues) {
266 Value rewriteValue;
267 Operation *definingOp = value.getDefiningOp();
268 if (definingOp && keepHostOpInDevice(*definingOp)) {
269 rewriteValue = builder.clone(*value.getDefiningOp())->getResult(0);
270 } else {
271 rewriteValue = block.addArgument(value.getType(), value.getLoc());
272 newFnArgTypes.push_back(rewriteValue.getType());
273 }
274 value.replaceAllUsesWith(rewriteValue);
275 }
276
277 // Move target operations to the end of the new block.
278 for (omp::TargetOp targetOp : targetOps)
279 targetOp->moveBefore(&block, block.end());
280
281 // Add terminator to the new block.
282 builder.setInsertionPointToEnd(&block);
283 LLVM::ReturnOp::create(builder, funcOp.getLoc(), ValueRange());
284
285 // Replace old region with the new one, now only containing the required
286 // operations, and remove the temporary operation clone.
287 region.takeBody(newFuncOp->getRegion(0));
288 newFuncOp->erase();
289
290 // Update function type after modifying the terminator and argument list.
291 funcOp.setType(LLVM::LLVMFunctionType::get(
292 LLVM::LLVMVoidType::get(&getContext()), newFnArgTypes));
293
294 return success();
295 }
296};
297} // namespace
return success()
static std::optional< omp::DeclareTargetDeviceType > getDeclareTargetDevice(Operation &op)
Provide the device_type of an omp.declare_target attribute, if defined.
static bool keepHostOpInDevice(Operation &op)
Some host operations, like llvm.mlir.addressof and constants, must remain in the device module becaus...
static void collectRewrite(omp::MapInfoOp mapOp, llvm::SetVector< omp::MapInfoOp > &rewrites)
Add an omp.map.info operation and all its members recursively to the output set to be later rewritten...
b getContext())
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
iterator_range< args_iterator > addArguments(TypeRange types, ArrayRef< Location > locs)
Add one argument to the argument list for each type specified in the list.
Definition Block.cpp:165
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition Block.cpp:158
BlockArgListType getArguments()
Definition Block.h:112
iterator end()
Definition Block.h:169
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
This class helps build Operations.
Definition Builders.h:210
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition Operation.h:237
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:740
Operation * cloneWithoutRegions(IRMapping &mapper)
Create a partial copy of this operation without traversing into attached regions.
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
void erase()
Remove this operation from its parent block and delete it.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
BlockArgListType getArguments()
Definition Region.h:94
Block & emplaceBlock()
Definition Region.h:46
unsigned getNumArguments()
Definition Region.h:136
ValueTypeRange< BlockArgListType > getArgumentTypes()
Returns the argument types of the first block within the region.
Definition Region.cpp:36
void takeBody(Region &other)
Takes body of another region (that region will have no body after this operation completes).
Definition Region.h:253
RetT walk(FnT &&callback)
Walk all nested operations, blocks or regions (including this region), depending on the type of callb...
Definition Region.h:297
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static WalkResult skip()
Definition WalkResult.h:48
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.