MLIR 24.0.0git
OpenMPDialect.cpp
Go to the documentation of this file.
1//===- OpenMPDialect.cpp - MLIR Dialect for OpenMP implementation ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the OpenMP dialect and its operations.
10//
11//===----------------------------------------------------------------------===//
12
20#include "mlir/IR/Attributes.h"
22#include "mlir/IR/Matchers.h"
25#include "mlir/IR/SymbolTable.h"
26#include "mlir/IR/Value.h"
30
31#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/PostOrderIterator.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/STLForwardCompat.h"
35#include "llvm/ADT/SmallString.h"
36#include "llvm/ADT/StringRef.h"
37#include "llvm/ADT/TypeSwitch.h"
38#include "llvm/ADT/bit.h"
39#include "llvm/Support/InterleavedRange.h"
40#include <cstddef>
41#include <iterator>
42#include <optional>
43#include <variant>
44
45#include "mlir/Dialect/OpenMP/OpenMPOpsDialect.cpp.inc"
46#include "mlir/Dialect/OpenMP/OpenMPOpsEnums.cpp.inc"
47#include "mlir/Dialect/OpenMP/OpenMPOpsInterfaces.cpp.inc"
48#include "mlir/Dialect/OpenMP/OpenMPTypeInterfaces.cpp.inc"
49#include "mlir/Support/LLVM.h"
50
51using namespace mlir;
52using namespace mlir::omp;
53
56 return attrs.empty() ? nullptr : ArrayAttr::get(context, attrs);
57}
58
61 return boolArray.empty() ? nullptr : DenseBoolArrayAttr::get(ctx, boolArray);
62}
63
66 return intArray.empty() ? nullptr : DenseI64ArrayAttr::get(ctx, intArray);
67}
68
69namespace {
70struct MemRefPointerLikeModel
71 : public PointerLikeType::ExternalModel<MemRefPointerLikeModel,
72 MemRefType> {
73 Type getElementType(Type pointer) const {
74 return llvm::cast<MemRefType>(pointer).getElementType();
75 }
76};
77
78struct LLVMPointerPointerLikeModel
79 : public PointerLikeType::ExternalModel<LLVMPointerPointerLikeModel,
80 LLVM::LLVMPointerType> {
81 Type getElementType(Type pointer) const { return Type(); }
82};
83} // namespace
84
85/// Generate a name of a canonical loop nest of the format
86/// `<prefix>(_r<idx>_s<idx>)*`. Hereby, `_r<idx>` identifies the region
87/// argument index of an operation that has multiple regions, if the operation
88/// has multiple regions.
89/// `_s<idx>` identifies the position of an operation within a region, where
90/// only operations that may potentially contain loops ("container operations"
91/// i.e. have region arguments) are counted. Again, it is omitted if there is
92/// only one such operation in a region. If there are canonical loops nested
93/// inside each other, also may also use the format `_d<num>` where <num> is the
94/// nesting depth of the loop.
95///
96/// The generated name is a best-effort to make canonical loop unique within an
97/// SSA namespace. This also means that regions with IsolatedFromAbove property
98/// do not consider any parents or siblings.
99static std::string generateLoopNestingName(StringRef prefix,
100 CanonicalLoopOp op) {
101 struct Component {
102 /// If true, this component describes a region operand of an operation (the
103 /// operand's owner) If false, this component describes an operation located
104 /// in a parent region
105 bool isRegionArgOfOp;
106 bool skip = false;
107 bool isUnique = false;
108
109 size_t idx;
110 Operation *op;
111 Region *parentRegion;
112 size_t loopDepth;
113
114 Operation *&getOwnerOp() {
115 assert(isRegionArgOfOp && "Must describe a region operand");
116 return op;
117 }
118 size_t &getArgIdx() {
119 assert(isRegionArgOfOp && "Must describe a region operand");
120 return idx;
121 }
122
123 Operation *&getContainerOp() {
124 assert(!isRegionArgOfOp && "Must describe a operation of a region");
125 return op;
126 }
127 size_t &getOpPos() {
128 assert(!isRegionArgOfOp && "Must describe a operation of a region");
129 return idx;
130 }
131 bool isLoopOp() const {
132 assert(!isRegionArgOfOp && "Must describe a operation of a region");
133 return isa<CanonicalLoopOp>(op);
134 }
135 Region *&getParentRegion() {
136 assert(!isRegionArgOfOp && "Must describe a operation of a region");
137 return parentRegion;
138 }
139 size_t &getLoopDepth() {
140 assert(!isRegionArgOfOp && "Must describe a operation of a region");
141 return loopDepth;
142 }
143
144 void skipIf(bool v = true) { skip = skip || v; }
145 };
146
147 // List of ancestors, from inner to outer.
148 // Alternates between
149 // * region argument of an operation
150 // * operation within a region
151 SmallVector<Component> components;
152
153 // Gather a list of parent regions and operations, and the position within
154 // their parent
155 Operation *o = op.getOperation();
156 while (o) {
157 // Operation within a region
158 Region *r = o->getParentRegion();
159 if (!r)
160 break;
161
162 llvm::ReversePostOrderTraversal<Block *> traversal(&r->getBlocks().front());
163 size_t idx = 0;
164 bool found = false;
165 size_t sequentialIdx = -1;
166 bool isOnlyContainerOp = true;
167 for (Block *b : traversal) {
168 for (Operation &op : *b) {
169 if (&op == o && !found) {
170 sequentialIdx = idx;
171 found = true;
172 }
173 if (op.getNumRegions()) {
174 idx += 1;
175 if (idx > 1)
176 isOnlyContainerOp = false;
177 }
178 if (found && !isOnlyContainerOp)
179 break;
180 }
181 }
182
183 Component &containerOpInRegion = components.emplace_back();
184 containerOpInRegion.isRegionArgOfOp = false;
185 containerOpInRegion.isUnique = isOnlyContainerOp;
186 containerOpInRegion.getContainerOp() = o;
187 containerOpInRegion.getOpPos() = sequentialIdx;
188 containerOpInRegion.getParentRegion() = r;
189
190 Operation *parent = r->getParentOp();
191
192 // Region argument of an operation
193 Component &regionArgOfOperation = components.emplace_back();
194 regionArgOfOperation.isRegionArgOfOp = true;
195 regionArgOfOperation.isUnique = true;
196 regionArgOfOperation.getArgIdx() = 0;
197 regionArgOfOperation.getOwnerOp() = parent;
198
199 // The IsolatedFromAbove trait of the parent operation implies that each
200 // individual region argument has its own separate namespace, so no
201 // ambiguity.
202 if (!parent || parent->hasTrait<mlir::OpTrait::IsIsolatedFromAbove>())
203 break;
204
205 // Component only needed if operation has multiple region operands. Region
206 // arguments may be optional, but we currently do not consider this.
207 if (parent->getRegions().size() > 1) {
208 auto getRegionIndex = [](Operation *o, Region *r) {
209 for (auto [idx, region] : llvm::enumerate(o->getRegions())) {
210 if (&region == r)
211 return idx;
212 }
213 llvm_unreachable("Region not child of its parent operation");
214 };
215 regionArgOfOperation.isUnique = false;
216 regionArgOfOperation.getArgIdx() = getRegionIndex(parent, r);
217 }
218
219 // next parent
220 o = parent;
221 }
222
223 // Determine whether a region-argument component is not needed
224 for (Component &c : components)
225 c.skipIf(c.isRegionArgOfOp && c.isUnique);
226
227 // Find runs of nested loops and determine each loop's depth in the loop nest
228 size_t numSurroundingLoops = 0;
229 for (Component &c : llvm::reverse(components)) {
230 if (c.skip)
231 continue;
232
233 // non-skipped multi-argument operands interrupt the loop nest
234 if (c.isRegionArgOfOp) {
235 numSurroundingLoops = 0;
236 continue;
237 }
238
239 // Multiple loops in a region means each of them is the outermost loop of a
240 // new loop nest
241 if (!c.isUnique)
242 numSurroundingLoops = 0;
243
244 c.getLoopDepth() = numSurroundingLoops;
245
246 // Next loop is surrounded by one more loop
247 if (isa<CanonicalLoopOp>(c.getContainerOp()))
248 numSurroundingLoops += 1;
249 }
250
251 // In loop nests, skip all but the innermost loop that contains the depth
252 // number
253 bool isLoopNest = false;
254 for (Component &c : components) {
255 if (c.skip || c.isRegionArgOfOp)
256 continue;
257
258 if (!isLoopNest && c.getLoopDepth() >= 1) {
259 // Innermost loop of a loop nest of at least two loops
260 isLoopNest = true;
261 } else if (isLoopNest) {
262 // Non-innermost loop of a loop nest
263 c.skipIf(c.isUnique);
264
265 // If there is no surrounding loop left, this must have been the outermost
266 // loop; leave loop-nest mode for the next iteration
267 if (c.getLoopDepth() == 0)
268 isLoopNest = false;
269 }
270 }
271
272 // Skip non-loop unambiguous regions (but they should interrupt loop nests, so
273 // we mark them as skipped only after computing loop nests)
274 for (Component &c : components)
275 c.skipIf(!c.isRegionArgOfOp && c.isUnique &&
276 !isa<CanonicalLoopOp>(c.getContainerOp()));
277
278 // Components can be skipped if they are already disambiguated by their parent
279 // (or does not have a parent)
280 bool newRegion = true;
281 for (Component &c : llvm::reverse(components)) {
282 c.skipIf(newRegion && c.isUnique);
283
284 // non-skipped components disambiguate unique children
285 if (!c.skip)
286 newRegion = true;
287
288 // ...except canonical loops that need a suffix for each nest
289 if (!c.isRegionArgOfOp && c.getContainerOp())
290 newRegion = false;
291 }
292
293 // Compile the nesting name string
294 SmallString<64> Name{prefix};
295 llvm::raw_svector_ostream NameOS(Name);
296 for (auto &c : llvm::reverse(components)) {
297 if (c.skip)
298 continue;
299
300 if (c.isRegionArgOfOp)
301 NameOS << "_r" << c.getArgIdx();
302 else if (c.getLoopDepth() >= 1)
303 NameOS << "_d" << c.getLoopDepth();
304 else
305 NameOS << "_s" << c.getOpPos();
306 }
307
308 return NameOS.str().str();
309}
310
311void OpenMPDialect::initialize() {
312 declarePromisedInterface<ConvertToLLVMPatternInterface, OpenMPDialect>();
313
314 MemRefType::attachInterface<MemRefPointerLikeModel>(*getContext());
315 LLVM::LLVMPointerType::attachInterface<LLVMPointerPointerLikeModel>(
316 *getContext());
317
318 // Attach default offload module interface to module op to access
319 // offload functionality through
320 mlir::ModuleOp::attachInterface<mlir::omp::OffloadModuleDefaultModel>(
321 *getContext());
322
323 // Attach default declare target interfaces to operations which can be marked
324 // as declare target (Global Operations and Functions/Subroutines in dialects
325 // that Fortran (or other languages that lower to MLIR) translates too
326 mlir::LLVM::GlobalOp::attachInterface<
328 *getContext());
329 mlir::LLVM::LLVMFuncOp::attachInterface<
331 *getContext());
332 mlir::func::FuncOp::attachInterface<
334}
335
336//===----------------------------------------------------------------------===//
337// Dialect operation attribute verification
338//===----------------------------------------------------------------------===//
339
340static LogicalResult verifyDeclareTargetAttr(Operation *op, Attribute attr) {
341 if (!isa<DeclareTargetInterface>(op))
342 return op->emitError() << "omp.declare_target can only be applied to "
343 "DeclareTargetInterface ops";
344
345 auto declareTargetAttr = dyn_cast<DeclareTargetAttr>(attr);
346 if (!declareTargetAttr)
347 return op->emitError()
348 << "omp.declare_target must be an #omp.declaretarget attribute";
349
350 if (isa<mlir::FunctionOpInterface>(op)) {
351 if (declareTargetAttr.getAutomap())
352 return op->emitOpError()
353 << "omp.declare_target 'automap' is not valid on functions";
354
355 // TODO: Disallow the `local` clause (OpenMP 6.0).
356 if (declareTargetAttr.getCaptureClause() ==
357 mlir::omp::DeclareTargetCaptureClause::link)
358 return op->emitOpError()
359 << "omp.declare_target 'link' is not valid on functions";
360 } else {
361 // TODO: Disallow the `indirect` clause (OpenMP 5.1).
362 if (declareTargetAttr.getImplicit())
363 return op->emitOpError()
364 << "omp.declare_target 'implicit' is only valid on functions";
365 }
366 return success();
367}
368
369LogicalResult
370OpenMPDialect::verifyOperationAttribute(Operation *op,
371 NamedAttribute attribute) {
372 if (attribute.getName() == "omp.declare_target")
373 return verifyDeclareTargetAttr(op, attribute.getValue());
374
375 return success();
376}
377
378//===----------------------------------------------------------------------===//
379// Parser and printer for Allocate Clause
380//===----------------------------------------------------------------------===//
381
382/// Parse an allocate clause with allocators and a list of operands with types.
383///
384/// allocate-operand-list :: = allocate-operand |
385/// allocator-operand `,` allocate-operand-list
386/// allocate-operand :: = ssa-id-and-type -> ssa-id-and-type
387/// ssa-id-and-type ::= ssa-id `:` type
388static ParseResult parseAllocateAndAllocator(
389 OpAsmParser &parser,
391 SmallVectorImpl<Type> &allocateTypes,
393 SmallVectorImpl<Type> &allocatorTypes) {
394
395 return parser.parseCommaSeparatedList([&]() {
397 Type type;
398 if (parser.parseOperand(operand) || parser.parseColonType(type))
399 return failure();
400 allocatorVars.push_back(operand);
401 allocatorTypes.push_back(type);
402 if (parser.parseArrow())
403 return failure();
404 if (parser.parseOperand(operand) || parser.parseColonType(type))
405 return failure();
406
407 allocateVars.push_back(operand);
408 allocateTypes.push_back(type);
409 return success();
410 });
411}
412
413/// Print allocate clause
415 OperandRange allocateVars,
416 TypeRange allocateTypes,
417 OperandRange allocatorVars,
418 TypeRange allocatorTypes) {
419 for (unsigned i = 0; i < allocateVars.size(); ++i) {
420 std::string separator = i == allocateVars.size() - 1 ? "" : ", ";
421 p << allocatorVars[i] << " : " << allocatorTypes[i] << " -> ";
422 p << allocateVars[i] << " : " << allocateTypes[i] << separator;
423 }
424}
425
426//===----------------------------------------------------------------------===//
427// Parser and printer for a clause attribute (StringEnumAttr)
428//===----------------------------------------------------------------------===//
429
430template <typename ClauseAttr>
431static ParseResult parseClauseAttr(AsmParser &parser, ClauseAttr &attr) {
432 using ClauseT = decltype(std::declval<ClauseAttr>().getValue());
433 StringRef enumStr;
434 SMLoc loc = parser.getCurrentLocation();
435 if (parser.parseKeyword(&enumStr))
436 return failure();
437 if (std::optional<ClauseT> enumValue = symbolizeEnum<ClauseT>(enumStr)) {
438 attr = ClauseAttr::get(parser.getContext(), *enumValue);
439 return success();
440 }
441 return parser.emitError(loc, "invalid clause value: '") << enumStr << "'";
442}
443
444template <typename ClauseAttr>
445static void printClauseAttr(OpAsmPrinter &p, Operation *op, ClauseAttr attr) {
446 p << stringifyEnum(attr.getValue());
447}
448
449//===----------------------------------------------------------------------===//
450// Parser and printer for Linear Clause
451//===----------------------------------------------------------------------===//
452
453/// linear ::= `linear` `(` linear-list `)`
454/// linear-list := linear-val | linear-val linear-list
455/// linear-val := ssa-id-and-type `=` ssa-id-and-type
456/// | `val` `(` ssa-id-and-type `=` ssa-id-and-type `)`
457/// | `ref` `(` ssa-id-and-type `=` ssa-id-and-type `)`
458/// | `uval` `(` ssa-id-and-type `=` ssa-id-and-type `)`
459static ParseResult parseLinearClause(
460 OpAsmParser &parser,
462 SmallVectorImpl<Type> &linearTypes,
464 SmallVectorImpl<Type> &linearStepTypes, ArrayAttr &linearModifiers,
465 ArrayAttr &linearSyms) {
466 SmallVector<Attribute> modifiers;
467 auto result = parser.parseCommaSeparatedList([&]() {
469 Type type, stepType;
471
472 std::optional<omp::LinearModifier> linearModifier;
473 if (succeeded(parser.parseOptionalKeyword("val"))) {
474 linearModifier = omp::LinearModifier::val;
475 } else if (succeeded(parser.parseOptionalKeyword("ref"))) {
476 linearModifier = omp::LinearModifier::ref;
477 } else if (succeeded(parser.parseOptionalKeyword("uval"))) {
478 linearModifier = omp::LinearModifier::uval;
479 }
480
481 bool hasLinearModifierParens = linearModifier.has_value();
482 if (hasLinearModifierParens && parser.parseLParen())
483 return failure();
484
485 if (parser.parseOperand(var) || parser.parseColonType(type) ||
486 parser.parseEqual() || parser.parseOperand(stepVar) ||
487 parser.parseColonType(stepType))
488 return failure();
489
490 if (hasLinearModifierParens && parser.parseRParen())
491 return failure();
492
493 linearVars.push_back(var);
494 linearTypes.push_back(type);
495 linearStepVars.push_back(stepVar);
496 linearStepTypes.push_back(stepType);
497 if (linearModifier) {
498 modifiers.push_back(
499 omp::LinearModifierAttr::get(parser.getContext(), *linearModifier));
500 } else {
501 modifiers.push_back(UnitAttr::get(parser.getContext()));
502 }
503 return success();
504 });
505 if (failed(result))
506 return failure();
507 linearModifiers = ArrayAttr::get(parser.getContext(), modifiers);
508 return success();
509}
510
511/// Print Linear Clause. `linearSyms` is only used by ops with a region, which
512/// print the linear clause with their entry block arguments.
514 ValueRange linearVars, TypeRange linearTypes,
515 ValueRange linearStepVars, TypeRange stepVarTypes,
516 ArrayAttr linearModifiers, ArrayAttr linearSyms) {
517 size_t linearVarsSize = linearVars.size();
518 for (unsigned i = 0; i < linearVarsSize; ++i) {
519 if (i != 0)
520 p << ", ";
521 // Print modifier keyword wrapper if present.
522 Attribute modAttr = linearModifiers ? linearModifiers[i] : nullptr;
523 auto mod = modAttr ? dyn_cast<omp::LinearModifierAttr>(modAttr) : nullptr;
524 if (mod) {
525 p << omp::stringifyLinearModifier(mod.getValue()) << "(";
526 }
527 p << linearVars[i] << " : " << linearTypes[i];
528 p << " = " << linearStepVars[i] << " : " << stepVarTypes[i];
529 if (mod)
530 p << ")";
531 }
532}
533
534//===----------------------------------------------------------------------===//
535// Verifier for Linear modifier
536//===----------------------------------------------------------------------===//
537
538/// OpenMP 5.2, Section 5.4.6: "A linear-modifier may be specified as ref or
539/// uval only on a declare simd directive."
540/// Also verifies that modifier count matches variable count.
541static LogicalResult
542verifyLinearModifiers(Operation *op, std::optional<ArrayAttr> linearModifiers,
543 OperandRange linearVars, bool isDeclareSimd = false) {
544 if (!linearModifiers)
545 return success();
546 if (linearModifiers->size() != linearVars.size())
547 return op->emitOpError()
548 << "expected as many linear modifiers as linear variables";
549 if (!isDeclareSimd) {
550 for (Attribute attr : *linearModifiers) {
551 if (!attr)
552 continue;
553 auto modAttr = dyn_cast<omp::LinearModifierAttr>(attr);
554 if (!modAttr)
555 continue;
556 omp::LinearModifier mod = modAttr.getValue();
557 if (mod == omp::LinearModifier::ref || mod == omp::LinearModifier::uval)
558 return op->emitOpError()
559 << "linear modifier '" << omp::stringifyLinearModifier(mod)
560 << "' may only be specified on a declare simd directive";
561 }
562 }
563 return success();
564}
565
566//===----------------------------------------------------------------------===//
567// Verifier for Nontemporal Clause
568//===----------------------------------------------------------------------===//
569
570static LogicalResult verifyNontemporalClause(Operation *op,
571 OperandRange nontemporalVars) {
572
573 // Check if each var is unique - OpenMP 5.0 -> 2.9.3.1 section
574 DenseSet<Value> nontemporalItems;
575 for (const auto &it : nontemporalVars)
576 if (!nontemporalItems.insert(it).second)
577 return op->emitOpError() << "nontemporal variable used more than once";
578
579 return success();
580}
581
582//===----------------------------------------------------------------------===//
583// Parser, verifier and printer for Aligned Clause
584//===----------------------------------------------------------------------===//
585static LogicalResult verifyAlignedClause(Operation *op,
586 std::optional<ArrayAttr> alignments,
587 OperandRange alignedVars) {
588 // Check if number of alignment values equals to number of aligned variables
589 if (!alignedVars.empty()) {
590 if (!alignments || alignments->size() != alignedVars.size())
591 return op->emitOpError()
592 << "expected as many alignment values as aligned variables";
593 } else {
594 if (alignments)
595 return op->emitOpError() << "unexpected alignment values attribute";
596 return success();
597 }
598
599 // Check if each var is aligned only once - OpenMP 4.5 -> 2.8.1 section
600 DenseSet<Value> alignedItems;
601 for (auto it : alignedVars)
602 if (!alignedItems.insert(it).second)
603 return op->emitOpError() << "aligned variable used more than once";
604
605 if (!alignments)
606 return success();
607
608 // Check if all alignment values are positive - OpenMP 4.5 -> 2.8.1 section
609 for (unsigned i = 0; i < (*alignments).size(); ++i) {
610 if (auto intAttr = llvm::dyn_cast<IntegerAttr>((*alignments)[i])) {
611 if (intAttr.getValue().sle(0))
612 return op->emitOpError() << "alignment should be greater than 0";
613 } else {
614 return op->emitOpError() << "expected integer alignment";
615 }
616 }
617
618 return success();
619}
620
621/// aligned ::= `aligned` `(` aligned-list `)`
622/// aligned-list := aligned-val | aligned-val aligned-list
623/// aligned-val := ssa-id-and-type `->` alignment
624static ParseResult
627 SmallVectorImpl<Type> &alignedTypes,
628 ArrayAttr &alignmentsAttr) {
629 SmallVector<Attribute> alignmentVec;
630 if (failed(parser.parseCommaSeparatedList([&]() {
631 if (parser.parseOperand(alignedVars.emplace_back()) ||
632 parser.parseColonType(alignedTypes.emplace_back()) ||
633 parser.parseArrow() ||
634 parser.parseAttribute(alignmentVec.emplace_back())) {
635 return failure();
636 }
637 return success();
638 })))
639 return failure();
640 SmallVector<Attribute> alignments(alignmentVec.begin(), alignmentVec.end());
641 alignmentsAttr = ArrayAttr::get(parser.getContext(), alignments);
642 return success();
643}
644
645/// Print Aligned Clause
647 ValueRange alignedVars, TypeRange alignedTypes,
648 std::optional<ArrayAttr> alignments) {
649 for (unsigned i = 0; i < alignedVars.size(); ++i) {
650 if (i != 0)
651 p << ", ";
652 p << alignedVars[i] << " : " << alignedVars[i].getType();
653 p << " -> " << (*alignments)[i];
654 }
655}
656
657static LogicalResult verifyAllocateClause(
658 Operation *op, ValueRange allocateVars, ValueRange allocatorVars,
659 DenseI64ArrayAttr allocateAlignments,
660 DenseI64ArrayAttr allocatePrivateIndices, ValueRange privateVars = {},
661 ArrayAttr privateSyms = nullptr, bool requirePrivateIndices = false) {
662 if (allocateVars.size() != allocatorVars.size())
663 return op->emitError(
664 "expected equal sizes for allocate and allocator variables");
665
666 if (allocateVars.empty()) {
667 if (allocateAlignments)
668 return op->emitError(
669 "unexpected allocate alignments without allocate variables");
670 if (allocatePrivateIndices)
671 return op->emitError(
672 "unexpected allocate private indices without allocate variables");
673 return success();
674 }
675
676 if (allocateAlignments) {
677 ArrayRef<int64_t> alignments = allocateAlignments.asArrayRef();
678 if (alignments.size() != allocateVars.size())
679 return op->emitError(
680 "expected as many allocate alignments as allocate variables");
681 for (int64_t alignment : alignments) {
682 if (alignment < 0)
683 return op->emitError("expected non-negative allocate alignments");
684 if (alignment != 0 && (alignment & (alignment - 1)) != 0)
685 return op->emitError(
686 "expected positive allocate alignments to be powers of two");
687 }
688 }
689
690 if (!allocatePrivateIndices) {
691 if (requirePrivateIndices)
692 return op->emitError(
693 "expected an allocate private index for each allocate variable");
694 return success();
695 }
696
697 ArrayRef<int64_t> indices = allocatePrivateIndices.asArrayRef();
698 if (indices.size() != allocateVars.size())
699 return op->emitError(
700 "expected as many allocate private indices as allocate variables");
701
702 DenseSet<int64_t> usedPrivateSlots;
703 for (auto [allocateVar, privateIndex] :
704 llvm::zip_equal(allocateVars, indices)) {
705 if (privateIndex < 0 ||
706 static_cast<uint64_t>(privateIndex) >= privateVars.size())
707 return op->emitError("allocate private index is out of range");
708 if (!usedPrivateSlots.insert(privateIndex).second)
709 return op->emitError(
710 "allocate private index refers to a private variable more than once");
711
712 Value privateVar = privateVars[privateIndex];
713 if (allocateVar.getType() != privateVar.getType())
714 return op->emitError()
715 << "type mismatch between allocate variable and private variable "
716 "at index "
717 << privateIndex;
718 if (allocateVar != privateVar)
719 return op->emitError()
720 << "allocate variable does not match private variable at index "
721 << privateIndex;
722
723 if (!privateSyms ||
724 static_cast<uint64_t>(privateIndex) >= privateSyms.size())
725 return op->emitError(
726 "allocate private index does not have a privatizer symbol");
727
728 auto privateSym = dyn_cast<SymbolRefAttr>(privateSyms[privateIndex]);
729 if (!privateSym)
730 return op->emitError(
731 "allocate private index does not reference a privatizer symbol");
732 PrivateClauseOp privatizer =
734 if (!privatizer)
735 return op->emitError() << "failed to lookup privatizer op with symbol: '"
736 << privateSym << "'";
737 if (privatizer.getDataSharingType() != DataSharingClauseType::Private &&
738 privatizer.getDataSharingType() != DataSharingClauseType::FirstPrivate)
739 return op->emitError(
740 "allocate private index must refer to private or firstprivate "
741 "storage");
742 }
743
744 return success();
745}
746
747//===----------------------------------------------------------------------===//
748// Parser, printer and verifier for Schedule Clause
749//===----------------------------------------------------------------------===//
750
751static ParseResult
753 SmallVectorImpl<SmallString<12>> &modifiers) {
754 if (modifiers.size() > 2)
755 return parser.emitError(parser.getNameLoc()) << " unexpected modifier(s)";
756 for (const auto &mod : modifiers) {
757 // Translate the string. If it has no value, then it was not a valid
758 // modifier!
759 auto symbol = symbolizeScheduleModifier(mod);
760 if (!symbol)
761 return parser.emitError(parser.getNameLoc())
762 << " unknown modifier type: " << mod;
763 }
764
765 // If we have one modifier that is "simd", then stick a "none" modiifer in
766 // index 0.
767 if (modifiers.size() == 1) {
768 if (symbolizeScheduleModifier(modifiers[0]) == ScheduleModifier::simd) {
769 modifiers.push_back(modifiers[0]);
770 modifiers[0] = stringifyScheduleModifier(ScheduleModifier::none);
771 }
772 } else if (modifiers.size() == 2) {
773 // If there are two modifier:
774 // First modifier should not be simd, second one should be simd
775 if (symbolizeScheduleModifier(modifiers[0]) == ScheduleModifier::simd ||
776 symbolizeScheduleModifier(modifiers[1]) != ScheduleModifier::simd)
777 return parser.emitError(parser.getNameLoc())
778 << " incorrect modifier order";
779 }
780 return success();
781}
782
783/// schedule ::= `schedule` `(` sched-list `)`
784/// sched-list ::= sched-val | sched-val sched-list |
785/// sched-val `,` sched-modifier
786/// sched-val ::= sched-with-chunk | sched-wo-chunk
787/// sched-with-chunk ::= sched-with-chunk-types (`=` ssa-id-and-type)?
788/// sched-with-chunk-types ::= `static` | `dynamic` | `guided`
789/// sched-wo-chunk ::= `auto` | `runtime`
790/// sched-modifier ::= sched-mod-val | sched-mod-val `,` sched-mod-val
791/// sched-mod-val ::= `monotonic` | `nonmonotonic` | `simd` | `none`
792static ParseResult
793parseScheduleClause(OpAsmParser &parser, ClauseScheduleKindAttr &scheduleAttr,
794 ScheduleModifierAttr &scheduleMod, UnitAttr &scheduleSimd,
795 std::optional<OpAsmParser::UnresolvedOperand> &chunkSize,
796 Type &chunkType) {
797 StringRef keyword;
798 if (parser.parseKeyword(&keyword))
799 return failure();
800 std::optional<mlir::omp::ClauseScheduleKind> schedule =
801 symbolizeClauseScheduleKind(keyword);
802 if (!schedule)
803 return parser.emitError(parser.getNameLoc()) << " expected schedule kind";
804
805 scheduleAttr = ClauseScheduleKindAttr::get(parser.getContext(), *schedule);
806 switch (*schedule) {
807 case ClauseScheduleKind::Static:
808 case ClauseScheduleKind::Dynamic:
809 case ClauseScheduleKind::Guided:
810 if (succeeded(parser.parseOptionalEqual())) {
811 chunkSize = OpAsmParser::UnresolvedOperand{};
812 if (parser.parseOperand(*chunkSize) || parser.parseColonType(chunkType))
813 return failure();
814 } else {
815 chunkSize = std::nullopt;
816 }
817 break;
818 case ClauseScheduleKind::Auto:
819 case ClauseScheduleKind::Runtime:
820 case ClauseScheduleKind::Distribute:
821 chunkSize = std::nullopt;
822 }
823
824 // If there is a comma, we have one or more modifiers..
826 while (succeeded(parser.parseOptionalComma())) {
827 StringRef mod;
828 if (parser.parseKeyword(&mod))
829 return failure();
830 modifiers.push_back(mod);
831 }
832
833 if (verifyScheduleModifiers(parser, modifiers))
834 return failure();
835
836 if (!modifiers.empty()) {
837 SMLoc loc = parser.getCurrentLocation();
838 if (std::optional<ScheduleModifier> mod =
839 symbolizeScheduleModifier(modifiers[0])) {
840 scheduleMod = ScheduleModifierAttr::get(parser.getContext(), *mod);
841 } else {
842 return parser.emitError(loc, "invalid schedule modifier");
843 }
844 // Only SIMD attribute is allowed here!
845 if (modifiers.size() > 1) {
846 assert(symbolizeScheduleModifier(modifiers[1]) == ScheduleModifier::simd);
847 scheduleSimd = UnitAttr::get(parser.getBuilder().getContext());
848 }
849 }
850
851 return success();
852}
853
854/// Print schedule clause
856 ClauseScheduleKindAttr scheduleKind,
857 ScheduleModifierAttr scheduleMod,
858 UnitAttr scheduleSimd, Value scheduleChunk,
859 Type scheduleChunkType) {
860 p << stringifyClauseScheduleKind(scheduleKind.getValue());
861 if (scheduleChunk)
862 p << " = " << scheduleChunk << " : " << scheduleChunk.getType();
863 if (scheduleMod)
864 p << ", " << stringifyScheduleModifier(scheduleMod.getValue());
865 if (scheduleSimd)
866 p << ", simd";
867}
868
869//===----------------------------------------------------------------------===//
870// Parser and printer for Order Clause
871//===----------------------------------------------------------------------===//
872
873// order ::= `order` `(` [order-modifier ':'] concurrent `)`
874// order-modifier ::= reproducible | unconstrained
875static ParseResult parseOrderClause(OpAsmParser &parser,
876 ClauseOrderKindAttr &order,
877 OrderModifierAttr &orderMod) {
878 StringRef enumStr;
879 SMLoc loc = parser.getCurrentLocation();
880 if (parser.parseKeyword(&enumStr))
881 return failure();
882 if (std::optional<OrderModifier> enumValue =
883 symbolizeOrderModifier(enumStr)) {
884 orderMod = OrderModifierAttr::get(parser.getContext(), *enumValue);
885 if (parser.parseOptionalColon())
886 return failure();
887 loc = parser.getCurrentLocation();
888 if (parser.parseKeyword(&enumStr))
889 return failure();
890 }
891 if (std::optional<ClauseOrderKind> enumValue =
892 symbolizeClauseOrderKind(enumStr)) {
893 order = ClauseOrderKindAttr::get(parser.getContext(), *enumValue);
894 return success();
895 }
896 return parser.emitError(loc, "invalid clause value: '") << enumStr << "'";
897}
898
900 ClauseOrderKindAttr order,
901 OrderModifierAttr orderMod) {
902 if (orderMod)
903 p << stringifyOrderModifier(orderMod.getValue()) << ":";
904 if (order)
905 p << stringifyClauseOrderKind(order.getValue());
906}
907
908template <typename ClauseTypeAttr, typename ClauseType>
909static ParseResult
910parseGranularityClause(OpAsmParser &parser, ClauseTypeAttr &prescriptiveness,
911 std::optional<OpAsmParser::UnresolvedOperand> &operand,
912 Type &operandType,
913 std::optional<ClauseType> (*symbolizeClause)(StringRef),
914 StringRef clauseName) {
915 StringRef enumStr;
916 if (succeeded(parser.parseOptionalKeyword(&enumStr))) {
917 if (std::optional<ClauseType> enumValue = symbolizeClause(enumStr)) {
918 prescriptiveness = ClauseTypeAttr::get(parser.getContext(), *enumValue);
919 if (parser.parseComma())
920 return failure();
921 } else {
922 return parser.emitError(parser.getCurrentLocation())
923 << "invalid " << clauseName << " modifier : '" << enumStr << "'";
924 ;
925 }
926 }
927
929 if (succeeded(parser.parseOperand(var))) {
930 operand = var;
931 } else {
932 return parser.emitError(parser.getCurrentLocation())
933 << "expected " << clauseName << " operand";
934 }
935
936 if (operand.has_value()) {
937 if (parser.parseColonType(operandType))
938 return failure();
939 }
940
941 return success();
942}
943
944template <typename ClauseTypeAttr, typename ClauseType>
945static void
947 ClauseTypeAttr prescriptiveness, Value operand,
948 mlir::Type operandType,
949 StringRef (*stringifyClauseType)(ClauseType)) {
950
951 if (prescriptiveness)
952 p << stringifyClauseType(prescriptiveness.getValue()) << ", ";
953
954 if (operand)
955 p << operand << ": " << operandType;
956}
957
958//===----------------------------------------------------------------------===//
959// Parser and printer for grainsize Clause
960//===----------------------------------------------------------------------===//
961
962// grainsize ::= `grainsize` `(` [strict ':'] grain-size `)`
963static ParseResult
964parseGrainsizeClause(OpAsmParser &parser, ClauseGrainsizeTypeAttr &grainsizeMod,
965 std::optional<OpAsmParser::UnresolvedOperand> &grainsize,
966 Type &grainsizeType) {
968 parser, grainsizeMod, grainsize, grainsizeType,
969 &symbolizeClauseGrainsizeType, "grainsize");
970}
971
973 ClauseGrainsizeTypeAttr grainsizeMod,
974 Value grainsize, mlir::Type grainsizeType) {
976 p, op, grainsizeMod, grainsize, grainsizeType,
977 &stringifyClauseGrainsizeType);
978}
979
980//===----------------------------------------------------------------------===//
981// Parser and printer for num_tasks Clause
982//===----------------------------------------------------------------------===//
983
984// numtask ::= `num_tasks` `(` [strict ':'] num-tasks `)`
985static ParseResult
986parseNumTasksClause(OpAsmParser &parser, ClauseNumTasksTypeAttr &numTasksMod,
987 std::optional<OpAsmParser::UnresolvedOperand> &numTasks,
988 Type &numTasksType) {
990 parser, numTasksMod, numTasks, numTasksType, &symbolizeClauseNumTasksType,
991 "num_tasks");
992}
993
995 ClauseNumTasksTypeAttr numTasksMod,
996 Value numTasks, mlir::Type numTasksType) {
998 p, op, numTasksMod, numTasks, numTasksType, &stringifyClauseNumTasksType);
999}
1000
1001//===----------------------------------------------------------------------===//
1002// Parser and printer for Heap Alloc Clause
1003//===----------------------------------------------------------------------===//
1004
1005/// operation ::= $in_type ( `(` $typeparams `)` )? ( `,` $shape )?
1006static ParseResult parseHeapAllocClause(
1007 OpAsmParser &parser, TypeAttr &inTypeAttr,
1009 SmallVectorImpl<Type> &typeparamsTypes,
1011 SmallVectorImpl<Type> &shapeTypes) {
1012 mlir::Type inType;
1013 if (parser.parseType(inType))
1014 return mlir::failure();
1015 inTypeAttr = TypeAttr::get(inType);
1016
1017 if (!parser.parseOptionalLParen()) {
1018 // parse the LEN params of the derived type. (<params> : <types>)
1019 if (parser.parseOperandList(typeparams, OpAsmParser::Delimiter::None) ||
1020 parser.parseColonTypeList(typeparamsTypes) || parser.parseRParen())
1021 return failure();
1022 }
1023
1024 if (!parser.parseOptionalComma()) {
1025 // parse size to scale by, vector of n dimensions of type index
1027 return failure();
1028
1029 // TODO: This overrides the actual types of the operands, which might cause
1030 // issues when they don't match. At the moment this is done in place of
1031 // making the corresponding operand type `Variadic<Index>` because index
1032 // types are lowered to I64 prior to LLVM IR translation.
1033 shapeTypes.append(shape.size(), IndexType::get(parser.getContext()));
1034 }
1035
1036 return success();
1037}
1038
1040 TypeAttr inType, ValueRange typeparams,
1041 TypeRange typeparamsTypes, ValueRange shape,
1042 TypeRange shapeTypes) {
1043 p << inType;
1044 if (!typeparams.empty()) {
1045 p << '(' << typeparams << " : " << typeparamsTypes << ')';
1046 }
1047 for (auto sh : shape) {
1048 p << ", ";
1049 p.printOperand(sh);
1050 }
1051}
1052
1053//===----------------------------------------------------------------------===//
1054// Parser, printer and verify for dyn_groupprivate Clause
1055//===----------------------------------------------------------------------===//
1056
1057static LogicalResult
1058verifyDynGroupprivateClause(Operation *op, AccessGroupModifierAttr accessGroup,
1059 FallbackModifierAttr fallback,
1060 Value dynGroupprivateSize) {
1061 if (!dynGroupprivateSize && (accessGroup || fallback))
1062 return op->emitOpError("dyn_groupprivate modifiers require a size operand");
1063
1064 return success();
1065}
1066
1068 OpAsmParser &parser, AccessGroupModifierAttr &accessGroupAttr,
1069 FallbackModifierAttr &fallbackAttr,
1070 std::optional<OpAsmParser::UnresolvedOperand> &dynGroupprivateSize,
1071 Type &sizeType) {
1072
1073 bool parsedAccessGroup = false;
1074 bool parsedFallback = false;
1075 bool parsedSize = false;
1076
1077 return parser.parseCommaSeparatedList([&]() -> ParseResult {
1078 // Parse AccessGroupModifier.
1079 if (succeeded(parser.parseOptionalKeyword("cgroup"))) {
1080 if (parsedAccessGroup)
1081 return parser.emitError(parser.getCurrentLocation(),
1082 "duplicate access group modifier");
1083 accessGroupAttr = AccessGroupModifierAttr::get(
1084 parser.getContext(), AccessGroupModifier::cgroup);
1085 parsedAccessGroup = true;
1086 return success();
1087 }
1088 // Parse FallbackModifier.
1089 if (succeeded(parser.parseOptionalKeyword("fallback"))) {
1090 if (parsedFallback)
1091 return parser.emitError(parser.getCurrentLocation(),
1092 "duplicate fallback modifier");
1093 if (parser.parseLParen())
1094 return parser.emitError(parser.getCurrentLocation(),
1095 "expected '(' after 'fallback'");
1096 llvm::StringRef fbKind;
1097 if (parser.parseKeyword(&fbKind))
1098 return parser.emitError(
1099 parser.getCurrentLocation(),
1100 "expected fallback modifier (abort/null/default_mem)");
1101 std::optional<FallbackModifier> fbEnum;
1102 if (fbKind == "abort")
1103 fbEnum = FallbackModifier::abort;
1104 else if (fbKind == "null")
1105 fbEnum = FallbackModifier::null;
1106 else if (fbKind == "default_mem")
1107 fbEnum = FallbackModifier::default_mem;
1108 else
1109 return parser.emitError(parser.getCurrentLocation(),
1110 "invalid fallback modifier '" + fbKind + "'");
1111 fallbackAttr = FallbackModifierAttr::get(parser.getContext(), *fbEnum);
1112 if (parser.parseRParen())
1113 return parser.emitError(parser.getCurrentLocation(),
1114 "expected ')' after fallback modifier");
1115 parsedFallback = true;
1116 return success();
1117 }
1118 // Parse size operand.
1120 if (succeeded(parser.parseOperand(operand))) {
1121 if (parsedSize)
1122 return parser.emitError(parser.getCurrentLocation(),
1123 "duplicate size operand");
1124 dynGroupprivateSize = operand;
1125 parsedSize = true;
1126 if (failed(parser.parseColon()) || failed(parser.parseType(sizeType)))
1127 return parser.emitError(parser.getCurrentLocation(),
1128 "expected ':' and type after size operand");
1129 return success();
1130 }
1131 return parser.emitError(parser.getCurrentLocation(),
1132 "expected dyn_groupprivate_size operand");
1133 });
1134}
1135
1137 AccessGroupModifierAttr modifierFirst,
1138 FallbackModifierAttr modifierSecond,
1139 Value dynGroupprivateSize,
1140 Type sizeType) {
1141
1142 bool needsComma = false;
1143
1144 if (modifierFirst) {
1145 printer << modifierFirst.getValue();
1146 needsComma = true;
1147 }
1148
1149 if (modifierSecond) {
1150 if (needsComma)
1151 printer << ", ";
1152 printer << "fallback(";
1153 printer << modifierSecond.getValue();
1154 printer << ")";
1155 needsComma = true;
1156 }
1157
1158 if (dynGroupprivateSize) {
1159 if (needsComma)
1160 printer << ", ";
1161 printer << dynGroupprivateSize << " : " << sizeType;
1162 }
1163}
1164
1165//===----------------------------------------------------------------------===//
1166// Parser and printer for in_reduction Clause
1167//===----------------------------------------------------------------------===//
1168
1169/// Parses an `in_reduction` clause for an operation that does not give its
1170/// list items entry block arguments (e.g. `omp.target`). The expected format is
1171/// a comma-separated list of `[byref] @sym %var` followed by `: types`.
1172static ParseResult parseInReductionClause(
1173 OpAsmParser &parser,
1175 SmallVectorImpl<Type> &inReductionTypes,
1176 DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms) {
1178 SmallVector<bool> isByRefVec;
1179
1180 if (parser.parseCommaSeparatedList([&]() {
1181 isByRefVec.push_back(parser.parseOptionalKeyword("byref").succeeded());
1182 if (parser.parseAttribute(symbolVec.emplace_back()) ||
1183 parser.parseOperand(inReductionVars.emplace_back()))
1184 return failure();
1185 return success();
1186 }))
1187 return failure();
1188
1189 if (parser.parseColon())
1190 return failure();
1191
1192 if (parser.parseCommaSeparatedList(
1193 [&]() { return parser.parseType(inReductionTypes.emplace_back()); }))
1194 return failure();
1195
1196 if (inReductionVars.size() != inReductionTypes.size())
1197 return failure();
1198
1199 inReductionByref = makeDenseBoolArrayAttr(parser.getContext(), isByRefVec);
1200 SmallVector<Attribute> symbolAttrs(symbolVec.begin(), symbolVec.end());
1201 inReductionSyms = ArrayAttr::get(parser.getContext(), symbolAttrs);
1202 return success();
1203}
1204
1205/// Prints an `in_reduction` clause for an operation that does not give its list
1206/// items entry block arguments (e.g. `omp.target`). Mirrors
1207/// `parseInReductionClause`.
1209 ValueRange inReductionVars,
1210 TypeRange inReductionTypes,
1211 DenseBoolArrayAttr inReductionByref,
1212 ArrayAttr inReductionSyms) {
1213 MLIRContext *ctx = op->getContext();
1214
1215 ArrayAttr syms = inReductionSyms;
1216 if (!syms) {
1217 SmallVector<Attribute> values(inReductionVars.size(), nullptr);
1218 syms = ArrayAttr::get(ctx, values);
1219 }
1220
1221 DenseBoolArrayAttr byref = inReductionByref;
1222 if (!byref) {
1223 SmallVector<bool> values(inReductionVars.size(), false);
1224 byref = DenseBoolArrayAttr::get(ctx, values);
1225 }
1226
1227 llvm::interleaveComma(
1228 llvm::zip_equal(inReductionVars, syms.getValue(), byref.asArrayRef()), p,
1229 [&p](auto t) {
1230 auto [var, sym, isByRef] = t;
1231 if (isByRef)
1232 p << "byref ";
1233 if (sym)
1234 p << sym << " ";
1235 p << var;
1236 });
1237 p << " : ";
1238 llvm::interleaveComma(inReductionTypes, p);
1239}
1240
1241//===----------------------------------------------------------------------===//
1242// Parsers for operations including clauses that define entry block arguments.
1243//===----------------------------------------------------------------------===//
1244
1245namespace {
1246struct MapParseArgs {
1247 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1248 SmallVectorImpl<Type> &types;
1249 MapParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1250 SmallVectorImpl<Type> &types)
1251 : vars(vars), types(types) {}
1252};
1253struct PrivateParseArgs {
1254 llvm::SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1255 llvm::SmallVectorImpl<Type> &types;
1256 ArrayAttr &syms;
1257 UnitAttr &needsBarrier;
1258 DenseI64ArrayAttr *mapIndices;
1259 PrivateParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1260 SmallVectorImpl<Type> &types, ArrayAttr &syms,
1261 UnitAttr &needsBarrier,
1262 DenseI64ArrayAttr *mapIndices = nullptr)
1263 : vars(vars), types(types), syms(syms), needsBarrier(needsBarrier),
1264 mapIndices(mapIndices) {}
1265};
1266
1267struct LinearParseArgs {
1268 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1269 SmallVectorImpl<Type> &types;
1270 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &stepVars;
1271 SmallVectorImpl<Type> &stepTypes;
1272 ArrayAttr &varTypes;
1273 ArrayAttr &modifiers;
1274 ArrayAttr &syms;
1275 LinearParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1276 SmallVectorImpl<Type> &types,
1277 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &stepVars,
1278 SmallVectorImpl<Type> &stepTypes, ArrayAttr &varTypes,
1279 ArrayAttr &modifiers, ArrayAttr &syms)
1280 : vars(vars), types(types), stepVars(stepVars), stepTypes(stepTypes),
1281 varTypes(varTypes), modifiers(modifiers), syms(syms) {}
1282};
1283
1284struct ReductionParseArgs {
1285 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars;
1286 SmallVectorImpl<Type> &types;
1287 DenseBoolArrayAttr &byref;
1288 ArrayAttr &syms;
1289 ArrayAttr *modifier;
1290 ReductionParseArgs(SmallVectorImpl<OpAsmParser::UnresolvedOperand> &vars,
1291 SmallVectorImpl<Type> &types, DenseBoolArrayAttr &byref,
1292 ArrayAttr &syms, ArrayAttr *mod = nullptr)
1293 : vars(vars), types(types), byref(byref), syms(syms), modifier(mod) {}
1294};
1295
1296struct AllRegionParseArgs {
1297 std::optional<MapParseArgs> hasDeviceAddrArgs;
1298 std::optional<MapParseArgs> hostEvalArgs;
1299 std::optional<ReductionParseArgs> inReductionArgs;
1300 std::optional<LinearParseArgs> linearArgs;
1301 std::optional<MapParseArgs> mapArgs;
1302 std::optional<PrivateParseArgs> privateArgs;
1303 std::optional<ReductionParseArgs> reductionArgs;
1304 std::optional<ReductionParseArgs> taskReductionArgs;
1305 std::optional<MapParseArgs> useDeviceAddrArgs;
1306 std::optional<MapParseArgs> useDevicePtrArgs;
1307};
1308} // namespace
1309
1310static inline constexpr StringRef getPrivateNeedsBarrierSpelling() {
1311 return "private_barrier";
1312}
1313
1314static ParseResult parseClauseWithRegionArgs(
1315 OpAsmParser &parser,
1317 SmallVectorImpl<Type> &types,
1318 SmallVectorImpl<OpAsmParser::Argument> &regionPrivateArgs,
1319 ArrayAttr *symbols = nullptr, DenseI64ArrayAttr *mapIndices = nullptr,
1320 DenseBoolArrayAttr *byref = nullptr, ArrayAttr *modifier = nullptr,
1321 UnitAttr *needsBarrier = nullptr) {
1323 SmallVector<int64_t> mapIndicesVec;
1324 SmallVector<bool> isByRefVec;
1325 unsigned regionArgOffset = regionPrivateArgs.size();
1326
1327 if (parser.parseLParen())
1328 return failure();
1329
1330 SmallVector<Attribute> modifiers;
1331 if (parser.parseCommaSeparatedList([&]() -> ParseResult {
1332 if (modifier) {
1333 ReductionModifier mod = ReductionModifier::defaultmod;
1334 if (succeeded(parser.parseOptionalKeyword("task")))
1335 mod = ReductionModifier::task;
1336 else if (succeeded(parser.parseOptionalKeyword("inscan")))
1337 mod = ReductionModifier::inscan;
1338 else if (succeeded(parser.parseOptionalKeyword("defaultmod")))
1339 mod = ReductionModifier::defaultmod;
1340 modifiers.push_back(
1341 ReductionModifierAttr::get(parser.getContext(), mod));
1342 }
1343 if (byref)
1344 isByRefVec.push_back(
1345 parser.parseOptionalKeyword("byref").succeeded());
1346
1347 if (symbols && parser.parseAttribute(symbolVec.emplace_back()))
1348 return failure();
1349
1350 if (parser.parseOperand(operands.emplace_back()) ||
1351 parser.parseArrow() ||
1352 parser.parseArgument(regionPrivateArgs.emplace_back()))
1353 return failure();
1354
1355 if (mapIndices) {
1356 if (parser.parseOptionalLSquare().succeeded()) {
1357 if (parser.parseKeyword("map_idx") || parser.parseEqual() ||
1358 parser.parseInteger(mapIndicesVec.emplace_back()) ||
1359 parser.parseRSquare())
1360 return failure();
1361 } else {
1362 mapIndicesVec.push_back(-1);
1363 }
1364 }
1365
1366 return success();
1367 }))
1368 return failure();
1369
1370 if (parser.parseColon() || parser.parseCommaSeparatedList([&]() {
1371 return parser.parseType(types.emplace_back());
1372 }))
1373 return failure();
1374
1375 if (llvm::any_of(modifiers, [](Attribute attr) {
1376 return cast<ReductionModifierAttr>(attr).getValue() !=
1377 ReductionModifier::defaultmod;
1378 }))
1379 *modifier = ArrayAttr::get(parser.getContext(), modifiers);
1380
1381 if (operands.size() != types.size())
1382 return failure();
1383
1384 if (parser.parseRParen())
1385 return failure();
1386
1387 if (needsBarrier) {
1389 .succeeded())
1390 *needsBarrier = mlir::UnitAttr::get(parser.getContext());
1391 }
1392
1393 auto *argsBegin = regionPrivateArgs.begin();
1394 MutableArrayRef argsSubrange(argsBegin + regionArgOffset,
1395 argsBegin + regionArgOffset + types.size());
1396 for (auto [prv, type] : llvm::zip_equal(argsSubrange, types)) {
1397 prv.type = type;
1398 }
1399
1400 if (symbols) {
1401 SmallVector<Attribute> symbolAttrs(symbolVec.begin(), symbolVec.end());
1402 *symbols = ArrayAttr::get(parser.getContext(), symbolAttrs);
1403 }
1404
1405 if (!mapIndicesVec.empty())
1406 *mapIndices =
1407 mlir::DenseI64ArrayAttr::get(parser.getContext(), mapIndicesVec);
1408
1409 if (byref)
1410 *byref = makeDenseBoolArrayAttr(parser.getContext(), isByRefVec);
1411
1412 return success();
1413}
1414
1415static ParseResult parseBlockArgClause(
1416 OpAsmParser &parser,
1418 StringRef keyword, std::optional<MapParseArgs> mapArgs) {
1419 if (succeeded(parser.parseOptionalKeyword(keyword))) {
1420 if (!mapArgs)
1421 return failure();
1422
1423 if (failed(parseClauseWithRegionArgs(parser, mapArgs->vars, mapArgs->types,
1424 entryBlockArgs)))
1425 return failure();
1426 }
1427 return success();
1428}
1429
1430static ParseResult parseBlockArgClause(
1431 OpAsmParser &parser,
1433 StringRef keyword, std::optional<PrivateParseArgs> privateArgs) {
1434 if (succeeded(parser.parseOptionalKeyword(keyword))) {
1435 if (!privateArgs)
1436 return failure();
1437
1438 if (failed(parseClauseWithRegionArgs(
1439 parser, privateArgs->vars, privateArgs->types, entryBlockArgs,
1440 &privateArgs->syms, privateArgs->mapIndices, /*byref=*/nullptr,
1441 /*modifier=*/nullptr, &privateArgs->needsBarrier)))
1442 return failure();
1443 }
1444 return success();
1445}
1446
1447static ParseResult parseBlockArgClause(
1448 OpAsmParser &parser,
1450 StringRef keyword, std::optional<ReductionParseArgs> reductionArgs) {
1451 if (succeeded(parser.parseOptionalKeyword(keyword))) {
1452 if (!reductionArgs)
1453 return failure();
1454 if (failed(parseClauseWithRegionArgs(
1455 parser, reductionArgs->vars, reductionArgs->types, entryBlockArgs,
1456 &reductionArgs->syms, /*mapIndices=*/nullptr, &reductionArgs->byref,
1457 reductionArgs->modifier)))
1458 return failure();
1459 }
1460 return success();
1461}
1462
1463/// linear-entry := [modifier `(`] symbol ssa-id `->` ssa-id `:` type `=`
1464/// ssa-id `:` type [`)`]
1465static ParseResult parseBlockArgClause(
1466 OpAsmParser &parser,
1468 StringRef keyword, std::optional<LinearParseArgs> linearArgs) {
1469 if (!linearArgs || failed(parser.parseOptionalKeyword(keyword)))
1470 return success();
1471
1472 MLIRContext *ctx = parser.getContext();
1473 SmallVector<Attribute> syms, modifiers;
1474 if (parser.parseLParen() ||
1475 parser.parseCommaSeparatedList([&]() -> ParseResult {
1476 std::optional<LinearModifier> modifier;
1477 if (succeeded(parser.parseOptionalKeyword("val")))
1478 modifier = LinearModifier::val;
1479 else if (succeeded(parser.parseOptionalKeyword("ref")))
1480 modifier = LinearModifier::ref;
1481 else if (succeeded(parser.parseOptionalKeyword("uval")))
1482 modifier = LinearModifier::uval;
1483 if (modifier && parser.parseLParen())
1484 return failure();
1485
1486 SymbolRefAttr sym;
1487 OpAsmParser::Argument &arg = entryBlockArgs.emplace_back();
1488 if (parser.parseAttribute(sym) ||
1489 parser.parseOperand(linearArgs->vars.emplace_back()) ||
1490 parser.parseArrow() || parser.parseArgument(arg) ||
1491 parser.parseColonType(linearArgs->types.emplace_back()) ||
1492 parser.parseEqual() ||
1493 parser.parseOperand(linearArgs->stepVars.emplace_back()) ||
1494 parser.parseColonType(linearArgs->stepTypes.emplace_back()))
1495 return failure();
1496 arg.type = linearArgs->types.back();
1497
1498 if (modifier && parser.parseRParen())
1499 return failure();
1500
1501 syms.push_back(sym);
1502 modifiers.push_back(
1503 modifier ? Attribute(LinearModifierAttr::get(ctx, *modifier))
1504 : Attribute(UnitAttr::get(ctx)));
1505 return success();
1506 }) ||
1507 parser.parseRParen())
1508 return failure();
1509
1510 linearArgs->syms = ArrayAttr::get(ctx, syms);
1511 linearArgs->modifiers = ArrayAttr::get(ctx, modifiers);
1512
1513 if (succeeded(parser.parseOptionalKeyword("linear_var_types")) &&
1514 (parser.parseLParen() || parser.parseAttribute(linearArgs->varTypes) ||
1515 parser.parseRParen()))
1516 return failure();
1517 return success();
1518}
1519
1520static ParseResult parseBlockArgRegion(OpAsmParser &parser, Region &region,
1521 AllRegionParseArgs args) {
1523
1524 if (failed(parseBlockArgClause(parser, entryBlockArgs, "has_device_addr",
1525 args.hasDeviceAddrArgs)))
1526 return parser.emitError(parser.getCurrentLocation())
1527 << "invalid `has_device_addr` format";
1528
1529 if (failed(parseBlockArgClause(parser, entryBlockArgs, "host_eval",
1530 args.hostEvalArgs)))
1531 return parser.emitError(parser.getCurrentLocation())
1532 << "invalid `host_eval` format";
1533
1534 if (failed(parseBlockArgClause(parser, entryBlockArgs, "in_reduction",
1535 args.inReductionArgs)))
1536 return parser.emitError(parser.getCurrentLocation())
1537 << "invalid `in_reduction` format";
1538
1539 if (failed(parseBlockArgClause(parser, entryBlockArgs, "linear",
1540 args.linearArgs)))
1541 return parser.emitError(parser.getCurrentLocation())
1542 << "invalid `linear` format";
1543
1544 if (failed(parseBlockArgClause(parser, entryBlockArgs, "map_entries",
1545 args.mapArgs)))
1546 return parser.emitError(parser.getCurrentLocation())
1547 << "invalid `map_entries` format";
1548
1549 if (failed(parseBlockArgClause(parser, entryBlockArgs, "private",
1550 args.privateArgs)))
1551 return parser.emitError(parser.getCurrentLocation())
1552 << "invalid `private` format";
1553
1554 if (failed(parseBlockArgClause(parser, entryBlockArgs, "reduction",
1555 args.reductionArgs)))
1556 return parser.emitError(parser.getCurrentLocation())
1557 << "invalid `reduction` format";
1558
1559 if (failed(parseBlockArgClause(parser, entryBlockArgs, "task_reduction",
1560 args.taskReductionArgs)))
1561 return parser.emitError(parser.getCurrentLocation())
1562 << "invalid `task_reduction` format";
1563
1564 if (failed(parseBlockArgClause(parser, entryBlockArgs, "use_device_addr",
1565 args.useDeviceAddrArgs)))
1566 return parser.emitError(parser.getCurrentLocation())
1567 << "invalid `use_device_addr` format";
1568
1569 if (failed(parseBlockArgClause(parser, entryBlockArgs, "use_device_ptr",
1570 args.useDevicePtrArgs)))
1571 return parser.emitError(parser.getCurrentLocation())
1572 << "invalid `use_device_addr` format";
1573
1574 return parser.parseRegion(region, entryBlockArgs);
1575}
1576
1577// These parseXyz functions correspond to the custom<Xyz> definitions
1578// in the .td file(s).
1579static ParseResult parseTargetOpRegion(
1580 OpAsmParser &parser, Region &region,
1582 SmallVectorImpl<Type> &hasDeviceAddrTypes,
1584 SmallVectorImpl<Type> &hostEvalTypes,
1586 SmallVectorImpl<Type> &mapTypes,
1588 llvm::SmallVectorImpl<Type> &privateTypes, ArrayAttr &privateSyms,
1589 UnitAttr &privateNeedsBarrier, DenseI64ArrayAttr &privateMaps) {
1590 AllRegionParseArgs args;
1591 args.hasDeviceAddrArgs.emplace(hasDeviceAddrVars, hasDeviceAddrTypes);
1592 args.hostEvalArgs.emplace(hostEvalVars, hostEvalTypes);
1593 args.mapArgs.emplace(mapVars, mapTypes);
1594 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1595 privateNeedsBarrier, &privateMaps);
1596 return parseBlockArgRegion(parser, region, args);
1597}
1598
1600 OpAsmParser &parser, Region &region,
1602 SmallVectorImpl<Type> &inReductionTypes,
1603 DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms,
1605 llvm::SmallVectorImpl<Type> &privateTypes, ArrayAttr &privateSyms,
1606 UnitAttr &privateNeedsBarrier) {
1607 AllRegionParseArgs args;
1608 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1609 inReductionByref, inReductionSyms);
1610 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1611 privateNeedsBarrier);
1612 return parseBlockArgRegion(parser, region, args);
1613}
1614
1616 OpAsmParser &parser, Region &region,
1618 SmallVectorImpl<Type> &inReductionTypes,
1619 DenseBoolArrayAttr &inReductionByref, ArrayAttr &inReductionSyms,
1621 llvm::SmallVectorImpl<Type> &privateTypes, ArrayAttr &privateSyms,
1622 UnitAttr &privateNeedsBarrier, ArrayAttr &reductionMods,
1624 SmallVectorImpl<Type> &reductionTypes, DenseBoolArrayAttr &reductionByref,
1625 ArrayAttr &reductionSyms) {
1626 AllRegionParseArgs args;
1627 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1628 inReductionByref, inReductionSyms);
1629 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1630 privateNeedsBarrier);
1631 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1632 reductionSyms, &reductionMods);
1633 return parseBlockArgRegion(parser, region, args);
1634}
1635
1636static ParseResult parsePrivateRegion(
1637 OpAsmParser &parser, Region &region,
1639 llvm::SmallVectorImpl<Type> &privateTypes, ArrayAttr &privateSyms,
1640 UnitAttr &privateNeedsBarrier) {
1641 AllRegionParseArgs args;
1642 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1643 privateNeedsBarrier);
1644 return parseBlockArgRegion(parser, region, args);
1645}
1646
1648 OpAsmParser &parser, Region &region,
1650 llvm::SmallVectorImpl<Type> &privateTypes, ArrayAttr &privateSyms,
1651 UnitAttr &privateNeedsBarrier, ArrayAttr &reductionMods,
1653 SmallVectorImpl<Type> &reductionTypes, DenseBoolArrayAttr &reductionByref,
1654 ArrayAttr &reductionSyms) {
1655 AllRegionParseArgs args;
1656 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1657 privateNeedsBarrier);
1658 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1659 reductionSyms, &reductionMods);
1660 return parseBlockArgRegion(parser, region, args);
1661}
1662
1664 OpAsmParser &parser, Region &region,
1666 SmallVectorImpl<Type> &linearTypes,
1668 SmallVectorImpl<Type> &linearStepTypes, ArrayAttr &linearVarTypes,
1669 ArrayAttr &linearModifiers, ArrayAttr &linearSyms,
1671 llvm::SmallVectorImpl<Type> &privateTypes, ArrayAttr &privateSyms,
1672 UnitAttr &privateNeedsBarrier, ArrayAttr &reductionMods,
1674 SmallVectorImpl<Type> &reductionTypes, DenseBoolArrayAttr &reductionByref,
1675 ArrayAttr &reductionSyms) {
1676 AllRegionParseArgs args;
1677 args.linearArgs.emplace(linearVars, linearTypes, linearStepVars,
1678 linearStepTypes, linearVarTypes, linearModifiers,
1679 linearSyms);
1680 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1681 privateNeedsBarrier);
1682 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1683 reductionSyms, &reductionMods);
1684 return parseBlockArgRegion(parser, region, args);
1685}
1686
1687static ParseResult parseTaskReductionRegion(
1688 OpAsmParser &parser, Region &region,
1690 SmallVectorImpl<Type> &taskReductionTypes,
1691 DenseBoolArrayAttr &taskReductionByref, ArrayAttr &taskReductionSyms) {
1692 AllRegionParseArgs args;
1693 args.taskReductionArgs.emplace(taskReductionVars, taskReductionTypes,
1694 taskReductionByref, taskReductionSyms);
1695 return parseBlockArgRegion(parser, region, args);
1696}
1697
1699 OpAsmParser &parser, Region &region,
1701 SmallVectorImpl<Type> &useDeviceAddrTypes,
1703 SmallVectorImpl<Type> &useDevicePtrTypes) {
1704 AllRegionParseArgs args;
1705 args.useDeviceAddrArgs.emplace(useDeviceAddrVars, useDeviceAddrTypes);
1706 args.useDevicePtrArgs.emplace(useDevicePtrVars, useDevicePtrTypes);
1707 return parseBlockArgRegion(parser, region, args);
1708}
1709
1710//===----------------------------------------------------------------------===//
1711// Printers for operations including clauses that define entry block arguments.
1712//===----------------------------------------------------------------------===//
1713
1714namespace {
1715struct MapPrintArgs {
1716 ValueRange vars;
1717 TypeRange types;
1718 MapPrintArgs(ValueRange vars, TypeRange types) : vars(vars), types(types) {}
1719};
1720struct PrivatePrintArgs {
1721 ValueRange vars;
1722 TypeRange types;
1723 ArrayAttr syms;
1724 UnitAttr needsBarrier;
1725 DenseI64ArrayAttr mapIndices;
1726 PrivatePrintArgs(ValueRange vars, TypeRange types, ArrayAttr syms,
1727 UnitAttr needsBarrier, DenseI64ArrayAttr mapIndices)
1728 : vars(vars), types(types), syms(syms), needsBarrier(needsBarrier),
1729 mapIndices(mapIndices) {}
1730};
1731struct LinearPrintArgs {
1732 ValueRange vars;
1733 TypeRange types;
1734 ValueRange stepVars;
1735 TypeRange stepTypes;
1736 ArrayAttr varTypes;
1737 ArrayAttr modifiers;
1738 ArrayAttr syms;
1739 LinearPrintArgs(ValueRange vars, TypeRange types, ValueRange stepVars,
1740 TypeRange stepTypes, ArrayAttr varTypes, ArrayAttr modifiers,
1741 ArrayAttr syms)
1742 : vars(vars), types(types), stepVars(stepVars), stepTypes(stepTypes),
1743 varTypes(varTypes), modifiers(modifiers), syms(syms) {}
1744};
1745struct ReductionPrintArgs {
1746 ValueRange vars;
1747 TypeRange types;
1748 DenseBoolArrayAttr byref;
1749 ArrayAttr syms;
1750 ArrayAttr modifier;
1751 ReductionPrintArgs(ValueRange vars, TypeRange types, DenseBoolArrayAttr byref,
1752 ArrayAttr syms, ArrayAttr mod = nullptr)
1753 : vars(vars), types(types), byref(byref), syms(syms), modifier(mod) {}
1754};
1755struct AllRegionPrintArgs {
1756 std::optional<MapPrintArgs> hasDeviceAddrArgs;
1757 std::optional<MapPrintArgs> hostEvalArgs;
1758 std::optional<ReductionPrintArgs> inReductionArgs;
1759 std::optional<LinearPrintArgs> linearArgs;
1760 std::optional<MapPrintArgs> mapArgs;
1761 std::optional<PrivatePrintArgs> privateArgs;
1762 std::optional<ReductionPrintArgs> reductionArgs;
1763 std::optional<ReductionPrintArgs> taskReductionArgs;
1764 std::optional<MapPrintArgs> useDeviceAddrArgs;
1765 std::optional<MapPrintArgs> useDevicePtrArgs;
1766};
1767} // namespace
1768
1770 OpAsmPrinter &p, MLIRContext *ctx, StringRef clauseName,
1771 ValueRange argsSubrange, ValueRange operands, TypeRange types,
1772 ArrayAttr symbols = nullptr, DenseI64ArrayAttr mapIndices = nullptr,
1773 DenseBoolArrayAttr byref = nullptr, ArrayAttr modifier = nullptr,
1774 UnitAttr needsBarrier = nullptr) {
1775 if (argsSubrange.empty())
1776 return;
1777
1778 p << clauseName << "(";
1779
1780 if (!symbols) {
1781 llvm::SmallVector<Attribute> values(operands.size(), nullptr);
1782 symbols = ArrayAttr::get(ctx, values);
1783 }
1784
1785 if (!mapIndices) {
1786 llvm::SmallVector<int64_t> values(operands.size(), -1);
1787 mapIndices = DenseI64ArrayAttr::get(ctx, values);
1788 }
1789
1790 if (!byref) {
1791 mlir::SmallVector<bool> values(operands.size(), false);
1792 byref = DenseBoolArrayAttr::get(ctx, values);
1793 }
1794
1795 unsigned index = 0;
1796 llvm::interleaveComma(
1797 llvm::zip_equal(operands, argsSubrange, symbols, mapIndices.asArrayRef(),
1798 byref.asArrayRef()),
1799 p, [&](auto t) {
1800 auto [op, arg, sym, map, isByRef] = t;
1801 if (modifier) {
1802 ReductionModifier mod =
1803 cast<ReductionModifierAttr>(modifier[index]).getValue();
1804 if (mod != ReductionModifier::defaultmod)
1805 p << stringifyReductionModifier(mod) << " ";
1806 }
1807 ++index;
1808 if (isByRef)
1809 p << "byref ";
1810 if (sym)
1811 p << sym << " ";
1812 p << op << " -> " << arg;
1813 if (map != -1)
1814 p << " [map_idx=" << map << "]";
1815 });
1816 p << " : ";
1817 llvm::interleaveComma(types, p);
1818 p << ") ";
1819
1820 if (needsBarrier)
1821 p << getPrivateNeedsBarrierSpelling() << " ";
1822}
1823
1825 StringRef clauseName, ValueRange argsSubrange,
1826 std::optional<MapPrintArgs> mapArgs) {
1827 if (mapArgs)
1828 printClauseWithRegionArgs(p, ctx, clauseName, argsSubrange, mapArgs->vars,
1829 mapArgs->types);
1830}
1831
1833 StringRef clauseName, ValueRange argsSubrange,
1834 std::optional<PrivatePrintArgs> privateArgs) {
1835 if (privateArgs)
1837 p, ctx, clauseName, argsSubrange, privateArgs->vars, privateArgs->types,
1838 privateArgs->syms, privateArgs->mapIndices, /*byref=*/nullptr,
1839 /*modifier=*/nullptr, privateArgs->needsBarrier);
1840}
1841
1842static void
1843printBlockArgClause(OpAsmPrinter &p, MLIRContext *ctx, StringRef clauseName,
1844 ValueRange argsSubrange,
1845 std::optional<ReductionPrintArgs> reductionArgs) {
1846 if (reductionArgs)
1847 printClauseWithRegionArgs(p, ctx, clauseName, argsSubrange,
1848 reductionArgs->vars, reductionArgs->types,
1849 reductionArgs->syms, /*mapIndices=*/nullptr,
1850 reductionArgs->byref, reductionArgs->modifier);
1851}
1852
1854 StringRef clauseName, ValueRange argsSubrange,
1855 std::optional<LinearPrintArgs> linearArgs) {
1856 if (!linearArgs || argsSubrange.empty())
1857 return;
1858
1859 p << clauseName << "(";
1860 for (auto [i, var] : llvm::enumerate(linearArgs->vars)) {
1861 if (i != 0)
1862 p << ", ";
1863 auto modifier =
1864 linearArgs->modifiers
1865 ? dyn_cast_if_present<LinearModifierAttr>(linearArgs->modifiers[i])
1866 : nullptr;
1867 if (modifier)
1868 p << stringifyLinearModifier(modifier.getValue()) << "(";
1869 if (linearArgs->syms)
1870 p << linearArgs->syms[i] << " ";
1871 p << var << " -> " << argsSubrange[i] << " : " << linearArgs->types[i]
1872 << " = " << linearArgs->stepVars[i] << " : " << linearArgs->stepTypes[i];
1873 if (modifier)
1874 p << ")";
1875 }
1876 p << ") ";
1877
1878 if (linearArgs->varTypes)
1879 p << "linear_var_types(" << linearArgs->varTypes << ") ";
1880}
1881
1883 const AllRegionPrintArgs &args) {
1884 auto iface = llvm::cast<mlir::omp::BlockArgOpenMPOpInterface>(op);
1885 MLIRContext *ctx = op->getContext();
1886
1887 printBlockArgClause(p, ctx, "has_device_addr",
1888 iface.getHasDeviceAddrBlockArgs(),
1889 args.hasDeviceAddrArgs);
1890 printBlockArgClause(p, ctx, "host_eval", iface.getHostEvalBlockArgs(),
1891 args.hostEvalArgs);
1892 printBlockArgClause(p, ctx, "in_reduction", iface.getInReductionBlockArgs(),
1893 args.inReductionArgs);
1894 printBlockArgClause(p, ctx, "linear", iface.getLinearBlockArgs(),
1895 args.linearArgs);
1896 printBlockArgClause(p, ctx, "map_entries", iface.getMapBlockArgs(),
1897 args.mapArgs);
1898 printBlockArgClause(p, ctx, "private", iface.getPrivateBlockArgs(),
1899 args.privateArgs);
1900 printBlockArgClause(p, ctx, "reduction", iface.getReductionBlockArgs(),
1901 args.reductionArgs);
1902 printBlockArgClause(p, ctx, "task_reduction",
1903 iface.getTaskReductionBlockArgs(),
1904 args.taskReductionArgs);
1905 printBlockArgClause(p, ctx, "use_device_addr",
1906 iface.getUseDeviceAddrBlockArgs(),
1907 args.useDeviceAddrArgs);
1908 printBlockArgClause(p, ctx, "use_device_ptr",
1909 iface.getUseDevicePtrBlockArgs(), args.useDevicePtrArgs);
1910
1911 p.printRegion(region, /*printEntryBlockArgs=*/false);
1912}
1913
1914// These parseXyz functions correspond to the custom<Xyz> definitions
1915// in the .td file(s).
1917 ValueRange hasDeviceAddrVars,
1918 TypeRange hasDeviceAddrTypes,
1919 ValueRange hostEvalVars,
1920 TypeRange hostEvalTypes, ValueRange mapVars,
1921 TypeRange mapTypes, ValueRange privateVars,
1922 TypeRange privateTypes, ArrayAttr privateSyms,
1923 UnitAttr privateNeedsBarrier,
1924 DenseI64ArrayAttr privateMaps) {
1925 AllRegionPrintArgs args;
1926 args.hasDeviceAddrArgs.emplace(hasDeviceAddrVars, hasDeviceAddrTypes);
1927 args.hostEvalArgs.emplace(hostEvalVars, hostEvalTypes);
1928 args.mapArgs.emplace(mapVars, mapTypes);
1929 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1930 privateNeedsBarrier, privateMaps);
1931 printBlockArgRegion(p, op, region, args);
1932}
1933
1935 OpAsmPrinter &p, Operation *op, Region &region, ValueRange inReductionVars,
1936 TypeRange inReductionTypes, DenseBoolArrayAttr inReductionByref,
1937 ArrayAttr inReductionSyms, ValueRange privateVars, TypeRange privateTypes,
1938 ArrayAttr privateSyms, UnitAttr privateNeedsBarrier) {
1939 AllRegionPrintArgs args;
1940 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1941 inReductionByref, inReductionSyms);
1942 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1943 privateNeedsBarrier,
1944 /*mapIndices=*/nullptr);
1945 printBlockArgRegion(p, op, region, args);
1946}
1947
1949 OpAsmPrinter &p, Operation *op, Region &region, ValueRange inReductionVars,
1950 TypeRange inReductionTypes, DenseBoolArrayAttr inReductionByref,
1951 ArrayAttr inReductionSyms, ValueRange privateVars, TypeRange privateTypes,
1952 ArrayAttr privateSyms, UnitAttr privateNeedsBarrier,
1953 ArrayAttr reductionMods, ValueRange reductionVars, TypeRange reductionTypes,
1954 DenseBoolArrayAttr reductionByref, ArrayAttr reductionSyms) {
1955 AllRegionPrintArgs args;
1956 args.inReductionArgs.emplace(inReductionVars, inReductionTypes,
1957 inReductionByref, inReductionSyms);
1958 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1959 privateNeedsBarrier,
1960 /*mapIndices=*/nullptr);
1961 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1962 reductionSyms, reductionMods);
1963 printBlockArgRegion(p, op, region, args);
1964}
1965
1967 ValueRange privateVars, TypeRange privateTypes,
1968 ArrayAttr privateSyms,
1969 UnitAttr privateNeedsBarrier) {
1970 AllRegionPrintArgs args;
1971 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1972 privateNeedsBarrier,
1973 /*mapIndices=*/nullptr);
1974 printBlockArgRegion(p, op, region, args);
1975}
1976
1978 OpAsmPrinter &p, Operation *op, Region &region, ValueRange privateVars,
1979 TypeRange privateTypes, ArrayAttr privateSyms, UnitAttr privateNeedsBarrier,
1980 ArrayAttr reductionMods, ValueRange reductionVars, TypeRange reductionTypes,
1981 DenseBoolArrayAttr reductionByref, ArrayAttr reductionSyms) {
1982 AllRegionPrintArgs args;
1983 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
1984 privateNeedsBarrier,
1985 /*mapIndices=*/nullptr);
1986 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
1987 reductionSyms, reductionMods);
1988 printBlockArgRegion(p, op, region, args);
1989}
1990
1992 OpAsmPrinter &p, Operation *op, Region &region, ValueRange linearVars,
1993 TypeRange linearTypes, ValueRange linearStepVars, TypeRange linearStepTypes,
1994 ArrayAttr linearVarTypes, ArrayAttr linearModifiers, ArrayAttr linearSyms,
1995 ValueRange privateVars, TypeRange privateTypes, ArrayAttr privateSyms,
1996 UnitAttr privateNeedsBarrier, ArrayAttr reductionMods,
1997 ValueRange reductionVars, TypeRange reductionTypes,
1998 DenseBoolArrayAttr reductionByref, ArrayAttr reductionSyms) {
1999 AllRegionPrintArgs args;
2000 args.linearArgs.emplace(linearVars, linearTypes, linearStepVars,
2001 linearStepTypes, linearVarTypes, linearModifiers,
2002 linearSyms);
2003 args.privateArgs.emplace(privateVars, privateTypes, privateSyms,
2004 privateNeedsBarrier,
2005 /*mapIndices=*/nullptr);
2006 args.reductionArgs.emplace(reductionVars, reductionTypes, reductionByref,
2007 reductionSyms, reductionMods);
2008 printBlockArgRegion(p, op, region, args);
2009}
2010
2012 Region &region,
2013 ValueRange taskReductionVars,
2014 TypeRange taskReductionTypes,
2015 DenseBoolArrayAttr taskReductionByref,
2016 ArrayAttr taskReductionSyms) {
2017 AllRegionPrintArgs args;
2018 args.taskReductionArgs.emplace(taskReductionVars, taskReductionTypes,
2019 taskReductionByref, taskReductionSyms);
2020 printBlockArgRegion(p, op, region, args);
2021}
2022
2024 Region &region,
2025 ValueRange useDeviceAddrVars,
2026 TypeRange useDeviceAddrTypes,
2027 ValueRange useDevicePtrVars,
2028 TypeRange useDevicePtrTypes) {
2029 AllRegionPrintArgs args;
2030 args.useDeviceAddrArgs.emplace(useDeviceAddrVars, useDeviceAddrTypes);
2031 args.useDevicePtrArgs.emplace(useDevicePtrVars, useDevicePtrTypes);
2032 printBlockArgRegion(p, op, region, args);
2033}
2034
2035template <typename ParsePrefixFn>
2036static ParseResult parseSplitIteratedList(
2037 OpAsmParser &parser,
2039 SmallVectorImpl<Type> &iteratedTypes,
2041 SmallVectorImpl<Type> &plainTypes, ParsePrefixFn &&parsePrefix) {
2042
2043 return parser.parseCommaSeparatedList([&]() -> ParseResult {
2044 if (failed(parsePrefix()))
2045 return failure();
2046
2048 Type ty;
2049 if (parser.parseOperand(v) || parser.parseColonType(ty))
2050 return failure();
2051
2052 if (llvm::isa<mlir::omp::IteratedType>(ty)) {
2053 iteratedVars.push_back(v);
2054 iteratedTypes.push_back(ty);
2055 } else {
2056 plainVars.push_back(v);
2057 plainTypes.push_back(ty);
2058 }
2059 return success();
2060 });
2061}
2062
2063template <typename PrintPrefixFn>
2065 TypeRange iteratedTypes,
2066 ValueRange plainVars, TypeRange plainTypes,
2067 PrintPrefixFn &&printPrefixForPlain,
2068 PrintPrefixFn &&printPrefixForIterated) {
2069
2070 bool first = true;
2071 auto emit = [&](Value v, Type t, auto &&printPrefix) {
2072 if (!first)
2073 p << ", ";
2074 printPrefix(v, t);
2075 p << v << " : " << t;
2076 first = false;
2077 };
2078
2079 for (unsigned i = 0; i < iteratedVars.size(); ++i)
2080 emit(iteratedVars[i], iteratedTypes[i], printPrefixForIterated);
2081 for (unsigned i = 0; i < plainVars.size(); ++i)
2082 emit(plainVars[i], plainTypes[i], printPrefixForPlain);
2083}
2084
2085/// Verify the per-variable modifier list has one entry per reduction variable.
2086static LogicalResult verifyReductionModifiers(Operation *op,
2087 OperandRange reductionVars,
2088 ArrayAttr reductionMods) {
2089 if (reductionMods && reductionMods.size() != reductionVars.size())
2090 return op->emitOpError(
2091 "expected as many reduction modifiers as reduction variables");
2092 return success();
2093}
2094
2095/// Verifies Reduction Clause
2096static LogicalResult
2097verifyReductionVarList(Operation *op, std::optional<ArrayAttr> reductionSyms,
2098 OperandRange reductionVars,
2099 std::optional<ArrayRef<bool>> reductionByref,
2100 ArrayAttr reductionMods = nullptr) {
2101 if (failed(verifyReductionModifiers(op, reductionVars, reductionMods)))
2102 return failure();
2103 if (!reductionVars.empty()) {
2104 if (!reductionSyms || reductionSyms->size() != reductionVars.size())
2105 return op->emitOpError()
2106 << "expected as many reduction symbol references "
2107 "as reduction variables";
2108 if (reductionByref && reductionByref->size() != reductionVars.size())
2109 return op->emitError() << "expected as many reduction variable by "
2110 "reference attributes as reduction variables";
2111 } else {
2112 if (reductionSyms)
2113 return op->emitOpError() << "unexpected reduction symbol references";
2114 return success();
2115 }
2116
2117 // TODO: The followings should be done in
2118 // SymbolUserOpInterface::verifySymbolUses.
2119 DenseSet<Value> accumulators;
2120 for (auto args : llvm::zip(reductionVars, *reductionSyms)) {
2121 Value accum = std::get<0>(args);
2122
2123 if (!accumulators.insert(accum).second)
2124 return op->emitOpError() << "accumulator variable used more than once";
2125
2126 Type varType = accum.getType();
2127 auto symbolRef = llvm::cast<SymbolRefAttr>(std::get<1>(args));
2128 auto decl =
2130 if (!decl)
2131 return op->emitOpError() << "expected symbol reference " << symbolRef
2132 << " to point to a reduction declaration";
2133
2134 if (decl.getAccumulatorType() && decl.getAccumulatorType() != varType)
2135 return op->emitOpError()
2136 << "expected accumulator (" << varType
2137 << ") to be the same type as reduction declaration ("
2138 << decl.getAccumulatorType() << ")";
2139 }
2140
2141 return success();
2142}
2143
2144//===----------------------------------------------------------------------===//
2145// Parser, printer and verifier for Copyprivate
2146//===----------------------------------------------------------------------===//
2147
2148/// copyprivate-entry-list ::= copyprivate-entry
2149/// | copyprivate-entry-list `,` copyprivate-entry
2150/// copyprivate-entry ::= ssa-id `->` symbol-ref `:` type
2151static ParseResult parseCopyprivate(
2152 OpAsmParser &parser,
2154 SmallVectorImpl<Type> &copyprivateTypes, ArrayAttr &copyprivateSyms) {
2156 if (failed(parser.parseCommaSeparatedList([&]() {
2157 if (parser.parseOperand(copyprivateVars.emplace_back()) ||
2158 parser.parseArrow() ||
2159 parser.parseAttribute(symsVec.emplace_back()) ||
2160 parser.parseColonType(copyprivateTypes.emplace_back()))
2161 return failure();
2162 return success();
2163 })))
2164 return failure();
2165 SmallVector<Attribute> syms(symsVec.begin(), symsVec.end());
2166 copyprivateSyms = ArrayAttr::get(parser.getContext(), syms);
2167 return success();
2168}
2169
2170/// Print Copyprivate clause
2172 OperandRange copyprivateVars,
2173 TypeRange copyprivateTypes,
2174 std::optional<ArrayAttr> copyprivateSyms) {
2175 if (!copyprivateSyms.has_value())
2176 return;
2177 llvm::interleaveComma(
2178 llvm::zip(copyprivateVars, *copyprivateSyms, copyprivateTypes), p,
2179 [&](const auto &args) {
2180 p << std::get<0>(args) << " -> " << std::get<1>(args) << " : "
2181 << std::get<2>(args);
2182 });
2183}
2184
2185/// Verifies CopyPrivate Clause
2186static LogicalResult
2188 std::optional<ArrayAttr> copyprivateSyms) {
2189 size_t copyprivateSymsSize =
2190 copyprivateSyms.has_value() ? copyprivateSyms->size() : 0;
2191 if (copyprivateSymsSize != copyprivateVars.size())
2192 return op->emitOpError() << "inconsistent number of copyprivate vars (= "
2193 << copyprivateVars.size()
2194 << ") and functions (= " << copyprivateSymsSize
2195 << "), both must be equal";
2196 if (!copyprivateSyms.has_value())
2197 return success();
2198
2199 for (auto copyprivateVarAndSym :
2200 llvm::zip(copyprivateVars, *copyprivateSyms)) {
2201 auto symbolRef =
2202 llvm::cast<SymbolRefAttr>(std::get<1>(copyprivateVarAndSym));
2203 std::optional<std::variant<mlir::func::FuncOp, mlir::LLVM::LLVMFuncOp>>
2204 funcOp;
2205 if (mlir::func::FuncOp mlirFuncOp =
2207 symbolRef))
2208 funcOp = mlirFuncOp;
2209 else if (mlir::LLVM::LLVMFuncOp llvmFuncOp =
2211 op, symbolRef))
2212 funcOp = llvmFuncOp;
2213
2214 auto getNumArguments = [&] {
2215 return std::visit([](auto &f) { return f.getNumArguments(); }, *funcOp);
2216 };
2217
2218 auto getArgumentType = [&](unsigned i) {
2219 return std::visit([i](auto &f) { return f.getArgumentTypes()[i]; },
2220 *funcOp);
2221 };
2222
2223 if (!funcOp)
2224 return op->emitOpError() << "expected symbol reference " << symbolRef
2225 << " to point to a copy function";
2226
2227 if (getNumArguments() != 2)
2228 return op->emitOpError()
2229 << "expected copy function " << symbolRef << " to have 2 operands";
2230
2231 Type argTy = getArgumentType(0);
2232 if (argTy != getArgumentType(1))
2233 return op->emitOpError() << "expected copy function " << symbolRef
2234 << " arguments to have the same type";
2235
2236 Type varType = std::get<0>(copyprivateVarAndSym).getType();
2237 if (argTy != varType)
2238 return op->emitOpError()
2239 << "expected copy function arguments' type (" << argTy
2240 << ") to be the same as copyprivate variable's type (" << varType
2241 << ")";
2242 }
2243
2244 return success();
2245}
2246
2247//===----------------------------------------------------------------------===//
2248// Parser, printer and verifier for DependVarList
2249//===----------------------------------------------------------------------===//
2250
2251/// depend-entry-list ::= depend-entry
2252/// | depend-entry-list `,` depend-entry
2253/// depend-entry ::= depend-kind `->` ssa-id `:` type
2254/// | depend-kind `->` ssa-id `:` iterated-type
2255static ParseResult parseDependVarList(
2256 OpAsmParser &parser,
2258 SmallVectorImpl<Type> &dependTypes, ArrayAttr &dependKinds,
2260 SmallVectorImpl<Type> &iteratedTypes, ArrayAttr &iteratedKinds) {
2263 if (failed(parser.parseCommaSeparatedList([&]() {
2264 StringRef keyword;
2265 OpAsmParser::UnresolvedOperand operand;
2266 Type ty;
2267 if (parser.parseKeyword(&keyword) || parser.parseArrow() ||
2268 parser.parseOperand(operand) || parser.parseColonType(ty))
2269 return failure();
2270 std::optional<ClauseTaskDepend> keywordDepend =
2271 symbolizeClauseTaskDepend(keyword);
2272 if (!keywordDepend)
2273 return failure();
2274 auto kindAttr =
2275 ClauseTaskDependAttr::get(parser.getContext(), *keywordDepend);
2276 if (llvm::isa<mlir::omp::IteratedType>(ty)) {
2277 iteratedVars.push_back(operand);
2278 iteratedTypes.push_back(ty);
2279 iterKindsVec.push_back(kindAttr);
2280 } else {
2281 dependVars.push_back(operand);
2282 dependTypes.push_back(ty);
2283 kindsVec.push_back(kindAttr);
2284 }
2285 return success();
2286 })))
2287 return failure();
2288 SmallVector<Attribute> kinds(kindsVec.begin(), kindsVec.end());
2289 dependKinds = ArrayAttr::get(parser.getContext(), kinds);
2290 SmallVector<Attribute> iterKinds(iterKindsVec.begin(), iterKindsVec.end());
2291 iteratedKinds = ArrayAttr::get(parser.getContext(), iterKinds);
2292 return success();
2293}
2294
2295/// Print Depend clause
2297 OperandRange dependVars, TypeRange dependTypes,
2298 std::optional<ArrayAttr> dependKinds,
2299 OperandRange iteratedVars,
2300 TypeRange iteratedTypes,
2301 std::optional<ArrayAttr> iteratedKinds) {
2302 bool first = true;
2303 auto printEntries = [&](OperandRange vars, TypeRange types,
2304 std::optional<ArrayAttr> kinds) {
2305 for (unsigned i = 0, e = vars.size(); i < e; ++i) {
2306 if (!first)
2307 p << ", ";
2308 p << stringifyClauseTaskDepend(
2309 llvm::cast<mlir::omp::ClauseTaskDependAttr>((*kinds)[i])
2310 .getValue())
2311 << " -> " << vars[i] << " : " << types[i];
2312 first = false;
2313 }
2314 };
2315 printEntries(dependVars, dependTypes, dependKinds);
2316 printEntries(iteratedVars, iteratedTypes, iteratedKinds);
2317}
2318
2319/// Verifies Depend clause
2320static LogicalResult verifyDependVarList(Operation *op,
2321 std::optional<ArrayAttr> dependKinds,
2322 OperandRange dependVars,
2323 std::optional<ArrayAttr> iteratedKinds,
2324 OperandRange iteratedVars) {
2325 if (!dependVars.empty()) {
2326 if (!dependKinds || dependKinds->size() != dependVars.size())
2327 return op->emitOpError() << "expected as many depend values"
2328 " as depend variables";
2329 } else {
2330 if (dependKinds && !dependKinds->empty())
2331 return op->emitOpError() << "unexpected depend values";
2332 }
2333
2334 if (!iteratedVars.empty()) {
2335 if (!iteratedKinds || iteratedKinds->size() != iteratedVars.size())
2336 return op->emitOpError() << "expected as many depend iterated values"
2337 " as depend iterated variables";
2338 } else {
2339 if (iteratedKinds && !iteratedKinds->empty())
2340 return op->emitOpError() << "unexpected depend iterated values";
2341 }
2342
2343 return success();
2344}
2345
2346//===----------------------------------------------------------------------===//
2347// Parser, printer and verifier for Synchronization Hint (2.17.12)
2348//===----------------------------------------------------------------------===//
2349
2350/// Parses a Synchronization Hint clause. The value of hint is an integer
2351/// which is a combination of different hints from `omp_sync_hint_t`.
2352///
2353/// hint-clause = `hint` `(` hint-value `)`
2354static ParseResult parseSynchronizationHint(OpAsmParser &parser,
2355 IntegerAttr &hintAttr) {
2356 StringRef hintKeyword;
2357 int64_t hint = 0;
2358 if (succeeded(parser.parseOptionalKeyword("none"))) {
2359 hintAttr = IntegerAttr::get(parser.getBuilder().getI64Type(), 0);
2360 return success();
2361 }
2362 auto parseKeyword = [&]() -> ParseResult {
2363 if (failed(parser.parseKeyword(&hintKeyword)))
2364 return failure();
2365 if (hintKeyword == "uncontended")
2366 hint |= 1;
2367 else if (hintKeyword == "contended")
2368 hint |= 2;
2369 else if (hintKeyword == "nonspeculative")
2370 hint |= 4;
2371 else if (hintKeyword == "speculative")
2372 hint |= 8;
2373 else
2374 return parser.emitError(parser.getCurrentLocation())
2375 << hintKeyword << " is not a valid hint";
2376 return success();
2377 };
2378 if (parser.parseCommaSeparatedList(parseKeyword))
2379 return failure();
2380 hintAttr = IntegerAttr::get(parser.getBuilder().getI64Type(), hint);
2381 return success();
2382}
2383
2384/// Prints a Synchronization Hint clause
2386 IntegerAttr hintAttr) {
2387 int64_t hint = hintAttr.getInt();
2388
2389 if (hint == 0) {
2390 p << "none";
2391 return;
2392 }
2393
2394 // Helper function to get n-th bit from the right end of `value`
2395 auto bitn = [](int value, int n) -> bool { return value & (1 << n); };
2396
2397 bool uncontended = bitn(hint, 0);
2398 bool contended = bitn(hint, 1);
2399 bool nonspeculative = bitn(hint, 2);
2400 bool speculative = bitn(hint, 3);
2401
2403 if (uncontended)
2404 hints.push_back("uncontended");
2405 if (contended)
2406 hints.push_back("contended");
2407 if (nonspeculative)
2408 hints.push_back("nonspeculative");
2409 if (speculative)
2410 hints.push_back("speculative");
2411
2412 llvm::interleaveComma(hints, p);
2413}
2414
2415/// Verifies a synchronization hint clause
2416static LogicalResult verifySynchronizationHint(Operation *op, uint64_t hint) {
2417
2418 // Helper function to get n-th bit from the right end of `value`
2419 auto bitn = [](int value, int n) -> bool { return value & (1 << n); };
2420
2421 bool uncontended = bitn(hint, 0);
2422 bool contended = bitn(hint, 1);
2423 bool nonspeculative = bitn(hint, 2);
2424 bool speculative = bitn(hint, 3);
2425
2426 if (uncontended && contended)
2427 return op->emitOpError() << "the hints omp_sync_hint_uncontended and "
2428 "omp_sync_hint_contended cannot be combined";
2429 if (nonspeculative && speculative)
2430 return op->emitOpError() << "the hints omp_sync_hint_nonspeculative and "
2431 "omp_sync_hint_speculative cannot be combined.";
2432 return success();
2433}
2434
2435//===----------------------------------------------------------------------===//
2436// Parser, printer and verifier for Target
2437//===----------------------------------------------------------------------===//
2438
2439// Helper function to get bitwise AND of `value` and 'flag' then return it as a
2440// boolean
2441static bool mapTypeToBool(ClauseMapFlags value, ClauseMapFlags flag) {
2442 return (value & flag) == flag;
2443}
2444
2445/// Parses a map_entries map type from a string format back into its numeric
2446/// value.
2447///
2448/// map-clause = `map_clauses ( ( `(` `always, `? `implicit, `? `ompx_hold, `?
2449/// `close, `? `present, `? ( `to` | `from` | `delete` `)` )+ `)` )
2450static ParseResult parseMapClause(OpAsmParser &parser,
2451 ClauseMapFlagsAttr &mapType) {
2452 ClauseMapFlags mapTypeBits = ClauseMapFlags::none;
2453 // This simply verifies the correct keyword is read in, the
2454 // keyword itself is stored inside of the operation
2455 auto parseTypeAndMod = [&]() -> ParseResult {
2456 StringRef mapTypeMod;
2457 if (parser.parseKeyword(&mapTypeMod))
2458 return failure();
2459
2460 if (mapTypeMod == "always")
2461 mapTypeBits |= ClauseMapFlags::always;
2462
2463 if (mapTypeMod == "implicit")
2464 mapTypeBits |= ClauseMapFlags::implicit;
2465
2466 if (mapTypeMod == "ompx_hold")
2467 mapTypeBits |= ClauseMapFlags::ompx_hold;
2468
2469 if (mapTypeMod == "close")
2470 mapTypeBits |= ClauseMapFlags::close;
2471
2472 if (mapTypeMod == "present")
2473 mapTypeBits |= ClauseMapFlags::present;
2474
2475 if (mapTypeMod == "to")
2476 mapTypeBits |= ClauseMapFlags::to;
2477
2478 if (mapTypeMod == "from")
2479 mapTypeBits |= ClauseMapFlags::from;
2480
2481 if (mapTypeMod == "tofrom")
2482 mapTypeBits |= ClauseMapFlags::to | ClauseMapFlags::from;
2483
2484 if (mapTypeMod == "delete")
2485 mapTypeBits |= ClauseMapFlags::del;
2486
2487 if (mapTypeMod == "storage")
2488 mapTypeBits |= ClauseMapFlags::storage;
2489
2490 if (mapTypeMod == "return_param")
2491 mapTypeBits |= ClauseMapFlags::return_param;
2492
2493 if (mapTypeMod == "private")
2494 mapTypeBits |= ClauseMapFlags::priv;
2495
2496 if (mapTypeMod == "literal")
2497 mapTypeBits |= ClauseMapFlags::literal;
2498
2499 if (mapTypeMod == "attach")
2500 mapTypeBits |= ClauseMapFlags::attach;
2501
2502 if (mapTypeMod == "attach_always")
2503 mapTypeBits |= ClauseMapFlags::attach_always;
2504
2505 if (mapTypeMod == "attach_never")
2506 mapTypeBits |= ClauseMapFlags::attach_never;
2507
2508 if (mapTypeMod == "attach_auto")
2509 mapTypeBits |= ClauseMapFlags::attach_auto;
2510
2511 if (mapTypeMod == "ref_ptr")
2512 mapTypeBits |= ClauseMapFlags::ref_ptr;
2513
2514 if (mapTypeMod == "ref_ptee")
2515 mapTypeBits |= ClauseMapFlags::ref_ptee;
2516
2517 if (mapTypeMod == "is_device_ptr")
2518 mapTypeBits |= ClauseMapFlags::is_device_ptr;
2519
2520 if (mapTypeMod == "target_param")
2521 mapTypeBits |= ClauseMapFlags::target_param;
2522
2523 return success();
2524 };
2525
2526 if (parser.parseCommaSeparatedList(parseTypeAndMod))
2527 return failure();
2528
2529 mapType =
2530 parser.getBuilder().getAttr<mlir::omp::ClauseMapFlagsAttr>(mapTypeBits);
2531
2532 return success();
2533}
2534
2535/// Prints a map_entries map type from its numeric value out into its string
2536/// format.
2537static void printMapClause(OpAsmPrinter &p, Operation *op,
2538 ClauseMapFlagsAttr mapType) {
2540 ClauseMapFlags mapFlags = mapType.getValue();
2541
2542 // handling of always, close, present placed at the beginning of the string
2543 // to aid readability
2544 if (mapTypeToBool(mapFlags, ClauseMapFlags::always))
2545 mapTypeStrs.push_back("always");
2546 if (mapTypeToBool(mapFlags, ClauseMapFlags::implicit))
2547 mapTypeStrs.push_back("implicit");
2548 if (mapTypeToBool(mapFlags, ClauseMapFlags::ompx_hold))
2549 mapTypeStrs.push_back("ompx_hold");
2550 if (mapTypeToBool(mapFlags, ClauseMapFlags::close))
2551 mapTypeStrs.push_back("close");
2552 if (mapTypeToBool(mapFlags, ClauseMapFlags::present))
2553 mapTypeStrs.push_back("present");
2554 if (mapTypeToBool(mapFlags, ClauseMapFlags::target_param))
2555 mapTypeStrs.push_back("target_param");
2556
2557 // special handling of to/from/tofrom/delete and release/alloc, release +
2558 // alloc are the abscense of one of the other flags, whereas tofrom requires
2559 // both the to and from flag to be set.
2560 bool to = mapTypeToBool(mapFlags, ClauseMapFlags::to);
2561 bool from = mapTypeToBool(mapFlags, ClauseMapFlags::from);
2562
2563 if (to && from)
2564 mapTypeStrs.push_back("tofrom");
2565 else if (from)
2566 mapTypeStrs.push_back("from");
2567 else if (to)
2568 mapTypeStrs.push_back("to");
2569
2570 if (mapTypeToBool(mapFlags, ClauseMapFlags::del))
2571 mapTypeStrs.push_back("delete");
2572 if (mapTypeToBool(mapFlags, ClauseMapFlags::return_param))
2573 mapTypeStrs.push_back("return_param");
2574 if (mapTypeToBool(mapFlags, ClauseMapFlags::storage))
2575 mapTypeStrs.push_back("storage");
2576 if (mapTypeToBool(mapFlags, ClauseMapFlags::priv))
2577 mapTypeStrs.push_back("private");
2578 if (mapTypeToBool(mapFlags, ClauseMapFlags::literal))
2579 mapTypeStrs.push_back("literal");
2580 if (mapTypeToBool(mapFlags, ClauseMapFlags::attach))
2581 mapTypeStrs.push_back("attach");
2582 if (mapTypeToBool(mapFlags, ClauseMapFlags::attach_always))
2583 mapTypeStrs.push_back("attach_always");
2584 if (mapTypeToBool(mapFlags, ClauseMapFlags::attach_never))
2585 mapTypeStrs.push_back("attach_never");
2586 if (mapTypeToBool(mapFlags, ClauseMapFlags::attach_auto))
2587 mapTypeStrs.push_back("attach_auto");
2588 if (mapTypeToBool(mapFlags, ClauseMapFlags::ref_ptr))
2589 mapTypeStrs.push_back("ref_ptr");
2590 if (mapTypeToBool(mapFlags, ClauseMapFlags::ref_ptee))
2591 mapTypeStrs.push_back("ref_ptee");
2592 if (mapTypeToBool(mapFlags, ClauseMapFlags::is_device_ptr))
2593 mapTypeStrs.push_back("is_device_ptr");
2594 if (mapFlags == ClauseMapFlags::none)
2595 mapTypeStrs.push_back("none");
2596
2597 for (unsigned int i = 0; i < mapTypeStrs.size(); ++i) {
2598 p << mapTypeStrs[i];
2599 if (i + 1 < mapTypeStrs.size()) {
2600 p << ", ";
2601 }
2602 }
2603}
2604
2605static ParseResult parseMembersIndex(OpAsmParser &parser,
2606 ArrayAttr &membersIdx) {
2607 SmallVector<Attribute> values, memberIdxs;
2608
2609 auto parseIndices = [&]() -> ParseResult {
2610 int64_t value;
2611 if (parser.parseInteger(value))
2612 return failure();
2613 values.push_back(IntegerAttr::get(parser.getBuilder().getIntegerType(64),
2614 APInt(64, value, /*isSigned=*/false)));
2615 return success();
2616 };
2617
2618 do {
2619 if (failed(parser.parseLSquare()))
2620 return failure();
2621
2622 if (parser.parseCommaSeparatedList(parseIndices))
2623 return failure();
2624
2625 if (failed(parser.parseRSquare()))
2626 return failure();
2627
2628 memberIdxs.push_back(ArrayAttr::get(parser.getContext(), values));
2629 values.clear();
2630 } while (succeeded(parser.parseOptionalComma()));
2631
2632 if (!memberIdxs.empty())
2633 membersIdx = ArrayAttr::get(parser.getContext(), memberIdxs);
2634
2635 return success();
2636}
2637
2638static void printMembersIndex(OpAsmPrinter &p, MapInfoOp op,
2639 ArrayAttr membersIdx) {
2640 if (!membersIdx)
2641 return;
2642
2643 llvm::interleaveComma(membersIdx, p, [&p](Attribute v) {
2644 p << "[";
2645 auto memberIdx = cast<ArrayAttr>(v);
2646 llvm::interleaveComma(memberIdx.getValue(), p, [&p](Attribute v2) {
2647 p << cast<IntegerAttr>(v2).getInt();
2648 });
2649 p << "]";
2650 });
2651}
2652
2654 VariableCaptureKindAttr mapCaptureType) {
2655 std::string typeCapStr;
2656 llvm::raw_string_ostream typeCap(typeCapStr);
2657 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::ByRef)
2658 typeCap << "ByRef";
2659 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::ByCopy)
2660 typeCap << "ByCopy";
2661 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::VLAType)
2662 typeCap << "VLAType";
2663 if (mapCaptureType.getValue() == mlir::omp::VariableCaptureKind::This)
2664 typeCap << "This";
2665 p << typeCapStr;
2666}
2667
2668static ParseResult parseCaptureType(OpAsmParser &parser,
2669 VariableCaptureKindAttr &mapCaptureType) {
2670 StringRef mapCaptureKey;
2671 if (parser.parseKeyword(&mapCaptureKey))
2672 return failure();
2673
2674 if (mapCaptureKey == "This")
2675 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2676 parser.getContext(), mlir::omp::VariableCaptureKind::This);
2677 if (mapCaptureKey == "ByRef")
2678 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2679 parser.getContext(), mlir::omp::VariableCaptureKind::ByRef);
2680 if (mapCaptureKey == "ByCopy")
2681 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2682 parser.getContext(), mlir::omp::VariableCaptureKind::ByCopy);
2683 if (mapCaptureKey == "VLAType")
2684 mapCaptureType = mlir::omp::VariableCaptureKindAttr::get(
2685 parser.getContext(), mlir::omp::VariableCaptureKind::VLAType);
2686
2687 return success();
2688}
2689
2690static LogicalResult verifyMapInfoForMapClause(
2691 Operation *op, mlir::omp::MapInfoOp mapInfoOp,
2694 &updateFromVars) {
2695 mlir::omp::ClauseMapFlags mapTypeBits = mapInfoOp.getMapType();
2696
2697 bool to = mapTypeToBool(mapTypeBits, ClauseMapFlags::to);
2698 bool from = mapTypeToBool(mapTypeBits, ClauseMapFlags::from);
2699 bool del = mapTypeToBool(mapTypeBits, ClauseMapFlags::del);
2700
2701 bool always = mapTypeToBool(mapTypeBits, ClauseMapFlags::always);
2702 bool close = mapTypeToBool(mapTypeBits, ClauseMapFlags::close);
2703 bool implicit = mapTypeToBool(mapTypeBits, ClauseMapFlags::implicit);
2704 bool attach = mapTypeToBool(mapTypeBits, ClauseMapFlags::attach);
2705
2706 if ((isa<TargetDataOp>(op) || isa<TargetOp>(op)) && del)
2707 return emitError(op->getLoc(),
2708 "to, from, tofrom and alloc map types are permitted");
2709
2710 if (isa<TargetEnterDataOp>(op) && (from || del))
2711 return emitError(op->getLoc(), "to and alloc map types are permitted");
2712
2713 if (isa<TargetExitDataOp>(op) && to)
2714 return emitError(op->getLoc(),
2715 "from, release and delete map types are permitted");
2716
2717 if (isa<TargetUpdateOp>(op)) {
2718 if (del) {
2719 return emitError(op->getLoc(),
2720 "at least one of to or from map types must be "
2721 "specified, other map types are not permitted");
2722 }
2723
2724 if (!to && !from && !attach) {
2725 return emitError(op->getLoc(),
2726 "at least one of to or from or attach map types must be "
2727 "specified, other map types are not permitted");
2728 }
2729
2730 auto updateVar = mapInfoOp.getVarPtr();
2731
2732 if ((to && from) || (to && updateFromVars.contains(updateVar)) ||
2733 (from && updateToVars.contains(updateVar))) {
2734 return emitError(
2735 op->getLoc(),
2736 "either to or from map types can be specified, not both");
2737 }
2738
2739 if (always || close || implicit) {
2740 return emitError(
2741 op->getLoc(),
2742 "present, mapper and iterator map type modifiers are permitted");
2743 }
2744
2745 // It's possible we have an attach map, in which case if there is no to
2746 // or from tied to it, we skip insertion.
2747 if (to || from) {
2748 to ? updateToVars.insert(updateVar) : updateFromVars.insert(updateVar);
2749 }
2750 }
2751
2752 if ((mapInfoOp.getVarPtrPtr() && !mapInfoOp.getVarPtrPtrType()) ||
2753 (!mapInfoOp.getVarPtrPtr() && mapInfoOp.getVarPtrPtrType())) {
2754 return emitError(op->getLoc(),
2755 "if varPtrPtr or varPtrPtrType is specified, then both "
2756 "must be present");
2757 }
2758
2759 return success();
2760}
2761
2762static LogicalResult verifyMapClause(Operation *op, OperandRange mapVars,
2763 OperandRange mapIterated) {
2766
2767 for (auto mapOp : mapVars) {
2768 if (!mapOp.getDefiningOp())
2769 return emitError(op->getLoc(), "missing map operation");
2770
2771 if (auto mapInfoOp = mapOp.getDefiningOp<mlir::omp::MapInfoOp>()) {
2772 if (failed(verifyMapInfoForMapClause(op, mapInfoOp, updateToVars,
2773 updateFromVars)))
2774 return failure();
2775 } else if (!isa<DeclareMapperInfoOp>(op)) {
2776 return emitError(op->getLoc(),
2777 "map argument is not a map entry operation");
2778 }
2779 }
2780
2781 // Verify iterated map entries.
2782 for (auto iterVal : mapIterated) {
2783 auto iterOp = iterVal.getDefiningOp<mlir::omp::IteratorOp>();
2784 if (!iterOp)
2785 return op->emitOpError() << "'map_iterated' arguments must be defined by "
2786 "'omp.iterator' ops";
2787
2788 // Check that the iterator body yields a value defined by omp.map.info.
2789 mlir::omp::YieldOp yieldOp = iterOp.getYieldOp();
2790 auto yieldedMapInfo =
2791 yieldOp && yieldOp.getNumOperands() == 1
2792 ? yieldOp.getResults()[0].getDefiningOp<mlir::omp::MapInfoOp>()
2793 : nullptr;
2794 if (!yieldedMapInfo)
2795 return op->emitOpError() << "'map_iterated' iterator body must yield "
2796 "a value defined by 'omp.map.info'";
2797
2798 if (failed(verifyMapInfoForMapClause(op, yieldedMapInfo, updateToVars,
2799 updateFromVars)))
2800 return failure();
2801 }
2802
2803 return success();
2804}
2805
2806template <typename OpType>
2807static LogicalResult verifyPrivateVarList(OpType &op);
2808
2809static LogicalResult verifyPrivateVarsMapping(TargetOp targetOp) {
2810 std::optional<DenseI64ArrayAttr> privateMapIndices =
2811 targetOp.getPrivateMapsAttr();
2812
2813 // None of the private operands are mapped.
2814 if (!privateMapIndices.has_value() || !privateMapIndices.value())
2815 return success();
2816
2817 OperandRange privateVars = targetOp.getPrivateVars();
2818
2819 if (privateMapIndices.value().size() !=
2820 static_cast<int64_t>(privateVars.size()))
2821 return emitError(targetOp.getLoc(), "sizes of `private` operand range and "
2822 "`private_maps` attribute mismatch");
2823
2824 return success();
2825}
2826
2827//===----------------------------------------------------------------------===//
2828// MapInfoOp
2829//===----------------------------------------------------------------------===//
2830
2831static LogicalResult verifyMapInfoDefinedArgs(Operation *op,
2832 StringRef clauseName,
2833 OperandRange vars) {
2834 for (Value var : vars)
2835 if (!llvm::isa_and_present<MapInfoOp>(var.getDefiningOp()))
2836 return op->emitOpError()
2837 << "'" << clauseName
2838 << "' arguments must be defined by 'omp.map.info' ops";
2839 return success();
2840}
2841
2842LogicalResult MapInfoOp::verify() {
2843 if (getMapperId() &&
2845 *this, getMapperIdAttr())) {
2846 return emitError("invalid mapper id");
2847 }
2848
2849 if (failed(verifyMapInfoDefinedArgs(*this, "members", getMembers())))
2850 return failure();
2851
2852 return success();
2853}
2854
2855//===----------------------------------------------------------------------===//
2856// TargetDataOp
2857//===----------------------------------------------------------------------===//
2858
2859void TargetDataOp::build(OpBuilder &builder, OperationState &state,
2860 const TargetDataOperands &clauses) {
2861 TargetDataOp::build(builder, state, clauses.device, clauses.ifExpr,
2862 clauses.mapVars, clauses.mapIterated,
2863 clauses.useDeviceAddrVars, clauses.useDevicePtrVars);
2864}
2865
2866LogicalResult TargetDataOp::verify() {
2867 if (getMapVars().empty() && getMapIterated().empty() &&
2868 getUseDevicePtrVars().empty() && getUseDeviceAddrVars().empty()) {
2869 return ::emitError(this->getLoc(),
2870 "At least one of map, use_device_ptr_vars, or "
2871 "use_device_addr_vars operand must be present");
2872 }
2873
2874 if (failed(verifyMapInfoDefinedArgs(*this, "use_device_ptr",
2875 getUseDevicePtrVars())))
2876 return failure();
2877
2878 if (failed(verifyMapInfoDefinedArgs(*this, "use_device_addr",
2879 getUseDeviceAddrVars())))
2880 return failure();
2881
2882 return verifyMapClause(*this, getMapVars(), getMapIterated());
2883}
2884
2885void TargetDataOp::getSuccessorRegions(
2887 if (!point.isParent()) {
2888 regions.push_back(RegionSuccessor(getOperation()));
2889 return;
2890 }
2891 regions.push_back(RegionSuccessor(&getRegion()));
2892}
2893
2894//===----------------------------------------------------------------------===//
2895// TargetEnterDataOp
2896//===----------------------------------------------------------------------===//
2897
2898void TargetEnterDataOp::build(
2899 OpBuilder &builder, OperationState &state,
2900 const TargetEnterExitUpdateDataOperands &clauses) {
2901 MLIRContext *ctx = builder.getContext();
2902 TargetEnterDataOp::build(
2903 builder, state, makeArrayAttr(ctx, clauses.dependKinds),
2904 clauses.dependVars, makeArrayAttr(ctx, clauses.dependIteratedKinds),
2905 clauses.dependIterated, clauses.device, clauses.ifExpr, clauses.mapVars,
2906 clauses.mapIterated, clauses.nowait);
2907}
2908
2909LogicalResult TargetEnterDataOp::verify() {
2910 LogicalResult verifyDependVars =
2911 verifyDependVarList(*this, getDependKinds(), getDependVars(),
2912 getDependIteratedKinds(), getDependIterated());
2913 return failed(verifyDependVars)
2914 ? verifyDependVars
2915 : verifyMapClause(*this, getMapVars(), getMapIterated());
2916}
2917
2918//===----------------------------------------------------------------------===//
2919// TargetExitDataOp
2920//===----------------------------------------------------------------------===//
2921
2922void TargetExitDataOp::build(OpBuilder &builder, OperationState &state,
2923 const TargetEnterExitUpdateDataOperands &clauses) {
2924 MLIRContext *ctx = builder.getContext();
2925 TargetExitDataOp::build(
2926 builder, state, makeArrayAttr(ctx, clauses.dependKinds),
2927 clauses.dependVars, makeArrayAttr(ctx, clauses.dependIteratedKinds),
2928 clauses.dependIterated, clauses.device, clauses.ifExpr, clauses.mapVars,
2929 clauses.mapIterated, clauses.nowait);
2930}
2931
2932LogicalResult TargetExitDataOp::verify() {
2933 LogicalResult verifyDependVars =
2934 verifyDependVarList(*this, getDependKinds(), getDependVars(),
2935 getDependIteratedKinds(), getDependIterated());
2936 return failed(verifyDependVars)
2937 ? verifyDependVars
2938 : verifyMapClause(*this, getMapVars(), getMapIterated());
2939}
2940
2941//===----------------------------------------------------------------------===//
2942// TargetUpdateOp
2943//===----------------------------------------------------------------------===//
2944
2945void TargetUpdateOp::build(OpBuilder &builder, OperationState &state,
2946 const TargetEnterExitUpdateDataOperands &clauses) {
2947 MLIRContext *ctx = builder.getContext();
2948 TargetUpdateOp::build(builder, state, makeArrayAttr(ctx, clauses.dependKinds),
2949 clauses.dependVars,
2950 makeArrayAttr(ctx, clauses.dependIteratedKinds),
2951 clauses.dependIterated, clauses.device, clauses.ifExpr,
2952 clauses.mapVars, clauses.mapIterated, clauses.nowait);
2953}
2954
2955LogicalResult TargetUpdateOp::verify() {
2956 LogicalResult verifyDependVars =
2957 verifyDependVarList(*this, getDependKinds(), getDependVars(),
2958 getDependIteratedKinds(), getDependIterated());
2959 return failed(verifyDependVars)
2960 ? verifyDependVars
2961 : verifyMapClause(*this, getMapVars(), getMapIterated());
2962}
2963
2964//===----------------------------------------------------------------------===//
2965// TargetOp
2966//===----------------------------------------------------------------------===//
2967
2968void TargetOp::build(OpBuilder &builder, OperationState &state,
2969 const TargetExtOperands &clauses) {
2970 MLIRContext *ctx = builder.getContext();
2971 TargetOp::build(
2972 builder, state, clauses.allocateVars, clauses.allocatorVars,
2973 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
2974 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices),
2975 makeArrayAttr(ctx, clauses.dependKinds), clauses.dependVars,
2976 makeArrayAttr(ctx, clauses.dependIteratedKinds), clauses.dependIterated,
2977 clauses.device, clauses.dynGroupprivateAccessGroup,
2978 clauses.dynGroupprivateFallback, clauses.dynGroupprivateSize,
2979 clauses.hasDeviceAddrVars, clauses.hostEvalVars, clauses.ifExpr,
2980 clauses.inReductionVars,
2981 makeDenseBoolArrayAttr(ctx, clauses.inReductionByref),
2982 makeArrayAttr(ctx, clauses.inReductionSyms), clauses.isDevicePtrVars,
2983 clauses.mapVars, clauses.mapIterated, clauses.nowait, clauses.privateVars,
2984 makeArrayAttr(ctx, clauses.privateSyms), clauses.privateNeedsBarrier,
2985 clauses.threadLimitVars, /*private_maps=*/nullptr, clauses.kernelType);
2986}
2987
2988bool TargetOp::hasHostEvalTripCount() {
2989 TargetExecMode mode = getKernelType();
2990 if (mode == TargetExecMode::spmd || mode == TargetExecMode::spmd_no_loop)
2991 return true;
2992
2993 if (mode == TargetExecMode::bare)
2994 return false;
2995
2996 // If it represents a `target teams distribute` construct, also evaluate the
2997 // `distribute` trip count on the host.
2998 Operation *capturedOp =
2999 cast<ComposableOpInterface>(getOperation()).findCapturedOp();
3000 if (auto loopNestOp = dyn_cast_if_present<LoopNestOp>(capturedOp)) {
3002 loopNestOp.gatherWrappers(loopWrappers);
3003
3004 LoopWrapperInterface *innermostWrapper = loopWrappers.begin();
3005 if (isa<SimdOp>(innermostWrapper))
3006 innermostWrapper = std::next(innermostWrapper);
3007
3008 auto numWrappers = std::distance(innermostWrapper, loopWrappers.end());
3009 if (numWrappers != 1)
3010 return false;
3011
3012 if (!isa<DistributeOp>(innermostWrapper))
3013 return false;
3014
3015 Operation *parentOp = innermostWrapper->getOperation()->getParentOp();
3016 if (isa_and_present<TeamsOp>(parentOp) &&
3017 parentOp->getParentOp() == getOperation())
3018 return true;
3019 }
3020
3021 return false;
3022}
3023
3024/// An `omp.target` `in_reduction` operand is captured by a `map_entries` entry
3025/// when the entry's `MapInfoOp` var_ptr is the same SSA value, or another
3026/// result of the same defining op. At this stage, exact identity can only be
3027/// required for block arguments, which have no defining op. Flang emits
3028/// `hlfir.declare` #0 for the `in_reduction` operand and #1 for the map
3029/// `var_ptr`; these collapse to the same value after lowering, but that cannot
3030/// be enforced here.
3031static bool targetInReductionCapturedBy(Value inReductionVar, Value mapVarPtr) {
3032 if (mapVarPtr == inReductionVar)
3033 return true;
3034 Operation *def = inReductionVar.getDefiningOp();
3035 return def && mapVarPtr.getDefiningOp() == def;
3036}
3037
3038LogicalResult TargetOp::verify() {
3040 getOperation(), getAllocateVars(), getAllocatorVars(),
3041 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3042 getPrivateVars(), getPrivateSymsAttr())))
3043 return failure();
3044
3045 if (getKernelType() == TargetExecMode::bare && !isCombined())
3046 return emitOpError() << "bare kernel requires 'omp.combined'";
3047
3048 if (failed(verifyDependVarList(*this, getDependKinds(), getDependVars(),
3049 getDependIteratedKinds(),
3050 getDependIterated())))
3051 return failure();
3052
3053 if (failed(verifyMapInfoDefinedArgs(*this, "has_device_addr",
3054 getHasDeviceAddrVars())))
3055 return failure();
3056
3057 if (failed(verifyMapClause(*this, getMapVars(), getMapIterated())))
3058 return failure();
3059
3061 *this, getDynGroupprivateAccessGroupAttr(),
3062 getDynGroupprivateFallbackAttr(), getDynGroupprivateSize())))
3063 return failure();
3064
3065 if (failed(verifyPrivateVarList(*this)))
3066 return failure();
3067
3068 if (failed(verifyReductionVarList(*this, getInReductionSyms(),
3069 getInReductionVars(),
3070 getInReductionByref())))
3071 return failure();
3072
3073 // An `in_reduction` operand on `omp.target` has no dedicated entry block
3074 // argument; inside the region it is accessed through the block argument of a
3075 // matching `map_entries` entry, and the host rewrites that map argument to
3076 // the reduction-private storage. Require every `in_reduction` operand to be
3077 // captured by at least one `map_entries` entry.
3078 for (Value inReductionVar : getInReductionVars()) {
3079 bool captured = false;
3080 for (Value mapVar : getMapVars()) {
3081 auto mapInfo = mapVar.getDefiningOp<MapInfoOp>();
3082 if (targetInReductionCapturedBy(inReductionVar, mapInfo.getVarPtr())) {
3083 captured = true;
3084 break;
3085 }
3086 }
3087 if (!captured)
3088 return emitOpError() << "in_reduction variable must be captured by a "
3089 "matching map_entries entry";
3090 }
3091
3092 return verifyPrivateVarsMapping(*this);
3093}
3094
3095LogicalResult TargetOp::verifyRegions() {
3096 auto teamsOps = getOps<TeamsOp>();
3097 auto numNestedTeams = std::distance(teamsOps.begin(), teamsOps.end());
3098 if (numNestedTeams > 1)
3099 return emitError("target containing multiple 'omp.teams' nested ops");
3100
3101 if (numNestedTeams == 0) {
3102 switch (getKernelType()) {
3103 case TargetExecMode::bare:
3104 return emitOpError()
3105 << "bare kernel must contain a nested 'omp.teams' operation";
3106 case TargetExecMode::spmd_no_loop:
3107 return emitOpError() << "spmd_no_loop kernel must contain a nested "
3108 "'omp.teams' operation";
3109 default:
3110 break;
3111 }
3112 }
3113
3114 Operation *capturedOp =
3115 cast<ComposableOpInterface>(getOperation()).findCapturedOp();
3116 if ((getKernelType() == TargetExecMode::spmd ||
3117 getKernelType() == TargetExecMode::spmd_no_loop) &&
3118 !isa_and_present<LoopNestOp>(capturedOp))
3119 return emitOpError()
3120 << "SPMD kernel must capture an 'omp.loop_nest' operation";
3121
3122 bool isTargetDevice = false;
3123 if (auto offloadMod = (*this)->getParentOfType<OffloadModuleInterface>())
3124 if (offloadMod.getIsTargetDevice())
3125 isTargetDevice = true;
3126
3127 // Check that host_eval values are only used in legal ways.
3128 llvm::ArrayRef<BlockArgument> hostEvalBlockArgs =
3129 cast<BlockArgOpenMPOpInterface>(getOperation()).getHostEvalBlockArgs();
3130
3131 bool hostEvalTripCount = hasHostEvalTripCount();
3132 for (Value hostEvalArg : hostEvalBlockArgs) {
3133 for (Operation *user : hostEvalArg.getUsers()) {
3134 if (auto teamsOp = dyn_cast<TeamsOp>(user)) {
3135 // Check if used in num_teams_lower or any of num_teams_upper_vars
3136 if (hostEvalArg == teamsOp.getNumTeamsLower() ||
3137 llvm::is_contained(teamsOp.getNumTeamsUpperVars(), hostEvalArg) ||
3138 llvm::is_contained(teamsOp.getThreadLimitVars(), hostEvalArg))
3139 continue;
3140
3141 return emitOpError() << "host_eval argument only legal as 'num_teams' "
3142 "and 'thread_limit' in 'omp.teams'";
3143 }
3144 if (auto parallelOp = dyn_cast<ParallelOp>(user)) {
3145 if (llvm::is_contained(parallelOp.getNumThreadsVars(), hostEvalArg))
3146 continue;
3147
3148 return emitOpError()
3149 << "host_eval argument only legal as 'num_threads' in "
3150 "'omp.parallel'";
3151 }
3152 if (auto loopNestOp = dyn_cast<LoopNestOp>(user)) {
3153 if (hostEvalTripCount &&
3154 (llvm::is_contained(loopNestOp.getLoopLowerBounds(), hostEvalArg) ||
3155 llvm::is_contained(loopNestOp.getLoopUpperBounds(), hostEvalArg) ||
3156 llvm::is_contained(loopNestOp.getLoopSteps(), hostEvalArg)))
3157 continue;
3158
3159 return emitOpError() << "host_eval argument only legal as loop bounds "
3160 "and steps in 'omp.loop_nest' when trip count "
3161 "must be evaluated in the host";
3162 }
3163
3164 return emitOpError() << "host_eval argument illegal use in '"
3165 << user->getName() << "' operation";
3166 }
3167 }
3168
3169 if (hostEvalTripCount && !isTargetDevice) {
3170 auto loopOp = cast<LoopNestOp>(capturedOp);
3171 for (auto arg : llvm::concat<Value>(loopOp.getLoopLowerBounds(),
3172 loopOp.getLoopUpperBounds(),
3173 loopOp.getLoopSteps())) {
3174 if (!llvm::is_contained(hostEvalBlockArgs, arg))
3175 return emitOpError() << "nested 'omp.loop_nest' bounds expected to "
3176 "be host-evaluated";
3177 }
3178 }
3179
3180 return success();
3181}
3182
3183void TargetOp::getSuccessorRegions(RegionBranchPoint point,
3185 if (!point.isParent()) {
3186 regions.push_back(RegionSuccessor(getOperation()));
3187 return;
3188 }
3189 regions.push_back(RegionSuccessor(&getRegion()));
3190}
3191
3192OperandRange TargetOp::getEntrySuccessorOperands(RegionSuccessor successor) {
3193 assert(successor.getSuccessor() == &getRegion());
3194 return getHostEvalVars();
3195}
3196
3197mlir::ValueRange TargetOp::getSuccessorInputs(RegionSuccessor successor) {
3198 if (successor.isOperation())
3199 return {};
3200 assert(successor == &getRegion());
3201 return mlir::cast<BlockArgOpenMPOpInterface>(getOperation())
3202 .getHostEvalBlockArgs();
3203}
3204
3205//===----------------------------------------------------------------------===//
3206// ParallelOp
3207//===----------------------------------------------------------------------===//
3208
3209void ParallelOp::build(OpBuilder &builder, OperationState &state,
3210 ArrayRef<NamedAttribute> attributes) {
3211 ParallelOp::build(builder, state, /*allocate_vars=*/ValueRange(),
3212 /*allocator_vars=*/ValueRange(),
3213 /*allocate_alignments=*/nullptr,
3214 /*allocate_private_indices=*/nullptr, /*if_expr=*/nullptr,
3215 /*num_threads_vars=*/ValueRange(),
3216 /*private_vars=*/ValueRange(),
3217 /*private_syms=*/nullptr, /*private_needs_barrier=*/false,
3218 /*proc_bind_kind=*/nullptr,
3219 /*reduction_mods =*/nullptr,
3220 /*reduction_vars=*/ValueRange(),
3221 /*reduction_byref=*/nullptr, /*reduction_syms=*/nullptr);
3222 state.addAttributes(attributes);
3223}
3224
3225void ParallelOp::build(OpBuilder &builder, OperationState &state,
3226 const ParallelOperands &clauses) {
3227 MLIRContext *ctx = builder.getContext();
3228 ParallelOp::build(builder, state, clauses.allocateVars, clauses.allocatorVars,
3229 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
3230 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices),
3231 clauses.ifExpr, clauses.numThreadsVars, clauses.privateVars,
3232 makeArrayAttr(ctx, clauses.privateSyms),
3233 clauses.privateNeedsBarrier, clauses.procBindKind,
3234 makeArrayAttr(ctx, clauses.reductionMods),
3235 clauses.reductionVars,
3236 makeDenseBoolArrayAttr(ctx, clauses.reductionByref),
3237 makeArrayAttr(ctx, clauses.reductionSyms));
3238}
3239
3240template <typename OpType>
3241static LogicalResult verifyPrivateVarList(OpType &op) {
3242 auto privateVars = op.getPrivateVars();
3243 auto privateSyms = op.getPrivateSymsAttr();
3244
3245 if (privateVars.empty() && (privateSyms == nullptr || privateSyms.empty()))
3246 return success();
3247
3248 auto numPrivateVars = privateVars.size();
3249 auto numPrivateSyms = (privateSyms == nullptr) ? 0 : privateSyms.size();
3250
3251 if (numPrivateVars != numPrivateSyms)
3252 return op.emitError() << "inconsistent number of private variables and "
3253 "privatizer op symbols, private vars: "
3254 << numPrivateVars
3255 << " vs. privatizer op symbols: " << numPrivateSyms;
3256
3257 for (auto privateVarInfo : llvm::zip_equal(privateVars, privateSyms)) {
3258 Type varType = std::get<0>(privateVarInfo).getType();
3259 SymbolRefAttr privateSym = cast<SymbolRefAttr>(std::get<1>(privateVarInfo));
3260 PrivateClauseOp privatizerOp =
3262
3263 if (privatizerOp == nullptr)
3264 return op.emitError() << "failed to lookup privatizer op with symbol: '"
3265 << privateSym << "'";
3266
3267 Type privatizerType = privatizerOp.getArgType();
3268
3269 if (privatizerType && (varType != privatizerType))
3270 return op.emitError()
3271 << "type mismatch between a "
3272 << stringifyDataSharingClauseType(
3273 privatizerOp.getDataSharingType())
3274 << " variable and its privatizer op, var type: " << varType
3275 << " vs. privatizer op type: " << privatizerType;
3276
3277 if (privatizerOp.getDataSharingType() == DataSharingClauseType::Linear)
3278 return op.emitError() << "`linear` privatizer '" << privateSym
3279 << "' can only be used in a `linear` clause";
3280 }
3281
3282 return success();
3283}
3284
3285/// Verifies that each linear variable has a `linear` privatizer.
3286template <typename OpType>
3287static LogicalResult verifyLinearSyms(OpType op) {
3288 OperandRange linearVars = op.getLinearVars();
3289 std::optional<ArrayAttr> linearSyms = op.getLinearSyms();
3290 if (linearVars.empty() && (!linearSyms || linearSyms->empty()))
3291 return success();
3292
3293 if (!linearSyms || linearSyms->size() != linearVars.size())
3294 return op.emitOpError()
3295 << "expected as many linear privatizers as linear variables";
3296
3297 for (auto [var, sym] : llvm::zip_equal(linearVars, *linearSyms)) {
3298 auto symRef = cast<SymbolRefAttr>(sym);
3299 auto privatizer =
3301 if (!privatizer)
3302 return op.emitOpError() << "failed to lookup privatizer op with symbol: '"
3303 << symRef << "'";
3304 if (privatizer.getDataSharingType() != DataSharingClauseType::Linear)
3305 return op.emitOpError() << "privatizer '" << symRef
3306 << "' of a linear variable must be `linear`";
3307 Type argType = privatizer.getArgType();
3308 if (argType && argType != var.getType())
3309 return op.emitOpError()
3310 << "type mismatch between a linear variable and its privatizer "
3311 "op, var type: "
3312 << var.getType() << " vs. privatizer op type: " << argType;
3313 }
3314 return success();
3315}
3316
3317LogicalResult ParallelOp::verify() {
3318 if (failed(verifyPrivateVarList(*this)))
3319 return failure();
3321 getOperation(), getAllocateVars(), getAllocatorVars(),
3322 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3323 getPrivateVars(), getPrivateSymsAttr(),
3324 /*requirePrivateIndices=*/true)))
3325 return failure();
3326
3327 return verifyReductionVarList(*this, getReductionSyms(), getReductionVars(),
3328 getReductionByref(), getReductionModsAttr());
3329}
3330
3331LogicalResult ParallelOp::verifyRegions() {
3332 auto distChildOps = getOps<DistributeOp>();
3333 int numDistChildOps = std::distance(distChildOps.begin(), distChildOps.end());
3334 if (numDistChildOps > 1)
3335 return emitError()
3336 << "multiple 'omp.distribute' nested inside of 'omp.parallel'";
3337
3338 if (numDistChildOps == 1) {
3339 if (!isComposite())
3340 return emitError()
3341 << "'omp.composite' attribute missing from composite operation";
3342
3343 auto *ompDialect = getContext()->getLoadedDialect<OpenMPDialect>();
3344 Operation &distributeOp = **distChildOps.begin();
3345 for (Operation &childOp : getOps()) {
3346 if (&childOp == &distributeOp || ompDialect != childOp.getDialect())
3347 continue;
3348
3349 if (!childOp.hasTrait<OpTrait::IsTerminator>())
3350 return emitError() << "unexpected OpenMP operation inside of composite "
3351 "'omp.parallel': "
3352 << childOp.getName();
3353 }
3354 } else if (isComposite()) {
3355 return emitError()
3356 << "'omp.composite' attribute present in non-composite operation";
3357 }
3358 return success();
3359}
3360
3361//===----------------------------------------------------------------------===//
3362// TeamsOp
3363//===----------------------------------------------------------------------===//
3364
3366 while ((op = op->getParentOp()))
3367 if (isa<OpenMPDialect>(op->getDialect()))
3368 return false;
3369 return true;
3370}
3371
3372void TeamsOp::build(OpBuilder &builder, OperationState &state,
3373 const TeamsOperands &clauses) {
3374 MLIRContext *ctx = builder.getContext();
3375 // TODO Store clauses in op: privateVars, privateSyms, privateNeedsBarrier
3376 TeamsOp::build(
3377 builder, state, clauses.allocateVars, clauses.allocatorVars,
3378 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
3379 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices),
3380 clauses.dynGroupprivateAccessGroup, clauses.dynGroupprivateFallback,
3381 clauses.dynGroupprivateSize, clauses.ifExpr, clauses.numTeamsLower,
3382 clauses.numTeamsUpperVars, /*private_vars=*/{}, /*private_syms=*/nullptr,
3383 /*private_needs_barrier=*/false,
3384 makeArrayAttr(ctx, clauses.reductionMods), clauses.reductionVars,
3385 makeDenseBoolArrayAttr(ctx, clauses.reductionByref),
3386 makeArrayAttr(ctx, clauses.reductionSyms), clauses.threadLimitVars);
3387}
3388
3389// Verify num_teams clause
3390static LogicalResult verifyNumTeamsClause(Operation *op, Value numTeamsLower,
3391 OperandRange numTeamsUpperVars) {
3392 // If lower is specified, upper must have exactly one value
3393 if (numTeamsLower) {
3394 if (numTeamsUpperVars.size() != 1)
3395 return op->emitError(
3396 "expected exactly one num_teams upper bound when lower bound is "
3397 "specified");
3398 if (numTeamsLower.getType() != numTeamsUpperVars[0].getType())
3399 return op->emitError(
3400 "expected num_teams upper bound and lower bound to be "
3401 "the same type");
3402 }
3403
3404 return success();
3405}
3406
3407LogicalResult TeamsOp::verify() {
3408 // Check parent region
3409 // TODO If nested inside of a target region, also check that it does not
3410 // contain any statements, declarations or directives other than this
3411 // omp.teams construct. The issue is how to support the initialization of
3412 // this operation's own arguments (allow SSA values across omp.target?).
3413 Operation *op = getOperation();
3414 auto parentTarget = llvm::dyn_cast_if_present<TargetOp>(op->getParentOp());
3415 if (!parentTarget && !opInGlobalImplicitParallelRegion(op))
3416 return emitError("expected to be nested inside of omp.target or not nested "
3417 "in any OpenMP dialect operations");
3418
3419 // Check for num_teams clause restrictions
3420 if (failed(verifyNumTeamsClause(op, this->getNumTeamsLower(),
3421 this->getNumTeamsUpperVars())))
3422 return failure();
3423
3424 if (parentTarget &&
3425 parentTarget.getKernelType() == TargetExecMode::spmd_no_loop &&
3426 (getNumTeamsLower() || !getNumTeamsUpperVars().empty()))
3427 return emitOpError() << "'num_teams' not allowed in SPMD-no-loop kernels";
3428
3430 getOperation(), getAllocateVars(), getAllocatorVars(),
3431 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3432 getPrivateVars(), getPrivateSymsAttr())))
3433 return failure();
3434
3436 op, getDynGroupprivateAccessGroupAttr(),
3437 getDynGroupprivateFallbackAttr(), getDynGroupprivateSize())))
3438 return failure();
3439
3440 if (failed(verifyPrivateVarList(*this)))
3441 return failure();
3442
3443 return verifyReductionVarList(*this, getReductionSyms(), getReductionVars(),
3444 getReductionByref(), getReductionModsAttr());
3445}
3446
3447//===----------------------------------------------------------------------===//
3448// SectionOp
3449//===----------------------------------------------------------------------===//
3450
3451OperandRange SectionOp::getPrivateVars() {
3452 return getParentOp().getPrivateVars();
3453}
3454
3455OperandRange SectionOp::getReductionVars() {
3456 return getParentOp().getReductionVars();
3457}
3458
3459//===----------------------------------------------------------------------===//
3460// SectionsOp
3461//===----------------------------------------------------------------------===//
3462
3463void SectionsOp::build(OpBuilder &builder, OperationState &state,
3464 const SectionsOperands &clauses) {
3465 MLIRContext *ctx = builder.getContext();
3466 // TODO Store clauses in op: privateVars, privateSyms, privateNeedsBarrier
3467 SectionsOp::build(builder, state, clauses.allocateVars, clauses.allocatorVars,
3468 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
3469 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices),
3470 clauses.nowait, /*private_vars=*/{},
3471 /*private_syms=*/nullptr, /*private_needs_barrier=*/nullptr,
3472 /*private_assume_bounded_recipe_effects=*/nullptr,
3473 makeArrayAttr(ctx, clauses.reductionMods),
3474 clauses.reductionVars,
3475 makeDenseBoolArrayAttr(ctx, clauses.reductionByref),
3476 makeArrayAttr(ctx, clauses.reductionSyms),
3477 /*reduction_assume_bounded_recipe_effects=*/nullptr);
3478}
3479
3480LogicalResult SectionsOp::verify() {
3481 if (isCombined())
3482 return emitOpError() << "cannot be a non-innermost combined construct leaf";
3483
3485 getOperation(), getAllocateVars(), getAllocatorVars(),
3486 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3487 getPrivateVars(), getPrivateSymsAttr())))
3488 return failure();
3489
3490 return verifyReductionVarList(*this, getReductionSyms(), getReductionVars(),
3491 getReductionByref(), getReductionModsAttr());
3492}
3493
3494LogicalResult SectionsOp::verifyRegions() {
3495 for (auto &inst : *getRegion().begin()) {
3496 if (!(isa<SectionOp>(inst) || isa<TerminatorOp>(inst))) {
3497 return emitOpError()
3498 << "expected omp.section op or terminator op inside region";
3499 }
3500 }
3501
3502 return success();
3503}
3504
3505/// Add arbitrary read, write, allocate, and free effects.
3508 effects.emplace_back(MemoryEffects::Read::get());
3509 effects.emplace_back(MemoryEffects::Write::get());
3510 effects.emplace_back(MemoryEffects::Allocate::get());
3511 effects.emplace_back(MemoryEffects::Free::get());
3512}
3513
3514/// Privatisation may read the original as a mold or firstprivate copy source.
3515/// Any lastprivate copy-back is explicit in the nested operations.
3518 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
3519
3520 OperandRange sourceVars = iface.getPrivateVars();
3521 for (OpOperand &source :
3522 MutableArrayRef(sourceVars.getBase(), sourceVars.size()))
3523 effects.emplace_back(MemoryEffects::Read::get(), &source);
3524 for (BlockArgument priv : iface.getPrivateBlockArgs()) {
3525 effects.emplace_back(MemoryEffects::Write::get(), priv);
3526 effects.emplace_back(MemoryEffects::Allocate::get(), priv);
3527 effects.emplace_back(MemoryEffects::Free::get(), priv);
3528 }
3529}
3530
3531/// Reductions initialise private accumulators and combine them into the
3532/// original variables.
3533static void
3536 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
3537
3538 auto addEffects = [&](OperandRange sourceVars,
3539 ArrayRef<BlockArgument> privateArgs) {
3540 for (OpOperand &source :
3541 MutableArrayRef(sourceVars.getBase(), sourceVars.size())) {
3542 effects.emplace_back(MemoryEffects::Read::get(), &source);
3543 effects.emplace_back(MemoryEffects::Write::get(), &source);
3544 }
3545
3546 for (BlockArgument priv : privateArgs) {
3547 effects.emplace_back(MemoryEffects::Allocate::get(), priv);
3548 effects.emplace_back(MemoryEffects::Free::get(), priv);
3549 effects.emplace_back(MemoryEffects::Read::get(), priv);
3550 effects.emplace_back(MemoryEffects::Write::get(), priv);
3551 }
3552 };
3553
3554 addEffects(iface.getReductionVars(), iface.getReductionBlockArgs());
3555 addEffects(iface.getInReductionVars(), iface.getInReductionBlockArgs());
3556}
3557
3560 &effects) {
3561 effects.emplace_back(MemoryEffects::Read::get());
3562 effects.emplace_back(MemoryEffects::Write::get());
3563}
3564
3565void SectionsOp::getEffects(
3567 &effects) {
3568 // The presence of the nowait clause eliminates the implicit barrier at the
3569 // end of a sections construct
3570 if (!getNowait()) {
3571 getBarrierEffects(effects);
3572 }
3573
3574 bool hasUnknownRecipeEffects =
3575 (!getPrivateVars().empty() && !getPrivateAssumeBoundedRecipeEffects()) ||
3576 (!getReductionVars().empty() &&
3577 !getReductionAssumeBoundedRecipeEffects());
3578
3579 if (hasUnknownRecipeEffects) {
3580 addUnknownMemoryEffects(effects);
3581 } else {
3582 getPrivatisationEffects(*this, effects);
3583 getReductionEffects(*this, effects);
3584 }
3585}
3586
3587//===----------------------------------------------------------------------===//
3588// ScopeOp
3589//===----------------------------------------------------------------------===//
3590
3591void ScopeOp::build(OpBuilder &builder, OperationState &state,
3592 const ScopeOperands &clauses) {
3593 MLIRContext *ctx = builder.getContext();
3594 ScopeOp::build(
3595 builder, state, clauses.allocateVars, clauses.allocatorVars,
3596 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
3597 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices),
3598 clauses.nowait, clauses.privateVars,
3599 makeArrayAttr(ctx, clauses.privateSyms), clauses.privateNeedsBarrier,
3600 makeArrayAttr(ctx, clauses.reductionMods), clauses.reductionVars,
3601 makeDenseBoolArrayAttr(ctx, clauses.reductionByref),
3602 makeArrayAttr(ctx, clauses.reductionSyms));
3603}
3604
3605LogicalResult ScopeOp::verify() {
3607 getOperation(), getAllocateVars(), getAllocatorVars(),
3608 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3609 getPrivateVars(), getPrivateSymsAttr(),
3610 /*requirePrivateIndices=*/true)))
3611 return failure();
3612
3613 if (failed(verifyPrivateVarList(*this)))
3614 return failure();
3615
3616 return verifyReductionVarList(*this, getReductionSyms(), getReductionVars(),
3617 getReductionByref(), getReductionModsAttr());
3618}
3619
3620//===----------------------------------------------------------------------===//
3621// SingleOp
3622//===----------------------------------------------------------------------===//
3623
3624void SingleOp::build(OpBuilder &builder, OperationState &state,
3625 const SingleOperands &clauses) {
3626 MLIRContext *ctx = builder.getContext();
3627 // TODO Store clauses in op: privateVars, privateSyms, privateNeedsBarrier
3628 SingleOp::build(
3629 builder, state, clauses.allocateVars, clauses.allocatorVars,
3630 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
3631 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices),
3632 clauses.copyprivateVars, makeArrayAttr(ctx, clauses.copyprivateSyms),
3633 /*copyprivate_assume_bounded_recipe_effects=*/nullptr, clauses.nowait,
3634 /*private_vars=*/{}, /*private_syms=*/nullptr,
3635 /*private_needs_barrier=*/nullptr,
3636 /*private_assume_bounded_recipe_effects=*/nullptr);
3637}
3638
3639LogicalResult SingleOp::verify() {
3641 getOperation(), getAllocateVars(), getAllocatorVars(),
3642 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3643 getPrivateVars(), getPrivateSymsAttr())))
3644 return failure();
3645
3646 return verifyCopyprivateVarList(*this, getCopyprivateVars(),
3647 getCopyprivateSyms());
3648}
3649
3650void SingleOp::getEffects(
3652 &effects) {
3653 // The presence of the nowait clause eliminates the implicit barrier at the
3654 // end of a single construct.
3655 if (!getNowait()) {
3656 getBarrierEffects(effects);
3657 }
3658
3659 bool hasUnknownRecipeEffects =
3660 (!getPrivateVars().empty() && !getPrivateAssumeBoundedRecipeEffects()) ||
3661 (!getCopyprivateVars().empty() &&
3662 !getCopyprivateAssumeBoundedRecipeEffects());
3663 if (hasUnknownRecipeEffects) {
3664 addUnknownMemoryEffects(effects);
3665 } else {
3666 getPrivatisationEffects(*this, effects);
3667 // The unknown executing thread supplies the value and the other threads
3668 // receive it, so each copyprivate operand may be both read and written.
3669 OperandRange copyprivateVars = getCopyprivateVars();
3670 for (OpOperand &variable :
3671 MutableArrayRef(copyprivateVars.getBase(), copyprivateVars.size())) {
3672 effects.emplace_back(MemoryEffects::Read::get(), &variable);
3673 effects.emplace_back(MemoryEffects::Write::get(), &variable);
3674 }
3675 }
3676}
3677
3678//===----------------------------------------------------------------------===//
3679// WorkshareOp
3680//===----------------------------------------------------------------------===//
3681
3682void WorkshareOp::build(OpBuilder &builder, OperationState &state,
3683 const WorkshareOperands &clauses) {
3684 WorkshareOp::build(builder, state, clauses.nowait);
3685}
3686
3687LogicalResult WorkshareOp::verify() {
3688 if (isCombined())
3689 return emitOpError() << "cannot be a non-innermost combined construct leaf";
3690
3691 return success();
3692}
3693
3694//===----------------------------------------------------------------------===//
3695// WorkshareLoopWrapperOp
3696//===----------------------------------------------------------------------===//
3697
3698LogicalResult WorkshareLoopWrapperOp::verifyRegions() {
3699 if (isa_and_nonnull<LoopWrapperInterface>((*this)->getParentOp()) ||
3700 getNestedWrapper())
3701 return emitOpError() << "expected to be a standalone loop wrapper";
3702
3703 return success();
3704}
3705
3706//===----------------------------------------------------------------------===//
3707// LoopWrapperInterface
3708//===----------------------------------------------------------------------===//
3709
3710LogicalResult LoopWrapperInterface::verifyImpl() {
3711 Operation *op = this->getOperation();
3712 if (!op->hasTrait<OpTrait::NoTerminator>() ||
3714 return emitOpError() << "loop wrapper must also have the `NoTerminator` "
3715 "and `SingleBlock` traits";
3716
3717 if (op->getNumRegions() != 1)
3718 return emitOpError() << "loop wrapper does not contain exactly one region";
3719
3720 Region &region = op->getRegion(0);
3721 if (range_size(region.getOps()) != 1)
3722 return emitOpError()
3723 << "loop wrapper does not contain exactly one nested op";
3724
3725 Operation &firstOp = *region.op_begin();
3726 if (!isa<LoopNestOp, LoopWrapperInterface>(firstOp))
3727 return emitOpError() << "nested in loop wrapper is not another loop "
3728 "wrapper or `omp.loop_nest`";
3729
3730 return success();
3731}
3732
3733//===----------------------------------------------------------------------===//
3734// ComposableOpInterface
3735//===----------------------------------------------------------------------===//
3736
3737Operation *ComposableOpInterface::findCapturedOp() {
3738 Operation *op = this->getOperation();
3739
3740 // Handle the composite case by returning the wrapped omp.loop_nest.
3741 if (auto wrapperOp = dyn_cast<LoopWrapperInterface>(op))
3742 return wrapperOp.getWrappedLoop();
3743
3744 // Do not look further if this op is not combined with any of its children.
3745 // Need to check for composite for the omp.parallel case, which is not a loop
3746 // wrapper itself.
3747 if (!isCombined() && !isComposite())
3748 return op;
3749
3750 Region &region = op->getRegion(0);
3751 for (Operation &nestedOp : region.getOps()) {
3752 if (auto wrapperOp = dyn_cast<LoopWrapperInterface>(&nestedOp))
3753 return wrapperOp.getWrappedLoop();
3754
3755 if (auto composableOp = dyn_cast<ComposableOpInterface>(&nestedOp))
3756 return composableOp.findCapturedOp();
3757 }
3758
3759 // This can only be reached if the op has an omp.combined attribute but the
3760 // corresponding nested composable op has been deleted. In that case, it's
3761 // correct to return this operation.
3762 return op;
3763}
3764
3765LogicalResult ComposableOpInterface::verifyImpl() {
3766 Operation *op = this->getOperation();
3767
3768 if (op->getNumRegions() != 1)
3769 return emitOpError() << "composable ops must have a single region";
3770
3771 if (isComposite() && !isa<LoopWrapperInterface, ParallelOp>(op))
3772 return emitOpError() << "non-loop wrapper cannot be composite";
3773
3774 // If combined, must have exactly one eligible nested op (composable or loop
3775 // wrapper).
3776 if (isCombined()) {
3777 Operation *nestedOp = nullptr;
3778 auto count = llvm::count_if(
3779 op->getRegion(0).getOps(), [&nestedOp](mlir::Operation &op) {
3780 if (isa<ComposableOpInterface, LoopWrapperInterface>(op)) {
3781 nestedOp = &op;
3782 return true;
3783 }
3784 return false;
3785 });
3786
3787 // Make an exception for ops marked as omp.combined with no eligible nested
3788 // ops: this situation should be disallowed, but it can be reached if an
3789 // MLIR optimization pass find that the child operation has no side effects
3790 // (many ComposableOpInterface ops have RecursiveMemoryEffects), so it gets
3791 // deleted without updating the parent's attribute.
3792 //
3793 // Since there's a well defined way of handling that situation (treat it as
3794 // non-combined), we relax the requirement here. Ensuring the parent is
3795 // updated every time a pass that can potentially remove a child composable
3796 // op runs is less preferable as a solution.
3797 if (count == 0)
3798 return success();
3799
3800 if (count > 1)
3801 return emitOpError()
3802 << "multiple eligible child ops found in combined op";
3803
3804 // This operation cannot be combined if its captured nested op can be
3805 // executed more than once (i.e. its block's successors can reach it) or if
3806 // it's not guaranteed to be executed before all exits of the region (i.e.
3807 // it doesn't dominate all blocks with no successors reachable from the
3808 // entry block).
3809 DominanceInfo domInfo;
3810 Block *parentBlock = nestedOp->getBlock();
3811
3812 for (Block *successor : parentBlock->getSuccessors())
3813 if (successor->isReachable(parentBlock))
3814 return emitOpError() << "nested combined child op is part of a loop";
3815
3816 for (Block &block : op->getRegion(0))
3817 if (domInfo.isReachableFromEntry(&block) && block.hasNoSuccessors() &&
3818 !domInfo.dominates(parentBlock, &block))
3819 return emitOpError()
3820 << "nested combined child op doesn't unconditionally execute";
3821 }
3822 return success();
3823}
3824
3825//===----------------------------------------------------------------------===//
3826// LoopOp
3827//===----------------------------------------------------------------------===//
3828
3829void LoopOp::build(OpBuilder &builder, OperationState &state,
3830 const LoopOperands &clauses) {
3831 MLIRContext *ctx = builder.getContext();
3832
3833 LoopOp::build(builder, state, clauses.bindKind, clauses.privateVars,
3834 makeArrayAttr(ctx, clauses.privateSyms),
3835 clauses.privateNeedsBarrier, clauses.order, clauses.orderMod,
3836 makeArrayAttr(ctx, clauses.reductionMods),
3837 clauses.reductionVars,
3838 makeDenseBoolArrayAttr(ctx, clauses.reductionByref),
3839 makeArrayAttr(ctx, clauses.reductionSyms));
3840}
3841
3842LogicalResult LoopOp::verify() {
3843 if (failed(verifyPrivateVarList(*this)))
3844 return failure();
3845
3846 return verifyReductionVarList(*this, getReductionSyms(), getReductionVars(),
3847 getReductionByref(), getReductionModsAttr());
3848}
3849
3850LogicalResult LoopOp::verifyRegions() {
3851 if (llvm::isa_and_nonnull<LoopWrapperInterface>((*this)->getParentOp()) ||
3852 getNestedWrapper())
3853 return emitOpError() << "expected to be a standalone loop wrapper";
3854
3855 return success();
3856}
3857
3858//===----------------------------------------------------------------------===//
3859// WsloopOp
3860//===----------------------------------------------------------------------===//
3861
3862void WsloopOp::build(OpBuilder &builder, OperationState &state,
3863 ArrayRef<NamedAttribute> attributes) {
3864 build(builder, state, /*allocate_vars=*/{}, /*allocator_vars=*/{},
3865 /*allocate_alignments=*/nullptr,
3866 /*allocate_private_indices=*/nullptr,
3867 /*linear_vars=*/ValueRange(), /*linear_step_vars=*/ValueRange(),
3868 /*linear_var_types*/ nullptr, /*linear_modifiers=*/nullptr,
3869 /*linear_syms=*/nullptr, /*nowait=*/false, /*order=*/nullptr,
3870 /*order_mod=*/nullptr,
3871 /*ordered=*/nullptr, /*private_vars=*/{}, /*private_syms=*/nullptr,
3872 /*private_needs_barrier=*/false,
3873 /*reduction_mods=*/nullptr, /*reduction_vars=*/ValueRange(),
3874 /*reduction_byref=*/nullptr,
3875 /*reduction_syms=*/nullptr, /*schedule_kind=*/nullptr,
3876 /*schedule_chunk=*/nullptr, /*schedule_mod=*/nullptr,
3877 /*schedule_simd=*/false);
3878 state.addAttributes(attributes);
3879}
3880
3881void WsloopOp::build(OpBuilder &builder, OperationState &state,
3882 const WsloopOperands &clauses) {
3883 MLIRContext *ctx = builder.getContext();
3884 WsloopOp::build(
3885 builder, state, clauses.allocateVars, clauses.allocatorVars,
3886 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
3887 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices),
3888 clauses.linearVars, clauses.linearStepVars, clauses.linearVarTypes,
3889 clauses.linearModifiers, makeArrayAttr(ctx, clauses.linearSyms),
3890 clauses.nowait, clauses.order, clauses.orderMod, clauses.ordered,
3891 clauses.privateVars, makeArrayAttr(ctx, clauses.privateSyms),
3892 clauses.privateNeedsBarrier, makeArrayAttr(ctx, clauses.reductionMods),
3893 clauses.reductionVars,
3894 makeDenseBoolArrayAttr(ctx, clauses.reductionByref),
3895 makeArrayAttr(ctx, clauses.reductionSyms), clauses.scheduleKind,
3896 clauses.scheduleChunk, clauses.scheduleMod, clauses.scheduleSimd);
3897}
3898
3899LogicalResult WsloopOp::verify() {
3901 getOperation(), getAllocateVars(), getAllocatorVars(),
3902 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
3903 getPrivateVars(), getPrivateSymsAttr())))
3904 return failure();
3905
3906 if (failed(
3907 verifyLinearModifiers(*this, getLinearModifiers(), getLinearVars())))
3908 return failure();
3909 if (getLinearVars().size() &&
3910 getLinearVarTypes().value().size() != getLinearVars().size())
3911 return emitError() << "Ill-formed type attributes for linear variables";
3912
3913 if (failed(verifyLinearSyms(*this)) || failed(verifyPrivateVarList(*this)))
3914 return failure();
3915
3916 return verifyReductionVarList(*this, getReductionSyms(), getReductionVars(),
3917 getReductionByref(), getReductionModsAttr());
3918}
3919
3920LogicalResult WsloopOp::verifyRegions() {
3921 bool isCompositeChildLeaf =
3922 llvm::dyn_cast_if_present<LoopWrapperInterface>((*this)->getParentOp());
3923
3924 if (LoopWrapperInterface nested = getNestedWrapper()) {
3925 if (!isComposite())
3926 return emitError()
3927 << "'omp.composite' attribute missing from composite wrapper";
3928
3929 // Check for the allowed leaf constructs that may appear in a composite
3930 // construct directly after DO/FOR.
3931 if (!isa<SimdOp>(nested))
3932 return emitError() << "only supported nested wrapper is 'omp.simd'";
3933
3934 } else if (isComposite() && !isCompositeChildLeaf) {
3935 return emitError()
3936 << "'omp.composite' attribute present in non-composite wrapper";
3937 } else if (!isComposite() && isCompositeChildLeaf) {
3938 return emitError()
3939 << "'omp.composite' attribute missing from composite wrapper";
3940 }
3941
3942 return success();
3943}
3944
3945//===----------------------------------------------------------------------===//
3946// Simd construct [2.9.3.1]
3947//===----------------------------------------------------------------------===//
3948
3949void SimdOp::build(OpBuilder &builder, OperationState &state,
3950 const SimdOperands &clauses) {
3951 MLIRContext *ctx = builder.getContext();
3952 SimdOp::build(
3953 builder, state, clauses.alignedVars,
3954 makeArrayAttr(ctx, clauses.alignments), clauses.ifExpr,
3955 clauses.linearVars, clauses.linearStepVars, clauses.linearVarTypes,
3956 clauses.linearModifiers, makeArrayAttr(ctx, clauses.linearSyms),
3957 clauses.nontemporalVars, clauses.order, clauses.orderMod,
3958 clauses.privateVars, makeArrayAttr(ctx, clauses.privateSyms),
3959 clauses.privateNeedsBarrier, makeArrayAttr(ctx, clauses.reductionMods),
3960 clauses.reductionVars,
3961 makeDenseBoolArrayAttr(ctx, clauses.reductionByref),
3962 makeArrayAttr(ctx, clauses.reductionSyms), clauses.safelen,
3963 clauses.simdlen);
3964}
3965
3966LogicalResult SimdOp::verify() {
3967 if (failed(verifyReductionModifiers(*this, getReductionVars(),
3968 getReductionModsAttr())))
3969 return failure();
3970
3971 if (getSimdlen().has_value() && getSafelen().has_value() &&
3972 getSimdlen().value() > getSafelen().value())
3973 return emitOpError()
3974 << "simdlen clause and safelen clause are both present, but the "
3975 "simdlen value is not less than or equal to safelen value";
3976
3977 if (verifyAlignedClause(*this, getAlignments(), getAlignedVars()).failed())
3978 return failure();
3979
3980 if (verifyNontemporalClause(*this, getNontemporalVars()).failed())
3981 return failure();
3982
3983 if (failed(
3984 verifyLinearModifiers(*this, getLinearModifiers(), getLinearVars())))
3985 return failure();
3986
3987 bool isCompositeChildLeaf =
3988 llvm::dyn_cast_if_present<LoopWrapperInterface>((*this)->getParentOp());
3989
3990 if (!isComposite() && isCompositeChildLeaf)
3991 return emitError()
3992 << "'omp.composite' attribute missing from composite wrapper";
3993
3994 if (isComposite() && !isCompositeChildLeaf)
3995 return emitError()
3996 << "'omp.composite' attribute present in non-composite wrapper";
3997
3998 // Firstprivate is not allowed for SIMD in the standard. Check that none of
3999 // the private decls are for firstprivate.
4000 std::optional<ArrayAttr> privateSyms = getPrivateSyms();
4001 if (privateSyms) {
4002 for (const Attribute &sym : *privateSyms) {
4003 auto symRef = cast<SymbolRefAttr>(sym);
4004 omp::PrivateClauseOp privatizer =
4006 getOperation(), symRef);
4007 if (!privatizer)
4008 return emitError() << "Cannot find privatizer '" << symRef << "'";
4009 if (privatizer.getDataSharingType() ==
4010 DataSharingClauseType::FirstPrivate)
4011 return emitError() << "FIRSTPRIVATE cannot be used with SIMD";
4012 }
4013 }
4014
4015 if (failed(verifyPrivateVarList(*this)))
4016 return failure();
4017
4018 if (getLinearVars().size() &&
4019 getLinearVarTypes().value().size() != getLinearVars().size())
4020 return emitError() << "Ill-formed type attributes for linear variables";
4021
4022 if (failed(verifyLinearSyms(*this)))
4023 return failure();
4024
4025 llvm::DenseSet<Value> privateVars(llvm::from_range, getPrivateVars());
4026 llvm::DenseSet<Value> reductionVars(llvm::from_range, getReductionVars());
4027 // TODO Check lastprivate vars when their support is added to SimdOp.
4028 for (Value var : getLinearVars()) {
4029 if (privateVars.contains(var) || reductionVars.contains(var))
4030 return emitOpError()
4031 << "linear variables cannot appear in other data-sharing clauses";
4032 }
4033
4034 return success();
4035}
4036
4037LogicalResult SimdOp::verifyRegions() {
4038 if (getNestedWrapper())
4039 return emitOpError() << "must wrap an 'omp.loop_nest' directly";
4040
4041 return success();
4042}
4043
4044//===----------------------------------------------------------------------===//
4045// Distribute construct [2.9.4.1]
4046//===----------------------------------------------------------------------===//
4047
4048void DistributeOp::build(OpBuilder &builder, OperationState &state,
4049 const DistributeOperands &clauses) {
4050 DistributeOp::build(
4051 builder, state, clauses.allocateVars, clauses.allocatorVars,
4052 makeDenseI64ArrayAttr(builder.getContext(), clauses.allocateAlignments),
4054 clauses.allocatePrivateIndices),
4055 clauses.distScheduleStatic, clauses.distScheduleChunkSize, clauses.order,
4056 clauses.orderMod, clauses.privateVars,
4057 makeArrayAttr(builder.getContext(), clauses.privateSyms),
4058 clauses.privateNeedsBarrier);
4059}
4060
4061LogicalResult DistributeOp::verify() {
4062 if (this->getDistScheduleChunkSize() && !this->getDistScheduleStatic())
4063 return emitOpError() << "chunk size set without "
4064 "dist_schedule_static being present";
4065
4067 getOperation(), getAllocateVars(), getAllocatorVars(),
4068 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
4069 getPrivateVars(), getPrivateSymsAttr())))
4070 return failure();
4071
4072 if (failed(verifyPrivateVarList(*this)))
4073 return failure();
4074
4075 return success();
4076}
4077
4078LogicalResult DistributeOp::verifyRegions() {
4079 if (LoopWrapperInterface nested = getNestedWrapper()) {
4080 if (!isComposite())
4081 return emitError()
4082 << "'omp.composite' attribute missing from composite wrapper";
4083 // Check for the allowed leaf constructs that may appear in a composite
4084 // construct directly after DISTRIBUTE.
4085 if (isa<WsloopOp>(nested)) {
4086 Operation *parentOp = (*this)->getParentOp();
4087 if (!llvm::dyn_cast_if_present<ParallelOp>(parentOp) ||
4088 !cast<ComposableOpInterface>(parentOp).isComposite()) {
4089 return emitError() << "an 'omp.wsloop' nested wrapper is only allowed "
4090 "when a composite 'omp.parallel' is the direct "
4091 "parent";
4092 }
4093 } else if (!isa<SimdOp>(nested))
4094 return emitError() << "only supported nested wrappers are 'omp.simd' and "
4095 "'omp.wsloop'";
4096 } else if (isComposite()) {
4097 return emitError()
4098 << "'omp.composite' attribute present in non-composite wrapper";
4099 }
4100
4101 return success();
4102}
4103
4104//===----------------------------------------------------------------------===//
4105// DeclareMapperOp / DeclareMapperInfoOp
4106//===----------------------------------------------------------------------===//
4107
4108void DeclareMapperInfoOp::build(OpBuilder &builder, OperationState &state,
4109 const DeclareMapperInfoOperands &clauses) {
4110 DeclareMapperInfoOp::build(builder, state, clauses.mapVars,
4111 clauses.mapIterated);
4112}
4113
4114LogicalResult DeclareMapperInfoOp::verify() {
4115 return verifyMapClause(*this, getMapVars(), getMapIterated());
4116}
4117
4118LogicalResult DeclareMapperOp::verifyRegions() {
4119 if (!llvm::isa_and_present<DeclareMapperInfoOp>(
4120 getRegion().getBlocks().front().getTerminator()))
4121 return emitOpError() << "expected terminator to be a DeclareMapperInfoOp";
4122
4123 return success();
4124}
4125
4126//===----------------------------------------------------------------------===//
4127// DeclareReductionOp
4128//===----------------------------------------------------------------------===//
4129
4130LogicalResult DeclareReductionOp::verifyRegions() {
4131 if (!getAllocRegion().empty()) {
4132 for (YieldOp yieldOp : getAllocRegion().getOps<YieldOp>()) {
4133 if (yieldOp.getResults().size() != 1 ||
4134 yieldOp.getResults().getTypes()[0] != getType())
4135 return emitOpError() << "expects alloc region to yield a value "
4136 "of the reduction type";
4137 }
4138 }
4139
4140 if (getInitializerRegion().empty())
4141 return emitOpError() << "expects non-empty initializer region";
4142 Block &initializerEntryBlock = getInitializerRegion().front();
4143
4144 if (initializerEntryBlock.getNumArguments() == 1) {
4145 if (!getAllocRegion().empty())
4146 return emitOpError() << "expects two arguments to the initializer region "
4147 "when an allocation region is used";
4148 } else if (initializerEntryBlock.getNumArguments() == 2) {
4149 if (getAllocRegion().empty())
4150 return emitOpError() << "expects one argument to the initializer region "
4151 "when no allocation region is used";
4152 } else {
4153 return emitOpError()
4154 << "expects one or two arguments to the initializer region";
4155 }
4156
4157 for (mlir::Value arg : initializerEntryBlock.getArguments())
4158 if (arg.getType() != getType())
4159 return emitOpError() << "expects initializer region argument to match "
4160 "the reduction type";
4161
4162 for (YieldOp yieldOp : getInitializerRegion().getOps<YieldOp>()) {
4163 if (yieldOp.getResults().size() != 1 ||
4164 yieldOp.getResults().getTypes()[0] != getType())
4165 return emitOpError() << "expects initializer region to yield a value "
4166 "of the reduction type";
4167 }
4168
4169 if (getReductionRegion().empty())
4170 return emitOpError() << "expects non-empty reduction region";
4171 Block &reductionEntryBlock = getReductionRegion().front();
4172 if (reductionEntryBlock.getNumArguments() != 2 ||
4173 reductionEntryBlock.getArgumentTypes()[0] !=
4174 reductionEntryBlock.getArgumentTypes()[1] ||
4175 reductionEntryBlock.getArgumentTypes()[0] != getType())
4176 return emitOpError() << "expects reduction region with two arguments of "
4177 "the reduction type";
4178 for (YieldOp yieldOp : getReductionRegion().getOps<YieldOp>()) {
4179 if (yieldOp.getResults().size() != 1 ||
4180 yieldOp.getResults().getTypes()[0] != getType())
4181 return emitOpError() << "expects reduction region to yield a value "
4182 "of the reduction type";
4183 }
4184
4185 if (!getAtomicReductionRegion().empty()) {
4186 Block &atomicReductionEntryBlock = getAtomicReductionRegion().front();
4187 if (atomicReductionEntryBlock.getNumArguments() != 2 ||
4188 atomicReductionEntryBlock.getArgumentTypes()[0] !=
4189 atomicReductionEntryBlock.getArgumentTypes()[1])
4190 return emitOpError() << "expects atomic reduction region with two "
4191 "arguments of the same type";
4192 auto ptrType = llvm::dyn_cast<PointerLikeType>(
4193 atomicReductionEntryBlock.getArgumentTypes()[0]);
4194 if (!ptrType ||
4195 (ptrType.getElementType() && ptrType.getElementType() != getType()))
4196 return emitOpError() << "expects atomic reduction region arguments to "
4197 "be accumulators containing the reduction type";
4198 }
4199
4200 if (getCleanupRegion().empty())
4201 return success();
4202 Block &cleanupEntryBlock = getCleanupRegion().front();
4203 if (cleanupEntryBlock.getNumArguments() != 1 ||
4204 cleanupEntryBlock.getArgument(0).getType() != getType())
4205 return emitOpError() << "expects cleanup region with one argument "
4206 "of the reduction type";
4207
4208 return success();
4209}
4210
4211//===----------------------------------------------------------------------===//
4212// TaskOp
4213//===----------------------------------------------------------------------===//
4214
4215void TaskOp::build(OpBuilder &builder, OperationState &state,
4216 const TaskOperands &clauses) {
4217 MLIRContext *ctx = builder.getContext();
4218 TaskOp::build(builder, state, clauses.iterated, clauses.affinityVars,
4219 clauses.allocateVars, clauses.allocatorVars,
4220 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
4221 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices),
4222 makeArrayAttr(ctx, clauses.dependKinds), clauses.dependVars,
4223 makeArrayAttr(ctx, clauses.dependIteratedKinds),
4224 clauses.dependIterated, clauses.final, clauses.ifExpr,
4225 clauses.inReductionVars,
4226 makeDenseBoolArrayAttr(ctx, clauses.inReductionByref),
4227 makeArrayAttr(ctx, clauses.inReductionSyms),
4228 /*reduction_assume_bounded_recipe_effects=*/nullptr,
4229 clauses.mergeable, clauses.priority,
4230 /*private_vars=*/clauses.privateVars,
4231 /*private_syms=*/makeArrayAttr(ctx, clauses.privateSyms),
4232 clauses.privateNeedsBarrier,
4233 /*private_assume_bounded_recipe_effects=*/nullptr,
4234 clauses.threadset, clauses.untied, clauses.eventHandle);
4235}
4236
4237LogicalResult TaskOp::verify() {
4239 getOperation(), getAllocateVars(), getAllocatorVars(),
4240 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
4241 getPrivateVars(), getPrivateSymsAttr())))
4242 return failure();
4243
4244 LogicalResult verifyDependVars =
4245 verifyDependVarList(*this, getDependKinds(), getDependVars(),
4246 getDependIteratedKinds(), getDependIterated());
4247 if (failed(verifyDependVars))
4248 return verifyDependVars;
4249
4250 if (failed(verifyPrivateVarList(*this)))
4251 return failure();
4252
4253 return verifyReductionVarList(*this, getInReductionSyms(),
4254 getInReductionVars(), getInReductionByref());
4255}
4256
4259 &effects) {
4260 effects.emplace_back(MemoryEffects::Read::get());
4261 effects.emplace_back(MemoryEffects::Write::get());
4262}
4263
4264static void
4267 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
4268 auto reductionVars = iface.getInReductionVars();
4269 for (auto &source :
4270 MutableArrayRef(reductionVars.getBase(), reductionVars.size())) {
4271 effects.emplace_back(MemoryEffects::Read::get(), &source);
4272 effects.emplace_back(MemoryEffects::Write::get(), &source);
4273 }
4274
4275 for (BlockArgument arg : iface.getInReductionBlockArgs()) {
4276 effects.emplace_back(MemoryEffects::Read::get(), arg);
4277 effects.emplace_back(MemoryEffects::Write::get(), arg);
4278 }
4279
4280 // The in_reduction clause does not necessarily allocate or free private
4281 // accumulators. We avoid attaching an allocate effect to these accumulators
4282 // as this would incorrectly imply they are fresh storage.
4283 if (!reductionVars.empty()) {
4284 effects.emplace_back(MemoryEffects::Allocate::get());
4285 effects.emplace_back(MemoryEffects::Free::get());
4286 }
4287}
4288
4289void TaskOp::getEffects(
4291 &effects) {
4292 // Also covers the memory effects of the DEPEND clause.
4294
4295 bool hasUnknownRecipeEffects =
4296 (!getPrivateVars().empty() && !getPrivateAssumeBoundedRecipeEffects()) ||
4297 (!getInReductionVars().empty() &&
4298 !getInReductionAssumeBoundedRecipeEffects());
4299
4300 if (hasUnknownRecipeEffects) {
4301 addUnknownMemoryEffects(effects);
4302 } else {
4303 getPrivatisationEffects(*this, effects);
4304 getInReductionEffects(*this, effects);
4305 }
4306}
4307
4308//===----------------------------------------------------------------------===//
4309// TaskgroupOp
4310//===----------------------------------------------------------------------===//
4311
4312void TaskgroupOp::build(OpBuilder &builder, OperationState &state,
4313 const TaskgroupOperands &clauses) {
4314 MLIRContext *ctx = builder.getContext();
4315 TaskgroupOp::build(builder, state, clauses.allocateVars,
4316 clauses.allocatorVars,
4317 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
4318 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices),
4319 clauses.taskReductionVars,
4320 makeDenseBoolArrayAttr(ctx, clauses.taskReductionByref),
4321 makeArrayAttr(ctx, clauses.taskReductionSyms),
4322 /*task_reduction_assume_bounded_recipe_effects=*/nullptr);
4323}
4324
4325LogicalResult TaskgroupOp::verify() {
4327 getOperation(), getAllocateVars(), getAllocatorVars(),
4328 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr())))
4329 return failure();
4330
4331 return verifyReductionVarList(*this, getTaskReductionSyms(),
4332 getTaskReductionVars(),
4333 getTaskReductionByref());
4334}
4335
4338 auto iface = dyn_cast<BlockArgOpenMPOpInterface>(op);
4339 auto taskVars = iface.getTaskReductionVars();
4340 for (auto &source : MutableArrayRef(taskVars.getBase(), taskVars.size())) {
4341 effects.emplace_back(MemoryEffects::Read::get(), &source);
4342 effects.emplace_back(MemoryEffects::Write::get(), &source);
4343 }
4344
4345 for (BlockArgument arg : iface.getTaskReductionBlockArgs()) {
4346 effects.emplace_back(MemoryEffects::Read::get(), arg);
4347 effects.emplace_back(MemoryEffects::Write::get(), arg);
4348 }
4349
4350 // The task_reduction clause does not necessarily allocate or free private
4351 // accumulators. We avoid attaching an allocate effect to these accumulators
4352 // as this would incorrectly imply they are fresh storage.
4353 if (!taskVars.empty()) {
4354 effects.emplace_back(MemoryEffects::Allocate::get());
4355 effects.emplace_back(MemoryEffects::Free::get());
4356 }
4357}
4358
4359void TaskgroupOp::getEffects(
4361 &effects) {
4363
4364 if (!getTaskReductionVars().empty() &&
4365 !getTaskReductionAssumeBoundedRecipeEffects())
4366 addUnknownMemoryEffects(effects);
4367 else
4368 getTaskReductionEffects(*this, effects);
4369}
4370
4371//===----------------------------------------------------------------------===//
4372// TaskloopContextOp
4373//===----------------------------------------------------------------------===//
4374
4375void TaskloopContextOp::build(OpBuilder &builder, OperationState &state,
4376 const TaskloopContextOperands &clauses) {
4377 MLIRContext *ctx = builder.getContext();
4378 TaskloopContextOp::build(
4379 builder, state, clauses.allocateVars, clauses.allocatorVars,
4380 makeDenseI64ArrayAttr(ctx, clauses.allocateAlignments),
4381 makeDenseI64ArrayAttr(ctx, clauses.allocatePrivateIndices), clauses.final,
4382 clauses.grainsizeMod, clauses.grainsize, clauses.ifExpr,
4383 clauses.inReductionVars,
4384 makeDenseBoolArrayAttr(ctx, clauses.inReductionByref),
4385 makeArrayAttr(ctx, clauses.inReductionSyms), clauses.mergeable,
4386 clauses.nogroup, clauses.numTasksMod, clauses.numTasks, clauses.priority,
4387 /*private_vars=*/clauses.privateVars,
4388 /*private_syms=*/makeArrayAttr(ctx, clauses.privateSyms),
4389 clauses.privateNeedsBarrier, makeArrayAttr(ctx, clauses.reductionMods),
4390 clauses.reductionVars,
4391 makeDenseBoolArrayAttr(ctx, clauses.reductionByref),
4392 makeArrayAttr(ctx, clauses.reductionSyms), clauses.threadset,
4393 clauses.untied);
4394 state.addAttribute("omp.combined", UnitAttr::get(ctx));
4395}
4396
4397TaskloopWrapperOp TaskloopContextOp::getLoopOp() {
4398 return cast<TaskloopWrapperOp>(
4399 *llvm::find_if(getRegion().front(), [](mlir::Operation &op) {
4400 return isa<TaskloopWrapperOp>(op);
4401 }));
4402}
4403
4404LogicalResult TaskloopContextOp::verify() {
4405 if (failed(verifyPrivateVarList(*this)))
4406 return failure();
4408 getOperation(), getAllocateVars(), getAllocatorVars(),
4409 getAllocateAlignmentsAttr(), getAllocatePrivateIndicesAttr(),
4410 getPrivateVars(), getPrivateSymsAttr())))
4411 return failure();
4412
4413 if (failed(verifyReductionVarList(*this, getReductionSyms(),
4414 getReductionVars(), getReductionByref(),
4415 getReductionModsAttr())) ||
4416 failed(verifyReductionVarList(*this, getInReductionSyms(),
4417 getInReductionVars(),
4418 getInReductionByref())))
4419 return failure();
4420
4421 if (!getReductionVars().empty() && getNogroup())
4422 return emitError("if a reduction clause is present on the taskloop "
4423 "directive, the nogroup clause must not be specified");
4424 for (auto var : getReductionVars()) {
4425 if (llvm::is_contained(getInReductionVars(), var))
4426 return emitError("the same list item cannot appear in both a reduction "
4427 "and an in_reduction clause");
4428 }
4429
4430 if (getGrainsize() && getNumTasks()) {
4431 return emitError(
4432 "the grainsize clause and num_tasks clause are mutually exclusive and "
4433 "may not appear on the same taskloop directive");
4434 }
4435
4436 // Without this restriction, any compound construct including `taskloop` would
4437 // fail to correctly identify the whole chain of operations (see
4438 // ComposableOpInterface::findCapturedOp()), as well as failing to do so even
4439 // for standalone `taskloop` constructs.
4440 if (!isCombined())
4441 return emitOpError("must always contain the 'omp.combined' attribute");
4442
4443 return success();
4444}
4445
4446LogicalResult TaskloopContextOp::verifyRegions() {
4447 Region &region = getRegion();
4448 auto loopWrapperIt = llvm::find_if(region.front(), [](mlir::Operation &op) {
4449 return isa<TaskloopWrapperOp>(op);
4450 });
4451 if (loopWrapperIt == region.front().end())
4452 return emitOpError()
4453 << "expected a TaskloopWrapperOp directly nested in the region";
4454
4455 auto loopWrapperOp = cast<TaskloopWrapperOp>(*loopWrapperIt);
4456 auto loopNestOp = dyn_cast<LoopNestOp>(loopWrapperOp.getWrappedLoop());
4457 // This will fail the verifier for TaskloopWrapperOp and print an error
4458 // message there.
4459 if (!loopNestOp)
4460 return failure();
4461
4462 std::function<bool(Value)> isValidBoundValue = [&](Value value) -> bool {
4463 Region *valueRegion = value.getParentRegion();
4464 // A loop bound value defined outside of the taskloop context region is
4465 // valid. A region is considered an ancestor of itself.
4466 if (!region.isAncestor(valueRegion))
4467 return true;
4468
4469 Operation *defOp = value.getDefiningOp();
4470 if (!defOp || defOp->getNumRegions() != 0 || !isPure(defOp))
4471 return false;
4472
4473 return llvm::all_of(defOp->getOperands(), isValidBoundValue);
4474 };
4475 auto hasUnsupportedTaskloopLocalBound = [&](OperandRange range) -> bool {
4476 return llvm::any_of(range,
4477 [&](Value value) { return !isValidBoundValue(value); });
4478 };
4479
4480 if (hasUnsupportedTaskloopLocalBound(loopNestOp.getLoopLowerBounds()) ||
4481 hasUnsupportedTaskloopLocalBound(loopNestOp.getLoopUpperBounds()) ||
4482 hasUnsupportedTaskloopLocalBound(loopNestOp.getLoopSteps())) {
4483 return emitOpError()
4484 << "expects loop bounds and steps to be defined outside of the "
4485 "taskloop.context region or by pure, regionless operations "
4486 "that do not depend on block arguments";
4487 }
4488
4489 return success();
4490}
4491
4492//===----------------------------------------------------------------------===//
4493// TaskloopWrapperOp
4494//===----------------------------------------------------------------------===//
4495
4496void TaskloopWrapperOp::build(OpBuilder &builder, OperationState &state,
4497 const TaskloopWrapperOperands &clauses) {
4498 TaskloopWrapperOp::build(builder, state);
4499}
4500
4501TaskloopContextOp TaskloopWrapperOp::getTaskloopContext() {
4502 return dyn_cast<TaskloopContextOp>(getOperation()->getParentOp());
4503}
4504
4505LogicalResult TaskloopWrapperOp::verify() {
4506 TaskloopContextOp context = getTaskloopContext();
4507 if (!context)
4508 return emitOpError() << "expected to be nested in a taskloop context op";
4509 return success();
4510}
4511
4512LogicalResult TaskloopWrapperOp::verifyRegions() {
4513 if (LoopWrapperInterface nested = getNestedWrapper()) {
4514 if (!isComposite())
4515 return emitError()
4516 << "'omp.composite' attribute missing from composite wrapper";
4517
4518 // Check for the allowed leaf constructs that may appear in a composite
4519 // construct directly after TASKLOOP.
4520 if (!isa<SimdOp>(nested))
4521 return emitError() << "only supported nested wrapper is 'omp.simd'";
4522 } else if (isComposite()) {
4523 return emitError()
4524 << "'omp.composite' attribute present in non-composite wrapper";
4525 }
4526
4527 return success();
4528}
4529
4530//===----------------------------------------------------------------------===//
4531// LoopNestOp
4532//===----------------------------------------------------------------------===//
4533
4534ParseResult LoopNestOp::parse(OpAsmParser &parser, OperationState &result) {
4535 // Parse an opening `(` followed by induction variables followed by `)`
4538 Type loopVarType;
4540 parser.parseColonType(loopVarType) ||
4541 // Parse loop bounds.
4542 parser.parseEqual() ||
4543 parser.parseOperandList(lbs, ivs.size(), OpAsmParser::Delimiter::Paren) ||
4544 parser.parseKeyword("to") ||
4545 parser.parseOperandList(ubs, ivs.size(), OpAsmParser::Delimiter::Paren))
4546 return failure();
4547
4548 for (auto &iv : ivs)
4549 iv.type = loopVarType;
4550
4551 auto *ctx = parser.getBuilder().getContext();
4552 // Parse "inclusive" flag.
4553 if (succeeded(parser.parseOptionalKeyword("inclusive")))
4554 result.addAttribute("loop_inclusive", UnitAttr::get(ctx));
4555
4556 // Parse step values.
4558 if (parser.parseKeyword("step") ||
4559 parser.parseOperandList(steps, ivs.size(), OpAsmParser::Delimiter::Paren))
4560 return failure();
4561
4562 // Parse collapse
4563 int64_t value = 0;
4564 if (!parser.parseOptionalKeyword("collapse") &&
4565 (parser.parseLParen() || parser.parseInteger(value) ||
4566 parser.parseRParen()))
4567 return failure();
4568 if (value > 1)
4569 result.addAttribute(
4570 "collapse_num_loops",
4571 IntegerAttr::get(parser.getBuilder().getI64Type(), value));
4572
4573 // Parse tiles
4575 auto parseTiles = [&]() -> ParseResult {
4576 int64_t tile;
4577 if (parser.parseInteger(tile))
4578 return failure();
4579 tiles.push_back(tile);
4580 return success();
4581 };
4582
4583 if (!parser.parseOptionalKeyword("tiles") &&
4584 (parser.parseLParen() || parser.parseCommaSeparatedList(parseTiles) ||
4585 parser.parseRParen()))
4586 return failure();
4587
4588 if (tiles.size() > 0)
4589 result.addAttribute("tile_sizes", DenseI64ArrayAttr::get(ctx, tiles));
4590
4591 // Parse the body.
4592 Region *region = result.addRegion();
4593 if (parser.parseRegion(*region, ivs))
4594 return failure();
4595
4596 // Resolve operands.
4597 if (parser.resolveOperands(lbs, loopVarType, result.operands) ||
4598 parser.resolveOperands(ubs, loopVarType, result.operands) ||
4599 parser.resolveOperands(steps, loopVarType, result.operands))
4600 return failure();
4601
4602 // Parse the optional attribute list.
4603 return parser.parseOptionalAttrDict(result.attributes);
4604}
4605
4606void LoopNestOp::print(OpAsmPrinter &p) {
4607 Region &region = getRegion();
4608 auto args = region.getArguments();
4609 p << " (" << args << ") : " << args[0].getType() << " = ("
4610 << getLoopLowerBounds() << ") to (" << getLoopUpperBounds() << ") ";
4611 if (getLoopInclusive())
4612 p << "inclusive ";
4613 p << "step (" << getLoopSteps() << ") ";
4614 if (int64_t numCollapse = getCollapseNumLoops())
4615 if (numCollapse > 1)
4616 p << "collapse(" << numCollapse << ") ";
4617
4618 if (const auto tiles = getTileSizes())
4619 p << "tiles(" << tiles.value() << ") ";
4620
4621 p.printRegion(region, /*printEntryBlockArgs=*/false);
4622}
4623
4624void LoopNestOp::build(OpBuilder &builder, OperationState &state,
4625 const LoopNestOperands &clauses) {
4626 MLIRContext *ctx = builder.getContext();
4627 LoopNestOp::build(builder, state, clauses.collapseNumLoops,
4628 clauses.loopLowerBounds, clauses.loopUpperBounds,
4629 clauses.loopSteps, clauses.loopInclusive,
4630 makeDenseI64ArrayAttr(ctx, clauses.tileSizes));
4631}
4632
4633LogicalResult LoopNestOp::verify() {
4634 if (getLoopLowerBounds().empty())
4635 return emitOpError() << "must represent at least one loop";
4636
4637 if (getLoopLowerBounds().size() != getIVs().size())
4638 return emitOpError() << "number of range arguments and IVs do not match";
4639
4640 for (auto [lb, iv] : llvm::zip_equal(getLoopLowerBounds(), getIVs())) {
4641 if (lb.getType() != iv.getType())
4642 return emitOpError()
4643 << "range argument type does not match corresponding IV type";
4644 }
4645
4646 uint64_t numIVs = getIVs().size();
4647
4648 if (const auto &numCollapse = getCollapseNumLoops())
4649 if (numCollapse > numIVs)
4650 return emitOpError()
4651 << "collapse value is larger than the number of loops";
4652
4653 if (const auto &tiles = getTileSizes())
4654 if (tiles.value().size() > numIVs)
4655 return emitOpError() << "too few canonical loops for tile dimensions";
4656
4657 if (!llvm::dyn_cast_if_present<LoopWrapperInterface>((*this)->getParentOp()))
4658 return emitOpError() << "expects parent op to be a loop wrapper";
4659
4660 return success();
4661}
4662
4663void LoopNestOp::gatherWrappers(
4665 Operation *parent = (*this)->getParentOp();
4666 while (auto wrapper =
4667 llvm::dyn_cast_if_present<LoopWrapperInterface>(parent)) {
4668 wrappers.push_back(wrapper);
4669 parent = parent->getParentOp();
4670 }
4671}
4672
4673//===----------------------------------------------------------------------===//
4674// OpenMP canonical loop handling
4675//===----------------------------------------------------------------------===//
4676
4677std::tuple<NewCliOp, OpOperand *, OpOperand *>
4678mlir::omp ::decodeCli(Value cli) {
4679
4680 // Defining a CLI for a generated loop is optional; if there is none then
4681 // there is no followup-tranformation
4682 if (!cli)
4683 return {{}, nullptr, nullptr};
4684
4685 assert(cli.getType() == CanonicalLoopInfoType::get(cli.getContext()) &&
4686 "Unexpected type of cli");
4687
4688 NewCliOp create = cast<NewCliOp>(cli.getDefiningOp());
4689 OpOperand *gen = nullptr;
4690 OpOperand *cons = nullptr;
4691 for (OpOperand &use : cli.getUses()) {
4692 auto op = cast<LoopTransformationInterface>(use.getOwner());
4693
4694 unsigned opnum = use.getOperandNumber();
4695 if (op.isGeneratee(opnum)) {
4696 assert(!gen && "Each CLI may have at most one def");
4697 gen = &use;
4698 } else if (op.isApplyee(opnum)) {
4699 assert(!cons && "Each CLI may have at most one consumer");
4700 cons = &use;
4701 } else {
4702 llvm_unreachable("Unexpected operand for a CLI");
4703 }
4704 }
4705
4706 return {create, gen, cons};
4707}
4708
4709ClauseProcBindKind
4710mlir::omp::convertProcBindKind(llvm::omp::ProcBindKind kind) {
4711 switch (kind) {
4712 case llvm::omp::ProcBindKind::OMP_PROC_BIND_close:
4713 return ClauseProcBindKind::Close;
4714 case llvm::omp::ProcBindKind::OMP_PROC_BIND_master:
4715 return ClauseProcBindKind::Master;
4716 case llvm::omp::ProcBindKind::OMP_PROC_BIND_primary:
4717 return ClauseProcBindKind::Primary;
4718 case llvm::omp::ProcBindKind::OMP_PROC_BIND_spread:
4719 return ClauseProcBindKind::Spread;
4720 case llvm::omp::ProcBindKind::OMP_PROC_BIND_default:
4721 case llvm::omp::ProcBindKind::OMP_PROC_BIND_unknown:
4722 break;
4723 }
4724 llvm_unreachable("unexpected proc-bind kind");
4725}
4726
4727void NewCliOp::build(::mlir::OpBuilder &odsBuilder,
4728 ::mlir::OperationState &odsState) {
4729 odsState.addTypes(CanonicalLoopInfoType::get(odsBuilder.getContext()));
4730}
4731
4732void NewCliOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
4733 Value result = getResult();
4734 auto [newCli, gen, cons] = decodeCli(result);
4735
4736 // Structured binding `gen` cannot be captured in lambdas before C++20
4737 OpOperand *generator = gen;
4738
4739 // Derive the CLI variable name from its generator:
4740 // * "canonloop" for omp.canonical_loop
4741 // * custom name for loop transformation generatees
4742 // * "cli" as fallback if no generator
4743 // * "_r<idx>" suffix for nested loops, where <idx> is the sequential order
4744 // at that level
4745 // * "_s<idx>" suffix for operations with multiple regions, where <idx> is
4746 // the index of that region
4747 std::string cliName{"cli"};
4748 if (gen) {
4749 cliName =
4751 .Case([&](CanonicalLoopOp op) {
4752 return generateLoopNestingName("canonloop", op);
4753 })
4754 .Case([&](UnrollHeuristicOp op) -> std::string {
4755 llvm_unreachable("heuristic unrolling does not generate a loop");
4756 })
4757 .Case([&](FuseOp op) -> std::string {
4758 unsigned opnum = generator->getOperandNumber();
4759 // The position of the first loop to be fused is the same position
4760 // as the resulting fused loop
4761 if (op.getFirst().has_value() && opnum != op.getFirst().value())
4762 return "canonloop_fuse";
4763 else
4764 return "fused";
4765 })
4766 .Case([&](TileOp op) -> std::string {
4767 auto [generateesFirst, generateesCount] =
4768 op.getGenerateesODSOperandIndexAndLength();
4769 unsigned firstGrid = generateesFirst;
4770 unsigned firstIntratile = generateesFirst + generateesCount / 2;
4771 unsigned end = generateesFirst + generateesCount;
4772 unsigned opnum = generator->getOperandNumber();
4773 // In the OpenMP apply and looprange clauses, indices are 1-based
4774 if (firstGrid <= opnum && opnum < firstIntratile) {
4775 unsigned gridnum = opnum - firstGrid + 1;
4776 return ("grid" + Twine(gridnum)).str();
4777 }
4778 if (firstIntratile <= opnum && opnum < end) {
4779 unsigned intratilenum = opnum - firstIntratile + 1;
4780 return ("intratile" + Twine(intratilenum)).str();
4781 }
4782 llvm_unreachable("Unexpected generatee argument");
4783 })
4784 .DefaultUnreachable("TODO: Custom name for this operation");
4785 }
4786
4787 setNameFn(result, cliName);
4788}
4789
4790LogicalResult NewCliOp::verify() {
4791 Value cli = getResult();
4792
4793 assert(cli.getType() == CanonicalLoopInfoType::get(cli.getContext()) &&
4794 "Unexpected type of cli");
4795
4796 // Check that the CLI is used in at most generator and one consumer
4797 OpOperand *gen = nullptr;
4798 OpOperand *cons = nullptr;
4799 for (mlir::OpOperand &use : cli.getUses()) {
4800 auto op = dyn_cast<mlir::omp::LoopTransformationInterface>(use.getOwner());
4801 if (!op) {
4802 InFlightDiagnostic error =
4803 emitOpError("CLI must only be used by loop transformations");
4804 error.attachNote(use.getOwner()->getLoc()).append("invalid use here:");
4805 return error;
4806 }
4807
4808 unsigned opnum = use.getOperandNumber();
4809 if (op.isGeneratee(opnum)) {
4810 if (gen) {
4811 InFlightDiagnostic error =
4812 emitOpError("CLI must have at most one generator");
4813 error.attachNote(gen->getOwner()->getLoc())
4814 .append("first generator here:");
4815 error.attachNote(use.getOwner()->getLoc())
4816 .append("second generator here:");
4817 return error;
4818 }
4819
4820 gen = &use;
4821 } else if (op.isApplyee(opnum)) {
4822 if (cons) {
4823 InFlightDiagnostic error =
4824 emitOpError("CLI must have at most one consumer");
4825 error.attachNote(cons->getOwner()->getLoc())
4826 .append("first consumer here:")
4827 .appendOp(*cons->getOwner(),
4828 OpPrintingFlags().printGenericOpForm());
4829 error.attachNote(use.getOwner()->getLoc())
4830 .append("second consumer here:")
4831 .appendOp(*use.getOwner(), OpPrintingFlags().printGenericOpForm());
4832 return error;
4833 }
4834
4835 cons = &use;
4836 } else {
4837 llvm_unreachable("Unexpected operand for a CLI");
4838 }
4839 }
4840
4841 // If the CLI is source of a transformation, it must have a generator
4842 if (cons && !gen) {
4843 InFlightDiagnostic error = emitOpError("CLI has no generator");
4844 error.attachNote(cons->getOwner()->getLoc())
4845 .append("see consumer here: ")
4846 .appendOp(*cons->getOwner(), OpPrintingFlags().printGenericOpForm());
4847 return error;
4848 }
4849
4850 return success();
4851}
4852
4853void CanonicalLoopOp::build(OpBuilder &odsBuilder, OperationState &odsState,
4854 Value tripCount) {
4855 odsState.addOperands(tripCount);
4856 odsState.addOperands(Value());
4857 (void)odsState.addRegion();
4858}
4859
4860void CanonicalLoopOp::build(OpBuilder &odsBuilder, OperationState &odsState,
4861 Value tripCount, ::mlir::Value cli) {
4862 odsState.addOperands(tripCount);
4863 odsState.addOperands(cli);
4864 (void)odsState.addRegion();
4865}
4866
4867void CanonicalLoopOp::getAsmBlockNames(OpAsmSetBlockNameFn setNameFn) {
4868 setNameFn(&getRegion().front(), "body_entry");
4869}
4870
4871void CanonicalLoopOp::getAsmBlockArgumentNames(Region &region,
4872 OpAsmSetValueNameFn setNameFn) {
4873 std::string ivName = generateLoopNestingName("iv", *this);
4874 setNameFn(region.getArgument(0), ivName);
4875}
4876
4877void CanonicalLoopOp::print(OpAsmPrinter &p) {
4878 if (getCli())
4879 p << '(' << getCli() << ')';
4880 p << ' ' << getInductionVar() << " : " << getInductionVar().getType()
4881 << " in range(" << getTripCount() << ") ";
4882
4883 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
4884 /*printBlockTerminators=*/true);
4885
4886 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
4887}
4888
4889mlir::ParseResult CanonicalLoopOp::parse(::mlir::OpAsmParser &parser,
4891 CanonicalLoopInfoType cliType =
4892 CanonicalLoopInfoType::get(parser.getContext());
4893
4894 // Parse (optional) omp.cli identifier
4896 SmallVector<mlir::Value, 1> cliOperand;
4897 if (!parser.parseOptionalLParen()) {
4898 if (parser.parseOperand(cli) ||
4899 parser.resolveOperand(cli, cliType, cliOperand) || parser.parseRParen())
4900 return failure();
4901 }
4902
4903 // We derive the type of tripCount from inductionVariable. MLIR requires the
4904 // type of tripCount to be known when calling resolveOperand so we have parse
4905 // the type before processing the inductionVariable.
4906 OpAsmParser::Argument inductionVariable;
4908 if (parser.parseArgument(inductionVariable, /*allowType*/ true) ||
4909 parser.parseKeyword("in") || parser.parseKeyword("range") ||
4910 parser.parseLParen() || parser.parseOperand(tripcount) ||
4911 parser.parseRParen() ||
4912 parser.resolveOperand(tripcount, inductionVariable.type, result.operands))
4913 return failure();
4914
4915 // Parse the loop body.
4916 Region *region = result.addRegion();
4917 if (parser.parseRegion(*region, {inductionVariable}))
4918 return failure();
4919
4920 // We parsed the cli operand forst, but because it is optional, it must be
4921 // last in the operand list.
4922 result.operands.append(cliOperand);
4923
4924 // Parse the optional attribute list.
4925 if (parser.parseOptionalAttrDict(result.attributes))
4926 return failure();
4927
4928 return mlir::success();
4929}
4930
4931LogicalResult CanonicalLoopOp::verify() {
4932 // The region's entry must accept the induction variable
4933 // It can also be empty if just created
4934 if (!getRegion().empty()) {
4935 Region &region = getRegion();
4936 if (region.getNumArguments() != 1)
4937 return emitOpError(
4938 "Canonical loop region must have exactly one argument");
4939
4940 if (getInductionVar().getType() != getTripCount().getType())
4941 return emitOpError(
4942 "Region argument must be the same type as the trip count");
4943 }
4944
4945 return success();
4946}
4947
4948Value CanonicalLoopOp::getInductionVar() { return getRegion().getArgument(0); }
4949
4950std::pair<unsigned, unsigned>
4951CanonicalLoopOp::getApplyeesODSOperandIndexAndLength() {
4952 // No applyees
4953 return {0, 0};
4954}
4955
4956std::pair<unsigned, unsigned>
4957CanonicalLoopOp::getGenerateesODSOperandIndexAndLength() {
4958 return getODSOperandIndexAndLength(odsIndex_cli);
4959}
4960
4961//===----------------------------------------------------------------------===//
4962// UnrollHeuristicOp
4963//===----------------------------------------------------------------------===//
4964
4965void UnrollHeuristicOp::build(::mlir::OpBuilder &odsBuilder,
4966 ::mlir::OperationState &odsState,
4967 ::mlir::Value cli) {
4968 odsState.addOperands(cli);
4969}
4970
4971void UnrollHeuristicOp::print(OpAsmPrinter &p) {
4972 p << '(' << getApplyee() << ')';
4973
4974 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
4975}
4976
4977mlir::ParseResult UnrollHeuristicOp::parse(::mlir::OpAsmParser &parser,
4979 auto cliType = CanonicalLoopInfoType::get(parser.getContext());
4980
4981 if (parser.parseLParen())
4982 return failure();
4983
4985 if (parser.parseOperand(applyee) ||
4986 parser.resolveOperand(applyee, cliType, result.operands))
4987 return failure();
4988
4989 if (parser.parseRParen())
4990 return failure();
4991
4992 // Optional output loop (full unrolling has none)
4993 if (!parser.parseOptionalArrow()) {
4994 if (parser.parseLParen() || parser.parseRParen())
4995 return failure();
4996 }
4997
4998 // Parse the optional attribute list.
4999 if (parser.parseOptionalAttrDict(result.attributes))
5000 return failure();
5001
5002 return mlir::success();
5003}
5004
5005std::pair<unsigned, unsigned>
5006UnrollHeuristicOp ::getApplyeesODSOperandIndexAndLength() {
5007 return getODSOperandIndexAndLength(odsIndex_applyee);
5008}
5009
5010std::pair<unsigned, unsigned>
5011UnrollHeuristicOp::getGenerateesODSOperandIndexAndLength() {
5012 return {0, 0};
5013}
5014
5015//===----------------------------------------------------------------------===//
5016// UnrollFullOp
5017//===----------------------------------------------------------------------===//
5018
5019void UnrollFullOp::build(::mlir::OpBuilder &odsBuilder,
5020 ::mlir::OperationState &odsState, ::mlir::Value cli) {
5021 odsState.addOperands(cli);
5022}
5023
5024void UnrollFullOp::print(OpAsmPrinter &p) {
5025 p << '(' << getApplyee() << ')';
5026
5027 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
5028}
5029
5030mlir::ParseResult UnrollFullOp::parse(::mlir::OpAsmParser &parser,
5032 auto cliType = CanonicalLoopInfoType::get(parser.getContext());
5033
5034 if (parser.parseLParen())
5035 return failure();
5036
5038 if (parser.parseOperand(applyee) ||
5039 parser.resolveOperand(applyee, cliType, result.operands))
5040 return failure();
5041
5042 if (parser.parseRParen())
5043 return failure();
5044
5045 // Optional output loop; full unrolling has none.
5046 if (!parser.parseOptionalArrow()) {
5047 if (parser.parseLParen() || parser.parseRParen())
5048 return failure();
5049 }
5050
5051 // Parse the optional attribute list.
5052 if (parser.parseOptionalAttrDict(result.attributes))
5053 return failure();
5054
5055 return mlir::success();
5056}
5057
5058std::pair<unsigned, unsigned>
5059UnrollFullOp::getApplyeesODSOperandIndexAndLength() {
5060 return getODSOperandIndexAndLength(odsIndex_applyee);
5061}
5062
5063std::pair<unsigned, unsigned>
5064UnrollFullOp::getGenerateesODSOperandIndexAndLength() {
5065 return {0, 0};
5066}
5067
5068LogicalResult UnrollFullOp::verify() {
5069 auto [create, gen, cons] = decodeCli(getApplyee());
5070 if (!gen)
5071 return emitOpError() << "applyee CLI has no generator";
5072
5073 // Full unrolling leaves no loop, so the trip count must be constant. Only
5074 // omp.canonical_loop states one.
5075 if (auto loop = dyn_cast<CanonicalLoopOp>(gen->getOwner())) {
5076 if (!matchPattern(loop.getTripCount(), m_Constant()))
5077 return emitOpError() << "applyee loop must have a constant trip count";
5078 }
5079
5080 return success();
5081}
5082
5083//===----------------------------------------------------------------------===//
5084// UnrollPartialOp
5085//===----------------------------------------------------------------------===//
5086
5087void UnrollPartialOp::build(::mlir::OpBuilder &odsBuilder,
5089 uint64_t unrollFactor) {
5090 odsState.addOperands(cli);
5091 Properties &props = odsState.getOrAddProperties<Properties>();
5092 props.unroll_factor = odsBuilder.getI64IntegerAttr(unrollFactor);
5093}
5094
5095void UnrollPartialOp::print(OpAsmPrinter &p) {
5096 p << '(' << getApplyee() << ')';
5097
5098 SmallVector<NamedAttribute> attrs((*this)->getDiscardableAttrs());
5099 attrs.emplace_back(getUnrollFactorAttrName(), getUnrollFactorAttr());
5100 llvm::sort(attrs);
5101 p.printOptionalAttrDict(attrs);
5102}
5103
5104mlir::ParseResult UnrollPartialOp::parse(::mlir::OpAsmParser &parser,
5106 auto cliType = CanonicalLoopInfoType::get(parser.getContext());
5107
5108 if (parser.parseLParen())
5109 return failure();
5110
5112 if (parser.parseOperand(applyee) ||
5113 parser.resolveOperand(applyee, cliType, result.operands))
5114 return failure();
5115
5116 if (parser.parseRParen())
5117 return failure();
5118
5119 // The unroll factor is carried by the `unroll_factor` attribute.
5120 if (parser.parseOptionalAttrDict(result.attributes))
5121 return failure();
5122
5123 return mlir::success();
5124}
5125
5126std::pair<unsigned, unsigned>
5127UnrollPartialOp::getApplyeesODSOperandIndexAndLength() {
5128 return getODSOperandIndexAndLength(odsIndex_applyee);
5129}
5130
5131std::pair<unsigned, unsigned>
5132UnrollPartialOp::getGenerateesODSOperandIndexAndLength() {
5133 return {0, 0};
5134}
5135
5136//===----------------------------------------------------------------------===//
5137// TileOp
5138//===----------------------------------------------------------------------===//
5139
5140static void printLoopTransformClis(OpAsmPrinter &p, TileOp op,
5141 OperandRange generatees,
5142 OperandRange applyees) {
5143 if (!generatees.empty())
5144 p << '(' << llvm::interleaved(generatees) << ')';
5145
5146 if (!applyees.empty())
5147 p << " <- (" << llvm::interleaved(applyees) << ')';
5148}
5149
5150static ParseResult parseLoopTransformClis(
5151 OpAsmParser &parser,
5154 if (parser.parseOptionalLess()) {
5155 // Syntax 1: generatees present
5156
5157 if (parser.parseOperandList(generateesOperands,
5159 return failure();
5160
5161 if (parser.parseLess())
5162 return failure();
5163 } else {
5164 // Syntax 2: generatees omitted
5165 }
5166
5167 // Parse `<-` (`<` has already been parsed)
5168 if (parser.parseMinus())
5169 return failure();
5170
5171 if (parser.parseOperandList(applyeesOperands,
5173 return failure();
5174
5175 return success();
5176}
5177
5178/// Check properties of the loop nest consisting of the transformation's
5179/// applyees:
5180/// 1. They are nested inside each other
5181/// 2. They are perfectly nested
5182/// (no code with side-effects in-between the loops)
5183/// 3. They are rectangular
5184/// (loop bounds are invariant in respect to the outer loops)
5185///
5186/// TODO: Generalize for LoopTransformationInterface.
5187static LogicalResult checkApplyeesNesting(TileOp op) {
5188 // Collect the loops from the nest
5189 bool isOnlyCanonLoops = true;
5191 for (Value applyee : op.getApplyees()) {
5192 auto [create, gen, cons] = decodeCli(applyee);
5193
5194 if (!gen)
5195 return op.emitOpError() << "applyee CLI has no generator";
5196
5197 auto loop = dyn_cast_or_null<CanonicalLoopOp>(gen->getOwner());
5198 canonLoops.push_back(loop);
5199 if (!loop)
5200 isOnlyCanonLoops = false;
5201 }
5202
5203 // FIXME: We currently can only verify non-rectangularity and perfect nest of
5204 // omp.canonical_loop.
5205 if (!isOnlyCanonLoops)
5206 return success();
5207
5208 DenseSet<Value> parentIVs;
5209 for (auto i : llvm::seq<int>(1, canonLoops.size())) {
5210 auto parentLoop = canonLoops[i - 1];
5211 auto loop = canonLoops[i];
5212
5213 if (parentLoop.getOperation() != loop.getOperation()->getParentOp())
5214 return op.emitOpError()
5215 << "tiled loop nest must be nested within each other";
5216
5217 parentIVs.insert(parentLoop.getInductionVar());
5218
5219 // Canonical loop must be perfectly nested, i.e. the body of the parent must
5220 // only contain the omp.canonical_loop of the nested loops, and
5221 // omp.terminator
5222 bool isPerfectlyNested = [&]() {
5223 auto &parentBody = parentLoop.getRegion();
5224 if (!parentBody.hasOneBlock())
5225 return false;
5226 auto &parentBlock = parentBody.getBlocks().front();
5227
5228 auto nestedLoopIt = parentBlock.begin();
5229 if (nestedLoopIt == parentBlock.end() ||
5230 (&*nestedLoopIt != loop.getOperation()))
5231 return false;
5232
5233 auto termIt = std::next(nestedLoopIt);
5234 if (termIt == parentBlock.end() || !isa<TerminatorOp>(termIt))
5235 return false;
5236
5237 if (std::next(termIt) != parentBlock.end())
5238 return false;
5239
5240 return true;
5241 }();
5242 if (!isPerfectlyNested)
5243 return op.emitOpError() << "tiled loop nest must be perfectly nested";
5244
5245 if (parentIVs.contains(loop.getTripCount()))
5246 return op.emitOpError() << "tiled loop nest must be rectangular";
5247 }
5248
5249 // TODO: The tile sizes must be computed before the loop, but checking this
5250 // requires dominance analysis. For instance:
5251 //
5252 // %canonloop = omp.new_cli
5253 // omp.canonical_loop(%canonloop) %iv : i32 in range(%tc) {
5254 // // write to %x
5255 // omp.terminator
5256 // }
5257 // %ts = llvm.load %x
5258 // omp.tile <- (%canonloop) sizes(%ts : i32)
5259
5260 return success();
5261}
5262
5263LogicalResult TileOp::verify() {
5264 if (getApplyees().empty())
5265 return emitOpError() << "must apply to at least one loop";
5266
5267 if (getSizes().size() != getApplyees().size())
5268 return emitOpError() << "there must be one tile size for each applyee";
5269
5270 if (!getGeneratees().empty() &&
5271 2 * getSizes().size() != getGeneratees().size())
5272 return emitOpError()
5273 << "expecting two times the number of generatees than applyees";
5274
5275 return checkApplyeesNesting(*this);
5276}
5277
5278std::pair<unsigned, unsigned> TileOp ::getApplyeesODSOperandIndexAndLength() {
5279 return getODSOperandIndexAndLength(odsIndex_applyees);
5280}
5281
5282std::pair<unsigned, unsigned> TileOp::getGenerateesODSOperandIndexAndLength() {
5283 return getODSOperandIndexAndLength(odsIndex_generatees);
5284}
5285
5286//===----------------------------------------------------------------------===//
5287// FuseOp
5288//===----------------------------------------------------------------------===//
5289
5290static void printLoopTransformClis(OpAsmPrinter &p, FuseOp op,
5291 OperandRange generatees,
5292 OperandRange applyees) {
5293 if (!generatees.empty())
5294 p << '(' << llvm::interleaved(generatees) << ')';
5295
5296 if (!applyees.empty())
5297 p << " <- (" << llvm::interleaved(applyees) << ')';
5298}
5299
5300LogicalResult FuseOp::verify() {
5301 if (getApplyees().size() < 2)
5302 return emitOpError() << "must apply to at least two loops";
5303
5304 if (getFirst().has_value() && getCount().has_value()) {
5305 int64_t first = getFirst().value();
5306 int64_t count = getCount().value();
5307 if ((unsigned)(first + count - 1) > getApplyees().size())
5308 return emitOpError() << "the numbers of applyees must be at least first "
5309 "minus one plus count attributes";
5310 if (!getGeneratees().empty() &&
5311 getGeneratees().size() != getApplyees().size() + 1 - count)
5312 return emitOpError() << "the number of generatees must be the number of "
5313 "aplyees plus one minus count";
5314
5315 } else {
5316 if (!getGeneratees().empty() && getGeneratees().size() != 1)
5317 return emitOpError()
5318 << "in a complete fuse the number of generatees must be exactly 1";
5319 }
5320 for (auto &&applyee : getApplyees()) {
5321 auto [create, gen, cons] = decodeCli(applyee);
5322
5323 if (!gen)
5324 return emitOpError() << "applyee CLI has no generator";
5325 auto loop = dyn_cast_or_null<CanonicalLoopOp>(gen->getOwner());
5326 if (!loop)
5327 return emitOpError()
5328 << "currently only supports omp.canonical_loop as applyee";
5329 }
5330 return success();
5331}
5332std::pair<unsigned, unsigned> FuseOp::getApplyeesODSOperandIndexAndLength() {
5333 return getODSOperandIndexAndLength(odsIndex_applyees);
5334}
5335
5336std::pair<unsigned, unsigned> FuseOp::getGenerateesODSOperandIndexAndLength() {
5337 return getODSOperandIndexAndLength(odsIndex_generatees);
5338}
5339
5340//===----------------------------------------------------------------------===//
5341// Critical construct (2.17.1)
5342//===----------------------------------------------------------------------===//
5343
5344void CriticalDeclareOp::build(OpBuilder &builder, OperationState &state,
5345 const CriticalDeclareOperands &clauses) {
5346 CriticalDeclareOp::build(builder, state, clauses.symName,
5347 clauses.symVisibility, clauses.hint);
5348}
5349
5350LogicalResult CriticalDeclareOp::verify() {
5351 return verifySynchronizationHint(*this, getHint());
5352}
5353
5354void CriticalOp::build(OpBuilder &builder, OperationState &state,
5355 FlatSymbolRefAttr name,
5356 function_ref<void(OpBuilder &, Location)> bodyBuilder) {
5357 assert(bodyBuilder && "expected a body builder callback");
5358 build(builder, state, name);
5359 OpBuilder::InsertionGuard guard(builder);
5360 builder.createBlock(state.regions.front().get());
5361 bodyBuilder(builder, state.location);
5362}
5363
5364LogicalResult CriticalOp::verify() {
5365 SymbolRefAttr currentName = getNameAttr();
5366
5367 CriticalOp parentCritical = (*this)->getParentOfType<CriticalOp>();
5368
5369 while (parentCritical) {
5370 SymbolRefAttr parentName = parentCritical.getNameAttr();
5371
5372 if (currentName == parentName) {
5373 if (currentName) {
5374 return emitOpError() << "cannot be nested inside another omp.critical "
5375 "region with the same name ("
5376 << currentName << ")";
5377 } else {
5378 return emitOpError() << "cannot be nested inside another unnamed "
5379 "omp.critical region";
5380 }
5381 }
5382
5383 parentCritical = parentCritical->getParentOfType<CriticalOp>();
5384 }
5385
5386 return success();
5387}
5388
5389LogicalResult CriticalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
5390 if (getNameAttr()) {
5391 SymbolRefAttr symbolRef = getNameAttr();
5392 auto decl = symbolTable.lookupNearestSymbolFrom<CriticalDeclareOp>(
5393 *this, symbolRef);
5394 if (!decl) {
5395 return emitOpError() << "expected symbol reference " << symbolRef
5396 << " to point to a critical declaration";
5397 }
5398 }
5399
5400 return success();
5401}
5402
5403//===----------------------------------------------------------------------===//
5404// Spec 5.1: Error directive (2.5.4)
5405//===----------------------------------------------------------------------===//
5406
5407LogicalResult ErrorOp::verify() {
5408 if (getMessage() && getMessageExpr())
5409 return emitOpError() << "the message must be provided either as a constant "
5410 "`message` attribute or as a `message_expr` "
5411 "operand, but not both";
5412 return success();
5413}
5414
5415//===----------------------------------------------------------------------===//
5416// Ordered construct
5417//===----------------------------------------------------------------------===//
5418
5419static LogicalResult verifyOrderedParent(Operation &op) {
5420 bool hasRegion = op.getNumRegions() > 0;
5421 auto loopOp = op.getParentOfType<LoopNestOp>();
5422 if (!loopOp) {
5423 if (hasRegion)
5424 return success();
5425
5426 // TODO: Consider if this needs to be the case only for the standalone
5427 // variant of the ordered construct.
5428 return op.emitOpError() << "must be nested inside of a loop";
5429 }
5430
5431 Operation *wrapper = loopOp->getParentOp();
5432 if (auto wsloopOp = dyn_cast<WsloopOp>(wrapper)) {
5433 IntegerAttr orderedAttr = wsloopOp.getOrderedAttr();
5434 if (!orderedAttr)
5435 return op.emitOpError() << "the enclosing worksharing-loop region must "
5436 "have an ordered clause";
5437
5438 if (hasRegion && orderedAttr.getInt() != 0)
5439 return op.emitOpError() << "the enclosing loop's ordered clause must not "
5440 "have a parameter present";
5441
5442 if (!hasRegion && orderedAttr.getInt() == 0)
5443 return op.emitOpError() << "the enclosing loop's ordered clause must "
5444 "have a parameter present";
5445 } else if (!isa<SimdOp>(wrapper)) {
5446 return op.emitOpError() << "must be nested inside of a worksharing, simd "
5447 "or worksharing simd loop";
5448 }
5449 return success();
5450}
5451
5452void OrderedOp::build(OpBuilder &builder, OperationState &state,
5453 const OrderedOperands &clauses) {
5454 OrderedOp::build(builder, state, clauses.doacrossDependType,
5455 clauses.doacrossNumLoops, clauses.doacrossDependVars);
5456}
5457
5458LogicalResult OrderedOp::verify() {
5459 if (failed(verifyOrderedParent(**this)))
5460 return failure();
5461
5462 auto wrapper = (*this)->getParentOfType<WsloopOp>();
5463 if (!wrapper || *wrapper.getOrdered() != *getDoacrossNumLoops())
5464 return emitOpError() << "number of variables in depend clause does not "
5465 << "match number of iteration variables in the "
5466 << "doacross loop";
5467
5468 return success();
5469}
5470
5471void OrderedRegionOp::build(OpBuilder &builder, OperationState &state,
5472 const OrderedRegionOperands &clauses) {
5473 OrderedRegionOp::build(builder, state, clauses.parLevelSimd);
5474}
5475
5476LogicalResult OrderedRegionOp::verify() { return verifyOrderedParent(**this); }
5477
5478//===----------------------------------------------------------------------===//
5479// TaskwaitOp
5480//===----------------------------------------------------------------------===//
5481
5482void TaskwaitOp::build(OpBuilder &builder, OperationState &state,
5483 const TaskwaitOperands &clauses) {
5484 // TODO Store clauses in op: depend_iterated_kinds, depend_iterated, nowait.
5485 MLIRContext *ctx = builder.getContext();
5486 TaskwaitOp::build(
5487 builder, state,
5488 /*depend_kinds=*/makeArrayAttr(ctx, clauses.dependKinds),
5489 /*depend_vars=*/clauses.dependVars,
5490 /*depend_iterated_kinds=*/makeArrayAttr(ctx, clauses.dependIteratedKinds),
5491 /*depend_iterated=*/ValueRange(clauses.dependIterated),
5492 /*nowait=*/clauses.nowait);
5493}
5494
5495//===----------------------------------------------------------------------===//
5496// Verifier for AtomicReadOp
5497//===----------------------------------------------------------------------===//
5498
5499LogicalResult AtomicReadOp::verify() {
5500 if (verifyCommon().failed())
5501 return mlir::failure();
5502
5503 int64_t version = 50;
5504 if (auto moduleOp = getOperation()->getParentOfType<ModuleOp>())
5505 if (Attribute verAttr = moduleOp->getDiscardableAttr("omp.version"))
5506 version = llvm::cast<VersionAttr>(verAttr).getVersion();
5507
5508 if (auto mo = getMemoryOrder()) {
5509 if (*mo == ClauseMemoryOrderKind::Release) {
5510 return emitError("memory-order must not be release for atomic reads");
5511 }
5512 if (*mo == ClauseMemoryOrderKind::Acq_rel) {
5513 // acq_rel is prohibited on read only in OpenMP 5.0; allowed in 5.1+.
5514 if (version < 51)
5515 return emitError("memory-order must not be acq_rel for atomic reads");
5516 }
5517 }
5518 return verifySynchronizationHint(*this, getHint());
5519}
5520
5521//===----------------------------------------------------------------------===//
5522// Verifier for AtomicWriteOp
5523//===----------------------------------------------------------------------===//
5524
5525LogicalResult AtomicWriteOp::verify() {
5526 if (verifyCommon().failed())
5527 return mlir::failure();
5528
5529 int64_t version = 50;
5530 if (auto moduleOp = getOperation()->getParentOfType<ModuleOp>())
5531 if (Attribute verAttr = moduleOp->getDiscardableAttr("omp.version"))
5532 version = llvm::cast<VersionAttr>(verAttr).getVersion();
5533
5534 if (auto mo = getMemoryOrder()) {
5535 if (*mo == ClauseMemoryOrderKind::Acquire) {
5536 return emitError("memory-order must not be acquire for atomic writes");
5537 }
5538 if (*mo == ClauseMemoryOrderKind::Acq_rel) {
5539 // acq_rel is prohibited on write only in OpenMP 5.0; allowed in 5.1+.
5540 if (version < 51)
5541 return emitError("memory-order must not be acq_rel for atomic writes");
5542 }
5543 }
5544 return verifySynchronizationHint(*this, getHint());
5545}
5546
5547//===----------------------------------------------------------------------===//
5548// Verifier for AtomicUpdateOp
5549//===----------------------------------------------------------------------===//
5550
5551LogicalResult AtomicUpdateOp::canonicalize(AtomicUpdateOp op,
5552 PatternRewriter &rewriter) {
5553 if (op.isNoOp()) {
5554 rewriter.eraseOp(op);
5555 return success();
5556 }
5557 if (Value writeVal = op.getWriteOpVal()) {
5558 rewriter.replaceOpWithNewOp<AtomicWriteOp>(
5559 op, op.getX(), writeVal, op.getHintAttr(), op.getMemoryOrderAttr());
5560 return success();
5561 }
5562 return failure();
5563}
5564
5565LogicalResult AtomicUpdateOp::verify() {
5566 if (verifyCommon().failed())
5567 return mlir::failure();
5568
5569 int64_t version = 50;
5570 if (auto moduleOp = getOperation()->getParentOfType<ModuleOp>())
5571 if (Attribute verAttr = moduleOp->getDiscardableAttr("omp.version"))
5572 version = llvm::cast<VersionAttr>(verAttr).getVersion();
5573
5574 if (auto mo = getMemoryOrder()) {
5575 if (*mo == ClauseMemoryOrderKind::Acq_rel ||
5576 *mo == ClauseMemoryOrderKind::Acquire) {
5577 // This restriction applies only to OpenMP 5.0; removed in 5.1.
5578 if (version < 51)
5579 return emitError(
5580 "memory-order must not be acq_rel or acquire for atomic updates");
5581 }
5582 }
5583
5584 return verifySynchronizationHint(*this, getHint());
5585}
5586
5587LogicalResult AtomicUpdateOp::verifyRegions() { return verifyRegionsCommon(); }
5588
5589//===----------------------------------------------------------------------===//
5590// Verifier for AtomicCaptureOp
5591//===----------------------------------------------------------------------===//
5592
5593AtomicReadOp AtomicCaptureOp::getAtomicReadOp() {
5594 if (auto op = dyn_cast<AtomicReadOp>(getFirstOp()))
5595 return op;
5596 return dyn_cast<AtomicReadOp>(getSecondOp());
5597}
5598
5599AtomicWriteOp AtomicCaptureOp::getAtomicWriteOp() {
5600 if (auto op = dyn_cast<AtomicWriteOp>(getFirstOp()))
5601 return op;
5602 return dyn_cast<AtomicWriteOp>(getSecondOp());
5603}
5604
5605AtomicUpdateOp AtomicCaptureOp::getAtomicUpdateOp() {
5606 if (auto op = dyn_cast<AtomicUpdateOp>(getFirstOp()))
5607 return op;
5608 return dyn_cast<AtomicUpdateOp>(getSecondOp());
5609}
5610
5611AtomicCompareOp AtomicCaptureOp::getAtomicCompareOp() {
5612 if (auto op = dyn_cast<AtomicCompareOp>(getFirstOp()))
5613 return op;
5614 return dyn_cast<AtomicCompareOp>(getSecondOp());
5615}
5616
5617LogicalResult AtomicCaptureOp::verify() {
5618 return verifySynchronizationHint(*this, getHint());
5619}
5620
5621LogicalResult AtomicCaptureOp::verifyRegions() {
5622 if (verifyRegionsCommon().failed())
5623 return mlir::failure();
5624
5625 if (getFirstOp()->getInherentAttr("hint").value_or(Attribute{}) ||
5626 getSecondOp()->getInherentAttr("hint").value_or(Attribute{}))
5627 return emitOpError(
5628 "operations inside capture region must not have hint clause");
5629
5630 if (getFirstOp()->getInherentAttr("memory_order").value_or(Attribute{}) ||
5631 getSecondOp()->getInherentAttr("memory_order").value_or(Attribute{}))
5632 return emitOpError(
5633 "operations inside capture region must not have memory_order clause");
5634 return success();
5635}
5636
5637//===----------------------------------------------------------------------===//
5638// AtomicCompareOp
5639//===----------------------------------------------------------------------===//
5640
5641LogicalResult AtomicCompareOp::verify() {
5642 if (verifyCommon().failed())
5643 return mlir::failure();
5644 // OpenMP 5.2 [15.8.3]: the fail clause argument must be one of seq_cst,
5645 // acquire or relaxed ('release' and 'acq_rel' are not valid failure
5646 // orderings and map to invalid cmpxchg failure orderings).
5647 if (auto failOrder = getFailMemoryOrder()) {
5648 if (*failOrder != ClauseMemoryOrderKind::Seq_cst &&
5649 *failOrder != ClauseMemoryOrderKind::Acquire &&
5650 *failOrder != ClauseMemoryOrderKind::Relaxed)
5651 return emitOpError(
5652 "fail_memory_order must be 'seq_cst', 'acquire' or 'relaxed'");
5653 }
5654 return verifySynchronizationHint(*this, getHint());
5655}
5656
5657LogicalResult AtomicCompareOp::verifyRegions() {
5658 if (verifyRegionsCommon().failed())
5659 return mlir::failure();
5660
5661 if (verifyOperator().failed())
5662 return mlir::failure();
5663
5664 Block &block = getRegion().front();
5665
5666 Operation *terminator = block.getTerminator();
5667 if (!terminator || !isa<YieldOp>(terminator))
5668 return emitOpError("region must be terminated with omp.yield");
5669
5670 return success();
5671}
5672
5673//===----------------------------------------------------------------------===//
5674// ThreadprivateOp
5675//===----------------------------------------------------------------------===//
5676
5677void ThreadprivateOp::getEffects(
5679 &effects) {
5680
5681 // Read the primary thread's copy and write to the thread-local versions.
5682 effects.emplace_back(MemoryEffects::Read::get(), &getSymAddrMutable());
5683 effects.emplace_back(MemoryEffects::Write::get(),
5684 cast<OpResult>(getTlsAddr()));
5685 // Threadprivate runtime bookeeping may or may not allocate new storage for
5686 // caches or thread-local storage, do not attach this effect to an address to
5687 // avoid incorrectly implying it is new storage.
5688 effects.emplace_back(MemoryEffects::Allocate::get());
5689}
5690//===----------------------------------------------------------------------===//
5691// CancelOp
5692//===----------------------------------------------------------------------===//
5693
5694void CancelOp::build(OpBuilder &builder, OperationState &state,
5695 const CancelOperands &clauses) {
5696 CancelOp::build(builder, state, clauses.cancelDirective, clauses.ifExpr);
5697}
5698
5700 Operation *parent = thisOp->getParentOp();
5701 while (parent) {
5702 if (parent->getDialect() == thisOp->getDialect())
5703 return parent;
5704 parent = parent->getParentOp();
5705 }
5706 return nullptr;
5707}
5708
5709LogicalResult CancelOp::verify() {
5710 ClauseCancellationConstructType cct = getCancelDirective();
5711 // The next OpenMP operation in the chain of parents
5712 Operation *structuralParent = getParentInSameDialect((*this).getOperation());
5713 if (!structuralParent)
5714 return emitOpError() << "Orphaned cancel construct";
5715
5716 if ((cct == ClauseCancellationConstructType::Parallel) &&
5717 !mlir::isa<ParallelOp>(structuralParent)) {
5718 return emitOpError() << "cancel parallel must appear "
5719 << "inside a parallel region";
5720 }
5721 if (cct == ClauseCancellationConstructType::Loop) {
5722 // structural parent will be omp.loop_nest, directly nested inside
5723 // omp.wsloop
5724 auto wsloopOp = mlir::dyn_cast<WsloopOp>(structuralParent->getParentOp());
5725
5726 if (!wsloopOp) {
5727 return emitOpError()
5728 << "cancel loop must appear inside a worksharing-loop region";
5729 }
5730 if (wsloopOp.getNowaitAttr()) {
5731 return emitError() << "A worksharing construct that is canceled "
5732 << "must not have a nowait clause";
5733 }
5734 if (wsloopOp.getOrderedAttr()) {
5735 return emitError() << "A worksharing construct that is canceled "
5736 << "must not have an ordered clause";
5737 }
5738
5739 } else if (cct == ClauseCancellationConstructType::Sections) {
5740 // structural parent will be an omp.section, directly nested inside
5741 // omp.sections
5742 auto sectionsOp =
5743 mlir::dyn_cast<SectionsOp>(structuralParent->getParentOp());
5744 if (!sectionsOp) {
5745 return emitOpError() << "cancel sections must appear "
5746 << "inside a sections region";
5747 }
5748 if (sectionsOp.getNowait()) {
5749 return emitError() << "A sections construct that is canceled "
5750 << "must not have a nowait clause";
5751 }
5752 }
5753 if ((cct == ClauseCancellationConstructType::Taskgroup) &&
5754 (!mlir::isa<omp::TaskOp>(structuralParent) &&
5755 !mlir::isa<omp::TaskloopWrapperOp>(structuralParent->getParentOp()))) {
5756 return emitOpError() << "cancel taskgroup must appear "
5757 << "inside a task region";
5758 }
5759 return success();
5760}
5761
5762//===----------------------------------------------------------------------===//
5763// CancellationPointOp
5764//===----------------------------------------------------------------------===//
5765
5766void CancellationPointOp::build(OpBuilder &builder, OperationState &state,
5767 const CancellationPointOperands &clauses) {
5768 CancellationPointOp::build(builder, state, clauses.cancelDirective);
5769}
5770
5771LogicalResult CancellationPointOp::verify() {
5772 ClauseCancellationConstructType cct = getCancelDirective();
5773 // The next OpenMP operation in the chain of parents
5774 Operation *structuralParent = getParentInSameDialect((*this).getOperation());
5775 if (!structuralParent)
5776 return emitOpError() << "Orphaned cancellation point";
5777
5778 if ((cct == ClauseCancellationConstructType::Parallel) &&
5779 !mlir::isa<ParallelOp>(structuralParent)) {
5780 return emitOpError() << "cancellation point parallel must appear "
5781 << "inside a parallel region";
5782 }
5783 // Strucutal parent here will be an omp.loop_nest. Get the parent of that to
5784 // find the wsloop
5785 if ((cct == ClauseCancellationConstructType::Loop) &&
5786 !mlir::isa<WsloopOp>(structuralParent->getParentOp())) {
5787 return emitOpError() << "cancellation point loop must appear "
5788 << "inside a worksharing-loop region";
5789 }
5790 if ((cct == ClauseCancellationConstructType::Sections) &&
5791 !mlir::isa<omp::SectionOp>(structuralParent)) {
5792 return emitOpError() << "cancellation point sections must appear "
5793 << "inside a sections region";
5794 }
5795 if ((cct == ClauseCancellationConstructType::Taskgroup) &&
5796 (!mlir::isa<omp::TaskOp>(structuralParent) &&
5797 !mlir::isa<omp::TaskloopWrapperOp>(structuralParent->getParentOp()))) {
5798 return emitOpError() << "cancellation point taskgroup must appear "
5799 << "inside a task region";
5800 }
5801 return success();
5802}
5803
5804//===----------------------------------------------------------------------===//
5805// MapBoundsOp
5806//===----------------------------------------------------------------------===//
5807
5808LogicalResult MapBoundsOp::verify() {
5809 auto extent = getExtent();
5810 auto upperbound = getUpperBound();
5811 if (!extent && !upperbound)
5812 return emitError("expected extent or upperbound.");
5813 return success();
5814}
5815
5816void PrivateClauseOp::build(OpBuilder &odsBuilder, OperationState &odsState,
5817 TypeRange /*result_types*/, StringAttr symName,
5818 TypeAttr type) {
5819 PrivateClauseOp::build(
5820 odsBuilder, odsState, symName, /*sym_visibility=*/nullptr, type,
5821 DataSharingClauseTypeAttr::get(odsBuilder.getContext(),
5822 DataSharingClauseType::Private));
5823}
5824
5825LogicalResult PrivateClauseOp::verifyRegions() {
5826 Type argType = getArgType();
5827 auto verifyTerminator = [&](Operation *terminator, bool yieldsValue,
5828 bool yieldsAnyType) -> LogicalResult {
5829 if (!terminator->getBlock()->getSuccessors().empty())
5830 return success();
5831
5832 if (!llvm::isa<YieldOp>(terminator))
5833 return mlir::emitError(terminator->getLoc())
5834 << "expected exit block terminator to be an `omp.yield` op.";
5835
5836 YieldOp yieldOp = llvm::cast<YieldOp>(terminator);
5837 TypeRange yieldedTypes = yieldOp.getResults().getTypes();
5838
5839 if (!yieldsValue) {
5840 if (yieldedTypes.empty())
5841 return success();
5842
5843 return mlir::emitError(terminator->getLoc())
5844 << "Did not expect any values to be yielded.";
5845 }
5846
5847 if (yieldedTypes.size() == 1 &&
5848 (yieldsAnyType || yieldedTypes.front() == argType))
5849 return success();
5850
5851 auto error = mlir::emitError(yieldOp.getLoc())
5852 << "Invalid yielded value. Expected ";
5853 if (yieldsAnyType)
5854 error << "a single value";
5855 else
5856 error << "type: " << argType;
5857 error << ", got: ";
5858
5859 if (yieldedTypes.empty())
5860 error << "None";
5861 else
5862 error << yieldedTypes;
5863
5864 return error;
5865 };
5866
5867 auto verifyRegion = [&](Region &region, unsigned expectedNumArgs,
5868 StringRef regionName, bool yieldsValue,
5869 bool yieldsAnyType = false) -> LogicalResult {
5870 assert(!region.empty());
5871
5872 if (region.getNumArguments() != expectedNumArgs)
5873 return mlir::emitError(region.getLoc())
5874 << "`" << regionName << "`: " << "expected " << expectedNumArgs
5875 << " region arguments, got: " << region.getNumArguments();
5876
5877 for (Block &block : region) {
5878 // MLIR will verify the absence of the terminator for us.
5879 if (!block.mightHaveTerminator())
5880 continue;
5881
5882 if (failed(verifyTerminator(block.getTerminator(), yieldsValue,
5883 yieldsAnyType)))
5884 return failure();
5885 }
5886
5887 return success();
5888 };
5889
5890 // Ensure all of the region arguments have the same type
5891 for (Region *region : getRegions())
5892 for (Type ty : region->getArgumentTypes())
5893 if (ty != argType)
5894 return emitError() << "Region argument type mismatch: got " << ty
5895 << " expected " << argType << ".";
5896
5897 mlir::Region &initRegion = getInitRegion();
5898 if (!initRegion.empty() &&
5899 failed(verifyRegion(getInitRegion(), /*expectedNumArgs=*/2, "init",
5900 /*yieldsValue=*/true)))
5901 return failure();
5902
5903 DataSharingClauseType dsType = getDataSharingType();
5904
5905 if (dsType == DataSharingClauseType::Private && !getCopyRegion().empty())
5906 return emitError("`private` clauses do not require a `copy` region.");
5907
5908 if (dsType == DataSharingClauseType::FirstPrivate && getCopyRegion().empty())
5909 return emitError(
5910 "`firstprivate` clauses require at least a `copy` region.");
5911
5912 if (dsType == DataSharingClauseType::FirstPrivate &&
5913 failed(verifyRegion(getCopyRegion(), /*expectedNumArgs=*/2, "copy",
5914 /*yieldsValue=*/true)))
5915 return failure();
5916
5917 if (dsType == DataSharingClauseType::Linear && !getCopyRegion().empty())
5918 return emitError("`linear` clauses do not require a `copy` region.");
5919
5920 if (!getDataAddressRegion().empty()) {
5921 if (dsType != DataSharingClauseType::Linear)
5922 return emitError(
5923 "only `linear` clauses can have a `data_address` region.");
5924 if (failed(verifyRegion(getDataAddressRegion(), /*expectedNumArgs=*/1,
5925 "data_address", /*yieldsValue=*/true,
5926 /*yieldsAnyType=*/true)))
5927 return failure();
5928 }
5929
5930 if (!getDeallocRegion().empty() &&
5931 failed(verifyRegion(getDeallocRegion(), /*expectedNumArgs=*/1, "dealloc",
5932 /*yieldsValue=*/false)))
5933 return failure();
5934
5935 return success();
5936}
5937
5938//===----------------------------------------------------------------------===//
5939// Spec 5.2: Masked construct (10.5)
5940//===----------------------------------------------------------------------===//
5941
5942void MaskedOp::build(OpBuilder &builder, OperationState &state,
5943 const MaskedOperands &clauses) {
5944 MaskedOp::build(builder, state, clauses.filteredThreadId);
5945}
5946
5947//===----------------------------------------------------------------------===//
5948// Spec 5.2: Dispatch construct (7.6)
5949//===----------------------------------------------------------------------===//
5950
5951void DispatchOp::build(OpBuilder &builder, OperationState &state,
5952 const DispatchOperands &clauses) {
5953 DispatchOp::build(builder, state, clauses.nocontext, clauses.novariants,
5954 clauses.nowait);
5955}
5956
5957//===----------------------------------------------------------------------===//
5958// Spec 5.2: Scan construct (5.6)
5959//===----------------------------------------------------------------------===//
5960
5961void ScanOp::build(OpBuilder &builder, OperationState &state,
5962 const ScanOperands &clauses) {
5963 ScanOp::build(builder, state, clauses.inclusiveVars, clauses.exclusiveVars);
5964}
5965
5966LogicalResult ScanOp::verify() {
5967 if (hasExclusiveVars() == hasInclusiveVars())
5968 return emitError(
5969 "Exactly one of EXCLUSIVE or INCLUSIVE clause is expected");
5970 if (WsloopOp parentWsLoopOp = (*this)->getParentOfType<WsloopOp>()) {
5971 if (parentWsLoopOp.hasReductionModifier(ReductionModifier::inscan))
5972 return success();
5973 }
5974 if (SimdOp parentSimdOp = (*this)->getParentOfType<SimdOp>()) {
5975 if (parentSimdOp.hasReductionModifier(ReductionModifier::inscan))
5976 return success();
5977 }
5978 return emitError("SCAN directive needs to be enclosed within a parent "
5979 "worksharing loop construct or SIMD construct with INSCAN "
5980 "reduction modifier");
5981}
5982
5983/// Verifies align clause in allocate directive
5984LogicalResult verifyAlignment(Operation &op,
5985 std::optional<uint64_t> alignment) {
5986 if (alignment.has_value()) {
5987 if ((alignment.value() != 0) && !llvm::has_single_bit(alignment.value()))
5988 return op.emitError()
5989 << "ALIGN value : " << alignment.value() << " must be power of 2";
5990 }
5991 return success();
5992}
5993
5994LogicalResult AllocateDirOp::verify() {
5995 return verifyAlignment(*getOperation(), getAlign());
5996}
5997
5998//===----------------------------------------------------------------------===//
5999// AllocSharedMemOp
6000//===----------------------------------------------------------------------===//
6001
6002LogicalResult AllocSharedMemOp::verify() {
6003 return verifyAlignment(*getOperation(), getMemAlignment());
6004}
6005
6006//===----------------------------------------------------------------------===//
6007// FreeSharedMemOp
6008//===----------------------------------------------------------------------===//
6009
6010LogicalResult FreeSharedMemOp::verify() {
6011 return verifyAlignment(*getOperation(), getMemAlignment());
6012}
6013
6014//===----------------------------------------------------------------------===//
6015// WorkdistributeOp
6016//===----------------------------------------------------------------------===//
6017
6018LogicalResult WorkdistributeOp::verify() {
6019 if (isCombined())
6020 return emitOpError() << "cannot be a non-innermost combined construct leaf";
6021
6022 // Check that region exists and is not empty
6023 Region &region = getRegion();
6024 if (region.empty())
6025 return emitOpError("region cannot be empty");
6026 // Verify single entry point.
6027 Block &entryBlock = region.front();
6028 if (entryBlock.empty())
6029 return emitOpError("region must contain a structured block");
6030 // Verify single exit point.
6031 bool hasTerminator = false;
6032 for (Block &block : region) {
6033 if (isa<TerminatorOp>(block.back())) {
6034 if (hasTerminator) {
6035 return emitOpError("region must have exactly one terminator");
6036 }
6037 hasTerminator = true;
6038 }
6039 }
6040 if (!hasTerminator) {
6041 return emitOpError("region must be terminated with omp.terminator");
6042 }
6043 auto walkResult = region.walk([&](Operation *op) -> WalkResult {
6044 // No implicit barrier at end
6045 if (isa<BarrierOp>(op)) {
6046 return emitOpError(
6047 "explicit barriers are not allowed in workdistribute region");
6048 }
6049 // Check for invalid nested constructs
6050 if (isa<ParallelOp>(op)) {
6051 return emitOpError(
6052 "nested parallel constructs not allowed in workdistribute");
6053 }
6054 if (isa<TeamsOp>(op)) {
6055 return emitOpError(
6056 "nested teams constructs not allowed in workdistribute");
6057 }
6058 return WalkResult::advance();
6059 });
6060 if (walkResult.wasInterrupted())
6061 return failure();
6062
6063 Operation *parentOp = (*this)->getParentOp();
6064 if (!llvm::dyn_cast<TeamsOp>(parentOp))
6065 return emitOpError("workdistribute must be nested under teams");
6066 return success();
6067}
6068
6069//===----------------------------------------------------------------------===//
6070// Declare simd [7.7]
6071//===----------------------------------------------------------------------===//
6072
6073LogicalResult DeclareSimdOp::verify() {
6074 // Must be nested inside a function-like op
6075 auto func =
6076 dyn_cast_if_present<mlir::FunctionOpInterface>((*this)->getParentOp());
6077 if (!func)
6078 return emitOpError() << "must be nested inside a function";
6079
6080 if (getInbranch() && getNotinbranch())
6081 return emitOpError("cannot have both 'inbranch' and 'notinbranch'");
6082
6083 if (failed(verifyLinearModifiers(*this, getLinearModifiers(), getLinearVars(),
6084 /*isDeclareSimd=*/true)))
6085 return failure();
6086
6087 if (getLinearSyms())
6088 return emitOpError("linear privatizers are not allowed");
6089
6090 return verifyAlignedClause(*this, getAlignments(), getAlignedVars());
6091}
6092
6093void DeclareSimdOp::build(OpBuilder &odsBuilder, OperationState &odsState,
6094 const DeclareSimdOperands &clauses) {
6095 MLIRContext *ctx = odsBuilder.getContext();
6096 DeclareSimdOp::build(
6097 odsBuilder, odsState, clauses.alignedVars,
6098 makeArrayAttr(ctx, clauses.alignments), clauses.inbranch,
6099 clauses.linearVars, clauses.linearStepVars, clauses.linearVarTypes,
6100 clauses.linearModifiers, makeArrayAttr(ctx, clauses.linearSyms),
6101 clauses.notinbranch, clauses.simdlen, clauses.uniformVars);
6102}
6103
6104//===----------------------------------------------------------------------===//
6105// Parser and printer for Uniform Clause
6106//===----------------------------------------------------------------------===//
6107
6108/// uniform ::= `uniform` `(` uniform-list `)`
6109/// uniform-list := uniform-val (`,` uniform-val)*
6110/// uniform-val := ssa-id `:` type
6111static ParseResult
6114 SmallVectorImpl<Type> &uniformTypes) {
6115 return parser.parseCommaSeparatedList([&]() -> mlir::ParseResult {
6116 if (parser.parseOperand(uniformVars.emplace_back()) ||
6117 parser.parseColonType(uniformTypes.emplace_back()))
6118 return mlir::failure();
6119 return mlir::success();
6120 });
6121}
6122
6123/// Print Uniform Clauses
6125 ValueRange uniformVars, TypeRange uniformTypes) {
6126 for (unsigned i = 0; i < uniformVars.size(); ++i) {
6127 if (i != 0)
6128 p << ", ";
6129 p << uniformVars[i] << " : " << uniformTypes[i];
6130 }
6131}
6132
6133//===----------------------------------------------------------------------===//
6134// Parser and printer for Affinity Clause
6135//===----------------------------------------------------------------------===//
6136
6137static ParseResult parseAffinityClause(
6138 OpAsmParser &parser,
6141 SmallVectorImpl<Type> &iteratedTypes,
6142 SmallVectorImpl<Type> &affinityVarTypes) {
6143 if (failed(parseSplitIteratedList(
6144 parser, iterated, iteratedTypes, affinityVars, affinityVarTypes,
6145 /*parsePrefix=*/[&]() -> ParseResult { return success(); })))
6146 return failure();
6147 return success();
6148}
6149
6151 ValueRange iterated, ValueRange affinityVars,
6152 TypeRange iteratedTypes,
6153 TypeRange affinityVarTypes) {
6154 auto nop = [&](Value, Type) {};
6155 printSplitIteratedList(p, iterated, iteratedTypes, affinityVars,
6156 affinityVarTypes,
6157 /*plain prefix*/ nop,
6158 /*iterated prefix*/ nop);
6159}
6160
6161//===----------------------------------------------------------------------===//
6162// Parser, printer, and verifier for Iterator modifier
6163//===----------------------------------------------------------------------===//
6164
6165static ParseResult
6170 SmallVectorImpl<Type> &lbTypes,
6171 SmallVectorImpl<Type> &ubTypes,
6172 SmallVectorImpl<Type> &stepTypes) {
6173
6174 llvm::SMLoc ivLoc = parser.getCurrentLocation();
6176
6177 // Parse induction variables: %i : i32, %j : i32
6178 if (parser.parseCommaSeparatedList([&]() -> ParseResult {
6179 OpAsmParser::Argument &arg = ivArgs.emplace_back();
6180 if (parser.parseArgument(arg))
6181 return failure();
6182
6183 // Optional type, default to Index if not provided
6184 if (succeeded(parser.parseOptionalColon())) {
6185 if (parser.parseType(arg.type))
6186 return failure();
6187 } else {
6188 arg.type = parser.getBuilder().getIndexType();
6189 }
6190 return success();
6191 }))
6192 return failure();
6193
6194 // ) = (
6195 if (parser.parseRParen() || parser.parseEqual() || parser.parseLParen())
6196 return failure();
6197
6198 // Parse Ranges: (%lb to %ub step %st, ...)
6199 if (parser.parseCommaSeparatedList([&]() -> ParseResult {
6200 OpAsmParser::UnresolvedOperand lb, ub, st;
6201 if (parser.parseOperand(lb) || parser.parseKeyword("to") ||
6202 parser.parseOperand(ub) || parser.parseKeyword("step") ||
6203 parser.parseOperand(st))
6204 return failure();
6205
6206 lbs.push_back(lb);
6207 ubs.push_back(ub);
6208 steps.push_back(st);
6209 return success();
6210 }))
6211 return failure();
6212
6213 if (parser.parseRParen())
6214 return failure();
6215
6216 if (ivArgs.size() != lbs.size())
6217 return parser.emitError(ivLoc)
6218 << "mismatch: " << ivArgs.size() << " variables but " << lbs.size()
6219 << " ranges";
6220
6221 for (auto &arg : ivArgs) {
6222 lbTypes.push_back(arg.type);
6223 ubTypes.push_back(arg.type);
6224 stepTypes.push_back(arg.type);
6225 }
6226
6227 return parser.parseRegion(region, ivArgs);
6228}
6229
6231 ValueRange lbs, ValueRange ubs,
6233 TypeRange) {
6234 Block &entry = region.front();
6235
6236 for (unsigned i = 0, e = entry.getNumArguments(); i < e; ++i) {
6237 if (i != 0)
6238 p << ", ";
6239 p.printRegionArgument(entry.getArgument(i));
6240 }
6241 p << ") = (";
6242
6243 // (%lb0 to %ub0 step %step0, %lb1 to %ub1 step %step1, ...)
6244 for (unsigned i = 0, e = lbs.size(); i < e; ++i) {
6245 if (i)
6246 p << ", ";
6247 p << lbs[i] << " to " << ubs[i] << " step " << steps[i];
6248 }
6249 p << ") ";
6250
6251 p.printRegion(region, /*printEntryBlockArgs=*/false,
6252 /*printBlockTerminators=*/true);
6253}
6254
6255YieldOp IteratorOp::getYieldOp() {
6256 YieldOp yield;
6257 for (Block &block : getRegion()) {
6258 auto blockYield =
6259 dyn_cast_if_present<YieldOp>(block.empty() ? nullptr : &block.back());
6260 if (!blockYield)
6261 continue;
6262 if (yield)
6263 return {};
6264 yield = blockYield;
6265 }
6266 return yield;
6267}
6268
6269LogicalResult IteratorOp::verify() {
6270 auto iteratedTy = llvm::dyn_cast<omp::IteratedType>(getIterated().getType());
6271 if (!iteratedTy)
6272 return emitOpError() << "result must be omp.iterated<entry_ty>";
6273
6274 Block::BlockArgListType ivs = getRegion().front().getArguments();
6275 if (getLoopLowerBounds().size() != ivs.size())
6276 return emitOpError() << "number of range arguments and IVs do not match";
6277
6278 for (auto [lb, iv] : llvm::zip_equal(getLoopLowerBounds(), ivs)) {
6279 if (lb.getType() != iv.getType())
6280 return emitOpError()
6281 << "range argument type does not match corresponding IV type";
6282 }
6283
6284 for (Value step : getLoopSteps()) {
6285 if (matchPattern(step, m_Zero()))
6286 return emitOpError() << "loop step must not be zero";
6287 }
6288
6289 YieldOp yield = getYieldOp();
6290 if (!yield) {
6291 bool hasYield = llvm::any_of(getRegion(), [](Block &block) {
6292 return !block.empty() && isa<YieldOp>(block.back());
6293 });
6294 if (hasYield)
6295 return emitOpError() << "region must contain exactly one omp.yield";
6296 return emitOpError() << "region must be terminated by omp.yield";
6297 }
6298
6299 if (yield.getNumOperands() != 1)
6300 return emitOpError()
6301 << "omp.yield in omp.iterator region must yield exactly one value";
6302
6303 mlir::Type yieldedTy = yield.getOperand(0).getType();
6304 mlir::Type elemTy = iteratedTy.getElementType();
6305
6306 if (yieldedTy != elemTy)
6307 return emitOpError() << "omp.iterated element type (" << elemTy
6308 << ") does not match omp.yield operand type ("
6309 << yieldedTy << ")";
6310
6311 return success();
6312}
6313
6314LogicalResult IteratorOp::verifyRegions() {
6315 // Translation routes only the omp.yield block back to the iterator loop.
6316 for (Block &block : getRegion()) {
6317 Operation *terminator = block.getTerminator();
6318 if (block.getNumSuccessors() == 0 && !isa<YieldOp>(terminator))
6319 return mlir::emitError(terminator->getLoc())
6320 << "expected exit block terminator to be an `omp.yield` op.";
6321 }
6322 return success();
6323}
6324
6325//===----------------------------------------------------------------------===//
6326// GroupprivateOp
6327//===----------------------------------------------------------------------===//
6328
6329LogicalResult
6330GroupprivateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
6331 auto *symbol = symbolTable.lookupNearestSymbolFrom(*this, getSymNameAttr());
6332 if (!symbol)
6333 return emitOpError() << "expected symbol reference '" << getSymName()
6334 << "' to point to a global variable";
6335
6336 if (isa<FunctionOpInterface>(symbol))
6337 return emitOpError() << "expected symbol reference '" << getSymName()
6338 << "' to point to a global variable, not a function";
6339
6340 return success();
6341}
6342
6343#define GET_ATTRDEF_CLASSES
6344#include "mlir/Dialect/OpenMP/OpenMPOpsAttributes.cpp.inc"
6345
6346#define GET_OP_CLASSES
6347#include "mlir/Dialect/OpenMP/OpenMPOps.cpp.inc"
6348
6349#define GET_TYPEDEF_CLASSES
6350#include "mlir/Dialect/OpenMP/OpenMPOpsTypes.cpp.inc"
return success()
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 &region, const Twine &name)
Definition EmitC.cpp:1506
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
if(!isCopyOut)
b getContext())
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 &region, 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 &region, 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 &region, 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 &region, 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 &region, 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 &region, 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 &region, ValueRange lbs, ValueRange ubs, ValueRange steps, TypeRange, TypeRange, TypeRange)
static void getInReductionEffects(Operation *op, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
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 &region, 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 &region, 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 &region, 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 &region, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &useDeviceAddrVars, SmallVectorImpl< Type > &useDeviceAddrTypes, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &useDevicePtrVars, SmallVectorImpl< Type > &useDevicePtrTypes)
static void printPrivateReductionRegion(OpAsmPrinter &p, Operation *op, Region &region, 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 &region, 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 void getTaskReductionEffects(Operation *op, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
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 &region, 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 &region, 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 &region, 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 &region, 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)
return success()
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 > &regionPrivateArgs, 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 void getTaskSchedulingPointEffects(llvm::SmallVectorImpl< SideEffects::EffectInstance< MemoryEffects::Effect > > &effects)
static LogicalResult verifyNumTeamsClause(Operation *op, Value numTeamsLower, OperandRange numTeamsUpperVars)
static bool opInGlobalImplicitParallelRegion(Operation *op)
static void printTargetOpRegion(OpAsmPrinter &p, Operation *op, Region &region, 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 &region, 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 &region, 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 > &copyprivateVars, SmallVectorImpl< Type > &copyprivateTypes, ArrayAttr &copyprivateSyms)
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,...
Definition SPIRVOps.cpp:230
static bool isUnique(It begin, It end)
Definition ShardOps.cpp:145
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.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
MutableArrayRef< BlockArgument > BlockArgListType
Definition Block.h:110
ValueTypeRange< BlockArgListType > getArgumentTypes()
Return a range containing the types of the arguments for this block.
Definition Block.cpp:154
unsigned getNumSuccessors()
Definition Block.cpp:270
bool empty()
Definition Block.h:173
BlockArgument getArgument(unsigned i)
Definition Block.h:154
unsigned getNumArguments()
Definition Block.h:153
Operation & front()
Definition Block.h:178
SuccessorRange getSuccessors()
Definition Block.h:280
Operation & back()
Definition Block.h:177
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
bool mightHaveTerminator()
Return "true" if this block might have a terminator.
Definition Block.cpp:255
BlockArgListType getArguments()
Definition Block.h:112
iterator end()
Definition Block.h:169
iterator begin()
Definition Block.h:168
IntegerType getI64Type()
Definition Builders.cpp:73
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
MLIRContext * getContext() const
Definition Builders.h:56
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:101
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.
Definition Dominance.h:143
bool dominates(Operation *a, Operation *b) const
Return true if operation A dominates operation B, i.e.
Definition Dominance.h:161
A symbol reference with a reference path containing a single element.
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.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region &region, 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.
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
This class represents an operand of an operation.
Definition Value.h:256
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.
Definition ValueRange.h:44
type_range getType() const
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition Operation.h:237
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:740
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
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'.
Definition Operation.h:255
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
user_range getUsers()
Returns a range of all users.
Definition Operation.h:927
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
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 represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
This class represents a successor of a region.
Region * getSuccessor() const
Return the given region successor.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
BlockArgListType getArguments()
Definition Region.h:94
OpIterator op_begin()
Return iterators that walk the operations nested directly within this region.
Definition Region.h:178
bool isAncestor(Region *other)
Return true if this region is ancestor of the other region.
Definition Region.h:234
iterator_range< OpIterator > getOps()
Definition Region.h:180
bool empty()
Definition Region.h:60
unsigned getNumArguments()
Definition Region.h:136
Location getLoc()
Return a location for this region.
Definition Region.cpp:31
BlockArgument getArgument(unsigned i)
Definition Region.h:137
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:198
BlockListType & getBlocks()
Definition Region.h:45
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.
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.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
type_range getType() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
MLIRContext * getContext() const
Utility to get the associated MLIRContext that this value is defined in.
Definition Value.h:108
Type getType() const
Return the type of this value.
Definition Value.h:105
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult advance()
Definition WalkResult.h:47
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< bool > content)
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.
Definition UseDefLists.h:38
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.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
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.
Definition Utils.cpp:311
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
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.
Definition Matchers.h:442
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.
Definition Value.h:496
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
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...
Definition Utils.cpp:1411
detail::DenseArrayAttrImpl< bool > DenseBoolArrayAttr
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
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)
SmallVector< std::unique_ptr< Region >, 1 > regions
Regions that the op will hold.
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.