22#include "llvm/Support/DebugLog.h"
23#include "llvm/Support/FormatVariadic.h"
34#define DEBUG_TYPE "omp-prepare-for-offload-privatization"
39#define GEN_PASS_DEF_PREPAREFOROMPOFFLOADPRIVATIZATIONPASS
40#include "mlir/Dialect/OpenMP/Transforms/Passes.h.inc"
52class PrepareForOMPOffloadPrivatizationPass
54 PrepareForOMPOffloadPrivatizationPass> {
56 void runOnOperation()
override {
57 ModuleOp mod = getOperation();
63 auto offloadModuleInterface =
64 dyn_cast<omp::OffloadModuleInterface>(mod.getOperation());
65 if (offloadModuleInterface && offloadModuleInterface.getIsTargetDevice())
68 getOperation()->walk([&](omp::TargetOp targetOp) {
69 if (!hasPrivateVars(targetOp) || !isTargetTaskDeferred(targetOp))
72 OperandRange privateVars = targetOp.getPrivateVars();
73 SmallVector<mlir::Value> newPrivVars;
75 omp::TaskOp cleanupTaskOp;
77 newPrivVars.reserve(privateVars.size());
78 std::optional<ArrayAttr> privateSyms = targetOp.getPrivateSyms();
79 for (
auto [privVarIdx, privVarSymPair] :
80 llvm::enumerate(llvm::zip_equal(privateVars, *privateSyms))) {
81 Value privVar = std::get<0>(privVarSymPair);
82 Attribute privSym = std::get<1>(privVarSymPair);
84 omp::PrivateClauseOp privatizer =
findPrivatizer(targetOp, privSym);
85 if (!privatizer.needsMap()) {
86 newPrivVars.push_back(privVar);
89 bool isFirstPrivate = privatizer.getDataSharingType() ==
90 omp::DataSharingClauseType::FirstPrivate;
92 Value mappedValue = targetOp.getMappedValueForPrivateVar(privVarIdx);
93 auto mapInfoOp = cast<omp::MapInfoOp>(mappedValue.
getDefiningOp());
95 if (mapInfoOp.getMapCaptureType() == omp::VariableCaptureKind::ByCopy) {
96 newPrivVars.push_back(privVar);
127 bool needsCleanupTask = !privatizer.getDeallocRegion().empty();
133 Value varPtr = mapInfoOp.getVarPtr();
134 Type varType = mapInfoOp.getVarPtrType();
135 bool isPrivatizedByValue =
136 !isa<LLVM::LLVMPointerType>(privVar.
getType());
138 assert(isa<LLVM::LLVMPointerType>(varPtr.
getType()));
140 allocateHeapMem(targetOp, varPtr, varType, mod, rewriter);
143 "Unable to allocate heap memory when trying to move "
144 "a private variable out of the stack and into the "
145 "heap for use by a deferred target task");
147 if (needsCleanupTask && !fakeDependVar)
148 fakeDependVar = heapMem;
158 if (!isPrivatizedByValue)
159 newPrivVars.push_back(heapMem);
169 if (varPtrDefiningOp) {
173 auto blockArg = cast<BlockArgument>(varPtr);
174 users.insert(blockArg.user_begin(), blockArg.user_end());
176 auto usesVarPtr = [&users](Operation *op) ->
bool {
177 return users.count(op);
180 SmallVector<Operation *> chainOfOps;
181 chainOfOps.push_back(mapInfoOp);
182 for (
auto member : mapInfoOp.getMembers()) {
183 omp::MapInfoOp memberMap =
184 cast<omp::MapInfoOp>(member.getDefiningOp());
185 if (usesVarPtr(memberMap))
186 chainOfOps.push_back(memberMap);
187 if (memberMap.getVarPtrPtr()) {
188 Operation *defOp = memberMap.getVarPtrPtr().getDefiningOp();
189 if (defOp && usesVarPtr(defOp))
190 chainOfOps.push_back(defOp);
195 llvm::sort(chainOfOps, [&](Operation *l, Operation *r) {
203 Operation *firstOp = chainOfOps.front();
204 Location loc = firstOp->
getLoc();
208 auto createAlwaysInlineFuncAndCallIt =
209 [&](Region ®ion, llvm::StringRef funcName,
210 llvm::ArrayRef<Value> args,
bool returnsValue) -> Value {
211 assert(!region.
empty() &&
"region cannot be empty");
212 LLVM::LLVMFuncOp func = createFuncOpForRegion(
213 loc, mod, region, funcName, rewriter, returnsValue);
214 auto call = LLVM::CallOp::create(rewriter, loc, func, args);
215 return call.getResult();
218 Value moldArg, newArg;
219 if (isPrivatizedByValue) {
220 moldArg = LLVM::LoadOp::create(rewriter, loc, varType, varPtr);
221 newArg = LLVM::LoadOp::create(rewriter, loc, varType, heapMem);
227 Value initializedVal;
228 if (!privatizer.getInitRegion().empty())
229 initializedVal = createAlwaysInlineFuncAndCallIt(
230 privatizer.getInitRegion(),
231 llvm::formatv(
"{0}_{1}", privatizer.getSymName(),
"init").str(),
232 {moldArg, newArg},
true);
234 initializedVal = newArg;
236 if (isFirstPrivate && !privatizer.getCopyRegion().empty())
237 initializedVal = createAlwaysInlineFuncAndCallIt(
238 privatizer.getCopyRegion(),
239 llvm::formatv(
"{0}_{1}", privatizer.getSymName(),
"copy").str(),
240 {moldArg, initializedVal},
true);
242 if (isPrivatizedByValue)
243 (void)LLVM::StoreOp::create(rewriter, loc, initializedVal, heapMem);
247 auto cloneModifyAndErase = [&](Operation *origOp) -> Operation * {
248 Operation *clonedOp = rewriter.
clone(*origOp);
261 mapInfoOp = cast<omp::MapInfoOp>(cloneModifyAndErase(mapInfoOp));
265 for (
auto member : mapInfoOp.getMembers()) {
266 auto memberMapInfoOp = cast<omp::MapInfoOp>(member.getDefiningOp());
267 if (!usesVarPtr(memberMapInfoOp))
270 cast<omp::MapInfoOp>(cloneModifyAndErase(memberMapInfoOp));
273 if (memberMapInfoOp.getVarPtrPtr()) {
274 Operation *varPtrPtrdefOp =
275 memberMapInfoOp.getVarPtrPtr().getDefiningOp();
285 if (isPrivatizedByValue) {
287 auto newPrivVar = LLVM::LoadOp::create(rewriter, mapInfoOp.getLoc(),
289 newPrivVars.push_back(newPrivVar);
293 if (needsCleanupTask) {
294 if (!cleanupTaskOp) {
295 assert(fakeDependVar &&
296 "Need a valid value to set up a dependency");
298 omp::TaskOperands taskOperands;
299 auto inDepend = omp::ClauseTaskDependAttr::get(
301 taskOperands.dependKinds.push_back(inDepend);
302 taskOperands.dependVars.push_back(fakeDependVar);
303 cleanupTaskOp = omp::TaskOp::create(rewriter, loc, taskOperands);
306 omp::TerminatorOp::create(rewriter, cleanupTaskOp.getLoc());
309 &*cleanupTaskOp.getRegion().getBlocks().begin());
310 (
void)createAlwaysInlineFuncAndCallIt(
311 privatizer.getDeallocRegion(),
312 llvm::formatv(
"{0}_{1}", privatizer.getSymName(),
"dealloc")
314 {initializedVal},
false);
315 llvm::FailureOr<LLVM::LLVMFuncOp> freeFunc =
317 assert(llvm::succeeded(freeFunc) &&
318 "Could not find free in the module");
319 (
void)LLVM::CallOp::create(rewriter, loc, freeFunc.value(),
323 assert(newPrivVars.size() == privateVars.size() &&
324 "The number of private variables must match before and after "
327 omp::ClauseTaskDependAttr outDepend = omp::ClauseTaskDependAttr::get(
328 rewriter.
getContext(), omp::ClauseTaskDepend::taskdependout);
330 if (!targetOp.getDependVars().empty()) {
331 std::optional<ArrayAttr> dependKinds = targetOp.getDependKinds();
332 assert(dependKinds &&
"bad depend clause in omp::TargetOp");
333 llvm::copy(*dependKinds, std::back_inserter(newDependKinds));
335 newDependKinds.push_back(outDepend);
336 ArrayAttr newDependKindsAttr =
337 ArrayAttr::get(rewriter.
getContext(), newDependKinds);
338 targetOp.getDependVarsMutable().append(fakeDependVar);
339 targetOp.setDependKindsAttr(newDependKindsAttr);
342 targetOp.getPrivateVarsMutable().clear();
343 targetOp.getPrivateVarsMutable().assign(newPrivVars);
348 bool hasPrivateVars(omp::TargetOp targetOp)
const {
349 return !targetOp.getPrivateVars().empty();
352 bool isTargetTaskDeferred(omp::TargetOp targetOp)
const {
353 return targetOp.getNowait();
356 template <
typename OpTy>
357 omp::PrivateClauseOp
findPrivatizer(OpTy op, Attribute privSym)
const {
358 SymbolRefAttr privatizerName = llvm::cast<SymbolRefAttr>(privSym);
359 omp::PrivateClauseOp privatizer =
367 std::int64_t
getSizeInBytes(
const DataLayout &dl, Type varType)
const {
371 LLVM::LLVMFuncOp getMalloc(ModuleOp mod, IRRewriter &rewriter)
const {
372 llvm::FailureOr<LLVM::LLVMFuncOp> mallocCall =
374 assert(llvm::succeeded(mallocCall) &&
375 "Could not find malloc in the module");
376 return mallocCall.value();
379 Value allocateHeapMem(omp::TargetOp targetOp, Value privVar, Type varType,
380 ModuleOp mod, IRRewriter &rewriter)
const {
381 OpBuilder::InsertionGuard guard(rewriter);
382 Value varPtr = privVar;
384 BlockArgument blockArg;
386 blockArg = mlir::dyn_cast<BlockArgument>(varPtr);
391 Location loc = definingOp ? definingOp->
getLoc() : blockArg.
getLoc();
392 LLVM::LLVMFuncOp mallocFn = getMalloc(mod, rewriter);
394 assert(mod.getDataLayoutSpec() &&
395 "MLIR module with no datalayout spec not handled yet");
397 const DataLayout &dl = DataLayout(mod);
400 Value sizeBytes = LLVM::ConstantOp::create(
401 rewriter, loc, mallocFn.getFunctionType().getParamType(0), distance);
404 LLVM::CallOp::create(rewriter, loc, mallocFn,
ValueRange{sizeBytes});
405 return mallocCallOp.getResult();
413 LLVM::LLVMFuncOp createFuncOpForRegion(Location loc, ModuleOp mod,
415 llvm::StringRef funcName,
416 IRRewriter &rewriter,
417 bool returnsValue =
false) {
419 OpBuilder::InsertionGuard guard(rewriter);
423 srcRegion.
cloneInto(&clonedRegion, mapper);
425 SmallVector<Type> paramTypes;
427 Type resultType = returnsValue
429 : LLVM::LLVMVoidType::get(rewriter.
getContext());
430 LLVM::LLVMFunctionType funcType =
431 LLVM::LLVMFunctionType::get(resultType, paramTypes);
433 LLVM::LLVMFuncOp func =
434 LLVM::LLVMFuncOp::create(rewriter, loc, funcName, funcType);
435 func.setAlwaysInline(
true);
437 func.getRegion().end());
438 for (
auto &block : func.getRegion().getBlocks()) {
439 if (isa<omp::YieldOp>(block.getTerminator())) {
440 omp::YieldOp yieldOp = cast<omp::YieldOp>(block.getTerminator());
443 yieldOp.getOperands());
static llvm::Value * getSizeInBytes(DataLayout &dl, const mlir::Type &type, Operation *clauseOp, llvm::Value *basePointer, llvm::Type *baseType, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static omp::PrivateClauseOp findPrivatizer(Operation *from, SymbolRefAttr symbolName)
Looks up from the operation from and returns the PrivateClauseOp with name symbolName.
Location getLoc() const
Return the location for this argument.
Block represents an ordered list of Operations.
MLIRContext * getContext() const
llvm::TypeSize getTypeAllocSize(Type t) const
Returns the offset in bytes between successive objects of the given type in the current scope,...
bool properlyDominates(Operation *a, Operation *b, bool enclosingOpOk=true) const
Return true if operation A properly dominates operation B, i.e.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
void replaceUsesOfWith(Value from, Value to)
Replace any uses of 'from' with 'to' within this operation.
Location getLoc()
The source location the operation was defined or derived from.
user_iterator user_begin()
void cloneInto(Region *dest, IRMapping &mapper)
Clone the internal blocks from this region into dest.
ValueTypeRange< BlockArgListType > getArgumentTypes()
Returns the argument types of the first block within the region.
BlockArgument getArgument(unsigned i)
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
void inlineRegionBefore(Region ®ion, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
void replaceAllOpUsesWith(Operation *from, ValueRange to)
Find uses of from and replace them with to.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
This class provides an abstraction over the different types of ranges over Values.
Type getType() const
Return the type of this value.
Block * getParentBlock()
Return the Block in which this Value is defined.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
FailureOr< LLVM::LLVMFuncOp > lookupOrCreateFreeFn(OpBuilder &b, Operation *moduleOp, SymbolTableCollection *symbolTables=nullptr)
FailureOr< LLVM::LLVMFuncOp > lookupOrCreateMallocFn(OpBuilder &b, Operation *moduleOp, Type indexType, SymbolTableCollection *symbolTables=nullptr)
Include the generated interface declarations.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet