13#include "mlir/Dialect/Arith/IR/Arith.h"
14#include "mlir/Dialect/Func/IR/FuncOps.h"
15#include "mlir/IR/DialectImplementation.h"
16#include "mlir/IR/Matchers.h"
17#include "mlir/IR/Operation.h"
18#include "mlir/IR/RegionGraphTraits.h"
19#include "mlir/IR/SymbolTable.h"
20#include "mlir/IR/TypeUtilities.h"
21#include "mlir/Interfaces/DataLayoutInterfaces.h"
22#include "mlir/Interfaces/FoldInterfaces.h"
23#include "mlir/Transforms/InliningUtils.h"
24#include "llvm/ADT/SCCIterator.h"
25#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/TypeSwitch.h"
30#include "llvm/Support/CheckedArithmetic.h"
31#include "llvm/Support/MathExtras.h"
32#include "llvm/Support/TypeSize.h"
41#include "aie/Dialect/AIEX/IR/AIEXDialect.cpp.inc"
43#include "aie/Dialect/AIEX/IR/AIEXEnums.cpp.inc"
45#include "aie/Dialect/AIEX/IR/AIEXInterfaces.cpp.inc"
47#define GET_TYPEDEF_CLASSES
48#include "aie/Dialect/AIEX/IR/AIEXTypes.cpp.inc"
50#define GET_ATTRDEF_CLASSES
51#include "aie/Dialect/AIEX/IR/AIEXAttrDefs.cpp.inc"
56void AIEXDialect::initialize() {
59#include "aie/Dialect/AIEX/IR/AIEX.cpp.inc"
62#define GET_TYPEDEF_LIST
63#include "aie/Dialect/AIEX/IR/AIEXTypes.cpp.inc"
66#define GET_ATTRDEF_LIST
67#include "aie/Dialect/AIEX/IR/AIEXAttrDefs.cpp.inc"
77#include "aie/Dialect/AIEX/IR/AIEX.cpp.inc"
113 mlir::Operation *op,
int tileCol,
115 mlir::BaseMemRefType referencedBufType,
116 llvm::SmallVector<int64_t, 4> inputSizes,
117 llvm::SmallVector<int64_t, 4> inputStrides,
118 llvm::SmallVector<int64_t, 4> &sizes,
119 llvm::SmallVector<int64_t, 4> &strides) {
120 assert(inputSizes.size() == inputStrides.size());
121 assert(sizes.size() == 4);
122 assert(strides.size() == 4);
124 DataLayout dataLayout = DataLayout::closest(op);
126 dataLayout.getTypeSizeInBits(referencedBufType.getElementType());
130 llvm::fill(sizes, 0);
131 llvm::fill(strides, 0);
133 if (inputSizes[0] == 0) {
140 int64_t inS[4] = {inputSizes[0], inputSizes[1], inputSizes[2], inputSizes[3]};
141 int64_t inT[4] = {inputStrides[0], inputStrides[1], inputStrides[2],
143 int64_t outS[4], outT[4];
146 inS, inT, outS, outT);
147 for (
int i = 0; i < 4; i++) {
149 strides[i] = outT[i];
154 mlir::Operation *forOp,
155 llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
156 mlir::BaseMemRefType referencedBufType,
int tileCol,
int tileRow,
157 llvm::SmallVector<int64_t, 4> inputSizes,
158 llvm::SmallVector<int64_t, 4> inputStrides,
159 llvm::SmallVector<int64_t, 4> hardwareSizes,
160 llvm::SmallVector<int64_t, 4> hardwareStrides,
161 bool skipTransformationChecks) {
163 auto addressGranularity = targetModel.getAddressGenGranularity();
164 DataLayout dataLayout = DataLayout::closest(forOp);
166 dataLayout.getTypeSizeInBits(referencedBufType.getElementType());
169 if (!targetModel.isCoreTile(tileCol, tileRow) &&
170 !targetModel.isMemTile(tileCol, tileRow) &&
171 !targetModel.isShimNOCTile(tileCol, tileRow))
172 return emitError() <<
"Unsupported tile type at (" << tileCol <<
", "
173 << tileRow <<
") Must be ShimNOC, Mem or Core.";
175 uint32_t wrap_bits = targetModel.getDmaBdWrapBits(tileCol, tileRow);
176 uint32_t step_bits = targetModel.getDmaBdStepBits(tileCol, tileRow);
178 for (
int i = 0; i < 4; i++) {
179 if (inputSizes[i] <= 0) {
180 return emitError() <<
"Size " << i <<
" must be a positive integer.";
185 std::stringstream msg;
186 msg <<
"Transfer sizes must be multiples of " << (addressGranularity / 8)
187 <<
" bytes. " << inputSizes[0] <<
" elements at " << (elemWidth / 8)
188 <<
" bytes each equal " << (inputSizes[0] * elemWidth / 8)
189 <<
" bytes, which is not divisible by " << (addressGranularity / 8)
191 return emitError() << msg.str();
194 for (
int i = 0; i < 3; i++) {
195 if (inputSizes[i] > 1 && inputStrides[i] < 1) {
199 return emitError() <<
"Stride " << i <<
" must be a positive integer.";
204 if (inputSizes[3] > 1 && inputStrides[3] < 0) {
205 return emitError() <<
"Stride 3 must be a non-negative integer.";
208 for (
int i = 0; i < 4; i++) {
211 if (i == 0 && inputStrides[i] == 1)
214 addressGranularity)) {
215 std::stringstream msg;
216 msg <<
"Stride " << i <<
" is " << inputStrides[i] <<
" elements * "
217 << (elemWidth / 8) <<
" bytes = " << (inputStrides[i] * elemWidth / 8)
218 <<
" bytes, which is not divisible by " << (addressGranularity / 8)
220 return emitError() << msg.str();
225 if (elemWidth != addressGranularity && inputSizes[0] > 1 &&
226 inputStrides[0] != 1)
227 return emitError() <<
"Stride 0 is " << inputStrides[0]
228 <<
" elements, but must be 1 for " << (elemWidth / 8)
229 <<
"-byte elements: the DMA moves whole "
230 << (addressGranularity / 8) <<
"-byte words.";
232 const AIE::DmaBdLayout *layout = targetModel.getDmaBdLayout(tileCol, tileRow);
234 inputStrides[0] != 1)
235 return emitError() <<
"Stride 0 is " << inputStrides[0]
236 <<
", but must be 1: this tile's buffer descriptors "
237 "have no d0 stride, the innermost dimension is "
238 "always contiguous.";
240 auto outOfRange = [&](
const char *what,
int dim, int64_t written,
241 int64_t encoded, int64_t lo, int64_t hi) {
242 return emitError() << what <<
" " << dim <<
" is " << written
243 <<
" (encoded as " << encoded <<
"), which exceeds the ["
244 << lo <<
":" << hi <<
"] range.";
247 int64_t maxWrap = (1 << wrap_bits) - 1;
248 int64_t maxStep = 1 << step_bits;
251 maxStep - 1 + targetModel.getDmaBdStepBias(tileCol, tileRow);
253 for (
int dim : {0, 1}) {
254 if (!skipTransformationChecks && hardwareSizes[dim] > maxWrap)
255 return outOfRange(
"Size", dim, inputSizes[dim], hardwareSizes[dim], 0,
260 bool pureRepeat = inputStrides[3] == 0;
262 pureRepeat ? targetModel.getMaxRepeatCount() + 1
263 : 1LL << targetModel.getDmaBdIterBits(tileCol, tileRow);
264 if (inputSizes[3] > maxCount)
265 return emitError() << (pureRepeat ?
"repeat count " :
"iteration count ")
266 << inputSizes[3] <<
" exceeds the [1:" << maxCount
268 for (
int dim : {0, 1, 2}) {
269 if (hardwareStrides[dim] > maxStep - 1)
270 return outOfRange(
"Stride", dim, inputStrides[dim], hardwareStrides[dim],
275 if (hardwareStrides[3] > maxStep - 1 && hardwareSizes[3] > 0)
276 return outOfRange(
"Stride", 3, inputStrides[3], hardwareStrides[3], 1,
289LogicalResult AIEX::CertWrite32DOp::verify() {
290 if (getAddressIsReg() && getAddress() > 23)
291 return emitOpError(
"has address_is_reg, so address ")
292 << getAddress() <<
" must be a register index in [0, 23]";
293 if (getValueIsReg() && getValue() > 23)
294 return emitOpError(
"has value_is_reg, so value ")
295 << getValue() <<
" must be a register index in [0, 23]";
299LogicalResult AIEX::CertApplyOffset57Op::verify() {
300 if (getNumEntries() == 0)
301 return emitOpError(
"num_entries must be at least 1");
305LogicalResult AIEX::UseTokenOp::verify() {
306 auto *parentOp = (*this)->getParentOp();
307 if (isa<func::FuncOp>(parentOp) || isa<AIE::CoreOp>(parentOp) ||
308 isa<AIE::MemOp>(parentOp) || isa<AIE::ShimDMAOp>(parentOp))
317LogicalResult AIEX::MulticastOp::verify() {
318 Region &body = getPorts();
319 assert(getOperation()->getNumRegions());
320 assert(!body.empty());
321 for (
auto &ops : body.front())
322 if (!isa<MultiDestOp, AIE::EndOp>(ops))
323 return ops.emitOpError(
"cannot be contained in a Multicast op");
332LogicalResult AIEX::BroadcastPacketOp::verify() {
333 Region &body = getPorts();
334 assert(getOperation()->getNumRegions());
335 assert(!body.empty());
336 for (
auto &ops : body.front())
337 if (!isa<BPIDOp, AIE::EndOp>(ops))
338 return ops.emitOpError(
"cannot be contained in a BroadcastPacket op");
349uint32_t AIEX::NpuDmaMemcpyNdOp::getAxcacheOrDefault() {
353int64_t AIEX::NpuDmaMemcpyNdOp::getOffsetInBytes() {
354 llvm::SmallVector<int64_t, 4> offsets =
355 llvm::map_to_vector(llvm::reverse(getMixedOffsets()), [](OpFoldResult s) {
356 return getConstantIntValue(s).value();
358 auto strides = llvm::to_vector<4>(llvm::reverse(getMixedStrides()));
360 size_t R = offsets.size();
361 size_t el_bit_width = getElementTypeBitwidth();
362 assert(el_bit_width % 8 == 0 &&
363 "Expected Memref element bitwidth to be multiple of 8.");
364 size_t S = el_bit_width / 8;
369 for (
size_t i = 0; i < R; i++) {
372 auto strideConst = getConstantIntValue(strides[i]);
373 assert(strideConst &&
374 "verifier requires a stride paired with a non-zero offset to be "
376 offset += offsets[i] * (*strideConst) * S;
385 llvm::ArrayRef<int64_t> strides) {
386 return sizes[1] == 1 && sizes[2] == 1 && strides[0] == 1 && strides[1] == 0 &&
397 llvm::ArrayRef<int64_t> strides) {
400 if (sizes[1] > 1 && strides[1] != sizes[0])
402 if (sizes[2] > 1 && strides[2] != sizes[0] * sizes[1])
408 int row, llvm::ArrayRef<int64_t> sizes,
409 llvm::ArrayRef<int64_t> strides) {
419bool AIEX::NpuDmaMemcpyNdOp::isLinearTransferWithoutTransformation() {
420 llvm::SmallVector<int64_t, 4> inputSizes =
421 llvm::map_to_vector(llvm::reverse(getMixedSizes()), [](OpFoldResult s) {
422 return getConstantIntValue(s).value();
424 llvm::SmallVector<int64_t, 4> inputStrides =
425 llvm::map_to_vector(llvm::reverse(getMixedStrides()), [](OpFoldResult s) {
426 return getConstantIntValue(s).value();
454struct LinearizeContiguousTransfer
455 :
public mlir::OpRewritePattern<AIEX::NpuDmaMemcpyNdOp> {
456 using OpRewritePattern::OpRewritePattern;
459 matchAndRewrite(AIEX::NpuDmaMemcpyNdOp op,
460 mlir::PatternRewriter &rewriter)
const override {
462 if (!llvm::all_of(op.getMixedSizes(), [](mlir::OpFoldResult s) {
463 return mlir::getConstantIntValue(s).has_value();
465 return mlir::failure();
466 if (!llvm::all_of(op.getMixedStrides(), [](mlir::OpFoldResult s) {
467 return mlir::getConstantIntValue(s).has_value();
469 return mlir::failure();
470 if (!llvm::all_of(op.getMixedOffsets(), [](mlir::OpFoldResult s) {
471 return mlir::getConstantIntValue(s).has_value();
473 return mlir::failure();
476 if (op.isLinearTransferWithoutTransformation())
477 return mlir::failure();
481 llvm::SmallVector<int64_t, 4> sizes = llvm::map_to_vector(
482 llvm::reverse(op.getMixedSizes()), [](mlir::OpFoldResult s) {
483 return mlir::getConstantIntValue(s).value();
485 llvm::SmallVector<int64_t, 4> strides = llvm::map_to_vector(
486 llvm::reverse(op.getMixedStrides()), [](mlir::OpFoldResult s) {
487 return mlir::getConstantIntValue(s).value();
489 llvm::SmallVector<int64_t, 4> offsets = llvm::map_to_vector(
490 llvm::reverse(op.getMixedOffsets()), [](mlir::OpFoldResult s) {
491 return mlir::getConstantIntValue(s).value();
496 return mlir::failure();
500 int64_t N = sizes[0] * sizes[1] * sizes[2];
501 llvm::SmallVector<int64_t, 4> newSizesOuter = {sizes[3], 1, 1, N};
502 llvm::SmallVector<int64_t, 4> newStridesOuter = {strides[3], 0, 0, 1};
509 int64_t linearOffset = offsets[0] * strides[0] + offsets[1] * strides[1] +
510 offsets[2] * strides[2];
511 llvm::SmallVector<int64_t, 4> newOffsetsOuter = {offsets[3], 0, 0,
514 rewriter.replaceOpWithNewOp<AIEX::NpuDmaMemcpyNdOp>(
515 op, op, newOffsetsOuter, newSizesOuter, newStridesOuter);
516 return mlir::success();
521void AIEX::NpuDmaMemcpyNdOp::getCanonicalizationPatterns(
522 mlir::RewritePatternSet &results, mlir::MLIRContext *context) {
523 results.add<LinearizeContiguousTransfer>(context);
529static std::optional<std::string>
531 uint32_t requestedBurstLength) {
532 if (requestedBurstLength != 0) {
534 auto pair = llvm::find_if(bel, [=](
const std::pair<uint32_t, uint32_t> &p) {
535 return p.second == requestedBurstLength;
538 if (pair == bel.end()) {
539 std::string errorMessage =
540 "Requested burst length is not supported by the target. "
541 "Supported burst lengths:";
544 std::accumulate(bel.begin(), bel.end(), errorMessage,
545 [](
const std::string &a,
auto b) {
546 return a +
" " + std::to_string(b.second);
560LogicalResult AIEX::NpuDmaMemcpyNdOp::verifyDynamicSizesStrides(
562 AIE::ShimDMAAllocationOp allocOp) {
566 "runtime sizes/strides require a shim_dma_allocation to resolve the "
567 "tile; none found.");
568 AIE::TileOp tile = allocOp.getTileOp();
572 if (!targetModel.
isShimNOCTile(tile.getCol(), tile.getRow()))
574 "runtime sizes/strides are only supported for shim NOC tile DMAs.");
577 if (getD0ZeroBefore() || getD1ZeroBefore() || getD2ZeroBefore() ||
578 getD0ZeroAfter() || getD1ZeroAfter() || getD2ZeroAfter())
580 "zero padding is not supported with runtime sizes/strides.");
587 auto sizes = getMixedSizes();
588 auto strides = getMixedStrides();
606 DataLayout dataLayout = DataLayout::closest(getOperation());
607 uint64_t elemWidth = dataLayout.getTypeSizeInBits(buffer.getElementType());
609 llvm::SmallVector<mlir::OpFoldResult, 4> sizesRev(llvm::reverse(sizes));
610 auto checkSize = [&](mlir::OpFoldResult ofr, int64_t hwVal, int64_t hi,
611 llvm::StringRef what) -> LogicalResult {
612 if (!getConstantIntValue(ofr))
614 if (hwVal < 0 || hwVal > hi)
615 return emitOpError(what) <<
" hardware value " << hwVal
616 <<
" exceeds hardware range [0:" << hi <<
"].";
619 auto hwSize = [&](mlir::OpFoldResult ofr) {
620 return getConstantIntValue(ofr).value_or(0);
622 int64_t d0Hw = (int64_t)(hwSize(sizesRev[0]) * elemWidth / gran);
623 int64_t d1Hw = hwSize(sizesRev[1]);
624 int64_t iterRaw = hwSize(sizesRev[3]);
625 int64_t iterHw = iterRaw > 1 ? iterRaw - 1 : 0;
626 std::optional<int64_t> outerStride = getConstantIntValue(strides.front());
627 bool pureRepeat = outerStride && *outerStride == 0;
628 AIE::AIETileType tileType =
629 targetModel.
getTileType(tile.getCol(), tile.getRow());
633 if (failed(checkSize(sizesRev[0], d0Hw, wrapMax,
"d0 size")) ||
634 failed(checkSize(sizesRev[1], d1Hw, wrapMax,
"d1 size")) ||
635 failed(checkSize(sizesRev[3], iterHw, maxCount - 1,
636 pureRepeat ?
"repeat count" :
"iteration size")))
642 llvm::SmallVector<mlir::OpFoldResult, 4> stridesRev(llvm::reverse(strides));
649 auto errorMessage = checkBurstLength(targetModel, getBurstLength());
650 if (errorMessage.has_value())
651 return emitOpError(errorMessage.value());
656LogicalResult AIEX::NpuDmaMemcpyNdOp::verify() {
657 BaseMemRefType buffer = getMemref().getType();
661 if (getOffsetParameterAttr() || getOffsetStateTableIdxAttr()) {
662 uint64_t elemBitWidth = buffer.getElementTypeBitWidth();
663 if (elemBitWidth == 0 || (elemBitWidth % 8) != 0)
664 return emitOpError(
"offset_parameter requires a whole-byte element type");
667 if (getElementTypeBitwidth() > addressGranularity) {
668 return emitOpError(
"Maximum element bit width allowed is ")
669 << addressGranularity <<
"bits. ";
671 if (buffer.hasStaticShape() &&
672 (buffer.getNumElements() * getElementTypeBitwidth()) <
673 addressGranularity) {
674 return emitOpError(
"Minimum data transfer size required is ")
675 << addressGranularity <<
"bits. ";
677 bool allStridesConstant = llvm::all_of(getMixedStrides(), [](OpFoldResult s) {
678 return getConstantIntValue(s).has_value();
680 bool allSizesConstant = llvm::all_of(getMixedSizes(), [](OpFoldResult s) {
681 return getConstantIntValue(s).has_value();
683 bool allOffsetsConstant = llvm::all_of(getMixedOffsets(), [](OpFoldResult s) {
684 return getConstantIntValue(s).has_value();
687 bool hasLengthParameter =
688 getLengthParameterAttr() || getLengthStateTableIdxAttr();
691 if (hasLengthParameter &&
692 (!allStridesConstant || !allSizesConstant || !allOffsetsConstant))
694 "length_parameter requires constant offsets, sizes and strides");
697 if (!allStridesConstant || !allSizesConstant || !allOffsetsConstant)
700 llvm::SmallVector<int64_t, 4> inputSizes =
701 llvm::map_to_vector(llvm::reverse(getMixedSizes()), [](OpFoldResult s) {
702 return getConstantIntValue(s).value();
704 llvm::SmallVector<int64_t, 4> inputStrides =
705 llvm::map_to_vector(llvm::reverse(getMixedStrides()), [](OpFoldResult s) {
706 return getConstantIntValue(s).value();
708 int64_t offset = getOffsetInBytes();
710 auto errorMessage = checkBurstLength(targetModel, getBurstLength());
711 if (errorMessage.has_value()) {
712 return emitOpError(errorMessage.value());
715 if (hasLengthParameter) {
717 *
this, getLengthUnit(), buffer,
718 inputSizes[0] * inputSizes[1] * inputSizes[2],
720 llvm::ArrayRef<int64_t>(inputSizes).take_front(3))))
728 if (offset % 4 != 0) {
729 return emitOpError(
"Offset must be 4-byte-aligned.");
733 if (
auto packetInfo = getPacket()) {
736 if (packetInfo->getPktType() > 7)
737 return emitOpError(
"Packet type field can only hold 3 bits.");
738 if (packetInfo->assignedId() > 31)
739 return emitOpError(
"Packet ID field can only hold 5 bits.");
745static LogicalResult verifyTransferCoversWholeObjects(
746 Operation *transfer, SymbolRefAttr alloc, std::optional<int64_t> moved,
747 AIE::ObjectFifoCreateOp fifo, SymbolTableCollection &symbols);
752AIEX::NpuDmaMemcpyNdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
753 BaseMemRefType buffer = getMemref().getType();
755 bool allStridesConstant = llvm::all_of(getMixedStrides(), [](OpFoldResult s) {
756 return getConstantIntValue(s).has_value();
758 bool allSizesConstant = llvm::all_of(getMixedSizes(), [](OpFoldResult s) {
759 return getConstantIntValue(s).has_value();
761 bool allOffsetsConstant = llvm::all_of(getMixedOffsets(), [](OpFoldResult s) {
762 return getConstantIntValue(s).has_value();
765 !allStridesConstant || !allSizesConstant || !allOffsetsConstant;
767 bool hasLengthParameter =
768 getLengthParameterAttr() || getLengthStateTableIdxAttr();
769 bool isAIE1 = targetModel.
getTargetArch() == AIE::AIEArch::AIE1;
770 AIE::DeviceOp dev = getOperation()->getParentOfType<AIE::DeviceOp>();
771 if (!dev && isAIE1 && !isDynamic && !hasLengthParameter)
774 if (
auto fifo = symbolTable.lookupSymbolIn<AIE::ObjectFifoCreateOp>(
775 dev, getMetadata().getRootReference());
777 failed(verifyTransferCoversWholeObjects(
778 *
this, getMetadata(), getStaticBytesStreamed(), fifo, symbolTable)))
780 auto allocOp = symbolTable.lookupSymbolIn<AIE::ShimDMAAllocationOp>(
781 dev, getMetadata().getRootReference());
782 if (AIE::TileOp tile = allocOp ? allocOp.getTileOp() :
nullptr) {
783 uint32_t numBds = targetModel.
getNumBDs(tile.getCol(), tile.getRow());
784 if (getId() >= numBds)
785 return emitOpError(
"programs buffer descriptor ID ")
786 << getId() <<
", but tile (" << tile.getCol() <<
", "
787 << tile.getRow() <<
") has " << numBds <<
" buffer descriptors";
789 int channel = allocOp.getChannelIndex();
790 AIE::DMAChannelDir dir = allocOp.getChannelDir();
794 tile.getCol(), tile.getRow(), channel, dir);
795 return emitOpError(
"programs buffer descriptor ID ")
796 << getId() <<
", which is not in the BD pool of "
797 << AIE::stringifyDMAChannelDir(dir) <<
" channel " << channel
798 <<
" of tile (" << tile.getCol() <<
", " << tile.getRow()
799 <<
"): ids " << first <<
" to " << last - 1;
803 return verifyDynamicSizesStrides(targetModel, buffer, allocOp);
809 auto tile = allocOp.getTileOp();
812 if (isAIE1 && hasLengthParameter)
813 return emitOpError(
"length_parameter is only supported on AIE2 and "
817 int col = tile.getCol();
818 int row = tile.getRow();
819 if (hasLengthParameter &&
823 llvm::SmallVector<int64_t, 4> inputSizes =
824 llvm::map_to_vector(llvm::reverse(getMixedSizes()), [](OpFoldResult s) {
825 return getConstantIntValue(s).value();
827 llvm::SmallVector<int64_t, 4> inputStrides =
828 llvm::map_to_vector(llvm::reverse(getMixedStrides()), [](OpFoldResult s) {
829 return getConstantIntValue(s).value();
831 llvm::SmallVector<int64_t, 4> hardwareSizes(4);
832 llvm::SmallVector<int64_t, 4> hardwareStrides(4);
834 inputSizes, inputStrides, hardwareSizes,
847 targetModel, col, row, inputSizes, inputStrides);
854 llvm::SmallVector<int64_t, 4> inputOffsets =
855 llvm::map_to_vector(llvm::reverse(getMixedOffsets()), [](OpFoldResult s) {
856 return getConstantIntValue(s).value();
862 if (!isAIE1 && !hasLengthParameter &&
864 row, inputOffsets, inputSizes,
868 *
this, [&] {
return emitOpError(); }, buffer, col, row,
869 inputSizes, inputStrides, hardwareSizes, hardwareStrides,
870 skipTransformationChecks))) {
881LogicalResult AIEX::NpuDmaWaitOp::verify() {
882 AIE::DeviceOp dev = (*this)->getParentOfType<AIE::DeviceOp>();
885 if (dev && !dev.lookupSymbol(getSymbol()))
886 return emitOpError(
"couldn't find symbol in parent device");
894LogicalResult AIEX::NpuPushQueueOp::verify() {
897 getRow(), getDirection(), getChannel())))
899 auto numBds = targetModel.
getNumBDs(getColumn(), getRow());
904 bdId && *bdId >= numBds)
905 return emitOpError(
"BD ID exceeds the maximum ID.");
912 return emitOpError(
"BD ID ") << *bdId <<
" is not accessible from channel ("
913 << AIE::stringifyDMAChannelDir(getDirection())
914 <<
", " << getChannel() <<
")";
920 getChannel(), getDirection()))
921 return emitOpError() <<
"bd_id " << *bdId <<
" is not in the BD pool of "
922 << AIE::stringifyDMAChannelDir(getDirection())
923 <<
" channel " << getChannel();
925 if (std::optional<uint64_t> repeatCount =
927 repeatCount && *repeatCount > maxRepeat)
928 return emitOpError(
"Repeat count exceeds the [0:")
929 << maxRepeat <<
"] range.";
930 if (getRepeatStateTableIdxAttr()) {
932 if (arch != AIE::AIEArch::AIE2 && arch != AIE::AIEArch::AIE2p)
933 return emitOpError(
"repeat_parameter is only supported on AIE2 and "
936 !targetModel.
isMemTile(getColumn(), getRow()))
937 return emitOpError(
"repeat_parameter is only supported on shim NOC "
938 "and mem tiles, got tile (")
939 << getColumn() <<
", " << getRow() <<
")";
941 return emitOpError(
"takes its repeat count from the scratchpad, so its "
942 "repeat_count operand must be 0");
945 return emitOpError(
"takes its repeat count from the scratchpad, so its "
946 "bd_id must be a constant");
948 return emitOpError(
"takes its repeat count from the scratchpad, whose "
949 "update clears the low two bits of the queue word, "
950 "so its bd_id must be a multiple of 4, got ")
960LogicalResult AIEX::NpuSyncOp::verify() {
961 for (
auto [name, count] : {std::pair{
"column_num", getColumnNum()},
962 std::pair{
"row_num", getRowNum()}})
963 if (std::optional<int64_t> value = getConstantIntValue(count);
965 return emitOpError() << name <<
" must cover at least one, got "
970LogicalResult AIEX::NpuWriteBdOp::verify() {
972 auto numBds = targetModel.
getNumBDs(getColumn(), getRow());
974 (getD0Size() >= 1) && (getD1Size() == 1) && (getIterationSize() == 0);
975 if (getBdId() >= numBds)
976 return emitOpError(
"BD ID exceeds the maximum ID.");
977 std::optional<uint32_t> channel = getChannel();
978 std::optional<AIE::DMAChannelDir> direction = getDirection();
979 if (channel.has_value() != direction.has_value())
980 return emitOpError(
"channel and direction must be given together");
981 if (channel && direction) {
984 return emitOpError() << stringifyDMAChannelDir(*direction) <<
" channel "
985 << *channel <<
" does not exist on this tile";
987 *channel, *direction))
988 return emitOpError() <<
"BD ID " << getBdId()
989 <<
" is not in the BD pool of "
990 << stringifyDMAChannelDir(*direction) <<
" channel "
993 return emitOpError(
"needs a channel and direction: a BD id on this tile "
994 "names a slot of its channel's BD pool");
996 if (getPacketId() > 31)
997 return emitOpError(
"Packet ID exceeds the maximum supported by 5 bits.");
998 if (getPacketType() > 7)
999 return emitOpError(
"Packet Type exceeds the maximum supported by 3 bits.");
1000 int64_t oooId = getOutOfOrderId();
1003 return emitOpError(
"out_of_order_id must be in [0, ")
1005 if (oooId != 0 && getEnablePacket() == 0)
1006 return emitOpError(
"out_of_order_id requires a packet-enabled BD");
1011 AIE::AIETileType tileType = targetModel.
getTileType(getColumn(), getRow());
1015 uint32_t maxWrap = wrapBits > 0 ? (1u << wrapBits) - 1 : 0;
1016 uint32_t maxStep = stepBits > 0 ? (1u << stepBits) - 1 : 0;
1017 uint32_t maxIter = iterBits > 0 ? (1u << iterBits) - 1 : 0;
1019 if (!isLinearTransfer && getD0Size() > maxWrap)
1020 return emitOpError() <<
"D0 Size exceeds the [0:" << maxWrap <<
"] range.";
1021 if (getD0Stride() > maxStep)
1022 return emitOpError() <<
"D0 Stride exceeds the [0:" << maxStep
1028 getD0Stride() > 1u - layout->
stepBias)
1029 return emitOpError(
"D0 Stride must encode a unit step: the BDs of this "
1030 "tile have no d0 stride field.");
1031 if (getD1Size() > maxWrap)
1032 return emitOpError() <<
"D1 Size exceeds the [0:" << maxWrap <<
"] range.";
1033 if (getD1Stride() > maxStep)
1034 return emitOpError() <<
"D1 Stride exceeds the [0:" << maxStep
1036 if (getD2Stride() > maxStep)
1037 return emitOpError() <<
"D2 Stride exceeds the [0:" << maxStep
1039 if (getIterationSize() > maxIter)
1040 return emitOpError() <<
"Iteration Size exceeds the [0:" << maxIter
1042 if (
static_cast<uint32_t
>(getIterationStride()) > maxStep)
1043 return emitOpError() <<
"Iteration Stride exceeds the [0:" << maxStep
1048 if (getBufferLength() > maxLen)
1049 return emitOpError() <<
"Buffer length exceeds the [0:" << maxLen
1051 if (targetModel.
isShimNOCTile(getColumn(), getRow()) && getD2Size() != 0)
1052 return emitOpError(
"ShimTile only supports 3 dimensions of sizes.");
1055 llvm::SmallVector<std::pair<AIE::DmaBdField, AIE::DmaBdField>, 3> padFields;
1058 uint64_t pads[3][2] = {{getD0ZeroBefore(), getD0ZeroAfter()},
1059 {getD1ZeroBefore(), getD1ZeroAfter()},
1060 {getD2ZeroBefore(), getD2ZeroAfter()}};
1061 for (
auto [d, pad] : llvm::enumerate(pads)) {
1062 if (d >= padFields.size()) {
1063 if (pad[0] || pad[1])
1064 return emitOpError()
1065 <<
"D" << d <<
" zero padding is not supported on this tile.";
1068 uint32_t maxBefore = padFields[d].first.mask();
1069 uint32_t maxAfter = padFields[d].second.mask();
1070 if (pad[0] > maxBefore || pad[1] > maxAfter)
1071 return emitOpError() <<
"D" << d
1072 <<
" pad_before/pad_after exceeds the [0:"
1073 << (pad[0] > maxBefore ? maxBefore : maxAfter)
1078 getBurstLength() != 0)
1079 return emitOpError(
"Only ShimTiles support burst length.");
1080 auto errorMessage = checkBurstLength(targetModel, getBurstLength());
1081 if (errorMessage.has_value()) {
1082 return emitOpError(errorMessage.value());
1084 if (!targetModel.
isShimNOCTile(getColumn(), getRow()) && getAxcache())
1085 return emitOpError(
"Only ShimTiles support AxCACHE configuration.");
1090uint32_t AIEX::NpuWriteBdOp::getAxcacheOrDefault() {
1096 return static_cast<uint32_t
>(*cst);
1097 return std::nullopt;
1104 if (
auto constant = v.getDefiningOp<arith::ConstantOp>())
1105 if (
auto attr = dyn_cast<IntegerAttr>(constant.getValue()))
1106 return attr.getValue().getZExtValue();
1108 if (!mlir::matchPattern(v, mlir::m_ConstantInt(&cst)))
1109 return std::nullopt;
1110 return cst.getZExtValue();
1114 mlir::Location loc, uint32_t value) {
1115 return arith::ConstantOp::create(
1116 builder, loc, builder.getI32IntegerAttr(
static_cast<int32_t
>(value)));
1120 mlir::Location loc, uint64_t value) {
1121 if (value <= std::numeric_limits<uint32_t>::max())
1123 return arith::ConstantOp::create(
1125 IntegerAttr::get(builder.getIntegerType(64),
1126 static_cast<int64_t
>(value)));
1136static bool hasQueryableStorageLayout(Type type) {
1137 if (type.isIntOrFloat() || isa<IndexType, DataLayoutTypeInterface>(type))
1139 if (
auto vector = dyn_cast<VectorType>(type))
1140 return hasQueryableStorageLayout(
vector.getElementType());
1141 if (
auto complex = dyn_cast<ComplexType>(type))
1142 return hasQueryableStorageLayout(complex.getElementType());
1148static std::optional<uint64_t>
1149getStaticMemRefStorageBytes(MemRefType type,
const DataLayout &layout) {
1150 if (!type || !type.hasStaticShape() ||
1151 !hasQueryableStorageLayout(type.getElementType()))
1152 return std::nullopt;
1153 if (
auto vector = dyn_cast<VectorType>(type.getElementType())) {
1157 return std::nullopt;
1158 int64_t elements = 1;
1159 for (int64_t dim :
vector.getShape()) {
1160 auto product = llvm::checkedMul(elements, dim);
1162 return std::nullopt;
1163 elements = *product;
1165 uint64_t inner =
vector.getShape().back();
1166 auto padded = llvm::checkedMulUnsigned(
1167 static_cast<uint64_t
>(elements) / inner, llvm::PowerOf2Ceil(inner));
1168 llvm::TypeSize bits = layout.getTypeSizeInBits(
vector.getElementType());
1169 if (!padded || bits.isScalable() ||
1170 !llvm::checkedMulUnsigned(*padded, bits.getFixedValue()))
1171 return std::nullopt;
1173 llvm::TypeSize elementBytes = layout.getTypeSize(type.getElementType());
1174 if (elementBytes.isScalable())
1175 return std::nullopt;
1176 if (llvm::is_contained(type.getShape(), int64_t{0}))
1178 uint64_t bytes = elementBytes.getFixedValue();
1179 for (int64_t dim : type.getShape()) {
1180 auto product = llvm::checkedMulUnsigned(bytes,
static_cast<uint64_t
>(dim));
1182 return std::nullopt;
1188template <
typename OpTy>
1189static LogicalResult verifyBufferWriteScope(OpTy op) {
1190 if (op.getBuffer() && !op->template getParentOfType<AIE::DeviceOp>())
1191 return op.emitOpError(
"must be inside a device when buffer is present");
1195template <
typename OpTy>
1197verifyBufferWrite(OpTy op, std::optional<uint32_t> wordOffset,
1199 auto bufferAttr = op.getBufferAttr();
1203 return op.emitOpError(
"address must be constant when buffer is present");
1204 auto device = op->template getParentOfType<AIE::DeviceOp>();
1206 return op.emitOpError(
"must be inside a device when buffer is present");
1209 auto buffer = names.
lookupIn<AIE::BufferOp>(device, bufferAttr.getAttr());
1211 return op.emitOpError()
1212 <<
"buffer '" << bufferAttr.getValue() <<
"' not found in device";
1213 auto bufferBytes = getStaticMemRefStorageBytes(buffer.getType(),
1214 DataLayout::closest(buffer));
1216 return op.emitOpError(
1217 "referenced buffer must have a static, fixed-size storage extent "
1218 "representable in 64 bits");
1220 uint64_t offsetBytes = uint64_t{*wordOffset} *
sizeof(uint32_t);
1221 auto end = llvm::checkedAddUnsigned(offsetBytes, writeBytes);
1223 return op.emitOpError(
"buffer-relative write range overflows 64-bit bytes");
1224 if (*end > *bufferBytes)
1225 return op.emitOpError() <<
"write range [" << offsetBytes <<
", " << *end
1226 <<
") exceeds buffer @" << bufferAttr.getValue()
1227 <<
" size " << *bufferBytes <<
" bytes";
1229 auto tile = buffer.getTileLike();
1230 const auto &targetModel = device.getTargetModel();
1233 uint64_t start = offsetBytes;
1234 if (
auto base = buffer.getAddress()) {
1236 return op.emitOpError(
"referenced buffer address must be nonnegative");
1237 start +=
static_cast<uint64_t
>(*base);
1238 if (start %
sizeof(uint32_t) != 0)
1239 return op.emitOpError() <<
"resolved buffer write address " << start
1240 <<
" is not 4-byte aligned";
1244 auto memoryEnd = llvm::checkedAddUnsigned(start, writeBytes);
1246 return op.emitOpError(
"resolved buffer write range overflows 64-bit bytes");
1247 if (*memoryEnd > memoryBytes)
1248 return op.emitOpError()
1249 <<
"write range [" << start <<
", " << *memoryEnd
1250 <<
") exceeds tile data memory size " << memoryBytes <<
" bytes";
1258LogicalResult AIEX::NpuWrite32Op::verify() {
1259 return verifyBufferWriteScope(*
this);
1267 sizeof(uint32_t), names);
1270template <
typename T>
1271static std::optional<uint32_t>
1272getAbsoluteAddress(T *op, uint32_t addressOffset,
1274 AIE::DeviceOp device =
1275 op->getOperation()->template getParentOfType<AIE::DeviceOp>();
1277 op->emitError(
"Must be inside a device.");
1278 return std::nullopt;
1282 uint32_t address = 0;
1286 if (
auto bufferSym = op->getBuffer()) {
1287 AIE::BufferOp buffer =
1288 names ? names->
lookup<AIE::BufferOp>(op->getBufferAttr().getAttr())
1291 op->emitError() <<
"buffer '" << *bufferSym <<
"' not found in device";
1292 return std::nullopt;
1295 auto bufferAddress = buffer.getAddress();
1296 if (!bufferAddress) {
1297 mlir::InFlightDiagnostic err =
1298 op->emitError(
"referenced buffer must have address assigned");
1299 err.attachNote(buffer.getLoc()) <<
"This buffer must have an address.";
1300 return std::nullopt;
1303 int col = buffer.getTileOp().getCol();
1304 int row = buffer.getTileOp().getRow();
1306 static_cast<uint32_t
>(*bufferAddress) +
1307 addressOffset *
sizeof(uint32_t);
1309 address = addressOffset;
1310 std::optional<uint32_t> col = op->getColumn();
1311 std::optional<uint32_t> row = op->getRow();
1324std::optional<uint32_t>
1328 return std::nullopt;
1329 return ::getAbsoluteAddress(
this, *addressOffset, names);
1336LogicalResult AIEX::NpuAddressPatchOp::verify() {
1340 if (getAddrVal() && !getAddrVal().getType().isInteger(32))
1341 return emitOpError(
"addr_val must be an i32 value");
1342 if (getArgIdx().has_value() ==
static_cast<bool>(getBuffer()))
1343 return emitOpError(
"must name the host buffer either by the 'arg_idx' "
1344 "attribute or by the 'buffer' operand, not both and not "
1353std::optional<uint32_t> AIEX::NpuUpdateFromScratchpadOp::getAbsoluteAddress(
1355 return ::getAbsoluteAddress(
this, getAddress(), names);
1358LogicalResult AIEX::NpuUpdateFromScratchpadOp::verify() {
1360 constexpr uint32_t kMaxStateTableEntries = 32;
1361 if (getStateTableIdx() >= kMaxStateTableEntries)
1362 return emitOpError(
"state_table_idx ")
1363 <<
static_cast<uint32_t
>(getStateTableIdx())
1364 <<
" exceeds maximum StateTable index ("
1365 << (kMaxStateTableEntries - 1) <<
").";
1375LogicalResult AIEX::NpuCreateScratchpadOp::verify() {
1377 if (getUsageType() != 0) {
1378 return emitOpError(
"usage_type must be 0 (got ")
1379 <<
static_cast<uint32_t
>(getUsageType())
1380 <<
"); other layouts are not supported.";
1385 constexpr uint32_t kMaxScratchpadSizeBytes = 128;
1386 if (getSize() == 0) {
1387 return emitOpError(
"size must be greater than 0.");
1389 if (getSize() % 4 != 0) {
1390 return emitOpError(
"size (")
1391 << getSize() <<
") must be a multiple of 4 bytes.";
1393 if (getSize() > kMaxScratchpadSizeBytes) {
1394 return emitOpError(
"size (")
1395 << getSize() <<
" bytes) exceeds maximum scratchpad size of "
1396 << kMaxScratchpadSizeBytes <<
" bytes.";
1401 uint32_t numEntries = getSize() / 4;
1402 if (Block *block = (*this)->getBlock()) {
1403 for (
auto updateOp : block->getOps<AIEX::NpuUpdateFromScratchpadOp>()) {
1404 if (updateOp.getStateTableIdx() < numEntries)
1406 return updateOp.emitOpError(
"state_table_idx ")
1407 <<
static_cast<uint32_t
>(updateOp.getStateTableIdx())
1408 <<
" is out of bounds for scratchpad of size " << getSize()
1409 <<
" bytes (" << numEntries <<
" entries) created by "
1410 << (*this)->getName() <<
".";
1418 auto runtimeSeq = getOperation()->getParentOfType<AIE::RuntimeSequenceOp>();
1423 NpuCreateScratchpadOp firstSeen;
1424 runtimeSeq.walk([&](NpuCreateScratchpadOp op) {
1426 return WalkResult::interrupt();
1428 if (firstSeen != *
this) {
1429 InFlightDiagnostic diag =
1430 emitOpError(
"only one 'aiex.npu.create_scratchpad' is allowed per "
1431 "runtime sequence");
1432 diag.attachNote(firstSeen.getLoc())
1433 <<
"previous 'aiex.npu.create_scratchpad' here";
1444LogicalResult AIEX::NpuMaskWrite32Op::verify() {
1445 return verifyBufferWriteScope(*
this);
1453 sizeof(uint32_t), names);
1456std::optional<uint32_t>
1460 return std::nullopt;
1461 return ::getAbsoluteAddress(
this, *addressOffset, names);
1468LogicalResult AIEX::NpuMaskPollOp::verify() {
1469 return verifyBufferWriteScope(*
this);
1477 sizeof(uint32_t), names);
1480std::optional<uint32_t>
1484 return std::nullopt;
1485 return ::getAbsoluteAddress(
this, *addressOffset, names);
1492LogicalResult AIEX::NpuBlockWriteOp::verify() {
1493 return verifyBufferWriteScope(*
this);
1500 auto type = dyn_cast<MemRefType>(getData().getType());
1501 DataLayout layout = DataLayout::closest(*
this);
1502 auto bytes = getStaticMemRefStorageBytes(type, layout);
1504 return emitOpError(
"payload must have a static, fixed-size storage extent "
1505 "representable in 64 bits when buffer is present");
1506 llvm::TypeSize elementBits = layout.getTypeSizeInBits(type.getElementType());
1507 if (elementBits.isScalable() || elementBits.getFixedValue() != 32)
1509 "payload must have 32-bit elements when buffer is present");
1510 return verifyBufferWrite(*
this, getAddress(), *bytes, names);
1513std::optional<uint32_t>
1515 return ::getAbsoluteAddress(
this, getAddress(), names);
1518DenseIntElementsAttr AIEX::NpuBlockWriteOp::getDataWords() {
1519 Value
memref = this->getData();
1520 DataLayout dataLayout = DataLayout::closest(*
this);
1521 int64_t width = dataLayout.getTypeSizeInBits(
1522 cast<MemRefType>(
memref.getType()).getElementType());
1524 emitWarning(
"Only 32-bit data type is supported for now");
1528 memref::GetGlobalOp getGlobal =
memref.getDefiningOp<memref::GetGlobalOp>();
1530 emitError(
"Only MemRefs from memref.get_global are supported");
1534 auto global = dyn_cast_if_present<memref::GlobalOp>(
1535 (*this)->getParentOfType<AIE::DeviceOp>().lookupSymbol(
1536 getGlobal.getName()));
1538 emitError(
"Global symbol not found");
1542 auto initVal = global.getInitialValue();
1544 emitError(
"Global symbol has no initial value");
1548 auto data = dyn_cast<DenseIntElementsAttr>(*initVal);
1550 emitError(
"Global symbol initial value is not a dense int array");
1561AIE::DMABDOp AIEX::DMAConfigureTaskOp::getFirstBd() {
1562 Region &body = getBody();
1566 auto bd_ops = body.front().getOps<AIE::DMABDOp>();
1567 if (bd_ops.empty() && body.front().getNumSuccessors() == 1) {
1571 Block &chain_entry = *body.front().getSuccessor(0);
1572 bd_ops = chain_entry.getOps<AIE::DMABDOp>();
1574 if (bd_ops.empty()) {
1577 return *bd_ops.begin();
1581AIEX::DMAConfigureTaskOp::canonicalize(AIEX::DMAConfigureTaskOp op,
1582 PatternRewriter &rewriter) {
1584 Region &body = op.getBody();
1585 bool did_rewrite =
false;
1586 for (
auto &block : body) {
1587 if (block.empty()) {
1590 auto ops_it = block.without_terminator();
1591 if (std::distance(ops_it.begin(), ops_it.end()) == 0) {
1592 rewriter.eraseOp(block.getTerminator());
1634 LogicalResult result = success();
1635 body.walk([&](AIE::DMABDOp bd) {
1638 if (failed(bd.verifyMixedSizesAndStrides())) {
1647 size_t numDims = bd.getMixedSizes().size();
1648 if (bd.getIteration()) {
1649 if (numDims + 1 > maxNDims) {
1650 bd.emitOpError() <<
"Cannot give more than "
1651 << std::to_string(maxNDims - 1)
1652 <<
" dimensions for step sizes and wraps alongside "
1653 "the iteration attribute on this tile (got "
1654 << std::to_string(numDims) <<
" dimensions).";
1656 }
else if (d3Unsupported && numDims > 3) {
1657 bd.emitOpError() <<
"Cannot give more than 3 dimensions for step sizes "
1658 "and wraps alongside the iteration attribute on "
1660 << std::to_string(numDims)
1661 <<
" dimensions): its fourth addressing dimension "
1662 "(d3) is not supported yet.";
1667 auto isConstant = [](OpFoldResult v) {
1668 return getConstantIntValue(v).has_value();
1670 if (numDims > maxNDims && llvm::all_of(bd.getMixedSizes(), isConstant) &&
1671 llvm::all_of(bd.getMixedStrides(), isConstant))
1673 if (numDims > maxNDims) {
1674 bd.emitOpError() <<
"Cannot give more than " << std::to_string(maxNDims)
1675 <<
" dimensions for step sizes and wraps on this tile "
1677 << std::to_string(numDims) <<
" dimensions).";
1684LogicalResult AIEX::DMAConfigureTaskOp::verify() {
1686 getDirection(), getChannel())))
1692 std::optional<int> col = getTileLike().tryGetCol();
1693 std::optional<int> row = getTileLike().tryGetRow();
1695 failed(verifyTaskBDDimensions(targetModel, *col, *row, getBody())))
1697 Region &body = getBody();
1704 LogicalResult result = success();
1705 bool taskHasPacket = getPacket().has_value();
1706 llvm::SmallVector<AIE::DMABDOp> bds;
1707 for (
auto &block : body) {
1708 if (block.empty()) {
1711 if (block.hasNoPredecessors() && !block.isEntryBlock()) {
1712 auto error = block.getTerminator()->emitError(
1713 "Block ending in this terminator does not form a chain with "
1721 block.walk([&](AIE::DMABDOp bd) {
1722 if (bd.getBurstLength() != 0 &&
1723 !targetModel.
isShimNOCTile(getTileID().col, getTileID().row)) {
1724 bd.emitOpError(
"Burst length is only supported in Shim NOC tiles that "
1725 "are connected to the memory-mapped NOC.");
1731 bd, bd.getPacket().value_or(AIE::PacketInfoAttr()))) ||
1733 failed(bd.verifyTransferInBounds()))
1740 bool onMemTile = col && row && targetModel.
isMemTile(*col, *row);
1741 uint32_t adjacentChannels =
1744 if (onMemTile &&
static_cast<uint32_t
>(getChannel()) >= adjacentChannels) {
1745 auto isNonLocal = [&](AIE::TileLike tile) {
1748 auto resourceCol = tile.tryGetCol();
1749 auto resourceRow = tile.tryGetRow();
1750 return resourceCol && resourceRow &&
1751 (*resourceCol != *col || *resourceRow != *row);
1753 body.walk([&](Operation *op) {
1754 Operation *resource =
nullptr;
1755 AIE::TileLike resourceTile;
1757 if (
auto bd = dyn_cast<AIE::DMABDOp>(op)) {
1758 auto buffer = bd.getBuffer().getDefiningOp<AIE::BufferOp>();
1762 resourceTile = buffer.getTileLike();
1764 }
else if (
auto useLock = dyn_cast<AIE::UseLockOp>(op)) {
1765 auto lock = useLock.getLock().getDefiningOp<AIE::LockOp>();
1767 useLock.emitOpError()
1768 <<
"requires a lock defined by aie.lock in a task on memtile DMA "
1775 resourceTile = lock.getTileLike();
1783 if (!resourceTile) {
1784 op->emitOpError() <<
"uses a " << what
1785 <<
" whose tile operand is not a tile";
1789 if (!isNonLocal(resourceTile))
1791 InFlightDiagnostic err = op->emitOpError()
1792 <<
"is in a task on memtile DMA channel "
1794 <<
" and attempts to access a non-local " << what
1795 <<
"; only channels below " << adjacentChannels
1796 <<
" reach neighboring tiles";
1797 err.attachNote(resource->getLoc()) << what;
1801 if (getOutOfOrder()) {
1803 if (getIssueToken()) {
1805 emitOpError(
"out_of_order channel cannot issue a completion token");
1806 err.attachNote() <<
"set issue_token = false on this out-of-order task";
1810 getOperation(), getDirection(), getOutOfOrder(),
1811 llvm::ArrayRef<AIE::DMABDOp>(bds),
1818LogicalResult AIEX::DMAStartTaskOp::verify() {
1819 if (getRepeatCountAttr() && getRepeatCountVal())
1821 "takes repeat_count or a runtime repeat count, not both");
1822 if (IntegerAttr rc = getRepeatCountAttr(); rc && rc.getInt() < 0)
1823 return emitOpError(
"repeat_count must be non-negative, got ")
1825 if (hasRepeatParameter() && (getRepeatCountAttr() || getRepeatCountVal()))
1826 return emitOpError(
"takes a repeat_parameter or a repeat count, not both");
1827 if (getRepeatParameterAttr() && getRepeatStateTableIdxAttr())
1828 return emitOpError(
"takes repeat_parameter or repeat_state_table_idx, "
1833std::optional<int64_t> AIEX::DMAConfigureTaskForOp::getStaticBytesStreamed() {
1835 for (Operation *user : getResult().getUsers()) {
1836 auto start = dyn_cast<AIEX::DMAStartTaskOp>(user);
1838 if (isa<AIEX::DMAAwaitTaskOp, AIEX::DMAFreeTaskOp>(user))
1842 return std::nullopt;
1846 if (start->getBlock() != (*this)->getBlock() ||
1847 start.getRepeatCountAttr() || start.getRepeatCountVal() ||
1848 start.hasRepeatParameter())
1849 return std::nullopt;
1854 std::optional<int64_t> repeat = getConstantIntValue(getRepeatCountValue());
1855 if (!repeat || *repeat < 0)
1856 return std::nullopt;
1858 Region &body = getBody();
1860 return std::nullopt;
1864 std::optional<int64_t> moved = 0;
1865 for (
auto scc = llvm::scc_begin(&body.front()); !scc.isAtEnd(); ++scc) {
1867 return std::nullopt;
1868 for (AIE::DMABDOp bd : scc->front()->getOps<AIE::DMABDOp>()) {
1871 std::optional<int64_t> len =
1872 bd.getLengthParameterAttr() || bd.getLengthStateTableIdxAttr()
1874 : bd.getStaticLenInBytes();
1875 if (!len || bd.getIteration() || bd.getNextBdId())
1876 return std::nullopt;
1877 moved = llvm::checkedAdd(*moved, *len);
1879 return std::nullopt;
1882 std::optional<int64_t> runs = llvm::checkedAdd(*repeat, int64_t{1});
1884 runs = llvm::checkedMul(*runs, starts);
1885 return runs ? llvm::checkedMul(*moved, *runs) : std::nullopt;
1892 SmallVector<int64_t> segmentBytes;
1894 int64_t objectBytes;
1897 static std::optional<BdChain>
get(ArrayRef<int64_t> segmentBytes,
1899 if (segmentBytes.size() == 1)
1901 std::optional<int64_t> objectBytes = 0;
1902 for (int64_t bytes : segmentBytes) {
1903 std::optional<int64_t> run = llvm::checkedMul(bytes, copies);
1904 if (bytes <= 0 || copies <= 0 || !run)
1905 return std::nullopt;
1906 objectBytes = llvm::checkedAdd(*objectBytes, *run);
1908 return std::nullopt;
1910 if (segmentBytes.empty())
1911 return std::nullopt;
1912 return BdChain{SmallVector<int64_t>(segmentBytes), copies, *objectBytes};
1916 bool endsOnBd(int64_t bytes)
const {
1917 int64_t rest = bytes % objectBytes;
1919 for (int64_t segment : segmentBytes) {
1920 if (rest < start + segment * copies)
1921 return (rest - start) % segment == 0;
1922 start += segment * copies;
1927 bool operator==(
const BdChain &other)
const {
1928 return segmentBytes == other.segmentBytes && copies == other.copies;
1933std::optional<int64_t> AIEX::NpuDmaMemcpyNdOp::getStaticBytesStreamed() {
1934 if (getLengthParameterAttr() || getLengthStateTableIdxAttr())
1935 return std::nullopt;
1936 uint64_t bits = getElementTypeBitwidth();
1938 return std::nullopt;
1939 std::optional<int64_t> bytes =
static_cast<int64_t
>(bits / 8);
1940 for (OpFoldResult size : getMixedSizes()) {
1941 std::optional<int64_t> extent = getConstantIntValue(size);
1942 bytes = bytes && extent ? llvm::checkedMul(*bytes, *extent) : std::nullopt;
1953static LogicalResult verifyTransferCoversWholeObjects(
1954 Operation *transfer, SymbolRefAttr alloc, std::optional<int64_t> moved,
1955 AIE::ObjectFifoCreateOp fifo, SymbolTableCollection &symbols) {
1956 if (fifo.getPadDimensions() || fifo.usesStream())
1958 if (!moved || *moved == 0)
1960 DataLayout layout = DataLayout::closest(transfer);
1962 auto objectBytesOf = [&](Type fifoType) -> std::optional<int64_t> {
1963 MemRefType elem = cast<AIE::AIEObjectFifoType>(fifoType).getElementType();
1964 return llvm::checkedMul(
1965 elem.getNumElements(),
1966 static_cast<int64_t
>(layout.getTypeSize(elem.getElementType())));
1976 SmallVector<Value> linkTiles;
1977 SmallVector<BdChain> chains;
1978 auto device = fifo->getParentOfType<AIE::DeviceOp>();
1979 auto resolve = [&](ArrayAttr refs) {
1980 std::vector<AIE::ObjectFifoCreateOp> fifos;
1981 for (Attribute ref : refs)
1982 if (
auto name = dyn_cast<FlatSymbolRefAttr>(ref))
1983 if (
auto linked = symbols.lookupSymbolIn<AIE::ObjectFifoCreateOp>(
1984 device, name.getAttr()))
1985 fifos.push_back(linked);
1988 auto self = FlatSymbolRefAttr::get(fifo.getSymNameAttr());
1990 for (AIE::ObjectFifoLinkOp link : device.getOps<AIE::ObjectFifoLinkOp>()) {
1991 if (!llvm::is_contained(link.getFifoIns(), self) &&
1992 !llvm::is_contained(link.getFifoOuts(), self))
1994 std::vector<AIE::ObjectFifoCreateOp> ins = resolve(link.getFifoIns());
1995 std::vector<AIE::ObjectFifoCreateOp> outs = resolve(link.getFifoOuts());
1996 std::optional<Value> sharedTile = link.getOptionalSharedTile();
1997 if (ins.empty() || outs.empty() || !sharedTile)
1999 linkTiles.push_back(*sharedTile);
2000 AIE::ObjectFifoCreateOp owner = link.getPoolOwner();
2002 cast<AIE::AIEObjectFifoType>(owner.getElemType()).getElementType();
2004 static_cast<int64_t
>(layout.getTypeSize(pool.getElementType()));
2005 SmallVector<std::pair<int64_t, int64_t>> segments =
2006 link.getPoolSegments();
2007 if (fifo != owner && (link.isJoin() || link.isDistribute())) {
2008 std::vector<AIE::ObjectFifoCreateOp> &many = link.isJoin() ? ins : outs;
2009 segments = {segments[llvm::find(many, fifo) - many.begin()]};
2011 SmallVector<int64_t> segmentBytes;
2012 for (
auto [offset, size] : segments) {
2013 std::optional<int64_t> bytes = llvm::checkedMul(size, width);
2016 segmentBytes.push_back(*bytes);
2018 int64_t copies = llvm::is_contained(outs, fifo)
2019 ? link.getRepeatCount().value_or(1)
2021 std::optional<BdChain> chain;
2022 if (segmentBytes.size() == segments.size())
2023 chain = BdChain::get(segmentBytes, copies);
2024 if (chain && !llvm::is_contained(chains, *chain))
2025 chains.push_back(*chain);
2032 auto addChain = [&](Value tile, Type fifoType) {
2033 if (llvm::is_contained(linkTiles, tile))
2035 std::optional<BdChain> chain;
2036 if (std::optional<int64_t> bytes = objectBytesOf(fifoType))
2037 chain = BdChain::get({*bytes}, 1);
2038 if (chain && !llvm::is_contained(chains, *chain))
2039 chains.push_back(*chain);
2042 dyn_cast_or_null<AIE::TileLike>(fifo.getProducerTile().getDefiningOp());
2045 if (!producer.isShimTile())
2046 addChain(fifo.getProducerTile(), fifo.getElemType());
2047 for (Value consumer : fifo.getConsumerTiles()) {
2048 auto tile = dyn_cast_or_null<AIE::TileLike>(consumer.getDefiningOp());
2049 if (!tile || !tile.isShimTile())
2050 addChain(consumer, fifo.getConsumerElemTypeOrDefault());
2056 auto sequence = transfer->getParentOfType<AIE::RuntimeSequenceOp>();
2057 if (!sequence || transfer->getBlock() != &sequence.getBody().front())
2062 if (llvm::any_of(transfer->getBlock()->getOps<AIEX::DmaChannelResetForOp>(),
2063 [&](AIEX::DmaChannelResetForOp reset) {
2064 return reset.getObjfifoAttr() == alloc;
2069 auto through = [&](Operation *op) -> std::optional<int64_t> {
2070 if (
auto memcpy = dyn_cast<AIEX::NpuDmaMemcpyNdOp>(op))
2071 return memcpy.getMetadata() == alloc ? memcpy.getStaticBytesStreamed()
2073 if (
auto task = dyn_cast<AIEX::DMAConfigureTaskForOp>(op))
2074 return task.getAlloc() == alloc ? task.getStaticBytesStreamed() : 0;
2075 if (
auto chain = dyn_cast<AIEX::DMAStartBdChainForOp>(op))
2076 return chain.getAllocAttr() == alloc ? std::nullopt
2077 : std::optional<int64_t>(0);
2083 for (Operation *prev = transfer->getPrevNode(); prev;
2084 prev = prev->getPrevNode())
2085 if (through(prev) != 0)
2087 std::optional<int64_t> total = 0;
2088 int64_t sharing = 0;
2089 WalkResult walk = sequence.walk([&](Operation *op) {
2090 std::optional<int64_t> bytes = through(op);
2093 return WalkResult::advance();
2094 if (!bytes || op->getBlock() != transfer->getBlock())
2095 return WalkResult::interrupt();
2096 total = llvm::checkedAdd(*total, *bytes);
2098 return WalkResult::interrupt();
2100 return WalkResult::advance();
2102 if (walk.wasInterrupted())
2104 const BdChain *partial = llvm::find_if(
2105 chains, [&](
const BdChain &chain) {
return !chain.endsOnBd(*total); });
2106 if (partial == chains.end())
2109 InFlightDiagnostic error = transfer->emitOpError()
2110 <<
"moves " << *moved
2111 <<
" bytes through objectFIFO @"
2112 << fifo.getSymName() <<
", which";
2114 error <<
", with this runtime sequence's other transfers through it ("
2115 << *total <<
" bytes in all),";
2116 error <<
" is not a whole number of its " << partial->objectBytes
2118 if (partial->segmentBytes.size() == 1)
2119 return error <<
"; the far end's buffer descriptor is sized by the "
2120 "object, so a partial one never completes";
2121 std::string segments;
2122 llvm::raw_string_ostream os(segments);
2123 llvm::interleaveComma(partial->segmentBytes, os);
2124 error <<
" and doesn't end on a segment boundary (segments of " << segments
2126 if (partial->copies > 1)
2127 error <<
", each sent " << partial->copies <<
" times in a row";
2128 return error <<
"); the far end's buffer descriptors are sized by the "
2129 "segments, so a partial one never completes";
2133AIEX::DMAConfigureTaskOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2134 FlatSymbolRefAttr alloc = getAllocAttr();
2135 AIE::DeviceOp dev = getOperation()->getParentOfType<AIE::DeviceOp>();
2138 auto allocation = dyn_cast_or_null<AIE::ShimDMAAllocationOp>(
2139 symbolTable.lookupSymbolIn(dev, alloc.getAttr()));
2141 return emitOpError(
"alloc ")
2142 << alloc <<
" names no aie.shim_dma_allocation";
2143 if (allocation.getTile() != getTile() ||
2144 allocation.getChannelDir() != getDirection() ||
2145 allocation.getChannelIndex() !=
static_cast<int>(getChannel()))
2146 return emitOpError(
"runs on another channel than its alloc ") << alloc;
2153LogicalResult AIEX::DMAConfigureTaskForOp::verifySymbolUses(
2154 SymbolTableCollection &symbolTable) {
2155 AIE::DeviceOp dev = getOperation()->getParentOfType<AIE::DeviceOp>();
2159 symbolTable.lookupSymbolIn(dev, getAlloc().getRootReference());
2161 return emitOpError() << getAlloc() <<
" does not name a symbol";
2167 LogicalResult named =
2168 TypeSwitch<Operation *, LogicalResult>(target)
2169 .Case([&](AIE::ShimDMAAllocationOp alloc) {
2170 tileValue = alloc.getTile();
2173 .Case([&](AIE::RouteEndpointOp endpoint) -> LogicalResult {
2174 tileValue = endpoint.getTile();
2175 if (endpoint.getBundle() == AIE::WireBundle::DMA)
2177 return emitOpError() << getAlloc() <<
" names a "
2178 << stringifyWireBundle(endpoint.getBundle())
2179 <<
" port, not a DMA channel";
2181 .Case([&](AIE::ObjectFifoCreateOp fifo) {
2182 return verifyTransferCoversWholeObjects(
2183 *
this, getAlloc(), getStaticBytesStreamed(), fifo, symbolTable);
2185 .Default([&](Operation *) -> LogicalResult {
2186 return emitOpError() << getAlloc()
2187 <<
" must name an aie.shim_dma_allocation, an "
2188 "aie.route_endpoint or an aie.objectfifo";
2194 auto tile = tileValue ? tileValue.getDefiningOp<AIE::TileOp>() : nullptr;
2198 return verifyTaskBDDimensions(targetModel, tile.getCol(), tile.getRow(),
2206AIE::BDChainOp AIEX::DMAStartBdChainOp::getBDChainOp() {
2207 AIE::DeviceOp device = (*this)->getParentOfType<AIE::DeviceOp>();
2208 AIE::BDChainOp chain = device.lookupSymbol<AIE::BDChainOp>(getSymbol());
2212LogicalResult AIEX::DMAStartBdChainOp::verify() {
2214 getDirection(), getChannel())))
2216 AIE::BDChainOp chain = getBDChainOp();
2218 return emitOpError(
"symbol does not reference valid BD chain");
2221 auto actualArgTypes = getArgs().getTypes();
2222 auto expectedArgTypes = chain.getRegion().getArgumentTypes();
2223 if (actualArgTypes.size() != expectedArgTypes.size()) {
2224 return emitOpError(
"Number of arguments mismatches.");
2226 for (
unsigned i = 0, n = expectedArgTypes.size(); i < n; i++) {
2227 if (actualArgTypes[i] != expectedArgTypes[i]) {
2228 return emitOpError(
"Argument ") << (i + 1) <<
" types mismatch: "
2229 <<
"expected " << expectedArgTypes[i]
2230 <<
" but got " << actualArgTypes[i];
2240uint32_t AIEX::NpuControlPacketOp::getRowFromAddr() {
2245uint32_t AIEX::NpuControlPacketOp::getColumnFromAddr() {
2250bool AIEX::NpuControlPacketOp::isOrdinaryWrite() {
2254bool AIEX::NpuControlPacketOp::isOrdinaryWrite(
2256 auto data = getData();
2257 if (getOpcode() != 0 || !data)
2264 uint32_t offset = getAddress() & ((1u << target.
getRowShift()) - 1);
2265 for (
size_t index = 0; index < data->size(); ++index)
2271LogicalResult AIEX::NpuControlPacketOp::verify() {
2274 return emitOpError(
"control packets are not yet supported on AIE4");
2277 uint32_t opcode = getOpcode();
2279 return emitOpError(
"opcode ")
2281 <<
" is reserved; expected 0 (write), 1 (read), or 2 (write with "
2284 bool isRead = opcode == 1;
2285 if (isRead && getData())
2286 return emitOpError(
"read control packet must not carry a data payload; "
2287 "the requested word count goes in the length attribute");
2288 if (!isRead && !getData())
2290 "control packet with a write opcode requires a data payload");
2293 std::optional<uint32_t> words;
2294 if (
auto data = getData())
2295 words = data->size();
2297 words = getLength();
2299 return emitOpError(
"read control packet requires a length attribute");
2301 return emitOpError(
"control packet payload must be at least 1 word");
2304 if (isRead && *words > getMaxDataWords())
2305 return emitOpError(
"read control packet length ")
2306 << *words <<
" exceeds the maximum of " << getMaxDataWords()
2312AIE::TileID AIEX::NpuControlPacketOp::getTileFromAddr() {
2313 return {
static_cast<int>(getColumnFromAddr()),
2314 static_cast<int>(getRowFromAddr())};
2317uint32_t AIEX::NpuControlPacketOp::getLocalAddress() {
2325LogicalResult AIEX::SetLockOp::verify() {
2329 return emitOpError(
"SetLockOp is not supported on AIE1.");
2331 if (!getLock().getDefiningOp<AIE::LockOp>())
2332 return emitOpError(
"lock operand is not an aie.lock");
2334 if (std::optional<int64_t> value = getConstantIntValue(getValue())) {
2336 return emitOpError(
"Lock value must be non-negative");
2338 return emitOpError(
"Lock value exceeds the maximum value of " +
2342 auto lockOp = getLockOp();
2343 auto lockIDOpt = getLockOp().getLockID();
2352 std::optional<int> col = lockOp.getTileLike().tryGetCol();
2353 std::optional<int> row = lockOp.getTileLike().tryGetRow();
2357 uint32_t lockID = lockOp.getLockIDValue();
2359 if (lockID >= targetModel.
getNumLocks(*col, *row)) {
2360 return emitOpError(
"Lock ID out of range for given tile. Max ID: " +
2361 std::to_string(targetModel.
getNumLocks(*col, *row) - 1));
2365 return emitOpError(
"Invalid lock ID and tile combination when trying to "
2366 "retrieve the local lock address.");
2376static LogicalResult verifyBdPoolPartition(Operation *op,
int col,
int row,
2377 uint32_t begin, uint32_t end) {
2379 if (begin >= end || end > numBds)
2380 return op->emitOpError()
2381 <<
"partition [" << begin <<
", " << end
2382 <<
") is not a nonempty range of the " << numBds
2383 <<
" buffer descriptors on tile (" << col <<
", " << row <<
")";
2387LogicalResult AIEX::DMABdPoolPopOp::verify() {
2388 if (failed(verifyBdPoolPartition(*
this, getColumn(), getRow(), getBdBegin(),
2391 std::optional<uint32_t>
id = getId();
2392 if (
id && (*
id < getBdBegin() || *
id >= getBdEnd()))
2393 return emitOpError() <<
"takes buffer descriptor ID " << *
id
2394 <<
", which is outside its partition [" << getBdBegin()
2395 <<
", " << getBdEnd() <<
")";
2399LogicalResult AIEX::DMABdPoolPushOp::verify() {
2400 return verifyBdPoolPartition(*
this, getColumn(), getRow(), getBdBegin(),
2408LogicalResult AIEX::DmaChannelResetOp::verify() {
2411 auto tile = dyn_cast_or_null<AIE::TileOp>(getTile().getDefiningOp());
2413 return emitOpError() <<
"tile operand must be produced by an aie.tile op";
2414 int col = tile.getCol();
2415 int row = tile.getRow();
2422 return emitOpError() <<
"tile (" << col <<
", " << row
2423 <<
") has no DMA channel reset (only core and mem "
2424 "tiles do; shim NOC DMA has no reset bit)";
2426 uint32_t numChannels =
2428 if (getChannel() >= numChannels)
2429 return emitOpError() <<
"channel " << getChannel()
2430 <<
" out of range for this tile and direction (tile "
2432 << numChannels <<
" DMA channel(s) in this direction)";
2437LogicalResult AIEX::DmaChannelResetForOp::verify() {
2443 AIE::DeviceOp dev = getOperation()->getParentOfType<AIE::DeviceOp>();
2451 return emitOpError() <<
"is not supported on AIE1 devices (the resident "
2452 "re-arm relies on the aie2p start-queue push)";
2453 Operation *target = dev.lookupSymbol(getObjfifo());
2456 if (!isa<AIE::ObjectFifoCreateOp, AIE::RouteEndpoint,
2457 AIE::ObjectFifoRearmBindingOp>(target))
2458 return emitOpError() <<
"'" << getObjfifo()
2459 <<
"' must reference an aie.objectfifo (or its "
2460 "aie.objectfifo_rearm_binding)";
2468LogicalResult AIEX::CoreResetOp::verify() {
2474 return emitOpError(
"aiex.core_reset is not supported on AIE1.");
2476 auto tile = dyn_cast_or_null<AIE::TileOp>(getTile().getDefiningOp());
2478 return emitOpError() <<
"tile operand must be produced by an aie.tile op";
2479 int col = tile.getCol();
2480 int row = tile.getRow();
2489 return emitOpError() <<
"tile (" << col <<
", " << row
2490 <<
") has no core to reset (only core tiles have a "
2491 "CORE_CONTROL register)";
2499uint64_t AIEX::BlockFloatType::getTotalSizeInBits()
const {
2500 return getBlockSize() * getMantissaBits() + getExponentBits() +
2501 getSubtileShiftBits();
2504llvm::TypeSize AIEX::BlockFloatType::getTypeSizeInBits(
2505 const mlir::DataLayout &dataLayout,
2506 mlir::DataLayoutEntryListRef params)
const {
2507 return llvm::TypeSize::getFixed(getTotalSizeInBits());
2510uint64_t AIEX::BlockFloatType::getABIAlignment(
2511 const mlir::DataLayout &dataLayout,
2512 mlir::DataLayoutEntryListRef params)
const {
2518std::optional<AIEX::BlockFloatType::BlockFormat>
2519AIEX::BlockFloatType::getBlockFormat(StringRef blockType) {
2520 static const llvm::StringMap<AIEX::BlockFloatType::BlockFormat>
2522 {
"v8bfp16ebs8", {8, 8, 8, 0}},
2523 {
"v16bfp16ebs16", {16, 8, 8, 0}},
2526 auto it = blockFormatsMap.find(blockType);
2527 if (it != blockFormatsMap.end()) {
2531 return std::nullopt;
2535AIEX::BlockFloatType::verify(function_ref<InFlightDiagnostic()> emitError,
2536 StringRef block_type) {
2537 if (!getBlockFormat(block_type))
2538 return emitError() <<
"Invalid block type: " << block_type
2539 <<
". Known types are: v8bfp16ebs8, v16bfp16ebs16.";
2548AIE::DeviceOp AIEX::ConfigureOp::getReferencedDeviceOp() {
2549 ModuleOp moduleOp = this->getOperation()->getParentOfType<ModuleOp>();
2551 emitError(
"aiex.configure must be inside of a module");
2554 Operation *maybeReferencedDevice =
2555 SymbolTable::lookupSymbolIn(moduleOp.getOperation(), getSymbolAttr());
2556 if (!maybeReferencedDevice) {
2557 emitError(
"No such device: '") << getSymbolAttr() <<
"'";
2560 AIE::DeviceOp referencedDevice =
2561 llvm::dyn_cast<AIE::DeviceOp>(maybeReferencedDevice);
2562 if (!referencedDevice) {
2563 emitError(
"Not a device: '") << getSymbolAttr() <<
"'";
2566 return referencedDevice;
2573LogicalResult AIEX::ReadScratchpadParameterOp::verify() {
2574 auto device = (*this)->getParentOfType<AIE::DeviceOp>();
2576 return emitOpError(
"must be inside an aie.device");
2578 if (!(*this)->getParentOfType<AIE::CoreOp>()) {
2579 return emitOpError(
"must be inside an aie.core");
2581 auto moduleOp = (*this)->getParentOfType<ModuleOp>();
2583 !moduleOp.lookupSymbol<AIEX::ScratchpadParameterOp>(getParameter())) {
2584 return emitOpError(
"references unknown parameter '")
2586 <<
"' (aiex.scratchpad_parameter ops are declared at module scope)";
2588 if (getResult().getType().isF32()) {
2590 "f32 parameters are not supported: the scratchpad encoding zeroes "
2591 "the top 2 bits, which clobbers the sign bit and top exponent bit "
2592 "of an f32. Use bf16 or an integer type up to i32 instead.");
2597LogicalResult AIEX::WaitScratchpadParametersOp::verify() {
2598 if (!(*this)->getParentOfType<AIE::CoreOp>()) {
2599 return emitOpError(
"must be inside an aie.core");
2604LogicalResult AIEX::ConfigureOp::verify() {
2605 AIE::DeviceOp parentDev = getOperation()->getParentOfType<AIE::DeviceOp>();
2606 AIE::DeviceOp referencedDev = getReferencedDeviceOp();
2607 if (!referencedDev) {
2610 if (parentDev.getDevice() != referencedDev.getDevice()) {
2611 emitError(
"Device types do not match: '")
2612 << AIE::stringifyAIEDevice(parentDev.getDevice()) <<
"' vs. '"
2613 << AIE::stringifyAIEDevice(referencedDev.getDevice()) <<
"'";
2623AIE::DeviceOp AIEX::RunOp::getCalleeDeviceOp() {
2624 AIEX::ConfigureOp configureOp =
2625 getOperation()->getParentOfType<AIEX::ConfigureOp>();
2629 AIE::DeviceOp referencedDevice = configureOp.getReferencedDeviceOp();
2630 return referencedDevice;
2633AIE::RuntimeSequenceOp
2635 AIEX::ConfigureOp configureOp =
2636 getOperation()->getParentOfType<AIEX::ConfigureOp>();
2640 AIE::DeviceOp referencedDevice = configureOp.getReferencedDeviceOp();
2641 if (!referencedDevice) {
2645 StringAttr name = getRuntimeSequenceSymbolAttr().getAttr();
2649 return tables->
lookupIn<AIE::RuntimeSequenceOp>(referencedDevice, name);
2656LogicalResult AIEX::NpuLoadPdiOp::canonicalize(AIEX::NpuLoadPdiOp op,
2657 PatternRewriter &rewriter) {
2659 Operation *nextOp = op->getNextNode();
2664 auto nextLoadPdi = dyn_cast<AIEX::NpuLoadPdiOp>(nextOp);
2669 if (op.getDeviceRefAttr() == nextLoadPdi.getDeviceRefAttr() &&
2670 op.getId() == nextLoadPdi.getId() &&
2671 op.getSize() == nextLoadPdi.getSize() &&
2672 op.getAddress() == nextLoadPdi.getAddress()) {
2674 rewriter.eraseOp(op);
2685static bool writesConfig(Operation *op) {
2686 return isa<AIEX::NpuLoadPdiOp, AIEX::NpuWriteConfigOp,
2687 AIEX::NpuWriteTeardownOp>(op);
2694static Operation *findConfigOpBefore(Operation *op,
2695 function_ref<
bool(Operation *)> visit) {
2696 for (Operation *prev = op->getPrevNode(); prev; prev = prev->getPrevNode())
2697 if (writesConfig(prev) && visit(prev))
2699 for (Operation &next : llvm::reverse(*op->getBlock())) {
2702 if (writesConfig(&next) && visit(&next))
2705 return visit(op) ? op :
nullptr;
2710static Operation *precedingReset(Operation *op) {
2711 return findConfigOpBefore(op, [&](Operation *prev) {
2712 return prev != op &&
2713 isa<AIEX::NpuLoadPdiOp, AIEX::NpuWriteTeardownOp>(prev);
2717bool AIEX::NpuLoadPdiOp::loadsSamePdi(NpuLoadPdiOp other) {
2718 return getDeviceRefAttr() == other.getDeviceRefAttr() &&
2719 getId() == other.getId() && getSize() == other.getSize() &&
2720 getAddress() == other.getAddress();
2723LogicalResult AIEX::NpuWriteConfigOp::verify() {
2724 Operation *found = precedingReset(*
this);
2726 return emitOpError(
"must follow the load_pdi that resets the array");
2727 auto reset = dyn_cast<AIEX::NpuLoadPdiOp>(found);
2732 bool tornDown =
true;
2733 Operation *later = reset;
2735 cast<AIEX::NpuLoadPdiOp>(findConfigOpBefore(reset, [&](Operation *op) {
2736 if (isa<AIEX::NpuWriteConfigOp>(op) &&
2737 !isa<AIEX::NpuWriteTeardownOp>(later))
2740 return isa<AIEX::NpuLoadPdiOp>(op);
2742 if (!before.loadsSamePdi(reset) || tornDown)
2744 InFlightDiagnostic diag = emitOpError(
2745 "follows a load_pdi the firmware skips, as it loads the PDI loaded "
2746 "just before it, so the array is not reset");
2747 diag.attachNote(before.getLoc()) <<
"the PDI is loaded here";
2752AIEX::NpuLoadPdiOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2753 FlatSymbolRefAttr ref = getDeviceRefAttr();
2756 auto device = (*this)->getParentOfType<AIE::DeviceOp>();
2757 Operation *scope = device ? device->getParentOp()
2758 : SymbolTable::getNearestSymbolTable(*
this);
2759 if (!isa_and_present<AIE::DeviceOp>(symbolTable.lookupSymbolIn(scope, ref)))
2760 return emitOpError() << ref <<
" is not a device";
2765AIEX::NpuWriteConfigOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2766 Operation *scope = (*this)->getParentOfType<AIE::DeviceOp>()->getParentOp();
2767 if (!isa_and_present<AIE::DeviceOp>(
2768 symbolTable.lookupSymbolIn(scope, getDeviceRefAttr())))
2769 return emitOpError() << getDeviceRefAttr() <<
" is not a device";
2770 auto reset = dyn_cast_or_null<AIEX::NpuLoadPdiOp>(precedingReset(*
this));
2771 FlatSymbolRefAttr resetRef = reset ? reset.getDeviceRefAttr() :
nullptr;
2772 auto empty = resetRef ? dyn_cast_or_null<AIE::DeviceOp>(
2773 symbolTable.lookupSymbolIn(scope, resetRef))
2779 !llvm::all_of(empty.getBody()->without_terminator(), [](Operation &op) {
2780 return isa<AIE::RuntimeSequenceOp>(op) &&
2781 llvm::all_of(op.getRegion(0),
2782 [](Block &block) { return block.empty(); });
2784 return emitOpError(
"must follow a load_pdi of an empty device, which "
2785 "resets the array");
2793LogicalResult AIEX::NpuWriteTeardownOp::verify() {
2794 Operation *prev = (*this)->getPrevNode();
2795 while (prev && !writesConfig(prev))
2796 prev = prev->getPrevNode();
2797 auto config = dyn_cast_or_null<AIEX::NpuWriteConfigOp>(prev);
2798 if (!config || config.getDeviceRefAttr() != getDeviceRefAttr())
2799 return emitOpError(
"must follow the write_config of ")
2800 << getDeviceRefAttr() <<
", with no load_pdi between";
2805AIEX::NpuWriteTeardownOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2806 Operation *scope = (*this)->getParentOfType<AIE::DeviceOp>()->getParentOp();
2807 auto device = dyn_cast_or_null<AIE::DeviceOp>(
2808 symbolTable.lookupSymbolIn(scope, getDeviceRefAttr()));
2810 return emitOpError() << getDeviceRefAttr() <<
" is not a device";
2814 InFlightDiagnostic diag =
2815 emitOpError() << getDeviceRefAttr()
2816 <<
" starts a shim DMA channel, which teardown cannot stop";
2817 diag.attachNote(shimStart->getLoc()) <<
"started here";
2821LogicalResult AIEX::SetDeviceOp::verify() {
2822 auto sequence = cast<AIE::RuntimeSequenceOp>((*this)->getParentOp());
2823 if (!llvm::hasSingleElement(sequence.getBody()))
2824 return emitOpError(
"requires a single-block runtime sequence");
2829AIEX::SetDeviceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2830 Operation *scope = (*this)->getParentOfType<AIE::DeviceOp>()->getParentOp();
2831 if (!isa_and_present<AIE::DeviceOp>(
2832 symbolTable.lookupSymbolIn(scope, getDeviceRefAttr())))
2833 return emitOpError() << getDeviceRefAttr() <<
" is not a device";
2837llvm::DenseMap<AIE::TileID, AIE::PacketInfoAttr>
2839 llvm::DenseMap<AIE::TileID, AIE::PacketInfoAttr> ids;
2840 for (
auto tile : device.getOps<AIE::TileOp>())
2841 if (
auto id = tile->getAttrOfType<AIE::PacketInfoAttr>(
"controller_id");
2842 id &&
id.isAssigned())
2843 ids[tile.getTileID()] = id;
2848static void collectStaticBds(AIE::DmaBody program,
2849 SmallVectorImpl<AIEX::StaticBd> &bds) {
2850 using Channel = std::optional<std::pair<int, AIE::DMAChannelDir>>;
2851 llvm::SmallPtrSet<Operation *, 16> reached;
2852 auto add = [&](AIE::DMABDOp bd, Channel channel) {
2854 if (std::optional<uint32_t>
id = bd.getBdId())
2855 bds.push_back({channel, *
id});
2857 Region &body = program.getDmaBody();
2859 for (Block &block : body)
2860 for (AIE::DMAStartOp start : block.getOps<AIE::DMAStartOp>()) {
2862 if (!start.getEndpoint())
2863 channel = {start.getChannelIndex(), start.getChannelDir()};
2864 llvm::SmallPtrSet<Block *, 16> visited;
2865 SmallVector<Block *, 16> worklist;
2866 if (Block *dest = start.getDest(); dest && visited.insert(dest).second)
2867 worklist.push_back(dest);
2868 while (!worklist.empty()) {
2869 Block *bdBlock = worklist.pop_back_val();
2870 for (AIE::DMABDOp bd : bdBlock->getOps<AIE::DMABDOp>())
2872 for (Block *successor : bdBlock->getSuccessors())
2873 if (visited.insert(successor).second)
2874 worklist.push_back(successor);
2878 for (Block &block : body)
2879 for (AIE::DMAOp dma : block.getOps<AIE::DMAOp>())
2880 for (Region &bdRegion : dma.getBds())
2881 bdRegion.walk([&](AIE::DMABDOp bd) {
2882 add(bd, std::make_pair(dma.getChannelIndex(), dma.getChannelDir()));
2884 body.walk([&](AIE::DMABDOp bd) {
2885 if (std::optional<uint32_t>
id = bd.getBdId();
id && !reached.contains(bd))
2886 bds.push_back({std::nullopt, *
id});
2892 SmallVector<StaticBd> bds;
2893 for (AIE::DeviceOp device : devices)
2894 for (AIE::DmaBody program : device.getOps<AIE::DmaBody>())
2895 if (program.getTileID() == tile)
2896 collectStaticBds(program, bds);
2900FailureOr<SmallVector<AIEX::ControlPacketMulticast>>
2902 SmallVector<ControlPacketMulticast> routes;
2903 auto device = reference ? module.lookupSymbol<AIE::DeviceOp>(reference)
2906 device && device.getOverlayAttr()
2907 ?
module.lookupSymbol<AIE::DeviceOp>(device.getOverlayAttr())
2910 overlay ? AIE::AIEDialect::CtrlPktMulticastAttrHelper(module.getContext())
2915 SymbolTable symbols(overlay);
2916 for (
auto [index, attribute] : llvm::enumerate(groups)) {
2917 auto group = dyn_cast<DictionaryAttr>(attribute);
2918 auto allocation = group ? group.getAs<FlatSymbolRefAttr>(
"allocation")
2919 : FlatSymbolRefAttr{};
2921 group ? group.getAs<IntegerAttr>(
"packet_id") : IntegerAttr{};
2922 auto tiles = group ? group.getAs<ArrayAttr>(
"tiles") : ArrayAttr{};
2923 if (!allocation || !packetId || !tiles || tiles.empty() ||
2924 packetId.getInt() < 0 ||
2925 packetId.getInt() > overlay.getTargetModel().getMaxPacketId() ||
2927 tiles, [](Attribute tile) { return isa<AIE::TileAttr>(tile); })) {
2928 overlay.emitOpError(
"aie.ctrl_pkt_multicast entry ")
2929 << index <<
" requires allocation, a valid packet_id, and tiles";
2932 llvm::SmallDenseSet<Attribute> destinations;
2933 for (Attribute tile : tiles)
2934 if (!destinations.insert(tile).second) {
2935 overlay.emitOpError(
"aie.ctrl_pkt_multicast entry ")
2936 << index <<
" repeats destination " << tile;
2940 symbols.lookup<AIE::ShimDMAAllocationOp>(allocation.getValue());
2941 if (!alloc || !
AIE::isMM2S(alloc.getChannelDir())) {
2942 overlay.emitOpError(
"aie.ctrl_pkt_multicast entry ")
2943 << index <<
" allocation " << allocation
2944 <<
" must reference an MM2S shim DMA allocation in this overlay";
2947 routes.push_back({alloc,
static_cast<uint32_t
>(packetId.getInt()), tiles});
2953 Operation *found =
nullptr;
2954 device.walk([&](Operation *op) {
2955 if (!isa<AIE::DMAStartOp, AIE::DMAOp>(op) ||
2956 !isa<AIE::ShimDMAOp>(op->getParentOp()))
2957 return WalkResult::advance();
2959 return WalkResult::interrupt();
std::pair< uint32_t, uint32_t > getBdIdRangeForChannel(int col, int row, int channel, DMAChannelDir dir) const
Return the half-open range of BD ids channel in dir can submit.
uint32_t getDmaBdStepBias(AIETileType tileType) const
DmaBdLayout::stepBias, or 1 without a layout.
virtual uint32_t getTileAddress(int col, int row) const
Return the base address of the tile's window.
bool isBdInChannelPool(int col, int row, uint32_t bd_id, int channel, DMAChannelDir dir) const
True iff bd_id is in the channel's pool, whether or not it exists.
bool isCoreTile(int col, int row) const
Return true if the given tile is a Core tile.
virtual uint64_t getDmaBdMaxLen(AIETileType tileType) const =0
Return the maximum transfer length, measured in address-generation granules (see getAddressGenGranula...
virtual const DmaBdLayout * getDmaBdLayout(AIETileType tileType) const
Return the register layout of a buffer descriptor on the given tile type, or null if the target has n...
virtual AIEArch getTargetArch() const =0
Return the target architecture.
bool isMemTile(int col, int row) const
Return true if the given tile is a Mem tile.
virtual uint32_t getDmaBdWrapBits(AIETileType tileType) const =0
Return the bit width of the wrap (size) field in a DMA buffer descriptor for the given tile type.
virtual uint32_t getLocalMemorySize() const =0
Return the size (in bytes) of the local data memory of a core.
virtual uint32_t getNumLocks(AIETileType tileType) const =0
Return the number of lock objects for a given tile type.
uint32_t getColumnFromAddress(uint32_t address) const
bool isOrdinaryWriteAddress(TileID tile, uint32_t offset) const
virtual uint32_t getDmaBdIterBits(AIETileType tileType) const =0
Return the bit width of the iteration (repeat) wrap/stride fields in a DMA buffer descriptor for the ...
virtual uint32_t getBDMaxDims(AIETileType tileType) const =0
Return the maximum number of addressing dimensions (wraps/strides) a single buffer descriptor support...
virtual std::vector< std::pair< uint32_t, uint32_t > > getShimBurstEncodingsAndLengths() const =0
virtual uint32_t getDmaBdStepBits(AIETileType tileType) const =0
Return the bit width of the step (stride) field in a DMA buffer descriptor for the given tile type.
virtual uint32_t getRowFromAddress(uint32_t address) const
Inverse of getTileAddress() for any address in the tile's window.
bool isBdChannelAccessible(int col, int row, uint32_t bd_id, int channel, DMAChannelDir dir) const
virtual std::optional< uint32_t > getLocalLockAddress(uint32_t lockId, TileID tile) const =0
virtual uint32_t getMaxChannelNumForAdjacentMemTile(int col, int row) const =0
virtual AIETileType getTileType(int col, int row) const =0
Return the tile type for the given tile coordinates.
virtual uint32_t getMaxRepeatCount() const =0
Return the largest DMA task repeat count (unsupported = 0).
bool isShimNOCTile(int col, int row) const
Return true if the given tile is a ShimNOC tile.
virtual uint32_t getNumBDs(AIETileType tileType) const =0
Return the size of the BD id space of a tile type (see getTotalNumBDs()).
virtual bool hasChannelLocalBdIds(int col, int row) const
True if data BD ids are channel-local, so a BD's address depends on its channel and direction.
virtual uint32_t getMaxLockValue() const =0
Return the maximum value that can be stored in a lock register.
virtual uint32_t getMaxOutOfOrderId() const =0
Return the largest out-of-order BD id (unsupported = 0).
virtual uint32_t getColumnShift() const =0
uint32_t getNumDMAChannels(int col, int row, AIE::DMAChannelDir dir) const
Return the number of DMA channels a tile has in one direction.
virtual uint32_t getDataMemoryOffset(int, int) const
Offset of data memory in the tile's window; buffer addresses are relative to it.
virtual uint32_t getRowShift() const =0
virtual uint32_t getAddressGenGranularity() const =0
Return the data bus width of the device.
virtual uint32_t getMemTileSize() const =0
Return the size (in bytes) of a MemTile.
OpTy lookupIn(mlir::Operation *symbolTableOp, mlir::StringAttr name)
mlir::Operation * lookup(mlir::StringAttr name) const
const V & get(const std::map< K, V > &pa, K k)
mlir::Operation * findShimDmaStart(AIE::DeviceOp device)
mlir::FailureOr< llvm::SmallVector< ControlPacketMulticast > > controlPacketMulticasts(mlir::ModuleOp module, mlir::FlatSymbolRefAttr reference)
bool isContiguousTransfer(llvm::ArrayRef< int64_t > sizes, llvm::ArrayRef< int64_t > strides)
llvm::DenseMap< AIE::TileID, AIE::PacketInfoAttr > controllerIdsOf(AIE::DeviceOp device)
mlir::LogicalResult verifyStridesWraps(mlir::Operation *forOp, llvm::function_ref< mlir::InFlightDiagnostic()> emitError, mlir::BaseMemRefType referencedBufType, int tileCol, int tileRow, llvm::SmallVector< int64_t, 4 > inputSizes, llvm::SmallVector< int64_t, 4 > inputStrides, llvm::SmallVector< int64_t, 4 > hardwareSizes, llvm::SmallVector< int64_t, 4 > hardwareStrides, bool skipTransformationChecks=false)
std::optional< uint64_t > getConstantInt64Operand(mlir::Value v)
bool isDecomposableNdDmaPattern(mlir::Operation *forOp, mlir::BaseMemRefType referencedBufType, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, llvm::ArrayRef< int64_t > offsetsInnermostFirst, llvm::ArrayRef< int64_t > sizesInnermostFirst, llvm::ArrayRef< int64_t > stridesInnermostFirst)
True when the pattern is fully constant, non-contiguous, currently illegal, and decomposeNdDmaPattern...
void encodeHardwareStridesWraps(Policy &p, uint64_t elemWidth, uint32_t addressGranularity, int64_t stepBias, typename Policy::V inputSizes[4], typename Policy::V inputStrides[4], typename Policy::V sizes[4], typename Policy::V strides[4])
llvm::SmallVector< StaticBd > staticBdIds(llvm::ArrayRef< AIE::DeviceOp > devices, AIE::TileID tile)
std::optional< uint32_t > getConstantIntOperand(mlir::Value v)
mlir::Value createConstantArgPlus(mlir::OpBuilder &builder, mlir::Location loc, uint64_t value)
bool isLinearModeTransfer(const AIE::AIETargetModel &targetModel, int col, int row, llvm::ArrayRef< int64_t > sizes, llvm::ArrayRef< int64_t > strides)
bool isConstMultipleOfGranule(int64_t value, uint64_t elemWidth, uint32_t addressGranularity)
bool isLinearTransfer(llvm::ArrayRef< int64_t > sizes, llvm::ArrayRef< int64_t > strides)
mlir::LogicalResult verifyConstBdRealizability(mlir::Operation *op, llvm::ArrayRef< mlir::OpFoldResult > sizes, llvm::ArrayRef< mlir::OpFoldResult > strides, uint64_t elemWidth, uint32_t gran)
void getHardwareStridesWraps(const AIE::AIETargetModel &targetModel, mlir::Operation *op, int tileCol, int tileRow, mlir::BaseMemRefType referencedBufType, llvm::SmallVector< int64_t, 4 > inputSizes, llvm::SmallVector< int64_t, 4 > inputStrides, llvm::SmallVector< int64_t, 4 > &sizes, llvm::SmallVector< int64_t, 4 > &strides)
mlir::Value createConstantI32(mlir::OpBuilder &builder, mlir::Location loc, uint32_t value)
mlir::LogicalResult verifyDMAChannel(mlir::Operation *op, TileLike tile, DMAChannelDir dir, int64_t channel)
void printTypedDynamicIndexList(mlir::OpAsmPrinter &printer, mlir::Operation *op, mlir::OperandRange values, llvm::ArrayRef< int64_t > integers, mlir::TypeRange types)
mlir::LogicalResult verifyLengthParameterTile(mlir::Operation *op, const AIETargetModel &targetModel, int col, int row)
mlir::LogicalResult verifyAssignedPacket(mlir::Operation *op, PacketInfoAttr packet, llvm::StringRef what="packet")
mlir::ParseResult parseTypedDynamicIndexList(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< mlir::OpAsmParser::UnresolvedOperand > &values, mlir::DenseI64ArrayAttr &integers, llvm::SmallVectorImpl< mlir::Type > &types)
mlir::Operation * lookupNamedOpIn(mlir::Operation *symbolTableOp, mlir::StringAttr name)
mlir::LogicalResult verifyDMABDOutOfOrderId(DMABDOp bd, bool packetEnabledByContext=false)
mlir::LogicalResult verifyOutOfOrderChannel(mlir::Operation *op, DMAChannelDir dir, bool outOfOrder, llvm::ArrayRef< DMABDOp > bds, bool packetEnabledByContext=false)
mlir::LogicalResult verifyLengthParameter(mlir::Operation *op, std::optional< int64_t > lengthUnit, mlir::BaseMemRefType buffer, std::optional< int64_t > lenElems, bool contiguous, llvm::ArrayRef< int64_t > innerSizes)
struct TileID { friend std::ostream &operator<<(std::ostream &os, const TileID &s) { os<< "TileID("<< s.col<< ", "<< s.row<< ")"; return os; } friend std::string to_string(const TileID &s) { std::ostringstream ss; ss<< s; return ss.str(); } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const TileID &s) { os<< to_string(s); return os; } inline bool operator<(const TileID &rhs) const { return std::tie(col, row)< std::tie(rhs.col, rhs.row); } bool operator==(const TileID &rhs) const { return std::tie(col, row)==std::tie(rhs.col, rhs.row); } bool operator!=(const TileID &rhs) const { return !(*this==rhs);} int col, row;} TileID
const AIETargetModel & getTargetModel(mlir::Operation *op)
bool isMM2S(DMAChannelDir dir)
True if dir moves data out of memory onto a stream (MM2S, ControlMM2S).
mlir::LogicalResult verifyDMABDIteration(DMABDOp bd, AIETileType tileType)
WireBundle getDMAChannelBundle(DMAChannelDir dir)
The stream-switch bundle the channels of dir use.
The register layout of one tile type's DMA buffer descriptor.
uint8_t stepBias
Step fields hold (step in granules - stepBias).
llvm::SmallVector< std::pair< DmaBdField, DmaBdField >, 3 > padFields() const
The (before, after) zero-padding fields, innermost dimension first.