Skip to content

Commit 4d20a42

Browse files
committed
[MLIR][OpenMP] Add host_eval clause to omp.target
This patch adds the `host_eval` clause to the `omp.target` operation. Additionally, it updates its op verifier to make sure all uses of block arguments defined by this clause fall within one of the few cases where they are allowed. MLIR to LLVM IR translation fails on translation of this clause with a not-yet-implemented error.
1 parent d74cf35 commit 4d20a42

File tree

7 files changed

+371
-15
lines changed

7 files changed

+371
-15
lines changed

mlir/docs/Dialects/OpenMPDialect/_index.md

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,8 @@ introduction of private copies of the same underlying variable defined outside
298298
the MLIR operation the clause is attached to. Currently, clauses with this
299299
property can be classified into three main categories:
300300
- Map-like clauses: `host_eval` (compiler internal, not defined by the OpenMP
301-
specification), `map`, `use_device_addr` and `use_device_ptr`.
301+
specification: [see more](#host-evaluated-clauses-in-target-regions)), `map`,
302+
`use_device_addr` and `use_device_ptr`.
302303
- Reduction-like clauses: `in_reduction`, `reduction` and `task_reduction`.
303304
- Privatization clauses: `private`.
304305

@@ -523,3 +524,58 @@ omp.parallel ... {
523524
omp.terminator
524525
} {omp.composite}
525526
```
527+
528+
## Host-Evaluated Clauses in Target Regions
529+
530+
The `omp.target` operation, which represents the OpenMP `target` construct, is
531+
marked with the `IsolatedFromAbove` trait. This means that, inside of its
532+
region, no MLIR values defined outside of the op itself can be used. This is
533+
consistent with the OpenMP specification of the `target` construct, which
534+
mandates that all host device values used inside of the `target` region must
535+
either be privatized (data-sharing) or mapped (data-mapping).
536+
537+
Normally, clauses applied to a construct are evaluated before entering that
538+
construct. Further, in some cases, the OpenMP specification stipulates that
539+
clauses be evaluated _on the host device_ on entry to a parent `target`
540+
construct. In particular, the `num_teams` and `thread_limit` clauses of the
541+
`teams` construct must be evaluated on the host device if it's nested inside or
542+
combined with a `target` construct.
543+
544+
Additionally, the runtime library targeted by the MLIR to LLVM IR translation of
545+
the OpenMP dialect supports the optimized launch of SPMD kernels (i.e.
546+
`target teams distribute parallel {do,for}` in OpenMP), which requires
547+
specifying in advance what the total trip count of the loop is. Consequently, it
548+
is also beneficial to evaluate the trip count on the host device prior to the
549+
kernel launch.
550+
551+
These host-evaluated values in MLIR would need to be placed outside of the
552+
`omp.target` region and also attached to the corresponding nested operations,
553+
which is not possible because of the `IsolatedFromAbove` trait. The solution
554+
implemented to address this problem has been to introduce the `host_eval`
555+
argument to the `omp.target` operation. It works similarly to a `map` clause,
556+
but its only intended use is to forward host-evaluated values to their
557+
corresponding operation inside of the region. Any uses outside of the previously
558+
described result in a verifier error.
559+
560+
```mlir
561+
// Initialize %0, %1, %2, %3...
562+
omp.target host_eval(%0 -> %nt, %1 -> %lb, %2 -> %ub, %3 -> %step : i32, i32, i32, i32) {
563+
omp.teams num_teams(to %nt : i32) {
564+
omp.parallel {
565+
omp.distribute {
566+
omp.wsloop {
567+
omp.loop_nest (%iv) : i32 = (%lb) to (%ub) step (%step) {
568+
// ...
569+
omp.yield
570+
}
571+
omp.terminator
572+
} {omp.composite}
573+
omp.terminator
574+
} {omp.composite}
575+
omp.terminator
576+
} {omp.composite}
577+
omp.terminator
578+
}
579+
omp.terminator
580+
}
581+
```

mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1213,9 +1213,10 @@ def TargetOp : OpenMP_Op<"target", traits = [
12131213
], clauses = [
12141214
// TODO: Complete clause list (defaultmap, uses_allocators).
12151215
OpenMP_AllocateClause, OpenMP_DependClause, OpenMP_DeviceClause,
1216-
OpenMP_HasDeviceAddrClause, OpenMP_IfClause, OpenMP_InReductionClause,
1217-
OpenMP_IsDevicePtrClause, OpenMP_MapClauseSkip<assemblyFormat = true>,
1218-
OpenMP_NowaitClause, OpenMP_PrivateClause, OpenMP_ThreadLimitClause
1216+
OpenMP_HasDeviceAddrClause, OpenMP_HostEvalClause, OpenMP_IfClause,
1217+
OpenMP_InReductionClause, OpenMP_IsDevicePtrClause,
1218+
OpenMP_MapClauseSkip<assemblyFormat = true>, OpenMP_NowaitClause,
1219+
OpenMP_PrivateClause, OpenMP_ThreadLimitClause
12191220
], singleRegion = true> {
12201221
let summary = "target construct";
12211222
let description = [{
@@ -1257,17 +1258,34 @@ def TargetOp : OpenMP_Op<"target", traits = [
12571258

12581259
return getMapVars()[mapInfoOpIdx];
12591260
}
1261+
1262+
/// Returns the innermost OpenMP dialect operation captured by this target
1263+
/// construct. For an operation to be detected as captured, it must be
1264+
/// inside a (possibly multi-level) nest of OpenMP dialect operation's
1265+
/// regions where none of these levels contain other operations considered
1266+
/// not-allowed for these purposes (i.e. only terminator operations are
1267+
/// allowed from the OpenMP dialect, and other dialect's operations are
1268+
/// allowed as long as they don't have a memory write effect).
1269+
///
1270+
/// If there are omp.loop_nest operations in the sequence of nested
1271+
/// operations, the top level one will be the one captured.
1272+
Operation *getInnermostCapturedOmpOp();
1273+
1274+
/// Checks whether this target region represents the MLIR equivalent to a
1275+
/// 'target teams distribute parallel {do, for} [simd]' OpenMP construct.
1276+
bool isTargetSPMDLoop();
12601277
}] # clausesExtraClassDeclaration;
12611278

12621279
let assemblyFormat = clausesAssemblyFormat # [{
1263-
custom<InReductionMapPrivateRegion>(
1264-
$region, $in_reduction_vars, type($in_reduction_vars),
1265-
$in_reduction_byref, $in_reduction_syms, $map_vars, type($map_vars),
1266-
$private_vars, type($private_vars), $private_syms, $private_maps)
1267-
attr-dict
1280+
custom<HostEvalInReductionMapPrivateRegion>(
1281+
$region, $host_eval_vars, type($host_eval_vars), $in_reduction_vars,
1282+
type($in_reduction_vars), $in_reduction_byref, $in_reduction_syms,
1283+
$map_vars, type($map_vars), $private_vars, type($private_vars),
1284+
$private_syms, $private_maps) attr-dict
12681285
}];
12691286

12701287
let hasVerifier = 1;
1288+
let hasRegionVerifier = 1;
12711289
}
12721290

12731291

mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp

Lines changed: 163 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -691,8 +691,10 @@ static ParseResult parseBlockArgRegion(OpAsmParser &parser, Region &region,
691691
return parser.parseRegion(region, entryBlockArgs);
692692
}
693693

694-
static ParseResult parseInReductionMapPrivateRegion(
694+
static ParseResult parseHostEvalInReductionMapPrivateRegion(
695695
OpAsmParser &parser, Region &region,
696+
SmallVectorImpl<OpAsmParser::UnresolvedOperand> &hostEvalVars,
697+
SmallVectorImpl<Type> &hostEvalTypes,
696698
SmallVectorImpl<OpAsmParser::UnresolvedOperand> &inReductionVars,
697699
SmallVectorImpl<Type> &inReductionTypes,
698700
DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms,
@@ -702,6 +704,7 @@ static ParseResult parseInReductionMapPrivateRegion(
702704
llvm::SmallVectorImpl<Type> &privateTypes, ArrayAttr &privateSyms,
703705
DenseI64ArrayAttr &privateMaps) {
704706
AllRegionParseArgs args;
707+
args.hostEvalArgs.emplace(hostEvalVars, hostEvalTypes);
705708
args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
706709
inReductionByref, inReductionSyms);
707710
args.mapArgs.emplace(mapVars, mapTypes);
@@ -931,13 +934,15 @@ static void printBlockArgRegion(OpAsmPrinter &p, Operation *op, Region &region,
931934
p.printRegion(region, /*printEntryBlockArgs=*/false);
932935
}
933936

934-
static void printInReductionMapPrivateRegion(
935-
OpAsmPrinter &p, Operation *op, Region &region, ValueRange inReductionVars,
937+
static void printHostEvalInReductionMapPrivateRegion(
938+
OpAsmPrinter &p, Operation *op, Region &region, ValueRange hostEvalVars,
939+
TypeRange hostEvalTypes, ValueRange inReductionVars,
936940
TypeRange inReductionTypes, DenseBoolArrayAttr inReductionByref,
937941
ArrayAttr inReductionSyms, ValueRange mapVars, TypeRange mapTypes,
938942
ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms,
939943
DenseI64ArrayAttr privateMaps) {
940944
AllRegionPrintArgs args;
945+
args.hostEvalArgs.emplace(hostEvalVars, hostEvalTypes);
941946
args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
942947
inReductionByref, inReductionSyms);
943948
args.mapArgs.emplace(mapVars, mapTypes);
@@ -1719,7 +1724,8 @@ void TargetOp::build(OpBuilder &builder, OperationState &state,
17191724
// inReductionByref, inReductionSyms.
17201725
TargetOp::build(builder, state, /*allocate_vars=*/{}, /*allocator_vars=*/{},
17211726
makeArrayAttr(ctx, clauses.dependKinds), clauses.dependVars,
1722-
clauses.device, clauses.hasDeviceAddrVars, clauses.ifExpr,
1727+
clauses.device, clauses.hasDeviceAddrVars,
1728+
clauses.hostEvalVars, clauses.ifExpr,
17231729
/*in_reduction_vars=*/{}, /*in_reduction_byref=*/nullptr,
17241730
/*in_reduction_syms=*/nullptr, clauses.isDevicePtrVars,
17251731
clauses.mapVars, clauses.nowait, clauses.privateVars,
@@ -1742,6 +1748,159 @@ LogicalResult TargetOp::verify() {
17421748
return verifyPrivateVarsMapping(*this);
17431749
}
17441750

1751+
LogicalResult TargetOp::verifyRegions() {
1752+
auto teamsOps = getOps<TeamsOp>();
1753+
if (std::distance(teamsOps.begin(), teamsOps.end()) > 1)
1754+
return emitError("target containing multiple 'omp.teams' nested ops");
1755+
1756+
// Check that host_eval values are only used in legal ways.
1757+
bool isTargetSPMD = isTargetSPMDLoop();
1758+
for (Value hostEvalArg :
1759+
cast<BlockArgOpenMPOpInterface>(getOperation()).getHostEvalBlockArgs()) {
1760+
for (Operation *user : hostEvalArg.getUsers()) {
1761+
if (auto teamsOp = dyn_cast<TeamsOp>(user)) {
1762+
if (llvm::is_contained({teamsOp.getNumTeamsLower(),
1763+
teamsOp.getNumTeamsUpper(),
1764+
teamsOp.getThreadLimit()},
1765+
hostEvalArg))
1766+
continue;
1767+
1768+
return emitOpError() << "host_eval argument only legal as 'num_teams' "
1769+
"and 'thread_limit' in 'omp.teams'";
1770+
}
1771+
if (auto parallelOp = dyn_cast<ParallelOp>(user)) {
1772+
if (isTargetSPMD && hostEvalArg == parallelOp.getNumThreads())
1773+
continue;
1774+
1775+
return emitOpError()
1776+
<< "host_eval argument only legal as 'num_threads' in "
1777+
"'omp.parallel' when representing target SPMD";
1778+
}
1779+
if (auto loopNestOp = dyn_cast<LoopNestOp>(user)) {
1780+
if (isTargetSPMD &&
1781+
(llvm::is_contained(loopNestOp.getLoopLowerBounds(), hostEvalArg) ||
1782+
llvm::is_contained(loopNestOp.getLoopUpperBounds(), hostEvalArg) ||
1783+
llvm::is_contained(loopNestOp.getLoopSteps(), hostEvalArg)))
1784+
continue;
1785+
1786+
return emitOpError()
1787+
<< "host_eval argument only legal as loop bounds and steps in "
1788+
"'omp.loop_nest' when representing target SPMD";
1789+
}
1790+
1791+
return emitOpError() << "host_eval argument illegal use in '"
1792+
<< user->getName() << "' operation";
1793+
}
1794+
}
1795+
return success();
1796+
}
1797+
1798+
/// Only allow OpenMP terminators and non-OpenMP ops that have known memory
1799+
/// effects, but don't include a memory write effect.
1800+
static bool siblingAllowedInCapture(Operation *op) {
1801+
if (!op)
1802+
return false;
1803+
1804+
bool isOmpDialect =
1805+
op->getContext()->getLoadedDialect<omp::OpenMPDialect>() ==
1806+
op->getDialect();
1807+
1808+
if (isOmpDialect)
1809+
return op->hasTrait<OpTrait::IsTerminator>();
1810+
1811+
if (auto memOp = dyn_cast<MemoryEffectOpInterface>(op)) {
1812+
SmallVector<SideEffects::EffectInstance<MemoryEffects::Effect>, 4> effects;
1813+
memOp.getEffects(effects);
1814+
return !llvm::any_of(effects, [&](MemoryEffects::EffectInstance &effect) {
1815+
return isa<MemoryEffects::Write>(effect.getEffect()) &&
1816+
isa<SideEffects::AutomaticAllocationScopeResource>(
1817+
effect.getResource());
1818+
});
1819+
}
1820+
return true;
1821+
}
1822+
1823+
Operation *TargetOp::getInnermostCapturedOmpOp() {
1824+
Dialect *ompDialect = (*this)->getDialect();
1825+
Operation *capturedOp = nullptr;
1826+
1827+
// Process in pre-order to check operations from outermost to innermost,
1828+
// ensuring we only enter the region of an operation if it meets the criteria
1829+
// for being captured. We stop the exploration of nested operations as soon as
1830+
// we process a region holding no operations to be captured.
1831+
walk<WalkOrder::PreOrder>([&](Operation *op) {
1832+
if (op == *this)
1833+
return WalkResult::advance();
1834+
1835+
// Ignore operations of other dialects or omp operations with no regions,
1836+
// because these will only be checked if they are siblings of an omp
1837+
// operation that can potentially be captured.
1838+
bool isOmpDialect = op->getDialect() == ompDialect;
1839+
bool hasRegions = op->getNumRegions() > 0;
1840+
if (!isOmpDialect || !hasRegions)
1841+
return WalkResult::skip();
1842+
1843+
// Don't capture this op if it has a not-allowed sibling, and stop recursing
1844+
// into nested operations.
1845+
for (Operation &sibling : op->getParentRegion()->getOps())
1846+
if (&sibling != op && !siblingAllowedInCapture(&sibling))
1847+
return WalkResult::interrupt();
1848+
1849+
// Don't continue capturing nested operations if we reach an omp.loop_nest.
1850+
// Otherwise, process the contents of this operation.
1851+
capturedOp = op;
1852+
return llvm::isa<LoopNestOp>(op) ? WalkResult::interrupt()
1853+
: WalkResult::advance();
1854+
});
1855+
1856+
return capturedOp;
1857+
}
1858+
1859+
bool TargetOp::isTargetSPMDLoop() {
1860+
// The expected MLIR representation for a target SPMD loop is:
1861+
// omp.target {
1862+
// omp.teams {
1863+
// omp.parallel {
1864+
// omp.distribute {
1865+
// omp.wsloop {
1866+
// omp.loop_nest ... { ... }
1867+
// } {omp.composite}
1868+
// } {omp.composite}
1869+
// omp.terminator
1870+
// } {omp.composite}
1871+
// omp.terminator
1872+
// }
1873+
// omp.terminator
1874+
// }
1875+
1876+
Operation *capturedOp = getInnermostCapturedOmpOp();
1877+
if (!isa_and_present<LoopNestOp>(capturedOp))
1878+
return false;
1879+
1880+
Operation *workshareOp = capturedOp->getParentOp();
1881+
1882+
// Accept an optional omp.simd loop wrapper as part of the SPMD pattern.
1883+
if (isa_and_present<SimdOp>(workshareOp))
1884+
workshareOp = workshareOp->getParentOp();
1885+
1886+
if (!isa_and_present<WsloopOp>(workshareOp))
1887+
return false;
1888+
1889+
Operation *distributeOp = workshareOp->getParentOp();
1890+
if (!isa_and_present<DistributeOp>(distributeOp))
1891+
return false;
1892+
1893+
Operation *parallelOp = distributeOp->getParentOp();
1894+
if (!isa_and_present<ParallelOp>(parallelOp))
1895+
return false;
1896+
1897+
Operation *teamsOp = parallelOp->getParentOp();
1898+
if (!isa_and_present<TeamsOp>(teamsOp))
1899+
return false;
1900+
1901+
return teamsOp->getParentOp() == (*this);
1902+
}
1903+
17451904
//===----------------------------------------------------------------------===//
17461905
// ParallelOp
17471906
//===----------------------------------------------------------------------===//

mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,10 @@ static LogicalResult checkImplementationStatus(Operation &op) {
174174
if (op.getHint())
175175
op.emitWarning("hint clause discarded");
176176
};
177+
auto checkHostEval = [&todo](auto op, LogicalResult &result) {
178+
if (!op.getHostEvalVars().empty())
179+
result = todo("host_eval");
180+
};
177181
auto checkIf = [&todo](auto op, LogicalResult &result) {
178182
if (op.getIfExpr())
179183
result = todo("if");
@@ -286,6 +290,7 @@ static LogicalResult checkImplementationStatus(Operation &op) {
286290
checkAllocate(op, result);
287291
checkDevice(op, result);
288292
checkHasDeviceAddr(op, result);
293+
checkHostEval(op, result);
289294
checkIf(op, result);
290295
checkInReduction(op, result);
291296
checkIsDevicePtr(op, result);

0 commit comments

Comments
 (0)