27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/STLForwardCompat.h"
31#include "llvm/ADT/SmallString.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/ADT/TypeSwitch.h"
34#include "llvm/ADT/bit.h"
35#include "llvm/Support/InterleavedRange.h"
41#include "mlir/Dialect/OpenMP/OpenMPOpsDialect.cpp.inc"
42#include "mlir/Dialect/OpenMP/OpenMPOpsEnums.cpp.inc"
43#include "mlir/Dialect/OpenMP/OpenMPOpsInterfaces.cpp.inc"
44#include "mlir/Dialect/OpenMP/OpenMPTypeInterfaces.cpp.inc"
51 return attrs.empty() ?
nullptr : ArrayAttr::get(context, attrs);
65struct MemRefPointerLikeModel
66 :
public PointerLikeType::ExternalModel<MemRefPointerLikeModel,
69 return llvm::cast<MemRefType>(pointer).getElementType();
73struct LLVMPointerPointerLikeModel
74 :
public PointerLikeType::ExternalModel<LLVMPointerPointerLikeModel,
75 LLVM::LLVMPointerType> {
100 bool isRegionArgOfOp;
110 assert(isRegionArgOfOp &&
"Must describe a region operand");
113 size_t &getArgIdx() {
114 assert(isRegionArgOfOp &&
"Must describe a region operand");
119 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
123 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
126 bool isLoopOp()
const {
127 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
128 return isa<CanonicalLoopOp>(op);
130 Region *&getParentRegion() {
131 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
134 size_t &getLoopDepth() {
135 assert(!isRegionArgOfOp &&
"Must describe a operation of a region");
139 void skipIf(
bool v =
true) { skip = skip || v; }
157 llvm::ReversePostOrderTraversal<Block *> traversal(&r->
getBlocks().front());
160 size_t sequentialIdx = -1;
161 bool isOnlyContainerOp =
true;
162 for (
Block *
b : traversal) {
164 if (&op == o && !found) {
168 if (op.getNumRegions()) {
171 isOnlyContainerOp =
false;
173 if (found && !isOnlyContainerOp)
178 Component &containerOpInRegion = components.emplace_back();
179 containerOpInRegion.isRegionArgOfOp =
false;
180 containerOpInRegion.isUnique = isOnlyContainerOp;
181 containerOpInRegion.getContainerOp() = o;
182 containerOpInRegion.getOpPos() = sequentialIdx;
183 containerOpInRegion.getParentRegion() = r;
188 Component ®ionArgOfOperation = components.emplace_back();
189 regionArgOfOperation.isRegionArgOfOp =
true;
190 regionArgOfOperation.isUnique =
true;
191 regionArgOfOperation.getArgIdx() = 0;
192 regionArgOfOperation.getOwnerOp() = parent;
204 for (
auto [idx, region] : llvm::enumerate(o->
getRegions())) {
208 llvm_unreachable(
"Region not child of its parent operation");
210 regionArgOfOperation.isUnique =
false;
211 regionArgOfOperation.getArgIdx() = getRegionIndex(parent, r);
219 for (Component &c : components)
220 c.skipIf(c.isRegionArgOfOp && c.isUnique);
223 size_t numSurroundingLoops = 0;
224 for (Component &c : llvm::reverse(components)) {
229 if (c.isRegionArgOfOp) {
230 numSurroundingLoops = 0;
237 numSurroundingLoops = 0;
239 c.getLoopDepth() = numSurroundingLoops;
242 if (isa<CanonicalLoopOp>(c.getContainerOp()))
243 numSurroundingLoops += 1;
248 bool isLoopNest =
false;
249 for (Component &c : components) {
250 if (c.skip || c.isRegionArgOfOp)
253 if (!isLoopNest && c.getLoopDepth() >= 1) {
256 }
else if (isLoopNest) {
258 c.skipIf(c.isUnique);
262 if (c.getLoopDepth() == 0)
269 for (Component &c : components)
270 c.skipIf(!c.isRegionArgOfOp && c.isUnique &&
271 !isa<CanonicalLoopOp>(c.getContainerOp()));
275 bool newRegion =
true;
276 for (Component &c : llvm::reverse(components)) {
277 c.skipIf(newRegion && c.isUnique);
284 if (!c.isRegionArgOfOp && c.getContainerOp())
290 llvm::raw_svector_ostream NameOS(Name);
291 for (
auto &c : llvm::reverse(components)) {
295 if (c.isRegionArgOfOp)
296 NameOS <<
"_r" << c.getArgIdx();
297 else if (c.getLoopDepth() >= 1)
298 NameOS <<
"_d" << c.getLoopDepth();
300 NameOS <<
"_s" << c.getOpPos();
303 return NameOS.str().str();
306void OpenMPDialect::initialize() {
309#include "mlir/Dialect/OpenMP/OpenMPOps.cpp.inc"
312#define GET_ATTRDEF_LIST
313#include "mlir/Dialect/OpenMP/OpenMPOpsAttributes.cpp.inc"
316#define GET_TYPEDEF_LIST
317#include "mlir/Dialect/OpenMP/OpenMPOpsTypes.cpp.inc"
320 declarePromisedInterface<ConvertToLLVMPatternInterface, OpenMPDialect>();
322 MemRefType::attachInterface<MemRefPointerLikeModel>(*
getContext());
323 LLVM::LLVMPointerType::attachInterface<LLVMPointerPointerLikeModel>(
328 mlir::ModuleOp::attachInterface<mlir::omp::OffloadModuleDefaultModel>(
334 mlir::LLVM::GlobalOp::attachInterface<
337 mlir::LLVM::LLVMFuncOp::attachInterface<
340 mlir::func::FuncOp::attachInterface<
349 if (!isa<DeclareTargetInterface>(op))
350 return op->
emitError() <<
"omp.declare_target can only be applied to "
351 "DeclareTargetInterface ops";
353 auto declareTargetAttr = dyn_cast<DeclareTargetAttr>(attr);
354 if (!declareTargetAttr)
356 <<
"omp.declare_target must be an #omp.declaretarget attribute";
358 if (isa<mlir::FunctionOpInterface>(op)) {
359 if (declareTargetAttr.getAutomap())
361 <<
"omp.declare_target 'automap' is not valid on functions";
364 if (declareTargetAttr.getCaptureClause() ==
365 mlir::omp::DeclareTargetCaptureClause::link)
367 <<
"omp.declare_target 'link' is not valid on functions";
370 if (declareTargetAttr.getImplicit())
372 <<
"omp.declare_target 'implicit' is only valid on functions";
378OpenMPDialect::verifyOperationAttribute(
Operation *op,
380 if (attribute.
getName() ==
"omp.declare_target")
408 allocatorVars.push_back(operand);
409 allocatorTypes.push_back(type);
415 allocateVars.push_back(operand);
416 allocateTypes.push_back(type);
427 for (
unsigned i = 0; i < allocateVars.size(); ++i) {
428 std::string separator = i == allocateVars.size() - 1 ?
"" :
", ";
429 p << allocatorVars[i] <<
" : " << allocatorTypes[i] <<
" -> ";
430 p << allocateVars[i] <<
" : " << allocateTypes[i] << separator;
438template <
typename ClauseAttr>
440 using ClauseT =
decltype(std::declval<ClauseAttr>().getValue());
445 if (std::optional<ClauseT> enumValue = symbolizeEnum<ClauseT>(enumStr)) {
446 attr = ClauseAttr::get(parser.
getContext(), *enumValue);
449 return parser.
emitError(loc,
"invalid clause value: '") << enumStr <<
"'";
452template <
typename ClauseAttr>
454 p << stringifyEnum(attr.getValue());
480 std::optional<omp::LinearModifier> linearModifier;
482 linearModifier = omp::LinearModifier::val;
484 linearModifier = omp::LinearModifier::ref;
486 linearModifier = omp::LinearModifier::uval;
489 bool hasLinearModifierParens = linearModifier.has_value();
490 if (hasLinearModifierParens && parser.
parseLParen())
498 if (hasLinearModifierParens && parser.
parseRParen())
501 linearVars.push_back(var);
502 linearTypes.push_back(type);
503 linearStepVars.push_back(stepVar);
504 linearStepTypes.push_back(stepType);
505 if (linearModifier) {
507 omp::LinearModifierAttr::get(parser.
getContext(), *linearModifier));
509 modifiers.push_back(UnitAttr::get(parser.
getContext()));
515 linearModifiers = ArrayAttr::get(parser.
getContext(), modifiers);
525 size_t linearVarsSize = linearVars.size();
526 for (
unsigned i = 0; i < linearVarsSize; ++i) {
530 Attribute modAttr = linearModifiers ? linearModifiers[i] :
nullptr;
531 auto mod = modAttr ? dyn_cast<omp::LinearModifierAttr>(modAttr) :
nullptr;
533 p << omp::stringifyLinearModifier(mod.getValue()) <<
"(";
535 p << linearVars[i] <<
" : " << linearTypes[i];
536 p <<
" = " << linearStepVars[i] <<
" : " << stepVarTypes[i];
552 if (!linearModifiers)
554 if (linearModifiers->size() != linearVars.size())
556 <<
"expected as many linear modifiers as linear variables";
557 if (!isDeclareSimd) {
558 for (
Attribute attr : *linearModifiers) {
561 auto modAttr = dyn_cast<omp::LinearModifierAttr>(attr);
564 omp::LinearModifier mod = modAttr.getValue();
565 if (mod == omp::LinearModifier::ref || mod == omp::LinearModifier::uval)
567 <<
"linear modifier '" << omp::stringifyLinearModifier(mod)
568 <<
"' may only be specified on a declare simd directive";
583 for (
const auto &it : nontemporalVars)
584 if (!nontemporalItems.insert(it).second)
585 return op->
emitOpError() <<
"nontemporal variable used more than once";
594 std::optional<ArrayAttr> alignments,
597 if (!alignedVars.empty()) {
598 if (!alignments || alignments->size() != alignedVars.size())
600 <<
"expected as many alignment values as aligned variables";
603 return op->
emitOpError() <<
"unexpected alignment values attribute";
609 for (
auto it : alignedVars)
610 if (!alignedItems.insert(it).second)
611 return op->
emitOpError() <<
"aligned variable used more than once";
617 for (
unsigned i = 0; i < (*alignments).size(); ++i) {
618 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>((*alignments)[i])) {
619 if (intAttr.getValue().sle(0))
620 return op->
emitOpError() <<
"alignment should be greater than 0";
622 return op->
emitOpError() <<
"expected integer alignment";
639 if (parser.parseOperand(alignedVars.emplace_back()) ||
640 parser.parseColonType(alignedTypes.emplace_back()) ||
641 parser.parseArrow() ||
642 parser.parseAttribute(alignmentVec.emplace_back())) {
649 alignmentsAttr = ArrayAttr::get(parser.getContext(), alignments);
656 std::optional<ArrayAttr> alignments) {
657 for (
unsigned i = 0; i < alignedVars.size(); ++i) {
660 p << alignedVars[i] <<
" : " << alignedVars[i].
getType();
661 p <<
" -> " << (*alignments)[i];
669 ArrayAttr privateSyms =
nullptr,
bool requirePrivateIndices =
false) {
670 if (allocateVars.size() != allocatorVars.size())
672 "expected equal sizes for allocate and allocator variables");
674 if (allocateVars.empty()) {
675 if (allocateAlignments)
677 "unexpected allocate alignments without allocate variables");
678 if (allocatePrivateIndices)
680 "unexpected allocate private indices without allocate variables");
684 if (allocateAlignments) {
686 if (alignments.size() != allocateVars.size())
688 "expected as many allocate alignments as allocate variables");
689 for (
int64_t alignment : alignments) {
691 return op->
emitError(
"expected non-negative allocate alignments");
692 if (alignment != 0 && (alignment & (alignment - 1)) != 0)
694 "expected positive allocate alignments to be powers of two");
698 if (!allocatePrivateIndices) {
699 if (requirePrivateIndices)
701 "expected an allocate private index for each allocate variable");
706 if (
indices.size() != allocateVars.size())
708 "expected as many allocate private indices as allocate variables");
711 for (
auto [allocateVar, privateIndex] :
712 llvm::zip_equal(allocateVars,
indices)) {
713 if (privateIndex < 0 ||
714 static_cast<uint64_t
>(privateIndex) >= privateVars.size())
715 return op->
emitError(
"allocate private index is out of range");
716 if (!usedPrivateSlots.insert(privateIndex).second)
718 "allocate private index refers to a private variable more than once");
720 Value privateVar = privateVars[privateIndex];
721 if (allocateVar.getType() != privateVar.
getType())
723 <<
"type mismatch between allocate variable and private variable "
726 if (allocateVar != privateVar)
728 <<
"allocate variable does not match private variable at index "
732 static_cast<uint64_t
>(privateIndex) >= privateSyms.size())
734 "allocate private index does not have a privatizer symbol");
736 auto privateSym = dyn_cast<SymbolRefAttr>(privateSyms[privateIndex]);
739 "allocate private index does not reference a privatizer symbol");
740 PrivateClauseOp privatizer =
743 return op->
emitError() <<
"failed to lookup privatizer op with symbol: '"
744 << privateSym <<
"'";
745 if (privatizer.getDataSharingType() != DataSharingClauseType::Private &&
746 privatizer.getDataSharingType() != DataSharingClauseType::FirstPrivate)
748 "allocate private index must refer to private or firstprivate "
762 if (modifiers.size() > 2)
764 for (
const auto &mod : modifiers) {
767 auto symbol = symbolizeScheduleModifier(mod);
770 <<
" unknown modifier type: " << mod;
775 if (modifiers.size() == 1) {
776 if (symbolizeScheduleModifier(modifiers[0]) == ScheduleModifier::simd) {
777 modifiers.push_back(modifiers[0]);
778 modifiers[0] = stringifyScheduleModifier(ScheduleModifier::none);
780 }
else if (modifiers.size() == 2) {
783 if (symbolizeScheduleModifier(modifiers[0]) == ScheduleModifier::simd ||
784 symbolizeScheduleModifier(modifiers[1]) != ScheduleModifier::simd)
786 <<
" incorrect modifier order";
802 ScheduleModifierAttr &scheduleMod, UnitAttr &scheduleSimd,
803 std::optional<OpAsmParser::UnresolvedOperand> &chunkSize,
808 std::optional<mlir::omp::ClauseScheduleKind> schedule =
809 symbolizeClauseScheduleKind(keyword);
813 scheduleAttr = ClauseScheduleKindAttr::get(parser.
getContext(), *schedule);
815 case ClauseScheduleKind::Static:
816 case ClauseScheduleKind::Dynamic:
817 case ClauseScheduleKind::Guided:
823 chunkSize = std::nullopt;
826 case ClauseScheduleKind::Auto:
827 case ClauseScheduleKind::Runtime:
828 case ClauseScheduleKind::Distribute:
829 chunkSize = std::nullopt;
838 modifiers.push_back(mod);
844 if (!modifiers.empty()) {
846 if (std::optional<ScheduleModifier> mod =
847 symbolizeScheduleModifier(modifiers[0])) {
848 scheduleMod = ScheduleModifierAttr::get(parser.
getContext(), *mod);
850 return parser.
emitError(loc,
"invalid schedule modifier");
853 if (modifiers.size() > 1) {
854 assert(symbolizeScheduleModifier(modifiers[1]) == ScheduleModifier::simd);
864 ClauseScheduleKindAttr scheduleKind,
865 ScheduleModifierAttr scheduleMod,
866 UnitAttr scheduleSimd,
Value scheduleChunk,
867 Type scheduleChunkType) {
868 p << stringifyClauseScheduleKind(scheduleKind.getValue());
870 p <<
" = " << scheduleChunk <<
" : " << scheduleChunk.
getType();
872 p <<
", " << stringifyScheduleModifier(scheduleMod.getValue());
884 ClauseOrderKindAttr &order,
885 OrderModifierAttr &orderMod) {
890 if (std::optional<OrderModifier> enumValue =
891 symbolizeOrderModifier(enumStr)) {
892 orderMod = OrderModifierAttr::get(parser.
getContext(), *enumValue);
899 if (std::optional<ClauseOrderKind> enumValue =
900 symbolizeClauseOrderKind(enumStr)) {
901 order = ClauseOrderKindAttr::get(parser.
getContext(), *enumValue);
904 return parser.
emitError(loc,
"invalid clause value: '") << enumStr <<
"'";
908 ClauseOrderKindAttr order,
909 OrderModifierAttr orderMod) {
911 p << stringifyOrderModifier(orderMod.getValue()) <<
":";
913 p << stringifyClauseOrderKind(order.getValue());
916template <
typename ClauseTypeAttr,
typename ClauseType>
919 std::optional<OpAsmParser::UnresolvedOperand> &operand,
921 std::optional<ClauseType> (*symbolizeClause)(StringRef),
922 StringRef clauseName) {
925 if (std::optional<ClauseType> enumValue = symbolizeClause(enumStr)) {
926 prescriptiveness = ClauseTypeAttr::get(parser.
getContext(), *enumValue);
931 <<
"invalid " << clauseName <<
" modifier : '" << enumStr <<
"'";
941 <<
"expected " << clauseName <<
" operand";
944 if (operand.has_value()) {
952template <
typename ClauseTypeAttr,
typename ClauseType>
955 ClauseTypeAttr prescriptiveness,
Value operand,
957 StringRef (*stringifyClauseType)(ClauseType)) {
959 if (prescriptiveness)
960 p << stringifyClauseType(prescriptiveness.getValue()) <<
", ";
963 p << operand <<
": " << operandType;
973 std::optional<OpAsmParser::UnresolvedOperand> &grainsize,
974 Type &grainsizeType) {
976 parser, grainsizeMod, grainsize, grainsizeType,
977 &symbolizeClauseGrainsizeType,
"grainsize");
981 ClauseGrainsizeTypeAttr grainsizeMod,
984 p, op, grainsizeMod, grainsize, grainsizeType,
985 &stringifyClauseGrainsizeType);
995 std::optional<OpAsmParser::UnresolvedOperand> &numTasks,
996 Type &numTasksType) {
998 parser, numTasksMod, numTasks, numTasksType, &symbolizeClauseNumTasksType,
1003 ClauseNumTasksTypeAttr numTasksMod,
1006 p, op, numTasksMod, numTasks, numTasksType, &stringifyClauseNumTasksType);
1022 return mlir::failure();
1023 inTypeAttr = TypeAttr::get(inType);
1052 if (!typeparams.empty()) {
1053 p <<
'(' << typeparams <<
" : " << typeparamsTypes <<
')';
1055 for (
auto sh :
shape) {
1067 FallbackModifierAttr fallback,
1068 Value dynGroupprivateSize) {
1069 if (!dynGroupprivateSize && (accessGroup || fallback))
1070 return op->
emitOpError(
"dyn_groupprivate modifiers require a size operand");
1076 OpAsmParser &parser, AccessGroupModifierAttr &accessGroupAttr,
1077 FallbackModifierAttr &fallbackAttr,
1078 std::optional<OpAsmParser::UnresolvedOperand> &dynGroupprivateSize,
1081 bool parsedAccessGroup =
false;
1082 bool parsedFallback =
false;
1083 bool parsedSize =
false;
1088 if (parsedAccessGroup)
1090 "duplicate access group modifier");
1091 accessGroupAttr = AccessGroupModifierAttr::get(
1092 parser.
getContext(), AccessGroupModifier::cgroup);
1093 parsedAccessGroup =
true;
1100 "duplicate fallback modifier");
1103 "expected '(' after 'fallback'");
1104 llvm::StringRef fbKind;
1108 "expected fallback modifier (abort/null/default_mem)");
1109 std::optional<FallbackModifier> fbEnum;
1110 if (fbKind ==
"abort")
1111 fbEnum = FallbackModifier::abort;
1112 else if (fbKind ==
"null")
1113 fbEnum = FallbackModifier::null;
1114 else if (fbKind ==
"default_mem")
1115 fbEnum = FallbackModifier::default_mem;
1118 "invalid fallback modifier '" + fbKind +
"'");
1119 fallbackAttr = FallbackModifierAttr::get(parser.
getContext(), *fbEnum);
1122 "expected ')' after fallback modifier");
1123 parsedFallback =
true;
1131 "duplicate size operand");
1132 dynGroupprivateSize = operand;
1136 "expected ':' and type after size operand");
1140 "expected dyn_groupprivate_size operand");
1145 AccessGroupModifierAttr modifierFirst,
1146 FallbackModifierAttr modifierSecond,
1147 Value dynGroupprivateSize,
1150 bool needsComma =
false;
1152 if (modifierFirst) {
1153 printer << modifierFirst.getValue();
1157 if (modifierSecond) {
1160 printer <<
"fallback(";
1161 printer << modifierSecond.getValue();
1166 if (dynGroupprivateSize) {
1169 printer << dynGroupprivateSize <<
" : " << sizeType;
1189 isByRefVec.push_back(parser.parseOptionalKeyword(
"byref").succeeded());
1190 if (parser.parseAttribute(symbolVec.emplace_back()) ||
1191 parser.parseOperand(inReductionVars.emplace_back()))
1201 [&]() { return parser.parseType(inReductionTypes.emplace_back()); }))
1204 if (inReductionVars.size() != inReductionTypes.size())
1209 inReductionSyms = ArrayAttr::get(parser.
getContext(), symbolAttrs);
1226 syms = ArrayAttr::get(ctx, values);
1235 llvm::interleaveComma(
1236 llvm::zip_equal(inReductionVars, syms.getValue(), byref.
asArrayRef()), p,
1238 auto [var, sym, isByRef] = t;
1246 llvm::interleaveComma(inReductionTypes, p);
1254struct MapParseArgs {
1255 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1256 SmallVectorImpl<Type> &types;
1257 MapParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1258 SmallVectorImpl<Type> &types)
1259 : vars(vars), types(types) {}
1261struct PrivateParseArgs {
1262 llvm::SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1263 llvm::SmallVectorImpl<Type> &types;
1265 UnitAttr &needsBarrier;
1267 PrivateParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1268 SmallVectorImpl<Type> &types,
ArrayAttr &syms,
1269 UnitAttr &needsBarrier,
1271 : vars(vars), types(types), syms(syms), needsBarrier(needsBarrier),
1272 mapIndices(mapIndices) {}
1275struct LinearParseArgs {
1276 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1277 SmallVectorImpl<Type> &types;
1278 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &stepVars;
1279 SmallVectorImpl<Type> &stepTypes;
1283 LinearParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1284 SmallVectorImpl<Type> &types,
1285 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &stepVars,
1286 SmallVectorImpl<Type> &stepTypes,
ArrayAttr &varTypes,
1288 : vars(vars), types(types), stepVars(stepVars), stepTypes(stepTypes),
1289 varTypes(varTypes), modifiers(modifiers), syms(syms) {}
1292struct ReductionParseArgs {
1293 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1294 SmallVectorImpl<Type> &types;
1298 ReductionParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1301 : vars(vars), types(types), byref(byref), syms(syms), modifier(mod) {}
1304struct AllRegionParseArgs {
1305 std::optional<MapParseArgs> hasDeviceAddrArgs;
1306 std::optional<MapParseArgs> hostEvalArgs;
1307 std::optional<ReductionParseArgs> inReductionArgs;
1308 std::optional<LinearParseArgs> linearArgs;
1309 std::optional<MapParseArgs> mapArgs;
1310 std::optional<PrivateParseArgs> privateArgs;
1311 std::optional<ReductionParseArgs> reductionArgs;
1312 std::optional<ReductionParseArgs> taskReductionArgs;
1313 std::optional<MapParseArgs> useDeviceAddrArgs;
1314 std::optional<MapParseArgs> useDevicePtrArgs;
1319 return "private_barrier";
1329 UnitAttr *needsBarrier =
nullptr) {
1333 unsigned regionArgOffset = regionPrivateArgs.size();
1341 ReductionModifier mod = ReductionModifier::defaultmod;
1342 if (succeeded(parser.parseOptionalKeyword(
"task")))
1343 mod = ReductionModifier::task;
1344 else if (succeeded(parser.parseOptionalKeyword(
"inscan")))
1345 mod = ReductionModifier::inscan;
1346 else if (succeeded(parser.parseOptionalKeyword(
"defaultmod")))
1347 mod = ReductionModifier::defaultmod;
1348 modifiers.push_back(
1349 ReductionModifierAttr::get(parser.getContext(), mod));
1352 isByRefVec.push_back(
1370 mapIndicesVec.push_back(-1);
1379 return parser.parseType(types.emplace_back());
1383 if (llvm::any_of(modifiers, [](
Attribute attr) {
1384 return cast<ReductionModifierAttr>(attr).getValue() !=
1385 ReductionModifier::defaultmod;
1387 *modifier = ArrayAttr::get(parser.
getContext(), modifiers);
1389 if (operands.size() != types.size())
1398 *needsBarrier = mlir::UnitAttr::get(parser.
getContext());
1401 auto *argsBegin = regionPrivateArgs.begin();
1403 argsBegin + regionArgOffset + types.size());
1404 for (
auto [prv, type] : llvm::zip_equal(argsSubrange, types)) {
1410 *symbols = ArrayAttr::get(parser.
getContext(), symbolAttrs);
1413 if (!mapIndicesVec.empty())
1426 StringRef keyword, std::optional<MapParseArgs> mapArgs) {
1441 StringRef keyword, std::optional<PrivateParseArgs> privateArgs) {
1447 parser, privateArgs->vars, privateArgs->types, entryBlockArgs,
1448 &privateArgs->syms, privateArgs->mapIndices,
nullptr,
1449 nullptr, &privateArgs->needsBarrier)))
1458 StringRef keyword, std::optional<ReductionParseArgs> reductionArgs) {
1463 parser, reductionArgs->vars, reductionArgs->types, entryBlockArgs,
1464 &reductionArgs->syms,
nullptr, &reductionArgs->byref,
1465 reductionArgs->modifier)))
1476 StringRef keyword, std::optional<LinearParseArgs> linearArgs) {
1484 std::optional<LinearModifier> modifier;
1485 if (succeeded(parser.parseOptionalKeyword(
"val")))
1486 modifier = LinearModifier::val;
1487 else if (succeeded(parser.parseOptionalKeyword(
"ref")))
1488 modifier = LinearModifier::ref;
1489 else if (succeeded(parser.parseOptionalKeyword(
"uval")))
1490 modifier = LinearModifier::uval;
1491 if (modifier && parser.parseLParen())
1495 OpAsmParser::Argument &arg = entryBlockArgs.emplace_back();
1496 if (parser.parseAttribute(sym) ||
1497 parser.parseOperand(linearArgs->vars.emplace_back()) ||
1498 parser.parseArrow() || parser.parseArgument(arg) ||
1499 parser.parseColonType(linearArgs->types.emplace_back()) ||
1500 parser.parseEqual() ||
1501 parser.parseOperand(linearArgs->stepVars.emplace_back()) ||
1502 parser.parseColonType(linearArgs->stepTypes.emplace_back()))
1504 arg.type = linearArgs->types.back();
1506 if (modifier && parser.parseRParen())
1509 syms.push_back(sym);
1510 modifiers.push_back(
1511 modifier ? Attribute(LinearModifierAttr::get(ctx, *modifier))
1512 : Attribute(UnitAttr::get(ctx)));
1518 linearArgs->syms = ArrayAttr::get(ctx, syms);
1519 linearArgs->modifiers = ArrayAttr::get(ctx, modifiers);
1529 AllRegionParseArgs args) {
1533 args.hasDeviceAddrArgs)))
1535 <<
"invalid `has_device_addr` format";
1538 args.hostEvalArgs)))
1540 <<
"invalid `host_eval` format";
1543 args.inReductionArgs)))
1545 <<
"invalid `in_reduction` format";
1550 <<
"invalid `linear` format";
1555 <<
"invalid `map_entries` format";
1560 <<
"invalid `private` format";
1563 args.reductionArgs)))
1565 <<
"invalid `reduction` format";
1568 args.taskReductionArgs)))
1570 <<
"invalid `task_reduction` format";
1573 args.useDeviceAddrArgs)))
1575 <<
"invalid `use_device_addr` format";
1578 args.useDevicePtrArgs)))
1580 <<
"invalid `use_device_addr` format";
1582 return parser.
parseRegion(region, entryBlockArgs);
1598 AllRegionParseArgs args;
1599 args.hasDeviceAddrArgs.emplace(hasDeviceAddrVars, hasDeviceAddrTypes);
1600 args.hostEvalArgs.emplace(hostEvalVars, hostEvalTypes);
1601 args.mapArgs.emplace(mapVars, mapTypes);
1602 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1603 privateNeedsBarrier, &privateMaps);
1614 UnitAttr &privateNeedsBarrier) {
1615 AllRegionParseArgs args;
1616 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1617 inReductionByref, inReductionSyms);
1618 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1619 privateNeedsBarrier);
1630 UnitAttr &privateNeedsBarrier,
ArrayAttr &reductionMods,
1634 AllRegionParseArgs args;
1635 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1636 inReductionByref, inReductionSyms);
1637 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1638 privateNeedsBarrier);
1639 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1640 reductionSyms, &reductionMods);
1648 UnitAttr &privateNeedsBarrier) {
1649 AllRegionParseArgs args;
1650 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1651 privateNeedsBarrier);
1659 UnitAttr &privateNeedsBarrier,
ArrayAttr &reductionMods,
1663 AllRegionParseArgs args;
1664 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1665 privateNeedsBarrier);
1666 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1667 reductionSyms, &reductionMods);
1680 UnitAttr &privateNeedsBarrier,
ArrayAttr &reductionMods,
1684 AllRegionParseArgs args;
1685 args.linearArgs.emplace(linearVars, linearTypes, linearStepVars,
1686 linearStepTypes, linearVarTypes, linearModifiers,
1688 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1689 privateNeedsBarrier);
1690 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1691 reductionSyms, &reductionMods);
1700 AllRegionParseArgs args;
1701 args.taskReductionArgs.emplace(taskReductionVars, taskReductionTypes,
1702 taskReductionByref, taskReductionSyms);
1712 AllRegionParseArgs args;
1713 args.useDeviceAddrArgs.emplace(useDeviceAddrVars, useDeviceAddrTypes);
1714 args.useDevicePtrArgs.emplace(useDevicePtrVars, useDevicePtrTypes);
1723struct MapPrintArgs {
1728struct PrivatePrintArgs {
1732 UnitAttr needsBarrier;
1736 : vars(vars), types(types), syms(syms), needsBarrier(needsBarrier),
1737 mapIndices(mapIndices) {}
1739struct LinearPrintArgs {
1750 : vars(vars), types(types), stepVars(stepVars), stepTypes(stepTypes),
1751 varTypes(varTypes), modifiers(modifiers), syms(syms) {}
1753struct ReductionPrintArgs {
1761 : vars(vars), types(types), byref(byref), syms(syms), modifier(mod) {}
1763struct AllRegionPrintArgs {
1764 std::optional<MapPrintArgs> hasDeviceAddrArgs;
1765 std::optional<MapPrintArgs> hostEvalArgs;
1766 std::optional<ReductionPrintArgs> inReductionArgs;
1767 std::optional<LinearPrintArgs> linearArgs;
1768 std::optional<MapPrintArgs> mapArgs;
1769 std::optional<PrivatePrintArgs> privateArgs;
1770 std::optional<ReductionPrintArgs> reductionArgs;
1771 std::optional<ReductionPrintArgs> taskReductionArgs;
1772 std::optional<MapPrintArgs> useDeviceAddrArgs;
1773 std::optional<MapPrintArgs> useDevicePtrArgs;
1782 UnitAttr needsBarrier =
nullptr) {
1783 if (argsSubrange.empty())
1786 p << clauseName <<
"(";
1790 symbols = ArrayAttr::get(ctx, values);
1804 llvm::interleaveComma(
1805 llvm::zip_equal(operands, argsSubrange, symbols, mapIndices.asArrayRef(),
1806 byref.asArrayRef()),
1808 auto [op, arg, sym, map, isByRef] = t;
1810 ReductionModifier mod =
1811 cast<ReductionModifierAttr>(modifier[index]).getValue();
1812 if (mod != ReductionModifier::defaultmod)
1813 p << stringifyReductionModifier(mod) <<
" ";
1820 p << op <<
" -> " << arg;
1822 p <<
" [map_idx=" << map <<
"]";
1825 llvm::interleaveComma(types, p);
1833 StringRef clauseName,
ValueRange argsSubrange,
1834 std::optional<MapPrintArgs> mapArgs) {
1841 StringRef clauseName,
ValueRange argsSubrange,
1842 std::optional<PrivatePrintArgs> privateArgs) {
1845 p, ctx, clauseName, argsSubrange, privateArgs->vars, privateArgs->types,
1846 privateArgs->syms, privateArgs->mapIndices,
nullptr,
1847 nullptr, privateArgs->needsBarrier);
1853 std::optional<ReductionPrintArgs> reductionArgs) {
1856 reductionArgs->vars, reductionArgs->types,
1857 reductionArgs->syms,
nullptr,
1858 reductionArgs->byref, reductionArgs->modifier);
1862 StringRef clauseName,
ValueRange argsSubrange,
1863 std::optional<LinearPrintArgs> linearArgs) {
1864 if (!linearArgs || argsSubrange.empty())
1867 p << clauseName <<
"(";
1868 for (
auto [i, var] : llvm::enumerate(linearArgs->vars)) {
1872 linearArgs->modifiers
1873 ? dyn_cast_if_present<LinearModifierAttr>(linearArgs->modifiers[i])
1876 p << stringifyLinearModifier(modifier.getValue()) <<
"(";
1877 if (linearArgs->syms)
1878 p << linearArgs->syms[i] <<
" ";
1879 p << var <<
" -> " << argsSubrange[i] <<
" : " << linearArgs->types[i]
1880 <<
" = " << linearArgs->stepVars[i] <<
" : " << linearArgs->stepTypes[i];
1886 if (linearArgs->varTypes)
1887 p <<
"linear_var_types(" << linearArgs->varTypes <<
") ";
1891 const AllRegionPrintArgs &args) {
1892 auto iface = llvm::cast<mlir::omp::BlockArgOpenMPOpInterface>(op);
1896 iface.getHasDeviceAddrBlockArgs(),
1897 args.hasDeviceAddrArgs);
1901 args.inReductionArgs);
1909 args.reductionArgs);
1911 iface.getTaskReductionBlockArgs(),
1912 args.taskReductionArgs);
1914 iface.getUseDeviceAddrBlockArgs(),
1915 args.useDeviceAddrArgs);
1917 iface.getUseDevicePtrBlockArgs(), args.useDevicePtrArgs);
1931 UnitAttr privateNeedsBarrier,
1933 AllRegionPrintArgs args;
1934 args.hasDeviceAddrArgs.emplace(hasDeviceAddrVars, hasDeviceAddrTypes);
1935 args.hostEvalArgs.emplace(hostEvalVars, hostEvalTypes);
1936 args.mapArgs.emplace(mapVars, mapTypes);
1937 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1938 privateNeedsBarrier, privateMaps);
1946 ArrayAttr privateSyms, UnitAttr privateNeedsBarrier) {
1947 AllRegionPrintArgs args;
1948 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1949 inReductionByref, inReductionSyms);
1950 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1951 privateNeedsBarrier,
1960 ArrayAttr privateSyms, UnitAttr privateNeedsBarrier,
1963 AllRegionPrintArgs args;
1964 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1965 inReductionByref, inReductionSyms);
1966 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1967 privateNeedsBarrier,
1969 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1970 reductionSyms, reductionMods);
1977 UnitAttr privateNeedsBarrier) {
1978 AllRegionPrintArgs args;
1979 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1980 privateNeedsBarrier,
1990 AllRegionPrintArgs args;
1991 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1992 privateNeedsBarrier,
1994 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1995 reductionSyms, reductionMods);
2004 UnitAttr privateNeedsBarrier,
ArrayAttr reductionMods,
2007 AllRegionPrintArgs args;
2008 args.linearArgs.emplace(linearVars, linearTypes, linearStepVars,
2009 linearStepTypes, linearVarTypes, linearModifiers,
2011 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
2012 privateNeedsBarrier,
2014 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
2015 reductionSyms, reductionMods);
2025 AllRegionPrintArgs args;
2026 args.taskReductionArgs.emplace(taskReductionVars, taskReductionTypes,
2027 taskReductionByref, taskReductionSyms);
2037 AllRegionPrintArgs args;
2038 args.useDeviceAddrArgs.emplace(useDeviceAddrVars, useDeviceAddrTypes);
2039 args.useDevicePtrArgs.emplace(useDevicePtrVars, useDevicePtrTypes);
2043template <
typename ParsePrefixFn>
2052 if (failed(parsePrefix()))
2060 if (llvm::isa<mlir::omp::IteratedType>(ty)) {
2061 iteratedVars.push_back(v);
2062 iteratedTypes.push_back(ty);
2064 plainVars.push_back(v);
2065 plainTypes.push_back(ty);
2071template <
typename Pr
intPrefixFn>
2075 PrintPrefixFn &&printPrefixForPlain,
2076 PrintPrefixFn &&printPrefixForIterated) {
2083 p << v <<
" : " << t;
2087 for (
unsigned i = 0; i < iteratedVars.size(); ++i)
2088 emit(iteratedVars[i], iteratedTypes[i], printPrefixForIterated);
2089 for (
unsigned i = 0; i < plainVars.size(); ++i)
2090 emit(plainVars[i], plainTypes[i], printPrefixForPlain);
2097 if (reductionMods && reductionMods.size() != reductionVars.size())
2099 "expected as many reduction modifiers as reduction variables");
2111 if (!reductionVars.empty()) {
2112 if (!reductionSyms || reductionSyms->size() != reductionVars.size())
2114 <<
"expected as many reduction symbol references "
2115 "as reduction variables";
2116 if (reductionByref && reductionByref->size() != reductionVars.size())
2117 return op->
emitError() <<
"expected as many reduction variable by "
2118 "reference attributes as reduction variables";
2121 return op->
emitOpError() <<
"unexpected reduction symbol references";
2128 for (
auto args : llvm::zip(reductionVars, *reductionSyms)) {
2129 Value accum = std::get<0>(args);
2131 if (!accumulators.insert(accum).second)
2132 return op->
emitOpError() <<
"accumulator variable used more than once";
2135 auto symbolRef = llvm::cast<SymbolRefAttr>(std::get<1>(args));
2139 return op->
emitOpError() <<
"expected symbol reference " << symbolRef
2140 <<
" to point to a reduction declaration";
2142 if (decl.getAccumulatorType() && decl.getAccumulatorType() != varType)
2144 <<
"expected accumulator (" << varType
2145 <<
") to be the same type as reduction declaration ("
2146 << decl.getAccumulatorType() <<
")";
2165 if (parser.parseOperand(copyprivateVars.emplace_back()) ||
2166 parser.parseArrow() ||
2167 parser.parseAttribute(symsVec.emplace_back()) ||
2168 parser.parseColonType(copyprivateTypes.emplace_back()))
2174 copyprivateSyms = ArrayAttr::get(parser.
getContext(), syms);
2182 std::optional<ArrayAttr> copyprivateSyms) {
2183 if (!copyprivateSyms.has_value())
2185 llvm::interleaveComma(
2186 llvm::zip(copyprivateVars, *copyprivateSyms, copyprivateTypes), p,
2187 [&](
const auto &args) {
2188 p << std::get<0>(args) <<
" -> " << std::get<1>(args) <<
" : "
2189 << std::get<2>(args);
2196 std::optional<ArrayAttr> copyprivateSyms) {
2197 size_t copyprivateSymsSize =
2198 copyprivateSyms.has_value() ? copyprivateSyms->size() : 0;
2199 if (copyprivateSymsSize != copyprivateVars.size())
2200 return op->
emitOpError() <<
"inconsistent number of copyprivate vars (= "
2201 << copyprivateVars.size()
2202 <<
") and functions (= " << copyprivateSymsSize
2203 <<
"), both must be equal";
2204 if (!copyprivateSyms.has_value())
2207 for (
auto copyprivateVarAndSym :
2208 llvm::zip(copyprivateVars, *copyprivateSyms)) {
2210 llvm::cast<SymbolRefAttr>(std::get<1>(copyprivateVarAndSym));
2211 std::optional<std::variant<mlir::func::FuncOp, mlir::LLVM::LLVMFuncOp>>
2213 if (mlir::func::FuncOp mlirFuncOp =
2216 funcOp = mlirFuncOp;
2217 else if (mlir::LLVM::LLVMFuncOp llvmFuncOp =
2220 funcOp = llvmFuncOp;
2222 auto getNumArguments = [&] {
2223 return std::visit([](
auto &f) {
return f.getNumArguments(); }, *funcOp);
2226 auto getArgumentType = [&](
unsigned i) {
2227 return std::visit([i](
auto &f) {
return f.getArgumentTypes()[i]; },
2232 return op->
emitOpError() <<
"expected symbol reference " << symbolRef
2233 <<
" to point to a copy function";
2235 if (getNumArguments() != 2)
2237 <<
"expected copy function " << symbolRef <<
" to have 2 operands";
2239 Type argTy = getArgumentType(0);
2240 if (argTy != getArgumentType(1))
2241 return op->
emitOpError() <<
"expected copy function " << symbolRef
2242 <<
" arguments to have the same type";
2244 Type varType = std::get<0>(copyprivateVarAndSym).getType();
2245 if (argTy != varType)
2247 <<
"expected copy function arguments' type (" << argTy
2248 <<
") to be the same as copyprivate variable's type (" << varType
2273 OpAsmParser::UnresolvedOperand operand;
2275 if (parser.parseKeyword(&keyword) || parser.parseArrow() ||
2276 parser.parseOperand(operand) || parser.parseColonType(ty))
2278 std::optional<ClauseTaskDepend> keywordDepend =
2279 symbolizeClauseTaskDepend(keyword);
2283 ClauseTaskDependAttr::get(parser.getContext(), *keywordDepend);
2284 if (llvm::isa<mlir::omp::IteratedType>(ty)) {
2285 iteratedVars.push_back(operand);
2286 iteratedTypes.push_back(ty);
2287 iterKindsVec.push_back(kindAttr);
2289 dependVars.push_back(operand);
2290 dependTypes.push_back(ty);
2291 kindsVec.push_back(kindAttr);
2297 dependKinds = ArrayAttr::get(parser.
getContext(), kinds);
2299 iteratedKinds = ArrayAttr::get(parser.
getContext(), iterKinds);
2306 std::optional<ArrayAttr> dependKinds,
2309 std::optional<ArrayAttr> iteratedKinds) {
2312 std::optional<ArrayAttr> kinds) {
2313 for (
unsigned i = 0, e = vars.size(); i < e; ++i) {
2316 p << stringifyClauseTaskDepend(
2317 llvm::cast<mlir::omp::ClauseTaskDependAttr>((*kinds)[i])
2319 <<
" -> " << vars[i] <<
" : " << types[i];
2323 printEntries(dependVars, dependTypes, dependKinds);
2324 printEntries(iteratedVars, iteratedTypes, iteratedKinds);
2329 std::optional<ArrayAttr> dependKinds,
2331 std::optional<ArrayAttr> iteratedKinds,
2333 if (!dependVars.empty()) {
2334 if (!dependKinds || dependKinds->size() != dependVars.size())
2335 return op->
emitOpError() <<
"expected as many depend values"
2336 " as depend variables";
2338 if (dependKinds && !dependKinds->empty())
2339 return op->
emitOpError() <<
"unexpected depend values";
2342 if (!iteratedVars.empty()) {
2343 if (!iteratedKinds || iteratedKinds->size() != iteratedVars.size())
2344 return op->
emitOpError() <<
"expected as many depend iterated values"
2345 " as depend iterated variables";
2347 if (iteratedKinds && !iteratedKinds->empty())
2348 return op->
emitOpError() <<
"unexpected depend iterated values";
2363 IntegerAttr &hintAttr) {
2364 StringRef hintKeyword;
2370 auto parseKeyword = [&]() -> ParseResult {
2373 if (hintKeyword ==
"uncontended")
2375 else if (hintKeyword ==
"contended")
2377 else if (hintKeyword ==
"nonspeculative")
2379 else if (hintKeyword ==
"speculative")
2383 << hintKeyword <<
" is not a valid hint";
2394 IntegerAttr hintAttr) {
2395 int64_t hint = hintAttr.getInt();
2403 auto bitn = [](
int value,
int n) ->
bool {
return value & (1 << n); };
2405 bool uncontended = bitn(hint, 0);
2406 bool contended = bitn(hint, 1);
2407 bool nonspeculative = bitn(hint, 2);
2408 bool speculative = bitn(hint, 3);
2412 hints.push_back(
"uncontended");
2414 hints.push_back(
"contended");
2416 hints.push_back(
"nonspeculative");
2418 hints.push_back(
"speculative");
2420 llvm::interleaveComma(hints, p);
2427 auto bitn = [](
int value,
int n) ->
bool {
return value & (1 << n); };
2429 bool uncontended = bitn(hint, 0);
2430 bool contended = bitn(hint, 1);
2431 bool nonspeculative = bitn(hint, 2);
2432 bool speculative = bitn(hint, 3);
2434 if (uncontended && contended)
2435 return op->
emitOpError() <<
"the hints omp_sync_hint_uncontended and "
2436 "omp_sync_hint_contended cannot be combined";
2437 if (nonspeculative && speculative)
2438 return op->
emitOpError() <<
"the hints omp_sync_hint_nonspeculative and "
2439 "omp_sync_hint_speculative cannot be combined.";
2450 return (value & flag) == flag;
2458static ParseResult parseMapClause(
OpAsmParser &parser,
2459 ClauseMapFlagsAttr &mapType) {
2460 ClauseMapFlags mapTypeBits = ClauseMapFlags::none;
2463 auto parseTypeAndMod = [&]() -> ParseResult {
2464 StringRef mapTypeMod;
2468 if (mapTypeMod ==
"always")
2469 mapTypeBits |= ClauseMapFlags::always;
2471 if (mapTypeMod ==
"implicit")
2472 mapTypeBits |= ClauseMapFlags::implicit;
2474 if (mapTypeMod ==
"ompx_hold")
2475 mapTypeBits |= ClauseMapFlags::ompx_hold;
2477 if (mapTypeMod ==
"close")
2478 mapTypeBits |= ClauseMapFlags::close;
2480 if (mapTypeMod ==
"present")
2481 mapTypeBits |= ClauseMapFlags::present;
2483 if (mapTypeMod ==
"to")
2484 mapTypeBits |= ClauseMapFlags::to;
2486 if (mapTypeMod ==
"from")
2487 mapTypeBits |= ClauseMapFlags::from;
2489 if (mapTypeMod ==
"tofrom")
2490 mapTypeBits |= ClauseMapFlags::to | ClauseMapFlags::from;
2492 if (mapTypeMod ==
"delete")
2493 mapTypeBits |= ClauseMapFlags::del;
2495 if (mapTypeMod ==
"storage")
2496 mapTypeBits |= ClauseMapFlags::storage;
2498 if (mapTypeMod ==
"return_param")
2499 mapTypeBits |= ClauseMapFlags::return_param;
2501 if (mapTypeMod ==
"private")
2502 mapTypeBits |= ClauseMapFlags::priv;
2504 if (mapTypeMod ==
"literal")
2505 mapTypeBits |= ClauseMapFlags::literal;
2507 if (mapTypeMod ==
"attach")
2508 mapTypeBits |= ClauseMapFlags::attach;
2510 if (mapTypeMod ==
"attach_always")
2511 mapTypeBits |= ClauseMapFlags::attach_always;
2513 if (mapTypeMod ==
"attach_never")
2514 mapTypeBits |= ClauseMapFlags::attach_never;
2516 if (mapTypeMod ==
"attach_auto")
2517 mapTypeBits |= ClauseMapFlags::attach_auto;
2519 if (mapTypeMod ==
"ref_ptr")
2520 mapTypeBits |= ClauseMapFlags::ref_ptr;
2522 if (mapTypeMod ==
"ref_ptee")
2523 mapTypeBits |= ClauseMapFlags::ref_ptee;
2525 if (mapTypeMod ==
"is_device_ptr")
2526 mapTypeBits |= ClauseMapFlags::is_device_ptr;
2528 if (mapTypeMod ==
"target_param")
2529 mapTypeBits |= ClauseMapFlags::target_param;
2546 ClauseMapFlagsAttr mapType) {
2548 ClauseMapFlags mapFlags = mapType.getValue();
2553 mapTypeStrs.push_back(
"always");
2555 mapTypeStrs.push_back(
"implicit");
2557 mapTypeStrs.push_back(
"ompx_hold");
2559 mapTypeStrs.push_back(
"close");
2561 mapTypeStrs.push_back(
"present");
2563 mapTypeStrs.push_back(
"target_param");
2572 mapTypeStrs.push_back(
"tofrom");
2574 mapTypeStrs.push_back(
"from");
2576 mapTypeStrs.push_back(
"to");
2579 mapTypeStrs.push_back(
"delete");
2581 mapTypeStrs.push_back(
"return_param");
2583 mapTypeStrs.push_back(
"storage");
2585 mapTypeStrs.push_back(
"private");
2587 mapTypeStrs.push_back(
"literal");
2589 mapTypeStrs.push_back(
"attach");
2591 mapTypeStrs.push_back(
"attach_always");
2593 mapTypeStrs.push_back(
"attach_never");
2595 mapTypeStrs.push_back(
"attach_auto");
2597 mapTypeStrs.push_back(
"ref_ptr");
2599 mapTypeStrs.push_back(
"ref_ptee");
2601 mapTypeStrs.push_back(
"is_device_ptr");
2602 if (mapFlags == ClauseMapFlags::none)
2603 mapTypeStrs.push_back(
"none");
2605 for (
unsigned int i = 0; i < mapTypeStrs.size(); ++i) {
2606 p << mapTypeStrs[i];
2607 if (i + 1 < mapTypeStrs.size()) {
2613static ParseResult parseMembersIndex(
OpAsmParser &parser,
2617 auto parseIndices = [&]() -> ParseResult {
2622 APInt(64, value,
false)));
2636 memberIdxs.push_back(ArrayAttr::get(parser.
getContext(), values));
2640 if (!memberIdxs.empty())
2641 membersIdx = ArrayAttr::get(parser.
getContext(), memberIdxs);
2651 llvm::interleaveComma(membersIdx, p, [&p](
Attribute v) {
2653 auto memberIdx = cast<ArrayAttr>(v);
2654 llvm::interleaveComma(memberIdx.getValue(), p, [&p](
Attribute v2) {
2655 p << cast<IntegerAttr>(v2).getInt();
2662 VariableCaptureKindAttr mapCaptureType) {
2663 std::string typeCapStr;
2664 llvm::raw_string_ostream typeCap(typeCapStr);
2665 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::ByRef)
2667 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::ByCopy)
2668 typeCap <<
"ByCopy";
2669 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::VLAType)
2670 typeCap <<
"VLAType";
2671 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::This)
2677 VariableCaptureKindAttr &mapCaptureType) {
2678 StringRef mapCaptureKey;
2682 if (mapCaptureKey ==
"This")
2683 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2684 parser.
getContext(), mlir::omp::VariableCaptureKind::This);
2685 if (mapCaptureKey ==
"ByRef")
2686 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2687 parser.
getContext(), mlir::omp::VariableCaptureKind::ByRef);
2688 if (mapCaptureKey ==
"ByCopy")
2689 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2690 parser.
getContext(), mlir::omp::VariableCaptureKind::ByCopy);
2691 if (mapCaptureKey ==
"VLAType")
2692 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2693 parser.
getContext(), mlir::omp::VariableCaptureKind::VLAType);
2699 Operation *op, mlir::omp::MapInfoOp mapInfoOp,
2703 mlir::omp::ClauseMapFlags mapTypeBits = mapInfoOp.getMapType();
2706 bool from =
mapTypeToBool(mapTypeBits, ClauseMapFlags::from);
2709 bool always =
mapTypeToBool(mapTypeBits, ClauseMapFlags::always);
2710 bool close =
mapTypeToBool(mapTypeBits, ClauseMapFlags::close);
2711 bool implicit =
mapTypeToBool(mapTypeBits, ClauseMapFlags::implicit);
2712 bool attach =
mapTypeToBool(mapTypeBits, ClauseMapFlags::attach);
2714 if ((isa<TargetDataOp>(op) || isa<TargetOp>(op)) && del)
2716 "to, from, tofrom and alloc map types are permitted");
2718 if (isa<TargetEnterDataOp>(op) && (from || del))
2719 return emitError(op->
getLoc(),
"to and alloc map types are permitted");
2721 if (isa<TargetExitDataOp>(op) && to)
2723 "from, release and delete map types are permitted");
2725 if (isa<TargetUpdateOp>(op)) {
2728 "at least one of to or from map types must be "
2729 "specified, other map types are not permitted");
2732 if (!to && !from && !attach) {
2734 "at least one of to or from or attach map types must be "
2735 "specified, other map types are not permitted");
2738 auto updateVar = mapInfoOp.getVarPtr();
2740 if ((to && from) || (to && updateFromVars.contains(updateVar)) ||
2741 (from && updateToVars.contains(updateVar))) {
2744 "either to or from map types can be specified, not both");
2747 if (always || close || implicit) {
2750 "present, mapper and iterator map type modifiers are permitted");
2756 to ? updateToVars.insert(updateVar) : updateFromVars.insert(updateVar);
2760 if ((mapInfoOp.getVarPtrPtr() && !mapInfoOp.getVarPtrPtrType()) ||
2761 (!mapInfoOp.getVarPtrPtr() && mapInfoOp.getVarPtrPtrType())) {
2763 "if varPtrPtr or varPtrPtrType is specified, then both "
2775 for (
auto mapOp : mapVars) {
2776 if (!mapOp.getDefiningOp())
2779 if (
auto mapInfoOp = mapOp.getDefiningOp<mlir::omp::MapInfoOp>()) {
2783 }
else if (!isa<DeclareMapperInfoOp>(op)) {
2785 "map argument is not a map entry operation");
2790 for (
auto iterVal : mapIterated) {
2791 auto iterOp = iterVal.getDefiningOp<mlir::omp::IteratorOp>();
2793 return op->
emitOpError() <<
"'map_iterated' arguments must be defined by "
2794 "'omp.iterator' ops";
2797 mlir::omp::YieldOp yieldOp = iterOp.getYieldOp();
2798 auto yieldedMapInfo =
2799 yieldOp && yieldOp.getNumOperands() == 1
2800 ? yieldOp.getResults()[0].getDefiningOp<mlir::omp::MapInfoOp>()
2802 if (!yieldedMapInfo)
2803 return op->
emitOpError() <<
"'map_iterated' iterator body must yield "
2804 "a value defined by 'omp.map.info'";
2814template <
typename OpType>
2818 std::optional<DenseI64ArrayAttr> privateMapIndices =
2819 targetOp.getPrivateMapsAttr();
2822 if (!privateMapIndices.has_value() || !privateMapIndices.value())
2827 if (privateMapIndices.value().size() !=
2828 static_cast<int64_t>(privateVars.size()))
2829 return emitError(targetOp.getLoc(),
"sizes of `private` operand range and "
2830 "`private_maps` attribute mismatch");
2840 StringRef clauseName,
2842 for (
Value var : vars)
2843 if (!llvm::isa_and_present<MapInfoOp>(var.getDefiningOp()))
2845 <<
"'" << clauseName
2846 <<
"' arguments must be defined by 'omp.map.info' ops";
2850LogicalResult MapInfoOp::verify() {
2851 if (getMapperId() &&
2853 *
this, getMapperIdAttr())) {
2868 const TargetDataOperands &clauses) {
2869 TargetDataOp::build(builder, state, clauses.device, clauses.ifExpr,
2870 clauses.mapVars, clauses.mapIterated,
2871 clauses.useDeviceAddrVars, clauses.useDevicePtrVars);
2874LogicalResult TargetDataOp::verify() {
2875 if (getMapVars().empty() && getMapIterated().empty() &&
2876 getUseDevicePtrVars().empty() && getUseDeviceAddrVars().empty()) {
2877 return ::emitError(this->getLoc(),
2878 "At least one of map, use_device_ptr_vars, or "
2879 "use_device_addr_vars operand must be present");
2883 getUseDevicePtrVars())))
2887 getUseDeviceAddrVars())))
2897void TargetEnterDataOp::build(
2901 TargetEnterDataOp::build(
2903 clauses.dependVars,
makeArrayAttr(ctx, clauses.dependIteratedKinds),
2904 clauses.dependIterated, clauses.device, clauses.ifExpr, clauses.mapVars,
2905 clauses.mapIterated, clauses.nowait);
2908LogicalResult TargetEnterDataOp::verify() {
2909 LogicalResult verifyDependVars =
2911 getDependIteratedKinds(), getDependIterated());
2912 return failed(verifyDependVars)
2924 TargetExitDataOp::build(
2926 clauses.dependVars,
makeArrayAttr(ctx, clauses.dependIteratedKinds),
2927 clauses.dependIterated, clauses.device, clauses.ifExpr, clauses.mapVars,
2928 clauses.mapIterated, clauses.nowait);
2931LogicalResult TargetExitDataOp::verify() {
2932 LogicalResult verifyDependVars =
2934 getDependIteratedKinds(), getDependIterated());
2935 return failed(verifyDependVars)
2947 TargetUpdateOp::build(builder, state,
makeArrayAttr(ctx, clauses.dependKinds),
2950 clauses.dependIterated, clauses.device, clauses.ifExpr,
2951 clauses.mapVars, clauses.mapIterated, clauses.nowait);
2954LogicalResult TargetUpdateOp::verify() {
2955 LogicalResult verifyDependVars =
2957 getDependIteratedKinds(), getDependIterated());
2958 return failed(verifyDependVars)
2971 builder, state, clauses.allocateVars, clauses.allocatorVars,
2974 makeArrayAttr(ctx, clauses.dependKinds), clauses.dependVars,
2975 makeArrayAttr(ctx, clauses.dependIteratedKinds), clauses.dependIterated,
2976 clauses.device, clauses.dynGroupprivateAccessGroup,
2977 clauses.dynGroupprivateFallback, clauses.dynGroupprivateSize,
2978 clauses.hasDeviceAddrVars, clauses.hostEvalVars, clauses.ifExpr,
2979 clauses.inReductionVars,
2981 makeArrayAttr(ctx, clauses.inReductionSyms), clauses.isDevicePtrVars,
2982 clauses.mapVars, clauses.mapIterated, clauses.nowait, clauses.privateVars,
2983 makeArrayAttr(ctx, clauses.privateSyms), clauses.privateNeedsBarrier,
2984 clauses.threadLimitVars,
nullptr, clauses.
kernelType);
2987bool TargetOp::hasHostEvalTripCount() {
2988 TargetExecMode mode = getKernelType();
2989 if (mode == TargetExecMode::spmd || mode == TargetExecMode::spmd_no_loop)
2992 if (mode == TargetExecMode::bare)
2998 cast<ComposableOpInterface>(getOperation()).findCapturedOp();
2999 if (
auto loopNestOp = dyn_cast_if_present<LoopNestOp>(capturedOp)) {
3001 loopNestOp.gatherWrappers(loopWrappers);
3003 LoopWrapperInterface *innermostWrapper = loopWrappers.begin();
3004 if (isa<SimdOp>(innermostWrapper))
3005 innermostWrapper = std::next(innermostWrapper);
3007 auto numWrappers = std::distance(innermostWrapper, loopWrappers.end());
3008 if (numWrappers != 1)
3011 if (!isa<DistributeOp>(innermostWrapper))
3015 if (isa_and_present<TeamsOp>(parentOp) &&
3031 if (mapVarPtr == inReductionVar)
3037LogicalResult TargetOp::verify() {
3039 getOperation(), getAllocateVars(), getAllocatorVars(),
3040 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3041 getPrivateVars(), getPrivateSymsAttr())))
3044 if (getKernelType() == TargetExecMode::bare && !isCombined())
3045 return emitOpError() <<
"bare kernel requires 'omp.combined'";
3048 getDependIteratedKinds(),
3049 getDependIterated())))
3053 getHasDeviceAddrVars())))
3060 *
this, getDynGroupprivateAccessGroupAttr(),
3061 getDynGroupprivateFallbackAttr(), getDynGroupprivateSize())))
3068 getInReductionVars(),
3069 getInReductionByref())))
3077 for (
Value inReductionVar : getInReductionVars()) {
3078 bool captured =
false;
3079 for (
Value mapVar : getMapVars()) {
3080 auto mapInfo = mapVar.getDefiningOp<MapInfoOp>();
3087 return emitOpError() <<
"in_reduction variable must be captured by a "
3088 "matching map_entries entry";
3094LogicalResult TargetOp::verifyRegions() {
3095 auto teamsOps = getOps<TeamsOp>();
3096 auto numNestedTeams = std::distance(teamsOps.begin(), teamsOps.end());
3097 if (numNestedTeams > 1)
3098 return emitError(
"target containing multiple 'omp.teams' nested ops");
3100 if (numNestedTeams == 0) {
3101 switch (getKernelType()) {
3102 case TargetExecMode::bare:
3103 return emitOpError()
3104 <<
"bare kernel must contain a nested 'omp.teams' operation";
3105 case TargetExecMode::spmd_no_loop:
3106 return emitOpError() <<
"spmd_no_loop kernel must contain a nested "
3107 "'omp.teams' operation";
3114 cast<ComposableOpInterface>(getOperation()).findCapturedOp();
3115 if ((getKernelType() == TargetExecMode::spmd ||
3116 getKernelType() == TargetExecMode::spmd_no_loop) &&
3117 !isa_and_present<LoopNestOp>(capturedOp))
3118 return emitOpError()
3119 <<
"SPMD kernel must capture an 'omp.loop_nest' operation";
3121 bool isTargetDevice =
false;
3122 if (
auto offloadMod = (*this)->getParentOfType<OffloadModuleInterface>())
3123 if (offloadMod.getIsTargetDevice())
3124 isTargetDevice =
true;
3128 cast<BlockArgOpenMPOpInterface>(getOperation()).getHostEvalBlockArgs();
3130 bool hostEvalTripCount = hasHostEvalTripCount();
3131 for (
Value hostEvalArg : hostEvalBlockArgs) {
3133 if (
auto teamsOp = dyn_cast<TeamsOp>(user)) {
3135 if (hostEvalArg == teamsOp.getNumTeamsLower() ||
3136 llvm::is_contained(teamsOp.getNumTeamsUpperVars(), hostEvalArg) ||
3137 llvm::is_contained(teamsOp.getThreadLimitVars(), hostEvalArg))
3140 return emitOpError() <<
"host_eval argument only legal as 'num_teams' "
3141 "and 'thread_limit' in 'omp.teams'";
3143 if (
auto parallelOp = dyn_cast<ParallelOp>(user)) {
3144 if (llvm::is_contained(parallelOp.getNumThreadsVars(), hostEvalArg))
3147 return emitOpError()
3148 <<
"host_eval argument only legal as 'num_threads' in "
3151 if (
auto loopNestOp = dyn_cast<LoopNestOp>(user)) {
3152 if (hostEvalTripCount &&
3153 (llvm::is_contained(loopNestOp.getLoopLowerBounds(), hostEvalArg) ||
3154 llvm::is_contained(loopNestOp.getLoopUpperBounds(), hostEvalArg) ||
3155 llvm::is_contained(loopNestOp.getLoopSteps(), hostEvalArg)))
3158 return emitOpError() <<
"host_eval argument only legal as loop bounds "
3159 "and steps in 'omp.loop_nest' when trip count "
3160 "must be evaluated in the host";
3163 return emitOpError() <<
"host_eval argument illegal use in '"
3164 << user->getName() <<
"' operation";
3168 if (hostEvalTripCount && !isTargetDevice) {
3169 auto loopOp = cast<LoopNestOp>(capturedOp);
3170 for (
auto arg : llvm::concat<Value>(loopOp.getLoopLowerBounds(),
3171 loopOp.getLoopUpperBounds(),
3172 loopOp.getLoopSteps())) {
3173 if (!llvm::is_contained(hostEvalBlockArgs, arg))
3174 return emitOpError() <<
"nested 'omp.loop_nest' bounds expected to "
3175 "be host-evaluated";
3188 ParallelOp::build(builder, state,
ValueRange(),
3203 const ParallelOperands &clauses) {
3205 ParallelOp::build(builder, state, clauses.allocateVars, clauses.allocatorVars,
3208 clauses.ifExpr, clauses.numThreadsVars, clauses.privateVars,
3210 clauses.privateNeedsBarrier, clauses.procBindKind,
3212 clauses.reductionVars,
3217template <
typename OpType>
3219 auto privateVars = op.getPrivateVars();
3220 auto privateSyms = op.getPrivateSymsAttr();
3222 if (privateVars.empty() && (privateSyms ==
nullptr || privateSyms.empty()))
3225 auto numPrivateVars = privateVars.size();
3226 auto numPrivateSyms = (privateSyms ==
nullptr) ? 0 : privateSyms.size();
3228 if (numPrivateVars != numPrivateSyms)
3229 return op.emitError() <<
"inconsistent number of private variables and "
3230 "privatizer op symbols, private vars: "
3232 <<
" vs. privatizer op symbols: " << numPrivateSyms;
3234 for (
auto privateVarInfo : llvm::zip_equal(privateVars, privateSyms)) {
3235 Type varType = std::get<0>(privateVarInfo).getType();
3236 SymbolRefAttr privateSym = cast<SymbolRefAttr>(std::get<1>(privateVarInfo));
3237 PrivateClauseOp privatizerOp =
3240 if (privatizerOp ==
nullptr)
3241 return op.emitError() <<
"failed to lookup privatizer op with symbol: '"
3242 << privateSym <<
"'";
3244 Type privatizerType = privatizerOp.getArgType();
3246 if (privatizerType && (varType != privatizerType))
3247 return op.emitError()
3248 <<
"type mismatch between a "
3249 << stringifyDataSharingClauseType(
3250 privatizerOp.getDataSharingType())
3251 <<
" variable and its privatizer op, var type: " << varType
3252 <<
" vs. privatizer op type: " << privatizerType;
3254 if (privatizerOp.getDataSharingType() == DataSharingClauseType::Linear)
3255 return op.emitError() <<
"`linear` privatizer '" << privateSym
3256 <<
"' can only be used in a `linear` clause";
3263template <
typename OpType>
3266 std::optional<ArrayAttr> linearSyms = op.getLinearSyms();
3267 if (linearVars.empty() && (!linearSyms || linearSyms->empty()))
3270 if (!linearSyms || linearSyms->size() != linearVars.size())
3271 return op.emitOpError()
3272 <<
"expected as many linear privatizers as linear variables";
3274 for (
auto [var, sym] : llvm::zip_equal(linearVars, *linearSyms)) {
3275 auto symRef = cast<SymbolRefAttr>(sym);
3279 return op.emitOpError() <<
"failed to lookup privatizer op with symbol: '"
3281 if (privatizer.getDataSharingType() != DataSharingClauseType::Linear)
3282 return op.emitOpError() <<
"privatizer '" << symRef
3283 <<
"' of a linear variable must be `linear`";
3284 Type argType = privatizer.getArgType();
3285 if (argType && argType != var.getType())
3286 return op.emitOpError()
3287 <<
"type mismatch between a linear variable and its privatizer "
3289 << var.getType() <<
" vs. privatizer op type: " << argType;
3294LogicalResult ParallelOp::verify() {
3298 getOperation(), getAllocateVars(), getAllocatorVars(),
3299 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3300 getPrivateVars(), getPrivateSymsAttr(),
3305 getReductionByref(), getReductionModsAttr());
3308LogicalResult ParallelOp::verifyRegions() {
3309 auto distChildOps = getOps<DistributeOp>();
3310 int numDistChildOps = std::distance(distChildOps.begin(), distChildOps.end());
3311 if (numDistChildOps > 1)
3313 <<
"multiple 'omp.distribute' nested inside of 'omp.parallel'";
3315 if (numDistChildOps == 1) {
3318 <<
"'omp.composite' attribute missing from composite operation";
3320 auto *ompDialect =
getContext()->getLoadedDialect<OpenMPDialect>();
3321 Operation &distributeOp = **distChildOps.begin();
3323 if (&childOp == &distributeOp || ompDialect != childOp.getDialect())
3327 return emitError() <<
"unexpected OpenMP operation inside of composite "
3329 << childOp.getName();
3331 }
else if (isComposite()) {
3333 <<
"'omp.composite' attribute present in non-composite operation";
3350 const TeamsOperands &clauses) {
3354 builder, state, clauses.allocateVars, clauses.allocatorVars,
3357 clauses.dynGroupprivateAccessGroup, clauses.dynGroupprivateFallback,
3358 clauses.dynGroupprivateSize, clauses.ifExpr, clauses.numTeamsLower,
3359 clauses.numTeamsUpperVars, {},
nullptr,
3361 makeArrayAttr(ctx, clauses.reductionMods), clauses.reductionVars,
3363 makeArrayAttr(ctx, clauses.reductionSyms), clauses.threadLimitVars);
3370 if (numTeamsLower) {
3371 if (numTeamsUpperVars.size() != 1)
3373 "expected exactly one num_teams upper bound when lower bound is "
3377 "expected num_teams upper bound and lower bound to be "
3384LogicalResult TeamsOp::verify() {
3391 auto parentTarget = llvm::dyn_cast_if_present<TargetOp>(op->
getParentOp());
3393 return emitError(
"expected to be nested inside of omp.target or not nested "
3394 "in any OpenMP dialect operations");
3398 this->getNumTeamsUpperVars())))
3402 parentTarget.getKernelType() == TargetExecMode::spmd_no_loop &&
3403 (getNumTeamsLower() || !getNumTeamsUpperVars().empty()))
3404 return emitOpError() <<
"'num_teams' not allowed in SPMD-no-loop kernels";
3407 getOperation(), getAllocateVars(), getAllocatorVars(),
3408 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3409 getPrivateVars(), getPrivateSymsAttr())))
3413 op, getDynGroupprivateAccessGroupAttr(),
3414 getDynGroupprivateFallbackAttr(), getDynGroupprivateSize())))
3421 getReductionByref(), getReductionModsAttr());
3429 return getParentOp().getPrivateVars();
3433 return getParentOp().getReductionVars();
3441 const SectionsOperands &clauses) {
3444 SectionsOp::build(builder, state, clauses.allocateVars, clauses.allocatorVars,
3451 clauses.reductionVars,
3457LogicalResult SectionsOp::verify() {
3459 return emitOpError() <<
"cannot be a non-innermost combined construct leaf";
3462 getOperation(), getAllocateVars(), getAllocatorVars(),
3463 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3464 getPrivateVars(), getPrivateSymsAttr())))
3468 getReductionByref(), getReductionModsAttr());
3471LogicalResult SectionsOp::verifyRegions() {
3472 for (
auto &inst : *getRegion().begin()) {
3473 if (!(isa<SectionOp>(inst) || isa<TerminatorOp>(inst))) {
3474 return emitOpError()
3475 <<
"expected omp.section op or terminator op inside region";
3495 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
3513 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
3531 addEffects(iface.getReductionVars(), iface.getReductionBlockArgs());
3532 addEffects(iface.getInReductionVars(), iface.getInReductionBlockArgs());
3533 addEffects(iface.getTaskReductionVars(), iface.getTaskReductionBlockArgs());
3543void SectionsOp::getEffects(
3552 bool hasUnknownRecipeEffects =
3553 (!getPrivateVars().empty() && !getPrivateAssumeBoundedRecipeEffects()) ||
3554 (!getReductionVars().empty() &&
3555 !getReductionAssumeBoundedRecipeEffects());
3557 if (hasUnknownRecipeEffects) {
3570 const ScopeOperands &clauses) {
3573 builder, state, clauses.allocateVars, clauses.allocatorVars,
3576 clauses.nowait, clauses.privateVars,
3577 makeArrayAttr(ctx, clauses.privateSyms), clauses.privateNeedsBarrier,
3578 makeArrayAttr(ctx, clauses.reductionMods), clauses.reductionVars,
3583LogicalResult ScopeOp::verify() {
3585 getOperation(), getAllocateVars(), getAllocatorVars(),
3586 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3587 getPrivateVars(), getPrivateSymsAttr(),
3595 getReductionByref(), getReductionModsAttr());
3603 const SingleOperands &clauses) {
3607 builder, state, clauses.allocateVars, clauses.allocatorVars,
3610 clauses.copyprivateVars,
makeArrayAttr(ctx, clauses.copyprivateSyms),
3611 nullptr, clauses.nowait,
3617LogicalResult SingleOp::verify() {
3619 getOperation(), getAllocateVars(), getAllocatorVars(),
3620 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3621 getPrivateVars(), getPrivateSymsAttr())))
3625 getCopyprivateSyms());
3628void SingleOp::getEffects(
3637 bool hasUnknownRecipeEffects =
3638 (!getPrivateVars().empty() && !getPrivateAssumeBoundedRecipeEffects()) ||
3639 (!getCopyprivateVars().empty() &&
3640 !getCopyprivateAssumeBoundedRecipeEffects());
3641 if (hasUnknownRecipeEffects) {
3661 const WorkshareOperands &clauses) {
3662 WorkshareOp::build(builder, state, clauses.nowait);
3665LogicalResult WorkshareOp::verify() {
3667 return emitOpError() <<
"cannot be a non-innermost combined construct leaf";
3676LogicalResult WorkshareLoopWrapperOp::verifyRegions() {
3677 if (isa_and_nonnull<LoopWrapperInterface>((*this)->getParentOp()) ||
3679 return emitOpError() <<
"expected to be a standalone loop wrapper";
3688LogicalResult LoopWrapperInterface::verifyImpl() {
3692 return emitOpError() <<
"loop wrapper must also have the `NoTerminator` "
3693 "and `SingleBlock` traits";
3696 return emitOpError() <<
"loop wrapper does not contain exactly one region";
3699 if (range_size(region.
getOps()) != 1)
3700 return emitOpError()
3701 <<
"loop wrapper does not contain exactly one nested op";
3704 if (!isa<LoopNestOp, LoopWrapperInterface>(firstOp))
3705 return emitOpError() <<
"nested in loop wrapper is not another loop "
3706 "wrapper or `omp.loop_nest`";
3715Operation *ComposableOpInterface::findCapturedOp() {
3719 if (
auto wrapperOp = dyn_cast<LoopWrapperInterface>(op))
3720 return wrapperOp.getWrappedLoop();
3725 if (!isCombined() && !isComposite())
3730 if (
auto wrapperOp = dyn_cast<LoopWrapperInterface>(&nestedOp))
3731 return wrapperOp.getWrappedLoop();
3733 if (
auto composableOp = dyn_cast<ComposableOpInterface>(&nestedOp))
3734 return composableOp.findCapturedOp();
3743LogicalResult ComposableOpInterface::verifyImpl() {
3747 return emitOpError() <<
"composable ops must have a single region";
3749 if (isComposite() && !isa<LoopWrapperInterface, ParallelOp>(op))
3750 return emitOpError() <<
"non-loop wrapper cannot be composite";
3756 auto count = llvm::count_if(
3758 if (isa<ComposableOpInterface, LoopWrapperInterface>(op)) {
3779 return emitOpError()
3780 <<
"multiple eligible child ops found in combined op";
3791 if (successor->isReachable(parentBlock))
3792 return emitOpError() <<
"nested combined child op is part of a loop";
3796 !domInfo.
dominates(parentBlock, &block))
3797 return emitOpError()
3798 <<
"nested combined child op doesn't unconditionally execute";
3808 const LoopOperands &clauses) {
3811 LoopOp::build(builder, state, clauses.bindKind, clauses.privateVars,
3813 clauses.privateNeedsBarrier, clauses.order, clauses.orderMod,
3815 clauses.reductionVars,
3820LogicalResult LoopOp::verify() {
3825 getReductionByref(), getReductionModsAttr());
3828LogicalResult LoopOp::verifyRegions() {
3829 if (llvm::isa_and_nonnull<LoopWrapperInterface>((*this)->getParentOp()) ||
3831 return emitOpError() <<
"expected to be a standalone loop wrapper";
3842 build(builder, state, {}, {},
3847 nullptr,
false,
nullptr,
3849 nullptr, {},
nullptr,
3860 const WsloopOperands &clauses) {
3863 builder, state, clauses.allocateVars, clauses.allocatorVars,
3866 clauses.linearVars, clauses.linearStepVars, clauses.linearVarTypes,
3867 clauses.linearModifiers,
makeArrayAttr(ctx, clauses.linearSyms),
3868 clauses.nowait, clauses.order, clauses.orderMod, clauses.ordered,
3869 clauses.privateVars,
makeArrayAttr(ctx, clauses.privateSyms),
3870 clauses.privateNeedsBarrier,
makeArrayAttr(ctx, clauses.reductionMods),
3871 clauses.reductionVars,
3873 makeArrayAttr(ctx, clauses.reductionSyms), clauses.scheduleKind,
3874 clauses.scheduleChunk, clauses.scheduleMod, clauses.scheduleSimd);
3877LogicalResult WsloopOp::verify() {
3879 getOperation(), getAllocateVars(), getAllocatorVars(),
3880 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3881 getPrivateVars(), getPrivateSymsAttr())))
3887 if (getLinearVars().size() &&
3888 getLinearVarTypes().value().size() != getLinearVars().size())
3889 return emitError() <<
"Ill-formed type attributes for linear variables";
3895 getReductionByref(), getReductionModsAttr());
3898LogicalResult WsloopOp::verifyRegions() {
3899 bool isCompositeChildLeaf =
3900 llvm::dyn_cast_if_present<LoopWrapperInterface>((*this)->getParentOp());
3902 if (LoopWrapperInterface nested = getNestedWrapper()) {
3905 <<
"'omp.composite' attribute missing from composite wrapper";
3909 if (!isa<SimdOp>(nested))
3910 return emitError() <<
"only supported nested wrapper is 'omp.simd'";
3912 }
else if (isComposite() && !isCompositeChildLeaf) {
3914 <<
"'omp.composite' attribute present in non-composite wrapper";
3915 }
else if (!isComposite() && isCompositeChildLeaf) {
3917 <<
"'omp.composite' attribute missing from composite wrapper";
3928 const SimdOperands &clauses) {
3931 builder, state, clauses.alignedVars,
3933 clauses.linearVars, clauses.linearStepVars, clauses.linearVarTypes,
3934 clauses.linearModifiers,
makeArrayAttr(ctx, clauses.linearSyms),
3935 clauses.nontemporalVars, clauses.order, clauses.orderMod,
3936 clauses.privateVars,
makeArrayAttr(ctx, clauses.privateSyms),
3937 clauses.privateNeedsBarrier,
makeArrayAttr(ctx, clauses.reductionMods),
3938 clauses.reductionVars,
3944LogicalResult SimdOp::verify() {
3946 getReductionModsAttr())))
3949 if (getSimdlen().has_value() && getSafelen().has_value() &&
3950 getSimdlen().value() > getSafelen().value())
3951 return emitOpError()
3952 <<
"simdlen clause and safelen clause are both present, but the "
3953 "simdlen value is not less than or equal to safelen value";
3965 bool isCompositeChildLeaf =
3966 llvm::dyn_cast_if_present<LoopWrapperInterface>((*this)->getParentOp());
3968 if (!isComposite() && isCompositeChildLeaf)
3970 <<
"'omp.composite' attribute missing from composite wrapper";
3972 if (isComposite() && !isCompositeChildLeaf)
3974 <<
"'omp.composite' attribute present in non-composite wrapper";
3978 std::optional<ArrayAttr> privateSyms = getPrivateSyms();
3980 for (
const Attribute &sym : *privateSyms) {
3981 auto symRef = cast<SymbolRefAttr>(sym);
3982 omp::PrivateClauseOp privatizer =
3984 getOperation(), symRef);
3986 return emitError() <<
"Cannot find privatizer '" << symRef <<
"'";
3987 if (privatizer.getDataSharingType() ==
3988 DataSharingClauseType::FirstPrivate)
3989 return emitError() <<
"FIRSTPRIVATE cannot be used with SIMD";
3996 if (getLinearVars().size() &&
3997 getLinearVarTypes().value().size() != getLinearVars().size())
3998 return emitError() <<
"Ill-formed type attributes for linear variables";
4006 for (
Value var : getLinearVars()) {
4007 if (privateVars.contains(var) || reductionVars.contains(var))
4008 return emitOpError()
4009 <<
"linear variables cannot appear in other data-sharing clauses";
4015LogicalResult SimdOp::verifyRegions() {
4016 if (getNestedWrapper())
4017 return emitOpError() <<
"must wrap an 'omp.loop_nest' directly";
4027 const DistributeOperands &clauses) {
4028 DistributeOp::build(
4029 builder, state, clauses.allocateVars, clauses.allocatorVars,
4032 clauses.allocatePrivateIndices),
4033 clauses.distScheduleStatic, clauses.distScheduleChunkSize, clauses.order,
4034 clauses.orderMod, clauses.privateVars,
4036 clauses.privateNeedsBarrier);
4039LogicalResult DistributeOp::verify() {
4040 if (this->getDistScheduleChunkSize() && !this->getDistScheduleStatic())
4041 return emitOpError() <<
"chunk size set without "
4042 "dist_schedule_static being present";
4045 getOperation(), getAllocateVars(), getAllocatorVars(),
4046 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
4047 getPrivateVars(), getPrivateSymsAttr())))
4056LogicalResult DistributeOp::verifyRegions() {
4057 if (LoopWrapperInterface nested = getNestedWrapper()) {
4060 <<
"'omp.composite' attribute missing from composite wrapper";
4063 if (isa<WsloopOp>(nested)) {
4065 if (!llvm::dyn_cast_if_present<ParallelOp>(parentOp) ||
4066 !cast<ComposableOpInterface>(parentOp).isComposite()) {
4067 return emitError() <<
"an 'omp.wsloop' nested wrapper is only allowed "
4068 "when a composite 'omp.parallel' is the direct "
4071 }
else if (!isa<SimdOp>(nested))
4072 return emitError() <<
"only supported nested wrappers are 'omp.simd' and "
4074 }
else if (isComposite()) {
4076 <<
"'omp.composite' attribute present in non-composite wrapper";
4087 const DeclareMapperInfoOperands &clauses) {
4088 DeclareMapperInfoOp::build(builder, state, clauses.mapVars,
4089 clauses.mapIterated);
4092LogicalResult DeclareMapperInfoOp::verify() {
4096LogicalResult DeclareMapperOp::verifyRegions() {
4097 if (!llvm::isa_and_present<DeclareMapperInfoOp>(
4098 getRegion().getBlocks().front().getTerminator()))
4099 return emitOpError() <<
"expected terminator to be a DeclareMapperInfoOp";
4108LogicalResult DeclareReductionOp::verifyRegions() {
4109 if (!getAllocRegion().empty()) {
4110 for (YieldOp yieldOp : getAllocRegion().getOps<YieldOp>()) {
4111 if (yieldOp.getResults().size() != 1 ||
4112 yieldOp.getResults().getTypes()[0] !=
getType())
4113 return emitOpError() <<
"expects alloc region to yield a value "
4114 "of the reduction type";
4118 if (getInitializerRegion().empty())
4119 return emitOpError() <<
"expects non-empty initializer region";
4120 Block &initializerEntryBlock = getInitializerRegion().
front();
4123 if (!getAllocRegion().empty())
4124 return emitOpError() <<
"expects two arguments to the initializer region "
4125 "when an allocation region is used";
4127 if (getAllocRegion().empty())
4128 return emitOpError() <<
"expects one argument to the initializer region "
4129 "when no allocation region is used";
4131 return emitOpError()
4132 <<
"expects one or two arguments to the initializer region";
4136 if (arg.getType() !=
getType())
4137 return emitOpError() <<
"expects initializer region argument to match "
4138 "the reduction type";
4140 for (YieldOp yieldOp : getInitializerRegion().getOps<YieldOp>()) {
4141 if (yieldOp.getResults().size() != 1 ||
4142 yieldOp.getResults().getTypes()[0] !=
getType())
4143 return emitOpError() <<
"expects initializer region to yield a value "
4144 "of the reduction type";
4147 if (getReductionRegion().empty())
4148 return emitOpError() <<
"expects non-empty reduction region";
4149 Block &reductionEntryBlock = getReductionRegion().
front();
4154 return emitOpError() <<
"expects reduction region with two arguments of "
4155 "the reduction type";
4156 for (YieldOp yieldOp : getReductionRegion().getOps<YieldOp>()) {
4157 if (yieldOp.getResults().size() != 1 ||
4158 yieldOp.getResults().getTypes()[0] !=
getType())
4159 return emitOpError() <<
"expects reduction region to yield a value "
4160 "of the reduction type";
4163 if (!getAtomicReductionRegion().empty()) {
4164 Block &atomicReductionEntryBlock = getAtomicReductionRegion().
front();
4168 return emitOpError() <<
"expects atomic reduction region with two "
4169 "arguments of the same type";
4170 auto ptrType = llvm::dyn_cast<PointerLikeType>(
4173 (ptrType.getElementType() && ptrType.getElementType() !=
getType()))
4174 return emitOpError() <<
"expects atomic reduction region arguments to "
4175 "be accumulators containing the reduction type";
4178 if (getCleanupRegion().empty())
4180 Block &cleanupEntryBlock = getCleanupRegion().
front();
4183 return emitOpError() <<
"expects cleanup region with one argument "
4184 "of the reduction type";
4194 const TaskOperands &clauses) {
4196 TaskOp::build(builder, state, clauses.iterated, clauses.affinityVars,
4197 clauses.allocateVars, clauses.allocatorVars,
4200 makeArrayAttr(ctx, clauses.dependKinds), clauses.dependVars,
4202 clauses.dependIterated, clauses.final, clauses.ifExpr,
4203 clauses.inReductionVars,
4205 makeArrayAttr(ctx, clauses.inReductionSyms), clauses.mergeable,
4206 clauses.priority, clauses.privateVars,
4208 clauses.privateNeedsBarrier, clauses.threadset, clauses.untied,
4209 clauses.eventHandle);
4212LogicalResult TaskOp::verify() {
4214 getOperation(), getAllocateVars(), getAllocatorVars(),
4215 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
4216 getPrivateVars(), getPrivateSymsAttr())))
4219 LogicalResult verifyDependVars =
4221 getDependIteratedKinds(), getDependIterated());
4222 if (
failed(verifyDependVars))
4223 return verifyDependVars;
4229 getInReductionVars(), getInReductionByref());
4237 const TaskgroupOperands &clauses) {
4239 TaskgroupOp::build(builder, state, clauses.allocateVars,
4240 clauses.allocatorVars,
4243 clauses.taskReductionVars,
4248LogicalResult TaskgroupOp::verify() {
4250 getOperation(), getAllocateVars(), getAllocatorVars(),
4251 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr())))
4255 getTaskReductionVars(),
4256 getTaskReductionByref());
4264 const TaskloopContextOperands &clauses) {
4266 TaskloopContextOp::build(
4267 builder, state, clauses.allocateVars, clauses.allocatorVars,
4270 clauses.grainsizeMod, clauses.grainsize, clauses.ifExpr,
4271 clauses.inReductionVars,
4273 makeArrayAttr(ctx, clauses.inReductionSyms), clauses.mergeable,
4274 clauses.nogroup, clauses.numTasksMod, clauses.numTasks, clauses.priority,
4275 clauses.privateVars,
4277 clauses.privateNeedsBarrier,
makeArrayAttr(ctx, clauses.reductionMods),
4278 clauses.reductionVars,
4280 makeArrayAttr(ctx, clauses.reductionSyms), clauses.threadset,
4282 state.
addAttribute(
"omp.combined", UnitAttr::get(ctx));
4285TaskloopWrapperOp TaskloopContextOp::getLoopOp() {
4286 return cast<TaskloopWrapperOp>(
4288 return isa<TaskloopWrapperOp>(op);
4292LogicalResult TaskloopContextOp::verify() {
4296 getOperation(), getAllocateVars(), getAllocatorVars(),
4297 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
4298 getPrivateVars(), getPrivateSymsAttr())))
4302 getReductionVars(), getReductionByref(),
4303 getReductionModsAttr())) ||
4305 getInReductionVars(),
4306 getInReductionByref())))
4309 if (!getReductionVars().empty() && getNogroup())
4310 return emitError(
"if a reduction clause is present on the taskloop "
4311 "directive, the nogroup clause must not be specified");
4312 for (
auto var : getReductionVars()) {
4313 if (llvm::is_contained(getInReductionVars(), var))
4314 return emitError(
"the same list item cannot appear in both a reduction "
4315 "and an in_reduction clause");
4318 if (getGrainsize() && getNumTasks()) {
4320 "the grainsize clause and num_tasks clause are mutually exclusive and "
4321 "may not appear on the same taskloop directive");
4329 return emitOpError(
"must always contain the 'omp.combined' attribute");
4334LogicalResult TaskloopContextOp::verifyRegions() {
4335 Region ®ion = getRegion();
4337 return isa<TaskloopWrapperOp>(op);
4339 if (loopWrapperIt == region.
front().
end())
4340 return emitOpError()
4341 <<
"expected a TaskloopWrapperOp directly nested in the region";
4343 auto loopWrapperOp = cast<TaskloopWrapperOp>(*loopWrapperIt);
4344 auto loopNestOp = dyn_cast<LoopNestOp>(loopWrapperOp.getWrappedLoop());
4350 std::function<
bool(
Value)> isValidBoundValue = [&](
Value value) ->
bool {
4351 Region *valueRegion = value.getParentRegion();
4357 Operation *defOp = value.getDefiningOp();
4361 return llvm::all_of(defOp->
getOperands(), isValidBoundValue);
4363 auto hasUnsupportedTaskloopLocalBound = [&](
OperandRange range) ->
bool {
4364 return llvm::any_of(range,
4365 [&](
Value value) {
return !isValidBoundValue(value); });
4368 if (hasUnsupportedTaskloopLocalBound(loopNestOp.getLoopLowerBounds()) ||
4369 hasUnsupportedTaskloopLocalBound(loopNestOp.getLoopUpperBounds()) ||
4370 hasUnsupportedTaskloopLocalBound(loopNestOp.getLoopSteps())) {
4371 return emitOpError()
4372 <<
"expects loop bounds and steps to be defined outside of the "
4373 "taskloop.context region or by pure, regionless operations "
4374 "that do not depend on block arguments";
4385 const TaskloopWrapperOperands &clauses) {
4386 TaskloopWrapperOp::build(builder, state);
4389TaskloopContextOp TaskloopWrapperOp::getTaskloopContext() {
4390 return dyn_cast<TaskloopContextOp>(getOperation()->getParentOp());
4393LogicalResult TaskloopWrapperOp::verify() {
4394 TaskloopContextOp context = getTaskloopContext();
4396 return emitOpError() <<
"expected to be nested in a taskloop context op";
4400LogicalResult TaskloopWrapperOp::verifyRegions() {
4401 if (LoopWrapperInterface nested = getNestedWrapper()) {
4404 <<
"'omp.composite' attribute missing from composite wrapper";
4408 if (!isa<SimdOp>(nested))
4409 return emitError() <<
"only supported nested wrapper is 'omp.simd'";
4410 }
else if (isComposite()) {
4412 <<
"'omp.composite' attribute present in non-composite wrapper";
4436 for (
auto &iv : ivs)
4437 iv.type = loopVarType;
4442 result.addAttribute(
"loop_inclusive", UnitAttr::get(ctx));
4458 "collapse_num_loops",
4463 auto parseTiles = [&]() -> ParseResult {
4467 tiles.push_back(
tile);
4476 if (tiles.size() > 0)
4495 Region ®ion = getRegion();
4497 p <<
" (" << args <<
") : " << args[0].getType() <<
" = ("
4498 << getLoopLowerBounds() <<
") to (" << getLoopUpperBounds() <<
") ";
4499 if (getLoopInclusive())
4501 p <<
"step (" << getLoopSteps() <<
") ";
4502 if (
int64_t numCollapse = getCollapseNumLoops())
4503 if (numCollapse > 1)
4504 p <<
"collapse(" << numCollapse <<
") ";
4507 p <<
"tiles(" << tiles.value() <<
") ";
4513 const LoopNestOperands &clauses) {
4515 LoopNestOp::build(builder, state, clauses.collapseNumLoops,
4516 clauses.loopLowerBounds, clauses.loopUpperBounds,
4517 clauses.loopSteps, clauses.loopInclusive,
4521LogicalResult LoopNestOp::verify() {
4522 if (getLoopLowerBounds().empty())
4523 return emitOpError() <<
"must represent at least one loop";
4525 if (getLoopLowerBounds().size() != getIVs().size())
4526 return emitOpError() <<
"number of range arguments and IVs do not match";
4528 for (
auto [lb, iv] : llvm::zip_equal(getLoopLowerBounds(), getIVs())) {
4529 if (lb.getType() != iv.getType())
4530 return emitOpError()
4531 <<
"range argument type does not match corresponding IV type";
4534 uint64_t numIVs = getIVs().size();
4536 if (
const auto &numCollapse = getCollapseNumLoops())
4537 if (numCollapse > numIVs)
4538 return emitOpError()
4539 <<
"collapse value is larger than the number of loops";
4542 if (tiles.value().size() > numIVs)
4543 return emitOpError() <<
"too few canonical loops for tile dimensions";
4545 if (!llvm::dyn_cast_if_present<LoopWrapperInterface>((*this)->getParentOp()))
4546 return emitOpError() <<
"expects parent op to be a loop wrapper";
4551void LoopNestOp::gatherWrappers(
4554 while (
auto wrapper =
4555 llvm::dyn_cast_if_present<LoopWrapperInterface>(parent)) {
4556 wrappers.push_back(wrapper);
4565std::tuple<NewCliOp, OpOperand *, OpOperand *>
4571 return {{},
nullptr,
nullptr};
4574 "Unexpected type of cli");
4580 auto op = cast<LoopTransformationInterface>(use.getOwner());
4582 unsigned opnum = use.getOperandNumber();
4583 if (op.isGeneratee(opnum)) {
4584 assert(!gen &&
"Each CLI may have at most one def");
4586 }
else if (op.isApplyee(opnum)) {
4587 assert(!cons &&
"Each CLI may have at most one consumer");
4590 llvm_unreachable(
"Unexpected operand for a CLI");
4594 return {create, gen, cons};
4600 case llvm::omp::ProcBindKind::OMP_PROC_BIND_close:
4601 return ClauseProcBindKind::Close;
4602 case llvm::omp::ProcBindKind::OMP_PROC_BIND_master:
4603 return ClauseProcBindKind::Master;
4604 case llvm::omp::ProcBindKind::OMP_PROC_BIND_primary:
4605 return ClauseProcBindKind::Primary;
4606 case llvm::omp::ProcBindKind::OMP_PROC_BIND_spread:
4607 return ClauseProcBindKind::Spread;
4608 case llvm::omp::ProcBindKind::OMP_PROC_BIND_default:
4609 case llvm::omp::ProcBindKind::OMP_PROC_BIND_unknown:
4612 llvm_unreachable(
"unexpected proc-bind kind");
4635 std::string cliName{
"cli"};
4639 .Case([&](CanonicalLoopOp op) {
4642 .Case([&](UnrollHeuristicOp op) -> std::string {
4643 llvm_unreachable(
"heuristic unrolling does not generate a loop");
4645 .Case([&](FuseOp op) -> std::string {
4646 unsigned opnum =
generator->getOperandNumber();
4649 if (op.getFirst().has_value() && opnum != op.getFirst().value())
4650 return "canonloop_fuse";
4654 .Case([&](TileOp op) -> std::string {
4655 auto [generateesFirst, generateesCount] =
4656 op.getGenerateesODSOperandIndexAndLength();
4657 unsigned firstGrid = generateesFirst;
4658 unsigned firstIntratile = generateesFirst + generateesCount / 2;
4659 unsigned end = generateesFirst + generateesCount;
4660 unsigned opnum =
generator->getOperandNumber();
4662 if (firstGrid <= opnum && opnum < firstIntratile) {
4663 unsigned gridnum = opnum - firstGrid + 1;
4664 return (
"grid" + Twine(gridnum)).str();
4666 if (firstIntratile <= opnum && opnum < end) {
4667 unsigned intratilenum = opnum - firstIntratile + 1;
4668 return (
"intratile" + Twine(intratilenum)).str();
4670 llvm_unreachable(
"Unexpected generatee argument");
4672 .DefaultUnreachable(
"TODO: Custom name for this operation");
4675 setNameFn(
result, cliName);
4678LogicalResult NewCliOp::verify() {
4679 Value cli = getResult();
4682 "Unexpected type of cli");
4688 auto op = dyn_cast<mlir::omp::LoopTransformationInterface>(use.getOwner());
4691 emitOpError(
"CLI must only be used by loop transformations");
4696 unsigned opnum = use.getOperandNumber();
4697 if (op.isGeneratee(opnum)) {
4700 emitOpError(
"CLI must have at most one generator");
4702 .
append(
"first generator here:");
4704 .
append(
"second generator here:");
4709 }
else if (op.isApplyee(opnum)) {
4712 emitOpError(
"CLI must have at most one consumer");
4714 .
append(
"first consumer here:")
4718 .
append(
"second consumer here:")
4725 llvm_unreachable(
"Unexpected operand for a CLI");
4733 .
append(
"see consumer here: ")
4756 setNameFn(&getRegion().front(),
"body_entry");
4759void CanonicalLoopOp::getAsmBlockArgumentNames(
Region ®ion,
4767 p <<
'(' << getCli() <<
')';
4768 p <<
' ' << getInductionVar() <<
" : " << getInductionVar().getType()
4769 <<
" in range(" << getTripCount() <<
") ";
4779 CanonicalLoopInfoType cliType =
4780 CanonicalLoopInfoType::get(parser.
getContext());
4805 if (parser.
parseRegion(*region, {inductionVariable}))
4810 result.operands.append(cliOperand);
4816 return mlir::success();
4819LogicalResult CanonicalLoopOp::verify() {
4822 if (!getRegion().empty()) {
4823 Region ®ion = getRegion();
4826 "Canonical loop region must have exactly one argument");
4830 "Region argument must be the same type as the trip count");
4836Value CanonicalLoopOp::getInductionVar() {
return getRegion().getArgument(0); }
4838std::pair<unsigned, unsigned>
4839CanonicalLoopOp::getApplyeesODSOperandIndexAndLength() {
4844std::pair<unsigned, unsigned>
4845CanonicalLoopOp::getGenerateesODSOperandIndexAndLength() {
4846 return getODSOperandIndexAndLength(odsIndex_cli);
4860 p <<
'(' << getApplyee() <<
')';
4867 auto cliType = CanonicalLoopInfoType::get(parser.
getContext());
4890 return mlir::success();
4893std::pair<unsigned, unsigned>
4894UnrollHeuristicOp ::getApplyeesODSOperandIndexAndLength() {
4895 return getODSOperandIndexAndLength(odsIndex_applyee);
4898std::pair<unsigned, unsigned>
4899UnrollHeuristicOp::getGenerateesODSOperandIndexAndLength() {
4913 p <<
'(' << getApplyee() <<
')';
4920 auto cliType = CanonicalLoopInfoType::get(parser.
getContext());
4943 return mlir::success();
4946std::pair<unsigned, unsigned>
4947UnrollFullOp::getApplyeesODSOperandIndexAndLength() {
4948 return getODSOperandIndexAndLength(odsIndex_applyee);
4951std::pair<unsigned, unsigned>
4952UnrollFullOp::getGenerateesODSOperandIndexAndLength() {
4956LogicalResult UnrollFullOp::verify() {
4957 auto [create, gen, cons] =
decodeCli(getApplyee());
4959 return emitOpError() <<
"applyee CLI has no generator";
4963 if (
auto loop = dyn_cast<CanonicalLoopOp>(gen->getOwner())) {
4965 return emitOpError() <<
"applyee loop must have a constant trip count";
4977 uint64_t unrollFactor) {
4984 p <<
'(' << getApplyee() <<
')';
4987 attrs.emplace_back(getUnrollFactorAttrName(), getUnrollFactorAttr());
4994 auto cliType = CanonicalLoopInfoType::get(parser.
getContext());
5011 return mlir::success();
5014std::pair<unsigned, unsigned>
5015UnrollPartialOp::getApplyeesODSOperandIndexAndLength() {
5016 return getODSOperandIndexAndLength(odsIndex_applyee);
5019std::pair<unsigned, unsigned>
5020UnrollPartialOp::getGenerateesODSOperandIndexAndLength() {
5031 if (!generatees.empty())
5032 p <<
'(' << llvm::interleaved(generatees) <<
')';
5034 if (!applyees.empty())
5035 p <<
" <- (" << llvm::interleaved(applyees) <<
')';
5077 bool isOnlyCanonLoops =
true;
5079 for (
Value applyee : op.getApplyees()) {
5080 auto [create, gen, cons] =
decodeCli(applyee);
5083 return op.emitOpError() <<
"applyee CLI has no generator";
5085 auto loop = dyn_cast_or_null<CanonicalLoopOp>(gen->getOwner());
5086 canonLoops.push_back(loop);
5088 isOnlyCanonLoops =
false;
5093 if (!isOnlyCanonLoops)
5097 for (
auto i : llvm::seq<int>(1, canonLoops.size())) {
5098 auto parentLoop = canonLoops[i - 1];
5099 auto loop = canonLoops[i];
5101 if (parentLoop.getOperation() != loop.getOperation()->getParentOp())
5102 return op.emitOpError()
5103 <<
"tiled loop nest must be nested within each other";
5105 parentIVs.insert(parentLoop.getInductionVar());
5110 bool isPerfectlyNested = [&]() {
5111 auto &parentBody = parentLoop.getRegion();
5112 if (!parentBody.hasOneBlock())
5114 auto &parentBlock = parentBody.getBlocks().
front();
5116 auto nestedLoopIt = parentBlock.
begin();
5117 if (nestedLoopIt == parentBlock.
end() ||
5118 (&*nestedLoopIt != loop.getOperation()))
5121 auto termIt = std::next(nestedLoopIt);
5122 if (termIt == parentBlock.
end() || !isa<TerminatorOp>(termIt))
5125 if (std::next(termIt) != parentBlock.
end())
5130 if (!isPerfectlyNested)
5131 return op.emitOpError() <<
"tiled loop nest must be perfectly nested";
5133 if (parentIVs.contains(loop.getTripCount()))
5134 return op.emitOpError() <<
"tiled loop nest must be rectangular";
5151LogicalResult TileOp::verify() {
5152 if (getApplyees().empty())
5153 return emitOpError() <<
"must apply to at least one loop";
5155 if (getSizes().size() != getApplyees().size())
5156 return emitOpError() <<
"there must be one tile size for each applyee";
5158 if (!getGeneratees().empty() &&
5159 2 * getSizes().size() != getGeneratees().size())
5160 return emitOpError()
5161 <<
"expecting two times the number of generatees than applyees";
5166std::pair<unsigned, unsigned> TileOp ::getApplyeesODSOperandIndexAndLength() {
5167 return getODSOperandIndexAndLength(odsIndex_applyees);
5170std::pair<unsigned, unsigned> TileOp::getGenerateesODSOperandIndexAndLength() {
5171 return getODSOperandIndexAndLength(odsIndex_generatees);
5181 if (!generatees.empty())
5182 p <<
'(' << llvm::interleaved(generatees) <<
')';
5184 if (!applyees.empty())
5185 p <<
" <- (" << llvm::interleaved(applyees) <<
')';
5188LogicalResult FuseOp::verify() {
5189 if (getApplyees().size() < 2)
5190 return emitOpError() <<
"must apply to at least two loops";
5192 if (getFirst().has_value() && getCount().has_value()) {
5193 int64_t first = getFirst().value();
5194 int64_t count = getCount().value();
5195 if ((
unsigned)(first + count - 1) > getApplyees().size())
5196 return emitOpError() <<
"the numbers of applyees must be at least first "
5197 "minus one plus count attributes";
5198 if (!getGeneratees().empty() &&
5199 getGeneratees().size() != getApplyees().size() + 1 - count)
5200 return emitOpError() <<
"the number of generatees must be the number of "
5201 "aplyees plus one minus count";
5204 if (!getGeneratees().empty() && getGeneratees().size() != 1)
5205 return emitOpError()
5206 <<
"in a complete fuse the number of generatees must be exactly 1";
5208 for (
auto &&applyee : getApplyees()) {
5209 auto [create, gen, cons] =
decodeCli(applyee);
5212 return emitOpError() <<
"applyee CLI has no generator";
5213 auto loop = dyn_cast_or_null<CanonicalLoopOp>(gen->getOwner());
5215 return emitOpError()
5216 <<
"currently only supports omp.canonical_loop as applyee";
5220std::pair<unsigned, unsigned> FuseOp::getApplyeesODSOperandIndexAndLength() {
5221 return getODSOperandIndexAndLength(odsIndex_applyees);
5224std::pair<unsigned, unsigned> FuseOp::getGenerateesODSOperandIndexAndLength() {
5225 return getODSOperandIndexAndLength(odsIndex_generatees);
5233 const CriticalDeclareOperands &clauses) {
5234 CriticalDeclareOp::build(builder, state, clauses.symName,
5235 clauses.symVisibility, clauses.hint);
5238LogicalResult CriticalDeclareOp::verify() {
5242LogicalResult CriticalOp::verify() {
5243 SymbolRefAttr currentName = getNameAttr();
5245 CriticalOp parentCritical = (*this)->getParentOfType<CriticalOp>();
5247 while (parentCritical) {
5248 SymbolRefAttr parentName = parentCritical.getNameAttr();
5250 if (currentName == parentName) {
5252 return emitOpError() <<
"cannot be nested inside another omp.critical "
5253 "region with the same name ("
5254 << currentName <<
")";
5256 return emitOpError() <<
"cannot be nested inside another unnamed "
5257 "omp.critical region";
5261 parentCritical = parentCritical->getParentOfType<CriticalOp>();
5268 if (getNameAttr()) {
5269 SymbolRefAttr symbolRef = getNameAttr();
5273 return emitOpError() <<
"expected symbol reference " << symbolRef
5274 <<
" to point to a critical declaration";
5285LogicalResult ErrorOp::verify() {
5286 if (getMessage() && getMessageExpr())
5287 return emitOpError() <<
"the message must be provided either as a constant "
5288 "`message` attribute or as a `message_expr` "
5289 "operand, but not both";
5306 return op.
emitOpError() <<
"must be nested inside of a loop";
5310 if (
auto wsloopOp = dyn_cast<WsloopOp>(wrapper)) {
5311 IntegerAttr orderedAttr = wsloopOp.getOrderedAttr();
5313 return op.
emitOpError() <<
"the enclosing worksharing-loop region must "
5314 "have an ordered clause";
5316 if (hasRegion && orderedAttr.getInt() != 0)
5317 return op.
emitOpError() <<
"the enclosing loop's ordered clause must not "
5318 "have a parameter present";
5320 if (!hasRegion && orderedAttr.getInt() == 0)
5321 return op.
emitOpError() <<
"the enclosing loop's ordered clause must "
5322 "have a parameter present";
5323 }
else if (!isa<SimdOp>(wrapper)) {
5324 return op.
emitOpError() <<
"must be nested inside of a worksharing, simd "
5325 "or worksharing simd loop";
5331 const OrderedOperands &clauses) {
5332 OrderedOp::build(builder, state, clauses.doacrossDependType,
5333 clauses.doacrossNumLoops, clauses.doacrossDependVars);
5336LogicalResult OrderedOp::verify() {
5340 auto wrapper = (*this)->getParentOfType<WsloopOp>();
5341 if (!wrapper || *wrapper.getOrdered() != *getDoacrossNumLoops())
5342 return emitOpError() <<
"number of variables in depend clause does not "
5343 <<
"match number of iteration variables in the "
5350 const OrderedRegionOperands &clauses) {
5351 OrderedRegionOp::build(builder, state, clauses.parLevelSimd);
5361 const TaskwaitOperands &clauses) {
5377LogicalResult AtomicReadOp::verify() {
5378 if (verifyCommon().
failed())
5379 return mlir::failure();
5382 if (
auto moduleOp = getOperation()->getParentOfType<ModuleOp>())
5383 if (
Attribute verAttr = moduleOp->getDiscardableAttr(
"omp.version"))
5384 version = llvm::cast<VersionAttr>(verAttr).getVersion();
5386 if (
auto mo = getMemoryOrder()) {
5387 if (*mo == ClauseMemoryOrderKind::Release) {
5388 return emitError(
"memory-order must not be release for atomic reads");
5390 if (*mo == ClauseMemoryOrderKind::Acq_rel) {
5393 return emitError(
"memory-order must not be acq_rel for atomic reads");
5403LogicalResult AtomicWriteOp::verify() {
5404 if (verifyCommon().
failed())
5405 return mlir::failure();
5408 if (
auto moduleOp = getOperation()->getParentOfType<ModuleOp>())
5409 if (
Attribute verAttr = moduleOp->getDiscardableAttr(
"omp.version"))
5410 version = llvm::cast<VersionAttr>(verAttr).getVersion();
5412 if (
auto mo = getMemoryOrder()) {
5413 if (*mo == ClauseMemoryOrderKind::Acquire) {
5414 return emitError(
"memory-order must not be acquire for atomic writes");
5416 if (*mo == ClauseMemoryOrderKind::Acq_rel) {
5419 return emitError(
"memory-order must not be acq_rel for atomic writes");
5429LogicalResult AtomicUpdateOp::canonicalize(AtomicUpdateOp op,
5435 if (
Value writeVal = op.getWriteOpVal()) {
5437 op, op.getX(), writeVal, op.getHintAttr(), op.getMemoryOrderAttr());
5443LogicalResult AtomicUpdateOp::verify() {
5444 if (verifyCommon().
failed())
5445 return mlir::failure();
5448 if (
auto moduleOp = getOperation()->getParentOfType<ModuleOp>())
5449 if (
Attribute verAttr = moduleOp->getDiscardableAttr(
"omp.version"))
5450 version = llvm::cast<VersionAttr>(verAttr).getVersion();
5452 if (
auto mo = getMemoryOrder()) {
5453 if (*mo == ClauseMemoryOrderKind::Acq_rel ||
5454 *mo == ClauseMemoryOrderKind::Acquire) {
5458 "memory-order must not be acq_rel or acquire for atomic updates");
5465LogicalResult AtomicUpdateOp::verifyRegions() {
return verifyRegionsCommon(); }
5471AtomicReadOp AtomicCaptureOp::getAtomicReadOp() {
5472 if (
auto op = dyn_cast<AtomicReadOp>(getFirstOp()))
5474 return dyn_cast<AtomicReadOp>(getSecondOp());
5477AtomicWriteOp AtomicCaptureOp::getAtomicWriteOp() {
5478 if (
auto op = dyn_cast<AtomicWriteOp>(getFirstOp()))
5480 return dyn_cast<AtomicWriteOp>(getSecondOp());
5483AtomicUpdateOp AtomicCaptureOp::getAtomicUpdateOp() {
5484 if (
auto op = dyn_cast<AtomicUpdateOp>(getFirstOp()))
5486 return dyn_cast<AtomicUpdateOp>(getSecondOp());
5489AtomicCompareOp AtomicCaptureOp::getAtomicCompareOp() {
5490 if (
auto op = dyn_cast<AtomicCompareOp>(getFirstOp()))
5492 return dyn_cast<AtomicCompareOp>(getSecondOp());
5495LogicalResult AtomicCaptureOp::verify() {
5499LogicalResult AtomicCaptureOp::verifyRegions() {
5500 if (verifyRegionsCommon().
failed())
5501 return mlir::failure();
5503 if (getFirstOp()->getInherentAttr(
"hint").value_or(
Attribute{}) ||
5504 getSecondOp()->getInherentAttr(
"hint").value_or(
Attribute{}))
5506 "operations inside capture region must not have hint clause");
5508 if (getFirstOp()->getInherentAttr(
"memory_order").value_or(
Attribute{}) ||
5509 getSecondOp()->getInherentAttr(
"memory_order").value_or(
Attribute{}))
5511 "operations inside capture region must not have memory_order clause");
5519LogicalResult AtomicCompareOp::verify() {
5520 if (verifyCommon().
failed())
5521 return mlir::failure();
5525 if (
auto failOrder = getFailMemoryOrder()) {
5526 if (*failOrder != ClauseMemoryOrderKind::Seq_cst &&
5527 *failOrder != ClauseMemoryOrderKind::Acquire &&
5528 *failOrder != ClauseMemoryOrderKind::Relaxed)
5530 "fail_memory_order must be 'seq_cst', 'acquire' or 'relaxed'");
5535LogicalResult AtomicCompareOp::verifyRegions() {
5536 if (verifyRegionsCommon().
failed())
5537 return mlir::failure();
5539 if (verifyOperator().
failed())
5540 return mlir::failure();
5545 if (!terminator || !isa<YieldOp>(terminator))
5546 return emitOpError(
"region must be terminated with omp.yield");
5556 const CancelOperands &clauses) {
5557 CancelOp::build(builder, state, clauses.cancelDirective, clauses.ifExpr);
5570LogicalResult CancelOp::verify() {
5571 ClauseCancellationConstructType cct = getCancelDirective();
5574 if (!structuralParent)
5575 return emitOpError() <<
"Orphaned cancel construct";
5577 if ((cct == ClauseCancellationConstructType::Parallel) &&
5578 !mlir::isa<ParallelOp>(structuralParent)) {
5579 return emitOpError() <<
"cancel parallel must appear "
5580 <<
"inside a parallel region";
5582 if (cct == ClauseCancellationConstructType::Loop) {
5585 auto wsloopOp = mlir::dyn_cast<WsloopOp>(structuralParent->
getParentOp());
5588 return emitOpError()
5589 <<
"cancel loop must appear inside a worksharing-loop region";
5591 if (wsloopOp.getNowaitAttr()) {
5592 return emitError() <<
"A worksharing construct that is canceled "
5593 <<
"must not have a nowait clause";
5595 if (wsloopOp.getOrderedAttr()) {
5596 return emitError() <<
"A worksharing construct that is canceled "
5597 <<
"must not have an ordered clause";
5600 }
else if (cct == ClauseCancellationConstructType::Sections) {
5604 mlir::dyn_cast<SectionsOp>(structuralParent->
getParentOp());
5606 return emitOpError() <<
"cancel sections must appear "
5607 <<
"inside a sections region";
5609 if (sectionsOp.getNowait()) {
5610 return emitError() <<
"A sections construct that is canceled "
5611 <<
"must not have a nowait clause";
5614 if ((cct == ClauseCancellationConstructType::Taskgroup) &&
5615 (!mlir::isa<omp::TaskOp>(structuralParent) &&
5616 !mlir::isa<omp::TaskloopWrapperOp>(structuralParent->
getParentOp()))) {
5617 return emitOpError() <<
"cancel taskgroup must appear "
5618 <<
"inside a task region";
5628 const CancellationPointOperands &clauses) {
5629 CancellationPointOp::build(builder, state, clauses.cancelDirective);
5632LogicalResult CancellationPointOp::verify() {
5633 ClauseCancellationConstructType cct = getCancelDirective();
5636 if (!structuralParent)
5637 return emitOpError() <<
"Orphaned cancellation point";
5639 if ((cct == ClauseCancellationConstructType::Parallel) &&
5640 !mlir::isa<ParallelOp>(structuralParent)) {
5641 return emitOpError() <<
"cancellation point parallel must appear "
5642 <<
"inside a parallel region";
5646 if ((cct == ClauseCancellationConstructType::Loop) &&
5647 !mlir::isa<WsloopOp>(structuralParent->
getParentOp())) {
5648 return emitOpError() <<
"cancellation point loop must appear "
5649 <<
"inside a worksharing-loop region";
5651 if ((cct == ClauseCancellationConstructType::Sections) &&
5652 !mlir::isa<omp::SectionOp>(structuralParent)) {
5653 return emitOpError() <<
"cancellation point sections must appear "
5654 <<
"inside a sections region";
5656 if ((cct == ClauseCancellationConstructType::Taskgroup) &&
5657 (!mlir::isa<omp::TaskOp>(structuralParent) &&
5658 !mlir::isa<omp::TaskloopWrapperOp>(structuralParent->
getParentOp()))) {
5659 return emitOpError() <<
"cancellation point taskgroup must appear "
5660 <<
"inside a task region";
5669LogicalResult MapBoundsOp::verify() {
5670 auto extent = getExtent();
5672 if (!extent && !upperbound)
5673 return emitError(
"expected extent or upperbound.");
5680 PrivateClauseOp::build(
5681 odsBuilder, odsState, symName,
nullptr, type,
5682 DataSharingClauseTypeAttr::get(odsBuilder.
getContext(),
5683 DataSharingClauseType::Private));
5686LogicalResult PrivateClauseOp::verifyRegions() {
5687 Type argType = getArgType();
5688 auto verifyTerminator = [&](
Operation *terminator,
bool yieldsValue,
5689 bool yieldsAnyType) -> LogicalResult {
5693 if (!llvm::isa<YieldOp>(terminator))
5695 <<
"expected exit block terminator to be an `omp.yield` op.";
5697 YieldOp yieldOp = llvm::cast<YieldOp>(terminator);
5698 TypeRange yieldedTypes = yieldOp.getResults().getTypes();
5701 if (yieldedTypes.empty())
5705 <<
"Did not expect any values to be yielded.";
5708 if (yieldedTypes.size() == 1 &&
5709 (yieldsAnyType || yieldedTypes.front() == argType))
5713 <<
"Invalid yielded value. Expected ";
5715 error <<
"a single value";
5717 error <<
"type: " << argType;
5720 if (yieldedTypes.empty())
5723 error << yieldedTypes;
5729 StringRef regionName,
bool yieldsValue,
5730 bool yieldsAnyType =
false) -> LogicalResult {
5731 assert(!region.
empty());
5735 <<
"`" << regionName <<
"`: " <<
"expected " << expectedNumArgs
5738 for (
Block &block : region) {
5752 for (
Region *region : getRegions())
5753 for (
Type ty : region->getArgumentTypes())
5755 return emitError() <<
"Region argument type mismatch: got " << ty
5756 <<
" expected " << argType <<
".";
5759 if (!initRegion.
empty() &&
5764 DataSharingClauseType dsType = getDataSharingType();
5766 if (dsType == DataSharingClauseType::Private && !getCopyRegion().empty())
5767 return emitError(
"`private` clauses do not require a `copy` region.");
5769 if (dsType == DataSharingClauseType::FirstPrivate && getCopyRegion().empty())
5771 "`firstprivate` clauses require at least a `copy` region.");
5773 if (dsType == DataSharingClauseType::FirstPrivate &&
5778 if (dsType == DataSharingClauseType::Linear && !getCopyRegion().empty())
5779 return emitError(
"`linear` clauses do not require a `copy` region.");
5781 if (!getDataAddressRegion().empty()) {
5782 if (dsType != DataSharingClauseType::Linear)
5784 "only `linear` clauses can have a `data_address` region.");
5786 "data_address",
true,
5791 if (!getDeallocRegion().empty() &&
5804 const MaskedOperands &clauses) {
5805 MaskedOp::build(builder, state, clauses.filteredThreadId);
5813 const DispatchOperands &clauses) {
5814 DispatchOp::build(builder, state, clauses.nocontext, clauses.novariants,
5823 const ScanOperands &clauses) {
5824 ScanOp::build(builder, state, clauses.inclusiveVars, clauses.exclusiveVars);
5827LogicalResult ScanOp::verify() {
5828 if (hasExclusiveVars() == hasInclusiveVars())
5830 "Exactly one of EXCLUSIVE or INCLUSIVE clause is expected");
5831 if (WsloopOp parentWsLoopOp = (*this)->getParentOfType<WsloopOp>()) {
5832 if (parentWsLoopOp.hasReductionModifier(ReductionModifier::inscan))
5835 if (SimdOp parentSimdOp = (*this)->getParentOfType<SimdOp>()) {
5836 if (parentSimdOp.hasReductionModifier(ReductionModifier::inscan))
5839 return emitError(
"SCAN directive needs to be enclosed within a parent "
5840 "worksharing loop construct or SIMD construct with INSCAN "
5841 "reduction modifier");
5846 std::optional<uint64_t> alignment) {
5847 if (alignment.has_value()) {
5848 if ((alignment.value() != 0) && !llvm::has_single_bit(alignment.value()))
5850 <<
"ALIGN value : " << alignment.value() <<
" must be power of 2";
5855LogicalResult AllocateDirOp::verify() {
5863LogicalResult AllocSharedMemOp::verify() {
5871LogicalResult FreeSharedMemOp::verify() {
5879LogicalResult WorkdistributeOp::verify() {
5881 return emitOpError() <<
"cannot be a non-innermost combined construct leaf";
5884 Region ®ion = getRegion();
5886 return emitOpError(
"region cannot be empty");
5889 if (entryBlock.
empty())
5890 return emitOpError(
"region must contain a structured block");
5892 bool hasTerminator =
false;
5893 for (
Block &block : region) {
5894 if (isa<TerminatorOp>(block.
back())) {
5895 if (hasTerminator) {
5896 return emitOpError(
"region must have exactly one terminator");
5898 hasTerminator =
true;
5901 if (!hasTerminator) {
5902 return emitOpError(
"region must be terminated with omp.terminator");
5906 if (isa<BarrierOp>(op)) {
5908 "explicit barriers are not allowed in workdistribute region");
5911 if (isa<ParallelOp>(op)) {
5913 "nested parallel constructs not allowed in workdistribute");
5915 if (isa<TeamsOp>(op)) {
5917 "nested teams constructs not allowed in workdistribute");
5921 if (walkResult.wasInterrupted())
5925 if (!llvm::dyn_cast<TeamsOp>(parentOp))
5926 return emitOpError(
"workdistribute must be nested under teams");
5934LogicalResult DeclareSimdOp::verify() {
5937 dyn_cast_if_present<mlir::FunctionOpInterface>((*this)->getParentOp());
5939 return emitOpError() <<
"must be nested inside a function";
5941 if (getInbranch() && getNotinbranch())
5942 return emitOpError(
"cannot have both 'inbranch' and 'notinbranch'");
5948 if (getLinearSyms())
5949 return emitOpError(
"linear privatizers are not allowed");
5955 const DeclareSimdOperands &clauses) {
5957 DeclareSimdOp::build(
5958 odsBuilder, odsState, clauses.alignedVars,
5960 clauses.linearVars, clauses.linearStepVars, clauses.linearVarTypes,
5961 clauses.linearModifiers,
makeArrayAttr(ctx, clauses.linearSyms),
5962 clauses.notinbranch, clauses.simdlen, clauses.uniformVars);
5979 return mlir::failure();
5980 return mlir::success();
5987 for (
unsigned i = 0; i < uniformVars.size(); ++i) {
5990 p << uniformVars[i] <<
" : " << uniformTypes[i];
6005 parser, iterated, iteratedTypes, affinityVars, affinityVarTypes,
6006 [&]() -> ParseResult {
return success(); })))
6040 OpAsmParser::Argument &arg = ivArgs.emplace_back();
6041 if (parser.parseArgument(arg))
6045 if (succeeded(parser.parseOptionalColon())) {
6046 if (parser.parseType(arg.type))
6049 arg.type = parser.getBuilder().getIndexType();
6061 OpAsmParser::UnresolvedOperand lb, ub, st;
6062 if (parser.parseOperand(lb) || parser.parseKeyword(
"to") ||
6063 parser.parseOperand(ub) || parser.parseKeyword(
"step") ||
6064 parser.parseOperand(st))
6069 steps.push_back(st);
6077 if (ivArgs.size() != lbs.size())
6079 <<
"mismatch: " << ivArgs.size() <<
" variables but " << lbs.size()
6082 for (
auto &arg : ivArgs) {
6083 lbTypes.push_back(arg.type);
6084 ubTypes.push_back(arg.type);
6085 stepTypes.push_back(arg.type);
6105 for (
unsigned i = 0, e = lbs.size(); i < e; ++i) {
6108 p << lbs[i] <<
" to " << ubs[i] <<
" step " << steps[i];
6116YieldOp IteratorOp::getYieldOp() {
6118 for (
Block &block : getRegion()) {
6120 dyn_cast_if_present<YieldOp>(block.
empty() ?
nullptr : &block.
back());
6130LogicalResult IteratorOp::verify() {
6131 auto iteratedTy = llvm::dyn_cast<omp::IteratedType>(getIterated().
getType());
6133 return emitOpError() <<
"result must be omp.iterated<entry_ty>";
6136 if (getLoopLowerBounds().size() != ivs.size())
6137 return emitOpError() <<
"number of range arguments and IVs do not match";
6139 for (
auto [lb, iv] : llvm::zip_equal(getLoopLowerBounds(), ivs)) {
6140 if (lb.getType() != iv.getType())
6141 return emitOpError()
6142 <<
"range argument type does not match corresponding IV type";
6145 for (
Value step : getLoopSteps()) {
6147 return emitOpError() <<
"loop step must not be zero";
6150 YieldOp yield = getYieldOp();
6152 bool hasYield = llvm::any_of(getRegion(), [](
Block &block) {
6153 return !block.
empty() && isa<YieldOp>(block.
back());
6156 return emitOpError() <<
"region must contain exactly one omp.yield";
6157 return emitOpError() <<
"region must be terminated by omp.yield";
6160 if (yield.getNumOperands() != 1)
6161 return emitOpError()
6162 <<
"omp.yield in omp.iterator region must yield exactly one value";
6164 mlir::Type yieldedTy = yield.getOperand(0).getType();
6165 mlir::Type elemTy = iteratedTy.getElementType();
6167 if (yieldedTy != elemTy)
6168 return emitOpError() <<
"omp.iterated element type (" << elemTy
6169 <<
") does not match omp.yield operand type ("
6170 << yieldedTy <<
")";
6175LogicalResult IteratorOp::verifyRegions() {
6177 for (
Block &block : getRegion()) {
6181 <<
"expected exit block terminator to be an `omp.yield` op.";
6194 return emitOpError() <<
"expected symbol reference '" << getSymName()
6195 <<
"' to point to a global variable";
6197 if (isa<FunctionOpInterface>(symbol))
6198 return emitOpError() <<
"expected symbol reference '" << getSymName()
6199 <<
"' to point to a global variable, not a function";
6204#define GET_ATTRDEF_CLASSES
6205#include "mlir/Dialect/OpenMP/OpenMPOpsAttributes.cpp.inc"
6207#define GET_OP_CLASSES
6208#include "mlir/Dialect/OpenMP/OpenMPOps.cpp.inc"
6210#define GET_TYPEDEF_CLASSES
6211#include "mlir/Dialect/OpenMP/OpenMPOpsTypes.cpp.inc"
if(failed(verifyVectorMemoryOp(getOperation(), memrefType, getVectorType()))) return failure()
static std::optional< int64_t > getUpperBound(Value iv)
Gets the constant upper bound on an affine.for iv.
static LogicalResult verifyRegion(emitc::SwitchOp op, Region ®ion, const Twine &name)
static const mlir::GenInfo * generator
static LogicalResult verifyNontemporalClause(Operation *op, OperandRange nontemporalVars)
static DenseI64ArrayAttr makeDenseI64ArrayAttr(MLIRContext *ctx, const ArrayRef< int64_t > intArray)
static void printDependVarList(OpAsmPrinter &p, Operation *op, OperandRange dependVars, TypeRange dependTypes, std::optional< ArrayAttr > dependKinds, OperandRange iteratedVars, TypeRange iteratedTypes, std::optional< ArrayAttr > iteratedKinds)
Print Depend clause.
static ParseResult parseTargetOpRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &hasDeviceAddrVars, SmallVectorImpl< Type > &hasDeviceAddrTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &hostEvalVars, SmallVectorImpl< Type > &hostEvalTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &mapVars, SmallVectorImpl< Type > &mapTypes, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier, DenseI64ArrayAttr &privateMaps)
static constexpr StringRef getPrivateNeedsBarrierSpelling()
static void printHeapAllocClause(OpAsmPrinter &p, Operation *op, TypeAttr inType, ValueRange typeparams, TypeRange typeparamsTypes, ValueRange shape, TypeRange shapeTypes)
static ParseResult parseInReductionPrivateReductionRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &inReductionVars, SmallVectorImpl< Type > &inReductionTypes, DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier, ArrayAttr &reductionMods, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &reductionVars, SmallVectorImpl< Type > &reductionTypes, DenseBoolArrayAttr &reductionByref, ArrayAttr &reductionSyms)
static ParseResult parseInReductionPrivateRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &inReductionVars, SmallVectorImpl< Type > &inReductionTypes, DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier)
static ArrayAttr makeArrayAttr(MLIRContext *context, llvm::ArrayRef< Attribute > attrs)
static ParseResult parseClauseAttr(AsmParser &parser, ClauseAttr &attr)
static void printLinearPrivateReductionRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange linearVars, TypeRange linearTypes, ValueRange linearStepVars, TypeRange linearStepTypes, ArrayAttr linearVarTypes, ArrayAttr linearModifiers, ArrayAttr linearSyms, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier, ArrayAttr reductionMods, ValueRange reductionVars, TypeRange reductionTypes, DenseBoolArrayAttr reductionByref, ArrayAttr reductionSyms)
static ParseResult parseLinearPrivateReductionRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &linearVars, SmallVectorImpl< Type > &linearTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &linearStepVars, SmallVectorImpl< Type > &linearStepTypes, ArrayAttr &linearVarTypes, ArrayAttr &linearModifiers, ArrayAttr &linearSyms, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier, ArrayAttr &reductionMods, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &reductionVars, SmallVectorImpl< Type > &reductionTypes, DenseBoolArrayAttr &reductionByref, ArrayAttr &reductionSyms)
static void printDynGroupprivateClause(OpAsmPrinter &printer, Operation *op, AccessGroupModifierAttr modifierFirst, FallbackModifierAttr modifierSecond, Value dynGroupprivateSize, Type sizeType)
static void printAllocateAndAllocator(OpAsmPrinter &p, Operation *op, OperandRange allocateVars, TypeRange allocateTypes, OperandRange allocatorVars, TypeRange allocatorTypes)
Print allocate clause.
static DenseBoolArrayAttr makeDenseBoolArrayAttr(MLIRContext *ctx, const ArrayRef< bool > boolArray)
static std::string generateLoopNestingName(StringRef prefix, CanonicalLoopOp op)
Generate a name of a canonical loop nest of the format <prefix>(_r<idx>_s<idx>)*.
static ParseResult parseAffinityClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &iterated, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &affinityVars, SmallVectorImpl< Type > &iteratedTypes, SmallVectorImpl< Type > &affinityVarTypes)
static void printSplitIteratedList(OpAsmPrinter &p, ValueRange iteratedVars, TypeRange iteratedTypes, ValueRange plainVars, TypeRange plainTypes, PrintPrefixFn &&printPrefixForPlain, PrintPrefixFn &&printPrefixForIterated)
static LogicalResult verifyDependVarList(Operation *op, std::optional< ArrayAttr > dependKinds, OperandRange dependVars, std::optional< ArrayAttr > iteratedKinds, OperandRange iteratedVars)
Verifies Depend clause.
static void addUnknownMemoryEffects(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Add arbitrary read, write, allocate, and free effects.
static void printBlockArgClause(OpAsmPrinter &p, MLIRContext *ctx, StringRef clauseName, ValueRange argsSubrange, std::optional< MapPrintArgs > mapArgs)
static void printAffinityClause(OpAsmPrinter &p, Operation *op, ValueRange iterated, ValueRange affinityVars, TypeRange iteratedTypes, TypeRange affinityVarTypes)
static void printBlockArgRegion(OpAsmPrinter &p, Operation *op, Region ®ion, const AllRegionPrintArgs &args)
static ParseResult parseGranularityClause(OpAsmParser &parser, ClauseTypeAttr &prescriptiveness, std::optional< OpAsmParser::UnresolvedOperand > &operand, Type &operandType, std::optional< ClauseType >(*symbolizeClause)(StringRef), StringRef clauseName)
static void printIteratorHeader(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange lbs, ValueRange ubs, ValueRange steps, TypeRange, TypeRange, TypeRange)
static LogicalResult verifyDeclareTargetAttr(Operation *op, Attribute attr)
static ParseResult parseHeapAllocClause(OpAsmParser &parser, TypeAttr &inTypeAttr, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &typeparams, SmallVectorImpl< Type > &typeparamsTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &shape, SmallVectorImpl< Type > &shapeTypes)
operation ::= $in_type ( ( $typeparams ) )? ( , $shape )?
static void printInReductionClause(OpAsmPrinter &p, Operation *op, ValueRange inReductionVars, TypeRange inReductionTypes, DenseBoolArrayAttr inReductionByref, ArrayAttr inReductionSyms)
Prints an in_reduction clause for an operation that does not give its list items entry block argument...
static void printClauseWithRegionArgs(OpAsmPrinter &p, MLIRContext *ctx, StringRef clauseName, ValueRange argsSubrange, ValueRange operands, TypeRange types, ArrayAttr symbols=nullptr, DenseI64ArrayAttr mapIndices=nullptr, DenseBoolArrayAttr byref=nullptr, ArrayAttr modifier=nullptr, UnitAttr needsBarrier=nullptr)
static ParseResult parseIteratorHeader(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &lbs, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &ubs, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &steps, SmallVectorImpl< Type > &lbTypes, SmallVectorImpl< Type > &ubTypes, SmallVectorImpl< Type > &stepTypes)
static LogicalResult verifyReductionVarList(Operation *op, std::optional< ArrayAttr > reductionSyms, OperandRange reductionVars, std::optional< ArrayRef< bool > > reductionByref, ArrayAttr reductionMods=nullptr)
Verifies Reduction Clause.
static ParseResult parseBlockArgRegion(OpAsmParser &parser, Region ®ion, AllRegionParseArgs args)
static ParseResult parseLoopTransformClis(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &generateesOperands, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &applyeesOperands)
static ParseResult parseSynchronizationHint(OpAsmParser &parser, IntegerAttr &hintAttr)
Parses a Synchronization Hint clause.
static void printLinearClause(OpAsmPrinter &p, Operation *op, ValueRange linearVars, TypeRange linearTypes, ValueRange linearStepVars, TypeRange stepVarTypes, ArrayAttr linearModifiers, ArrayAttr linearSyms)
Print Linear Clause.
static void printScheduleClause(OpAsmPrinter &p, Operation *op, ClauseScheduleKindAttr scheduleKind, ScheduleModifierAttr scheduleMod, UnitAttr scheduleSimd, Value scheduleChunk, Type scheduleChunkType)
Print schedule clause.
static ParseResult parsePrivateReductionRegion(OpAsmParser &parser, Region ®ion, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier, ArrayAttr &reductionMods, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &reductionVars, SmallVectorImpl< Type > &reductionTypes, DenseBoolArrayAttr &reductionByref, ArrayAttr &reductionSyms)
static void printCopyprivate(OpAsmPrinter &p, Operation *op, OperandRange copyprivateVars, TypeRange copyprivateTypes, std::optional< ArrayAttr > copyprivateSyms)
Print Copyprivate clause.
static ParseResult parseOrderClause(OpAsmParser &parser, ClauseOrderKindAttr &order, OrderModifierAttr &orderMod)
static bool mapTypeToBool(ClauseMapFlags value, ClauseMapFlags flag)
static void printAlignedClause(OpAsmPrinter &p, Operation *op, ValueRange alignedVars, TypeRange alignedTypes, std::optional< ArrayAttr > alignments)
Print Aligned Clause.
static bool targetInReductionCapturedBy(Value inReductionVar, Value mapVarPtr)
An omp.target in_reduction operand is captured by a map_entries entry when the entry's MapInfoOp var_...
static LogicalResult verifySynchronizationHint(Operation *op, uint64_t hint)
Verifies a synchronization hint clause.
static ParseResult parseUseDeviceAddrUseDevicePtrRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &useDeviceAddrVars, SmallVectorImpl< Type > &useDeviceAddrTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &useDevicePtrVars, SmallVectorImpl< Type > &useDevicePtrTypes)
static void printPrivateReductionRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier, ArrayAttr reductionMods, ValueRange reductionVars, TypeRange reductionTypes, DenseBoolArrayAttr reductionByref, ArrayAttr reductionSyms)
static ParseResult parseUniformClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &uniformVars, SmallVectorImpl< Type > &uniformTypes)
uniform ::= uniform ( uniform-list ) uniform-list := uniform-val (, uniform-val)* uniform-val := ssa-...
static void printInReductionPrivateRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange inReductionVars, TypeRange inReductionTypes, DenseBoolArrayAttr inReductionByref, ArrayAttr inReductionSyms, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier)
static LogicalResult verifyAllocateClause(Operation *op, ValueRange allocateVars, ValueRange allocatorVars, DenseI64ArrayAttr allocateAlignments, DenseI64ArrayAttr allocatePrivateIndices, ValueRange privateVars={}, ArrayAttr privateSyms=nullptr, bool requirePrivateIndices=false)
static void printSynchronizationHint(OpAsmPrinter &p, Operation *op, IntegerAttr hintAttr)
Prints a Synchronization Hint clause.
static void printGranularityClause(OpAsmPrinter &p, Operation *op, ClauseTypeAttr prescriptiveness, Value operand, mlir::Type operandType, StringRef(*stringifyClauseType)(ClauseType))
static ParseResult parseDependVarList(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &dependVars, SmallVectorImpl< Type > &dependTypes, ArrayAttr &dependKinds, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &iteratedVars, SmallVectorImpl< Type > &iteratedTypes, ArrayAttr &iteratedKinds)
depend-entry-list ::= depend-entry | depend-entry-list , depend-entry depend-entry ::= depend-kind ->...
static Operation * getParentInSameDialect(Operation *thisOp)
static void printUniformClause(OpAsmPrinter &p, Operation *op, ValueRange uniformVars, TypeRange uniformTypes)
Print Uniform Clauses.
static LogicalResult verifyCopyprivateVarList(Operation *op, OperandRange copyprivateVars, std::optional< ArrayAttr > copyprivateSyms)
Verifies CopyPrivate Clause.
static LogicalResult verifyAlignedClause(Operation *op, std::optional< ArrayAttr > alignments, OperandRange alignedVars)
static ParseResult parsePrivateRegion(OpAsmParser &parser, Region ®ion, llvm::SmallVectorImpl< OpAsmParser::UnresolvedOperand > &privateVars, llvm::SmallVectorImpl< Type > &privateTypes, ArrayAttr &privateSyms, UnitAttr &privateNeedsBarrier)
static void printNumTasksClause(OpAsmPrinter &p, Operation *op, ClauseNumTasksTypeAttr numTasksMod, Value numTasks, mlir::Type numTasksType)
static void printLoopTransformClis(OpAsmPrinter &p, TileOp op, OperandRange generatees, OperandRange applyees)
static ParseResult parseDynGroupprivateClause(OpAsmParser &parser, AccessGroupModifierAttr &accessGroupAttr, FallbackModifierAttr &fallbackAttr, std::optional< OpAsmParser::UnresolvedOperand > &dynGroupprivateSize, Type &sizeType)
static void printPrivateRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier)
static ParseResult parseSplitIteratedList(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &iteratedVars, SmallVectorImpl< Type > &iteratedTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &plainVars, SmallVectorImpl< Type > &plainTypes, ParsePrefixFn &&parsePrefix)
static void printTaskReductionRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange taskReductionVars, TypeRange taskReductionTypes, DenseBoolArrayAttr taskReductionByref, ArrayAttr taskReductionSyms)
static LogicalResult verifyMapInfoForMapClause(Operation *op, mlir::omp::MapInfoOp mapInfoOp, llvm::DenseSet< mlir::TypedValue< mlir::omp::PointerLikeType > > &updateToVars, llvm::DenseSet< mlir::TypedValue< mlir::omp::PointerLikeType > > &updateFromVars)
static void getPrivatisationEffects(Operation *op, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Privatisation may read the original as a mold or firstprivate copy source. Any lastprivate copy-back ...
static void printInReductionPrivateReductionRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange inReductionVars, TypeRange inReductionTypes, DenseBoolArrayAttr inReductionByref, ArrayAttr inReductionSyms, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier, ArrayAttr reductionMods, ValueRange reductionVars, TypeRange reductionTypes, DenseBoolArrayAttr reductionByref, ArrayAttr reductionSyms)
static void getBarrierEffects(llvm::SmallVectorImpl< SideEffects::EffectInstance< MemoryEffects::Effect > > &effects)
static LogicalResult verifyOrderedParent(Operation &op)
static void printOrderClause(OpAsmPrinter &p, Operation *op, ClauseOrderKindAttr order, OrderModifierAttr orderMod)
static ParseResult parseBlockArgClause(OpAsmParser &parser, llvm::SmallVectorImpl< OpAsmParser::Argument > &entryBlockArgs, StringRef keyword, std::optional< MapParseArgs > mapArgs)
static LogicalResult verifyPrivateVarsMapping(TargetOp targetOp)
static ParseResult parseScheduleClause(OpAsmParser &parser, ClauseScheduleKindAttr &scheduleAttr, ScheduleModifierAttr &scheduleMod, UnitAttr &scheduleSimd, std::optional< OpAsmParser::UnresolvedOperand > &chunkSize, Type &chunkType)
schedule ::= schedule ( sched-list ) sched-list ::= sched-val | sched-val sched-list | sched-val ,...
static LogicalResult verifyDynGroupprivateClause(Operation *op, AccessGroupModifierAttr accessGroup, FallbackModifierAttr fallback, Value dynGroupprivateSize)
static LogicalResult verifyLinearModifiers(Operation *op, std::optional< ArrayAttr > linearModifiers, OperandRange linearVars, bool isDeclareSimd=false)
OpenMP 5.2, Section 5.4.6: "A linear-modifier may be specified as ref or uval only on a declare simd ...
static void printClauseAttr(OpAsmPrinter &p, Operation *op, ClauseAttr attr)
static LogicalResult verifyLinearSyms(OpType op)
Verifies that each linear variable has a linear privatizer.
static ParseResult parseAllocateAndAllocator(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &allocateVars, SmallVectorImpl< Type > &allocateTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &allocatorVars, SmallVectorImpl< Type > &allocatorTypes)
Parse an allocate clause with allocators and a list of operands with types.
static void printMembersIndex(OpAsmPrinter &p, MapInfoOp op, ArrayAttr membersIdx)
static void getReductionEffects(Operation *op, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Reductions initialise private accumulators and combine them into the original variables....
static ParseResult parseClauseWithRegionArgs(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &operands, SmallVectorImpl< Type > &types, SmallVectorImpl< OpAsmParser::Argument > ®ionPrivateArgs, ArrayAttr *symbols=nullptr, DenseI64ArrayAttr *mapIndices=nullptr, DenseBoolArrayAttr *byref=nullptr, ArrayAttr *modifier=nullptr, UnitAttr *needsBarrier=nullptr)
static void printCaptureType(OpAsmPrinter &p, Operation *op, VariableCaptureKindAttr mapCaptureType)
static LogicalResult verifyReductionModifiers(Operation *op, OperandRange reductionVars, ArrayAttr reductionMods)
Verify the per-variable modifier list has one entry per reduction variable.
static LogicalResult verifyNumTeamsClause(Operation *op, Value numTeamsLower, OperandRange numTeamsUpperVars)
static bool opInGlobalImplicitParallelRegion(Operation *op)
static void printTargetOpRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange hasDeviceAddrVars, TypeRange hasDeviceAddrTypes, ValueRange hostEvalVars, TypeRange hostEvalTypes, ValueRange mapVars, TypeRange mapTypes, ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier, DenseI64ArrayAttr privateMaps)
static void printUseDeviceAddrUseDevicePtrRegion(OpAsmPrinter &p, Operation *op, Region ®ion, ValueRange useDeviceAddrVars, TypeRange useDeviceAddrTypes, ValueRange useDevicePtrVars, TypeRange useDevicePtrTypes)
static LogicalResult verifyMapClause(Operation *op, OperandRange mapVars, OperandRange mapIterated)
static LogicalResult verifyPrivateVarList(OpType &op)
static ParseResult parseNumTasksClause(OpAsmParser &parser, ClauseNumTasksTypeAttr &numTasksMod, std::optional< OpAsmParser::UnresolvedOperand > &numTasks, Type &numTasksType)
LogicalResult verifyAlignment(Operation &op, std::optional< uint64_t > alignment)
Verifies align clause in allocate directive.
static ParseResult parseAlignedClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &alignedVars, SmallVectorImpl< Type > &alignedTypes, ArrayAttr &alignmentsAttr)
aligned ::= aligned ( aligned-list ) aligned-list := aligned-val | aligned-val aligned-list aligned-v...
static ParseResult parseLinearClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &linearVars, SmallVectorImpl< Type > &linearTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &linearStepVars, SmallVectorImpl< Type > &linearStepTypes, ArrayAttr &linearModifiers, ArrayAttr &linearSyms)
linear ::= linear ( linear-list ) linear-list := linear-val | linear-val linear-list linear-val := ss...
static LogicalResult checkApplyeesNesting(TileOp op)
Check properties of the loop nest consisting of the transformation's applyees:
static ParseResult parseCaptureType(OpAsmParser &parser, VariableCaptureKindAttr &mapCaptureType)
static ParseResult parseTaskReductionRegion(OpAsmParser &parser, Region ®ion, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &taskReductionVars, SmallVectorImpl< Type > &taskReductionTypes, DenseBoolArrayAttr &taskReductionByref, ArrayAttr &taskReductionSyms)
static ParseResult parseGrainsizeClause(OpAsmParser &parser, ClauseGrainsizeTypeAttr &grainsizeMod, std::optional< OpAsmParser::UnresolvedOperand > &grainsize, Type &grainsizeType)
static ParseResult parseCopyprivate(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > ©privateVars, SmallVectorImpl< Type > ©privateTypes, ArrayAttr ©privateSyms)
copyprivate-entry-list ::= copyprivate-entry | copyprivate-entry-list , copyprivate-entry copyprivate...
static ParseResult parseInReductionClause(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &inReductionVars, SmallVectorImpl< Type > &inReductionTypes, DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms)
Parses an in_reduction clause for an operation that does not give its list items entry block argument...
static LogicalResult verifyMapInfoDefinedArgs(Operation *op, StringRef clauseName, OperandRange vars)
static void printGrainsizeClause(OpAsmPrinter &p, Operation *op, ClauseGrainsizeTypeAttr grainsizeMod, Value grainsize, mlir::Type grainsizeType)
static ParseResult verifyScheduleModifiers(OpAsmParser &parser, SmallVectorImpl< SmallString< 12 > > &modifiers)
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
static bool isUnique(It begin, It end)
static LogicalResult emit(SolverOp solver, const SMTEmissionOptions &options, mlir::raw_indented_ostream &stream)
Emit the SMT operations in the given 'solver' to the 'stream'.
static SmallVector< Value > getTileSizes(Location loc, x86::amx::TileType tType, RewriterBase &rewriter)
Maps the 2-dim vector shape to the two 16-bit tile sizes.
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseMinus()=0
Parse a '-' token.
@ Paren
Parens surrounding zero or more operands.
@ None
Zero or more operands with no delimiters.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalEqual()=0
Parse a = token if present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
virtual ParseResult parseLSquare()=0
Parse a [ token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseOptionalArrow()=0
Parse a '->' token if present.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual ParseResult parseColon()=0
Parse a : token.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalLess()=0
Parse a '<' token if present.
virtual ParseResult parseArrow()=0
Parse a '->' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalLParen()=0
Parse a ( token if present.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseOptionalLSquare()=0
Parse a [ token if present.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
Attributes are known-constant values of operations.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
MutableArrayRef< BlockArgument > BlockArgListType
ValueTypeRange< BlockArgListType > getArgumentTypes()
Return a range containing the types of the arguments for this block.
unsigned getNumSuccessors()
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
SuccessorRange getSuccessors()
Operation * getTerminator()
Get the terminator operation of this block.
bool mightHaveTerminator()
Return "true" if this block might have a terminator.
BlockArgListType getArguments()
IntegerAttr getI64IntegerAttr(int64_t value)
IntegerType getIntegerType(unsigned width)
MLIRContext * getContext() const
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Diagnostic & append(Arg1 &&arg1, Arg2 &&arg2, Args &&...args)
Append arguments to the diagnostic.
Diagnostic & appendOp(Operation &op, const OpPrintingFlags &flags)
Append an operation with the given printing flags.
A class for computing basic dominance information.
bool dominates(Operation *a, Operation *b) const
Return true if operation A dominates operation B, i.e.
This class represents a diagnostic that is inflight and set to be reported.
Diagnostic & attachNote(std::optional< Location > noteLoc=std::nullopt)
Attaches a note to this diagnostic.
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttribute represents a combination of a name and an Attribute value.
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region ®ion, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult parseArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument with the following syntax:
virtual ParseResult parseArgumentList(SmallVectorImpl< Argument > &result, Delimiter delimiter=Delimiter::None, bool allowType=false, bool allowAttrs=false)=0
Parse zero or more arguments with a specified surrounding delimiter.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
virtual void printRegionArgument(BlockArgument arg, ArrayRef< NamedAttribute > argAttrs={}, bool omitType=false)=0
Print a block argument in the usual format of: ssaName : type {attr1=42} loc("here") where location p...
virtual void printOperand(Value value)=0
Print implementations for various things an operation contains.
This class helps build Operations.
This class represents an operand of an operation.
Set of flags used to control the behavior of the various IR print methods (e.g.
This class provides the API for ops that are known to be isolated from above.
This class provides the API for ops that are known to be terminators.
This class indicates that the regions associated with this op don't have terminators.
This class implements the operand iterators for the Operation class.
type_range getType() const
Operation is the basic unit of execution within MLIR.
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Block * getBlock()
Returns the operation block that contains this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
operand_range getOperands()
Returns an iterator on the underlying Value's.
user_range getUsers()
Returns a range of all users.
Region * getParentRegion()
Returns the region to which the instruction belongs.
MLIRContext * getContext()
Return the context this operation is associated with.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
BlockArgListType getArguments()
OpIterator op_begin()
Return iterators that walk the operations nested directly within this region.
bool isAncestor(Region *other)
Return true if this region is ancestor of the other region.
iterator_range< OpIterator > getOps()
unsigned getNumArguments()
Location getLoc()
Return a location for this region.
BlockArgument getArgument(unsigned i)
Operation * getParentOp()
Return the parent operation this region is attached to.
BlockListType & getBlocks()
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class represents a specific instance of an effect.
static DerivedEffect * get()
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
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 various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over Values.
type_range getType() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
MLIRContext * getContext() const
Utility to get the associated MLIRContext that this value is defined in.
Type getType() const
Return the type of this value.
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
A utility result that is used to signal how to proceed with an ongoing walk:
static WalkResult advance()
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< bool > content)
ArrayRef< T > asArrayRef() const
bool isReachableFromEntry(Block *a) const
Return true if the specified block is reachable from the entry block of its region.
Operation * getOwner() const
Return the owner of this operand.
TargetEnterDataOperands TargetEnterExitUpdateDataOperands
omp.target_enter_data, omp.target_exit_data and omp.target_update take the same clauses,...
std::tuple< NewCliOp, OpOperand *, OpOperand * > decodeCli(mlir::Value cli)
Find the omp.new_cli, generator, and consumer of a canonical loop info.
ClauseProcBindKind convertProcBindKind(llvm::omp::ProcBindKind kind)
Convert a proc_bind kind from the LLVM frontend enum to the corresponding OpenMP dialect enum.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
A functor used to set the name of the start of a result group of an operation.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
llvm::TypeSwitch< T, ResultT > TypeSwitch
SmallVector< Loops, 8 > tile(ArrayRef< scf::ForOp > forOps, ArrayRef< Value > sizes, ArrayRef< scf::ForOp > targets)
Performs tiling fo imperfectly nested loops (with interchange) by strip-mining the forOps by sizes an...
detail::DenseArrayAttrImpl< bool > DenseBoolArrayAttr
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
function_ref< void(Block *, StringRef)> OpAsmSetBlockNameFn
A functor used to set the name of blocks in regions directly nested under an operation.
This is the representation of an operand reference.
This class provides APIs and verifiers for ops with regions having a single block.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
T & getOrAddProperties()
Get (or create) the properties of the provided type to be set on the operation on creation.
void addOperands(ValueRange newOperands)
void addAttributes(ArrayRef< NamedAttribute > newAttributes)
Add an array of named attributes.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
void addTypes(ArrayRef< Type > newTypes)
Region * addRegion()
Create a region that should be attached to the operation.
Extended TargetOperands with kernel_type attribute.
TargetExecModeAttr kernelType
Kernel execution mode for the target region.