MLIR-AIE 1.4.6.dev
AIEXDialect.cpp
Go to the documentation of this file.
1//===- AIEXDialect.cpp ------------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2019-2022 Xilinx, Inc.
4// Copyright (C) 2022-2026 Advanced Micro Devices, Inc.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12
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"
26
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"
33
34#include <cstdint>
35#include <limits>
36#include <numeric>
37
38using namespace mlir;
39using namespace xilinx;
40
41#include "aie/Dialect/AIEX/IR/AIEXDialect.cpp.inc"
42
43#include "aie/Dialect/AIEX/IR/AIEXEnums.cpp.inc"
44
45#include "aie/Dialect/AIEX/IR/AIEXInterfaces.cpp.inc"
46
47#define GET_TYPEDEF_CLASSES
48#include "aie/Dialect/AIEX/IR/AIEXTypes.cpp.inc"
49
50#define GET_ATTRDEF_CLASSES
51#include "aie/Dialect/AIEX/IR/AIEXAttrDefs.cpp.inc"
52
53namespace xilinx::AIEX {
54
55// FIXME: use Tablegen'd dialect class
56void AIEXDialect::initialize() {
57 addOperations<
58#define GET_OP_LIST
59#include "aie/Dialect/AIEX/IR/AIEX.cpp.inc"
60 >();
61 addTypes<
62#define GET_TYPEDEF_LIST
63#include "aie/Dialect/AIEX/IR/AIEXTypes.cpp.inc"
64 >();
65 addAttributes<
66#define GET_ATTRDEF_LIST
67#include "aie/Dialect/AIEX/IR/AIEXAttrDefs.cpp.inc"
68 >();
69}
70
71} // namespace xilinx::AIEX
72
75
76#define GET_OP_CLASSES
77#include "aie/Dialect/AIEX/IR/AIEX.cpp.inc"
78
79/* Return the correct values to write to the hardware registers to configure
80 strides and wraps given the input user-facing strides and wraps.
81
82 In the IR, we express strides in units of element data type, but the hardware
83 requires it in units of address granularity. Address granularity currently is
84 4 bytes for all hardware.
85
86
87 User-facing strides/wraps relate to hardware as follows:
88
89 - By default, stride 0 and size 1 is assumed if unspecified.
90 - If only N strides/wraps are defined, those define the lowest N dimensions.
91
92 inputStride[3] == iteration_stride / elemSizeFac + 1
93 inputWrap[3] == iteration_size + 1
94 Highest-dimension stride/wrap is iteration count / iteration stride.
95 inputStride[2] == d2_stride / elemSizeFac + 1
96 Note: d2_size is not specified in hardware as it is
97 implicit from the total buffer transfer length
98 inputStride[1] == d1_stride / elemSizeFac + 1
99 inputSize[1] == d1_size
100 inputStride[0] == d0_stride / elemSizeFac + 1
101 inputSize[0] == d0_size / elemSizeFac
102
103 where elemSizeFac == bufferElementSize / addressGranularity
104 where bufferElementSize == size in bytes of elements in buffer,
105 e.g. 4 for int32
106 where addressGranularity == transfer granularity in hardware, which is
107 4 bytes for all current hardware
108
109 Note: strides are expressed offset by one from user input strides, because the
110 hardware does not support a 0 stride (repeat).
111 */
113 mlir::Operation *op, int tileCol,
114 int tileRow,
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);
123
124 DataLayout dataLayout = DataLayout::closest(op);
125 auto elemWidth =
126 dataLayout.getTypeSizeInBits(referencedBufType.getElementType());
127 auto addressGranularity = targetModel.getAddressGenGranularity();
128
129 // Output strides and sizes are default-initialized to 0
130 llvm::fill(sizes, 0);
131 llvm::fill(strides, 0);
132
133 if (inputSizes[0] == 0) {
134 // Illegal input, this won't transfer anything at all.
135 // Leave it to the verification functions to complain to the user.
136 return;
137 }
138
139 ConstStridePolicy policy;
140 int64_t inS[4] = {inputSizes[0], inputSizes[1], inputSizes[2], inputSizes[3]};
141 int64_t inT[4] = {inputStrides[0], inputStrides[1], inputStrides[2],
142 inputStrides[3]};
143 int64_t outS[4], outT[4];
144 encodeHardwareStridesWraps(policy, elemWidth, addressGranularity,
145 targetModel.getDmaBdStepBias(tileCol, tileRow),
146 inS, inT, outS, outT);
147 for (int i = 0; i < 4; i++) {
148 sizes[i] = outS[i];
149 strides[i] = outT[i];
150 }
151}
152
153mlir::LogicalResult AIEX::verifyStridesWraps(
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) {
162 const auto &targetModel = AIE::getTargetModel(forOp);
163 auto addressGranularity = targetModel.getAddressGenGranularity();
164 DataLayout dataLayout = DataLayout::closest(forOp);
165 auto elemWidth =
166 dataLayout.getTypeSizeInBits(referencedBufType.getElementType());
167
168 // ShimPLTiles have no ShimDMA, so BD field widths are meaningless here.
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.";
174
175 uint32_t wrap_bits = targetModel.getDmaBdWrapBits(tileCol, tileRow);
176 uint32_t step_bits = targetModel.getDmaBdStepBits(tileCol, tileRow);
177
178 for (int i = 0; i < 4; i++) {
179 if (inputSizes[i] <= 0) {
180 return emitError() << "Size " << i << " must be a positive integer.";
181 }
182 }
183
184 if (!isConstMultipleOfGranule(inputSizes[0], elemWidth, addressGranularity)) {
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)
190 << ". ";
191 return emitError() << msg.str();
192 }
193
194 for (int i = 0; i < 3; i++) {
195 if (inputSizes[i] > 1 && inputStrides[i] < 1) {
196 // If inputSize[i] == 1, anything is allowable in the stride, since that
197 // stride will never be applied. For any larger size, we must verify that
198 // the stride is positive.
199 return emitError() << "Stride " << i << " must be a positive integer.";
200 }
201 }
202 // A value of zero is allowable for the fourth-dimension stride
203 // (this indicates an interation stride for the repeat of 0)
204 if (inputSizes[3] > 1 && inputStrides[3] < 0) {
205 return emitError() << "Stride 3 must be a non-negative integer.";
206 }
207
208 for (int i = 0; i < 4; i++) {
209 // strides[0] == 1 is ok iff the transfer size is a multiple of
210 // addressGranularity, which is checked below
211 if (i == 0 && inputStrides[i] == 1)
212 continue;
213 if (!isConstMultipleOfGranule(inputStrides[i], elemWidth,
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)
219 << ". ";
220 return emitError() << msg.str();
221 }
222 }
223 // The innermost dimension steps whole granules, so for elements of another
224 // width it can only be contiguous.
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.";
231 // BDs without a d0 step field always step d0 by one granule.
232 const AIE::DmaBdLayout *layout = targetModel.getDmaBdLayout(tileCol, tileRow);
233 if (layout && !layout->d0Stride.exists() && inputSizes[0] > 1 &&
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.";
239
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.";
245 };
246
247 int64_t maxWrap = (1 << wrap_bits) - 1;
248 int64_t maxStep = 1 << step_bits;
249 // The largest stride, in granules, a step field holds.
250 int64_t maxStride =
251 maxStep - 1 + targetModel.getDmaBdStepBias(tileCol, tileRow);
252
253 for (int dim : {0, 1}) {
254 if (!skipTransformationChecks && hardwareSizes[dim] > maxWrap)
255 return outOfRange("Size", dim, inputSizes[dim], hardwareSizes[dim], 0,
256 maxWrap);
257 }
258 // A zero d3 stride is a pure repeat: the lowerings leave the iteration fields
259 // 0 and carry the count on the queue push, so the repeat limit applies.
260 bool pureRepeat = inputStrides[3] == 0;
261 int64_t maxCount =
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
267 << "] range.";
268 for (int dim : {0, 1, 2}) {
269 if (hardwareStrides[dim] > maxStep - 1)
270 return outOfRange("Stride", dim, inputStrides[dim], hardwareStrides[dim],
271 1, maxStride);
272 }
273 // strides[3] exceeding the range is ok iff the sizes[3] is one, which is
274 // checked below
275 if (hardwareStrides[3] > maxStep - 1 && hardwareSizes[3] > 0)
276 return outOfRange("Stride", 3, inputStrides[3], hardwareStrides[3], 1,
277 maxStride);
278
279 return success();
280}
281
282//===----------------------------------------------------------------------===//
283// UseTokenOp
284//===----------------------------------------------------------------------===//
285
286// A field flagged as a register must name one of r0..r23. The bound cannot be
287// an attribute constraint, because the same field holds a full 32-bit
288// immediate when unflagged.
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]";
296 return success();
297}
298
299LogicalResult AIEX::CertApplyOffset57Op::verify() {
300 if (getNumEntries() == 0)
301 return emitOpError("num_entries must be at least 1");
302 return success();
303}
304
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))
309 return success();
310 return failure();
311}
312
313//===----------------------------------------------------------------------===//
314// MulticastOp
315//===----------------------------------------------------------------------===//
316
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");
324
325 return success();
326}
327
328//===----------------------------------------------------------------------===//
329// BroadcastPacketOp
330//===----------------------------------------------------------------------===//
331
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");
339
340 return success();
341}
342
343//===----------------------------------------------------------------------===//
344// NpuDmaMemcpyNdOp
345//===----------------------------------------------------------------------===//
346
347/* Calculates the offset value to be written to the
348 */
349uint32_t AIEX::NpuDmaMemcpyNdOp::getAxcacheOrDefault() {
350 return getAxcache().value_or(AIE::getTargetModel(*this).getDefaultAxCache());
351}
352
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();
357 });
358 auto strides = llvm::to_vector<4>(llvm::reverse(getMixedStrides()));
359 size_t offset = 0;
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;
365 // A dimension only contributes to the byte offset when its (constant) offset
366 // is non-zero; a runtime stride paired with a zero offset is fine and must
367 // not be forced to a constant. The verifier requires any stride multiplied by
368 // a non-zero offset to be constant.
369 for (size_t i = 0; i < R; i++) {
370 if (offsets[i] == 0)
371 continue;
372 auto strideConst = getConstantIntValue(strides[i]);
373 assert(strideConst &&
374 "verifier requires a stride paired with a non-zero offset to be "
375 "constant");
376 offset += offsets[i] * (*strideConst) * S;
377 }
378 return offset;
379}
380
381// Returns true when sizes/strides describe a plain contiguous transfer with
382// no data layout transformation (d1/d2 sizes == 1, d0 stride == 1).
383// d3 (repeat) is intentionally excluded.
384bool AIEX::isLinearTransfer(llvm::ArrayRef<int64_t> sizes,
385 llvm::ArrayRef<int64_t> strides) {
386 return sizes[1] == 1 && sizes[2] == 1 && strides[0] == 1 && strides[1] == 0 &&
387 strides[2] == 0;
388}
389
390// Returns true when sizes/strides (innermost-first) describe a contiguous
391// row-major scan: innermost stride == 1 and each outer stride equals the
392// product of all inner sizes. The repeat dimension (index 3) is excluded.
393// Size-1 dimensions are allowed to carry any stride value because that stride
394// is never applied during the transfer (the loop runs only once).
395// This is the vector-form counterpart of AIE::isContiguousBDTransfer.
396bool AIEX::isContiguousTransfer(llvm::ArrayRef<int64_t> sizes,
397 llvm::ArrayRef<int64_t> strides) {
398 if (strides[0] != 1)
399 return false;
400 if (sizes[1] > 1 && strides[1] != sizes[0])
401 return false;
402 if (sizes[2] > 1 && strides[2] != sizes[0] * sizes[1])
403 return false;
404 return true;
405}
406
407bool AIEX::isLinearModeTransfer(const AIE::AIETargetModel &targetModel, int col,
408 int row, llvm::ArrayRef<int64_t> sizes,
409 llvm::ArrayRef<int64_t> strides) {
410 return isLinearTransfer(sizes, strides) ||
411 (targetModel.isShimNOCTile(col, row) &&
412 isContiguousTransfer(sizes, strides));
413}
414
415// dma_memcpy_nd transfers of the form [*, 1, 1, len][*, 0, 0, 1] do not
416// specify any data layout transformation, but simply express a contiguous
417// transfer of `len`. The 4th dimension is excluded because a repeat count
418// is still compatible with a linear transfer.
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();
423 });
424 llvm::SmallVector<int64_t, 4> inputStrides =
425 llvm::map_to_vector(llvm::reverse(getMixedStrides()), [](OpFoldResult s) {
426 return getConstantIntValue(s).value();
427 });
428 return isLinearTransfer(inputSizes, inputStrides);
429}
430
431// Canonicalization pattern: rewrite a contiguous row-major access pattern to
432// the canonical linear form [s3, 1, 1, N][st3, 0, 0, 1].
433//
434// Using outermost-first index notation (matching the IR syntax), a 4D access
435// [s3, s2, s1, s0][st3, st2, st1, st0] is a contiguous linear scan when:
436// st0 == 1
437// s1 == 1 || st1 == s0 (stride irrelevant when size is 1)
438// s2 == 1 || st2 == s0 * s1
439// yielding a total of N = s0 * s1 * s2 contiguous elements. The repeat
440// dimension s3 / stride st3 is unchanged by the fold.
441//
442// Note: this pattern applies only to NpuDmaMemcpyNdOp. The analogous
443// dimensionsToStream / dimensionsFromStreamPerConsumer attributes on
444// ObjectFifoCreateOp are not canonicalized here; they are lowered separately
445// by the ObjectFifo stateful transform pass.
446//
447// This fold is always semantically valid and never introduces new hardware
448// limit violations: in the resulting linear form, isLinearTransferWithout-
449// Transformation() returns true, so verifyStridesWraps() skips the 10-bit
450// d0 wrap-size check. The hardware uses a wider buffer_length register in
451// linear mode (32-bit on shim tiles, 17-bit on mem tiles, 14-bit on core
452// tiles), so N can be much larger than the 10-bit ND wrap limit.
453namespace {
454struct LinearizeContiguousTransfer
455 : public mlir::OpRewritePattern<AIEX::NpuDmaMemcpyNdOp> {
456 using OpRewritePattern::OpRewritePattern;
457
458 mlir::LogicalResult
459 matchAndRewrite(AIEX::NpuDmaMemcpyNdOp op,
460 mlir::PatternRewriter &rewriter) const override {
461 // Only constant sizes/strides/offsets can be analysed statically.
462 if (!llvm::all_of(op.getMixedSizes(), [](mlir::OpFoldResult s) {
463 return mlir::getConstantIntValue(s).has_value();
464 }))
465 return mlir::failure();
466 if (!llvm::all_of(op.getMixedStrides(), [](mlir::OpFoldResult s) {
467 return mlir::getConstantIntValue(s).has_value();
468 }))
469 return mlir::failure();
470 if (!llvm::all_of(op.getMixedOffsets(), [](mlir::OpFoldResult s) {
471 return mlir::getConstantIntValue(s).has_value();
472 }))
473 return mlir::failure();
474
475 // Skip ops that are already in canonical linear form.
476 if (op.isLinearTransferWithoutTransformation())
477 return mlir::failure();
478
479 // getMixedSizes/Strides/Offsets return outermost-first; reverse to
480 // innermost-first so index 0 = d0 (innermost) and index 3 = repeat.
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();
484 });
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();
488 });
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();
492 });
493
494 // Require a contiguous row-major scan.
495 if (!AIEX::isContiguousTransfer(sizes, strides))
496 return mlir::failure();
497
498 // Fold d0/d1/d2 into one linear count; keep the repeat dimension intact.
499 // Build directly in outermost-first order for the replacement op.
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};
503
504 // getOffsetInBytes() computes: sum(offsets[i] * strides[i] * elemSize).
505 // After folding, the intermediate strides become 0, so any non-zero offset
506 // in those dimensions would silently contribute 0 bytes. Preserve the
507 // correct start address by collapsing the innermost three offset/stride
508 // pairs into a single linear element index at d0.
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,
512 linearOffset};
513
514 rewriter.replaceOpWithNewOp<AIEX::NpuDmaMemcpyNdOp>(
515 op, op, newOffsetsOuter, newSizesOuter, newStridesOuter);
516 return mlir::success();
517 }
518};
519} // namespace
520
521void AIEX::NpuDmaMemcpyNdOp::getCanonicalizationPatterns(
522 mlir::RewritePatternSet &results, mlir::MLIRContext *context) {
523 results.add<LinearizeContiguousTransfer>(context);
524}
525
526// Helper method to check if a requested burst length is supported by the target
527// model. Returns an error message if the burst length is not supported or an
528// empty option otherwise.
529static std::optional<std::string>
530checkBurstLength(const xilinx::AIE::AIETargetModel &targetModel,
531 uint32_t requestedBurstLength) {
532 if (requestedBurstLength != 0) {
533 auto bel = targetModel.getShimBurstEncodingsAndLengths();
534 auto pair = llvm::find_if(bel, [=](const std::pair<uint32_t, uint32_t> &p) {
535 return p.second == requestedBurstLength;
536 });
537
538 if (pair == bel.end()) {
539 std::string errorMessage =
540 "Requested burst length is not supported by the target. "
541 "Supported burst lengths:";
542
543 errorMessage =
544 std::accumulate(bel.begin(), bel.end(), errorMessage,
545 [](const std::string &a, auto b) {
546 return a + " " + std::to_string(b.second);
547 });
548
549 return errorMessage;
550 }
551 }
552
553 return std::nullopt;
554}
555
556// Verify the supported scope for a dma_memcpy_nd carrying runtime (SSA)
557// offsets/sizes/strides, hard-erroring on any statically-provable violation.
558// The scope here is exactly what the dynamic BD encoder (AIEDmaToNpu.cpp
559// lowerDynamic) can lower; runtime values are never silently masked.
560LogicalResult AIEX::NpuDmaMemcpyNdOp::verifyDynamicSizesStrides(
561 const AIE::AIETargetModel &targetModel, mlir::BaseMemRefType buffer,
562 AIE::ShimDMAAllocationOp allocOp) {
563 // Shim NOC only.
564 if (!allocOp)
565 return emitOpError(
566 "runtime sizes/strides require a shim_dma_allocation to resolve the "
567 "tile; none found.");
568 AIE::TileOp tile = allocOp.getTileOp();
569 // Coordinate-dependent checks must wait until logical tiles are placed.
570 if (!tile)
571 return success();
572 if (!targetModel.isShimNOCTile(tile.getCol(), tile.getRow()))
573 return emitOpError(
574 "runtime sizes/strides are only supported for shim NOC tile DMAs.");
575
576 // No zero-padding with runtime sizes/strides.
577 if (getD0ZeroBefore() || getD1ZeroBefore() || getD2ZeroBefore() ||
578 getD0ZeroAfter() || getD1ZeroAfter() || getD2ZeroAfter())
579 return emitOpError(
580 "zero padding is not supported with runtime sizes/strides.");
581
582 // Per-field runtime values are allowed: any individual size/stride may be an
583 // SSA value while others stay constant. Only the runtime-dependent fields
584 // need runtime handling; the encoder produces the same word for a constant
585 // operand either way, so the static ≡ dynamic byte-identity holds field by
586 // field.
587 auto sizes = getMixedSizes();
588 auto strides = getMixedStrides();
589
590 // The innermost stride may be runtime like any other dimension: the encoder
591 // resolves its collapse-to-zero case with a select, and its realizability
592 // (unit stride, or granule-aligned) is enforced below for constants and by a
593 // host-side check (buildBdWords) for runtime values.
594
595 // (The memref must also trace to a runtime-sequence block argument through
596 // static subview/cast offsets; that structural check, with the same clean
597 // diagnostic, is enforced by the lowering in AIEDmaToNpu.cpp, which already
598 // owns the trace utility. It is not duplicated here to keep the dialect
599 // verifier free of the analysis-layer dependency.)
600
601 // A constant size must fit its hardware wrap field (an out-of-range constant
602 // is a hard error, never a silent truncation); runtime sizes are guarded at
603 // lowering. Bounds are checked on the ENCODED value, matching
604 // verifyStridesWraps: d0 wrap scaled to granules (size * elemWidth / gran),
605 // iteration wrap biased by -1, d1 a raw element count. Sizes outermost-first.
606 DataLayout dataLayout = DataLayout::closest(getOperation());
607 uint64_t elemWidth = dataLayout.getTypeSizeInBits(buffer.getElementType());
608 uint32_t gran = targetModel.getAddressGenGranularity();
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))
613 return success();
614 if (hwVal < 0 || hwVal > hi)
615 return emitOpError(what) << " hardware value " << hwVal
616 << " exceeds hardware range [0:" << hi << "].";
617 return success();
618 };
619 auto hwSize = [&](mlir::OpFoldResult ofr) {
620 return getConstantIntValue(ofr).value_or(0);
621 };
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());
630 int64_t wrapMax = (1LL << targetModel.getDmaBdWrapBits(tileType)) - 1;
631 int64_t maxCount = pureRepeat ? targetModel.getMaxRepeatCount() + 1
632 : 1LL << targetModel.getDmaBdIterBits(tileType);
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")))
637 return failure();
638
639 // Realizability of the CONSTANT size/stride operands (divisibility +
640 // positivity, innermost-first). Runtime operands get a host-side check at
641 // lowering time. Shared with the dma_task path.
642 llvm::SmallVector<mlir::OpFoldResult, 4> stridesRev(llvm::reverse(strides));
643 if (failed(verifyConstBdRealizability(getOperation(), sizesRev, stridesRev,
644 elemWidth, gran)))
645 return failure();
646
647 // Runtime fields are checked at dispatch instead; see buildBdWords.
648
649 auto errorMessage = checkBurstLength(targetModel, getBurstLength());
650 if (errorMessage.has_value())
651 return emitOpError(errorMessage.value());
652
653 return success();
654}
655
656LogicalResult AIEX::NpuDmaMemcpyNdOp::verify() {
657 BaseMemRefType buffer = getMemref().getType();
658 const auto &targetModel = AIE::getTargetModel(*this);
659 auto addressGranularity = targetModel.getAddressGenGranularity();
660
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");
665 }
666
667 if (getElementTypeBitwidth() > addressGranularity) {
668 return emitOpError("Maximum element bit width allowed is ")
669 << addressGranularity << "bits. ";
670 }
671 if (buffer.hasStaticShape() &&
672 (buffer.getNumElements() * getElementTypeBitwidth()) <
673 addressGranularity) {
674 return emitOpError("Minimum data transfer size required is ")
675 << addressGranularity << "bits. ";
676 }
677 bool allStridesConstant = llvm::all_of(getMixedStrides(), [](OpFoldResult s) {
678 return getConstantIntValue(s).has_value();
679 });
680 bool allSizesConstant = llvm::all_of(getMixedSizes(), [](OpFoldResult s) {
681 return getConstantIntValue(s).has_value();
682 });
683 bool allOffsetsConstant = llvm::all_of(getMixedOffsets(), [](OpFoldResult s) {
684 return getConstantIntValue(s).has_value();
685 });
686
687 bool hasLengthParameter =
688 getLengthParameterAttr() || getLengthStateTableIdxAttr();
689 // Runtime offsets, sizes and strides lower only through EmitC, which has no
690 // scratchpad.
691 if (hasLengthParameter &&
692 (!allStridesConstant || !allSizesConstant || !allOffsetsConstant))
693 return emitOpError(
694 "length_parameter requires constant offsets, sizes and strides");
695
696 // The dynamic scope check needs the allocation resolved by verifySymbolUses.
697 if (!allStridesConstant || !allSizesConstant || !allOffsetsConstant)
698 return success();
699
700 llvm::SmallVector<int64_t, 4> inputSizes =
701 llvm::map_to_vector(llvm::reverse(getMixedSizes()), [](OpFoldResult s) {
702 return getConstantIntValue(s).value();
703 });
704 llvm::SmallVector<int64_t, 4> inputStrides =
705 llvm::map_to_vector(llvm::reverse(getMixedStrides()), [](OpFoldResult s) {
706 return getConstantIntValue(s).value();
707 });
708 int64_t offset = getOffsetInBytes();
709
710 auto errorMessage = checkBurstLength(targetModel, getBurstLength());
711 if (errorMessage.has_value()) {
712 return emitOpError(errorMessage.value());
713 }
714
715 if (hasLengthParameter) {
717 *this, getLengthUnit(), buffer,
718 inputSizes[0] * inputSizes[1] * inputSizes[2],
719 AIEX::isContiguousTransfer(inputSizes, inputStrides),
720 llvm::ArrayRef<int64_t>(inputSizes).take_front(3))))
721 return failure();
722 }
723
724 // AIE1 does not use the NPU alignment and packet-header checks.
725 if (targetModel.getTargetArch() == AIE::AIEArch::AIE1)
726 return success();
727
728 if (offset % 4 != 0) {
729 return emitOpError("Offset must be 4-byte-aligned.");
730 }
731
732 // packet header
733 if (auto packetInfo = getPacket()) {
734 if (failed(AIE::verifyAssignedPacket(*this, *packetInfo)))
735 return failure();
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.");
740 }
741
742 return success();
743}
744
745static LogicalResult verifyTransferCoversWholeObjects(
746 Operation *transfer, SymbolRefAttr alloc, std::optional<int64_t> moved,
747 AIE::ObjectFifoCreateOp fifo, SymbolTableCollection &symbols);
748
749// The verifier-owned collection shares the device symbol table across memcpy
750// checks without retaining allocation pointers between verification calls.
751LogicalResult
752AIEX::NpuDmaMemcpyNdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
753 BaseMemRefType buffer = getMemref().getType();
754 const auto &targetModel = AIE::getTargetModel(*this);
755 bool allStridesConstant = llvm::all_of(getMixedStrides(), [](OpFoldResult s) {
756 return getConstantIntValue(s).has_value();
757 });
758 bool allSizesConstant = llvm::all_of(getMixedSizes(), [](OpFoldResult s) {
759 return getConstantIntValue(s).has_value();
760 });
761 bool allOffsetsConstant = llvm::all_of(getMixedOffsets(), [](OpFoldResult s) {
762 return getConstantIntValue(s).has_value();
763 });
764 bool isDynamic =
765 !allStridesConstant || !allSizesConstant || !allOffsetsConstant;
766
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)
772 return success();
773 if (dev)
774 if (auto fifo = symbolTable.lookupSymbolIn<AIE::ObjectFifoCreateOp>(
775 dev, getMetadata().getRootReference());
776 fifo &&
777 failed(verifyTransferCoversWholeObjects(
778 *this, getMetadata(), getStaticBytesStreamed(), fifo, symbolTable)))
779 return failure();
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";
788 // The id must also be in the channel's BD pool (AIE4 shims have two).
789 int channel = allocOp.getChannelIndex();
790 AIE::DMAChannelDir dir = allocOp.getChannelDir();
791 if (!targetModel.isBdInChannelPool(tile.getCol(), tile.getRow(), getId(),
792 channel, dir)) {
793 auto [first, last] = targetModel.getBdIdRangeForChannel(
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;
800 }
801 }
802 if (isDynamic)
803 return verifyDynamicSizesStrides(targetModel, buffer, allocOp);
804
805 // Static transfers can precede allocation lowering, so defer tile checks
806 // until metadata names a shim DMA allocation.
807 if (!allocOp)
808 return success();
809 auto tile = allocOp.getTileOp();
810 // Defer coordinate-dependent checks until logical tiles are placed.
811 if (!tile) {
812 if (isAIE1 && hasLengthParameter)
813 return emitOpError("length_parameter is only supported on AIE2 and "
814 "AIE2P devices");
815 return success();
816 }
817 int col = tile.getCol();
818 int row = tile.getRow();
819 if (hasLengthParameter &&
820 failed(AIE::verifyLengthParameterTile(*this, targetModel, col, row)))
821 return failure();
822
823 llvm::SmallVector<int64_t, 4> inputSizes =
824 llvm::map_to_vector(llvm::reverse(getMixedSizes()), [](OpFoldResult s) {
825 return getConstantIntValue(s).value();
826 });
827 llvm::SmallVector<int64_t, 4> inputStrides =
828 llvm::map_to_vector(llvm::reverse(getMixedStrides()), [](OpFoldResult s) {
829 return getConstantIntValue(s).value();
830 });
831 llvm::SmallVector<int64_t, 4> hardwareSizes(4);
832 llvm::SmallVector<int64_t, 4> hardwareStrides(4);
833 getHardwareStridesWraps(targetModel, getOperation(), col, row, buffer,
834 inputSizes, inputStrides, hardwareSizes,
835 hardwareStrides);
836
837 // dma_memcpy_nd transfers of the form [1, 1, 1, len][0, 0, 0, 1] do not
838 // specify any data layout transformation, but simply express a contiguous
839 // transfer of `len`. For backwards compatibility, we allow this to proceed
840 // even if it exceeds the maximum stride/wrap size of any one dimension,
841 // and simply do not lower any data layout transformations, since there is
842 // no other way to express this at the dma_memcpy_nd interface otherwise.
843 // A contiguous row-major ND access is also exempt from the ND wrap-size
844 // limit: aie-dma-to-npu lowers it to linear mode (d0_size=d1_size=0),
845 // and LinearizeContiguousTransfer canonicalizes it to explicit linear form.
846 bool skipTransformationChecks = AIEX::isLinearModeTransfer(
847 targetModel, col, row, inputSizes, inputStrides);
848 // An oversized non-contiguous pattern that aie-decompose-large-dma-bd can
849 // split into hardware-legal sub-transfers is also allowed to verify: the
850 // pass rewrites it before BD lowering. Truly undecomposable patterns (e.g.
851 // oversized strides) still fail below. isDecomposableNdDmaPattern
852 // suppresses its own diagnostics, so no stray error is emitted for the
853 // accepted case.
854 llvm::SmallVector<int64_t, 4> inputOffsets =
855 llvm::map_to_vector(llvm::reverse(getMixedOffsets()), [](OpFoldResult s) {
856 return getConstantIntValue(s).value();
857 });
858 // aie-decompose-large-dma-bd leaves a transfer with a runtime length
859 // alone, so it must be legal as written.
860 // AIE1 patterns must fit directly, even when the decomposition pass is
861 // scheduled: verification must not rely on it to legalize AIE1 transfers.
862 if (!isAIE1 && !hasLengthParameter &&
863 AIEX::isDecomposableNdDmaPattern(getOperation(), buffer, targetModel, col,
864 row, inputOffsets, inputSizes,
865 inputStrides)) {
866 // ok: will be decomposed before lowering
867 } else if (failed(verifyStridesWraps(
868 *this, [&] { return emitOpError(); }, buffer, col, row,
869 inputSizes, inputStrides, hardwareSizes, hardwareStrides,
870 skipTransformationChecks))) {
871 return failure();
872 }
873
874 return success();
875}
876
877//===----------------------------------------------------------------------===//
878// NpuDmaWaitOp
879//===----------------------------------------------------------------------===//
880
881LogicalResult AIEX::NpuDmaWaitOp::verify() {
882 AIE::DeviceOp dev = (*this)->getParentOfType<AIE::DeviceOp>();
883 // Some passes (e.g. aie-standard-lowering) use aiex ops outside a DeviceOp,
884 // so we can't expect the device to always exist.
885 if (dev && !dev.lookupSymbol(getSymbol()))
886 return emitOpError("couldn't find symbol in parent device");
887 return success();
888}
889
890//===----------------------------------------------------------------------===//
891// NpuPushQueueOp
892//===----------------------------------------------------------------------===//
893
894LogicalResult AIEX::NpuPushQueueOp::verify() {
895 const auto &targetModel = AIE::getTargetModel(*this);
896 if (failed(AIE::verifyDMAChannel(getOperation(), targetModel, getColumn(),
897 getRow(), getDirection(), getChannel())))
898 return failure();
899 auto numBds = targetModel.getNumBDs(getColumn(), getRow());
900 // bd_id and repeat_count are SSA operands; range-check them only when they
901 // are compile-time constants. A runtime repeat_count is checked on the host
902 // when lowered (AIEDmaToNpu); a runtime bd_id comes from the tile's BD pool.
903 if (std::optional<uint32_t> bdId = getConstantIntOperand(getBdId());
904 bdId && *bdId >= numBds)
905 return emitOpError("BD ID exceeds the maximum ID.");
906 // Stream DMA channels queue only BDs from their own (directed) pool.
907 if (std::optional<uint32_t> bdId = getConstantIntOperand(getBdId());
908 bdId &&
909 AIE::getDMAChannelBundle(getDirection()) == AIE::WireBundle::DMA &&
910 !targetModel.isBdInChannelPool(getColumn(), getRow(), *bdId, getChannel(),
911 getDirection()))
912 return emitOpError("BD ID ") << *bdId << " is not accessible from channel ("
913 << AIE::stringifyDMAChannelDir(getDirection())
914 << ", " << getChannel() << ")";
915 // Control and trace DMA channels have a smaller private pool.
916 if (std::optional<uint32_t> bdId = getConstantIntOperand(getBdId());
917 bdId &&
918 AIE::getDMAChannelBundle(getDirection()) != AIE::WireBundle::DMA &&
919 !targetModel.isBdChannelAccessible(getColumn(), getRow(), *bdId,
920 getChannel(), getDirection()))
921 return emitOpError() << "bd_id " << *bdId << " is not in the BD pool of "
922 << AIE::stringifyDMAChannelDir(getDirection())
923 << " channel " << getChannel();
924 uint32_t maxRepeat = targetModel.getMaxRepeatCount();
925 if (std::optional<uint64_t> repeatCount =
926 getConstantInt64Operand(getRepeatCount());
927 repeatCount && *repeatCount > maxRepeat)
928 return emitOpError("Repeat count exceeds the [0:")
929 << maxRepeat << "] range.";
930 if (getRepeatStateTableIdxAttr()) {
931 AIE::AIEArch arch = targetModel.getTargetArch();
932 if (arch != AIE::AIEArch::AIE2 && arch != AIE::AIEArch::AIE2p)
933 return emitOpError("repeat_parameter is only supported on AIE2 and "
934 "AIE2P devices");
935 if (!targetModel.isShimNOCTile(getColumn(), getRow()) &&
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() << ")";
940 if (getConstantInt64Operand(getRepeatCount()) != uint64_t{0})
941 return emitOpError("takes its repeat count from the scratchpad, so its "
942 "repeat_count operand must be 0");
943 std::optional<uint32_t> bdId = getConstantIntOperand(getBdId());
944 if (!bdId)
945 return emitOpError("takes its repeat count from the scratchpad, so its "
946 "bd_id must be a constant");
947 if (*bdId % 4 != 0)
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 ")
951 << *bdId;
952 }
953 return success();
954}
955
956//===----------------------------------------------------------------------===//
957// NpuWriteBdOp
958//===----------------------------------------------------------------------===//
959
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);
964 value && *value < 1)
965 return emitOpError() << name << " must cover at least one, got "
966 << *value;
967 return success();
968}
969
970LogicalResult AIEX::NpuWriteBdOp::verify() {
971 const auto &targetModel = AIE::getTargetModel(*this);
972 auto numBds = targetModel.getNumBDs(getColumn(), getRow());
973 bool isLinearTransfer =
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) {
982 if (*channel >=
983 targetModel.getNumDMAChannels(getColumn(), getRow(), *direction))
984 return emitOpError() << stringifyDMAChannelDir(*direction) << " channel "
985 << *channel << " does not exist on this tile";
986 if (!targetModel.isBdChannelAccessible(getColumn(), getRow(), getBdId(),
987 *channel, *direction))
988 return emitOpError() << "BD ID " << getBdId()
989 << " is not in the BD pool of "
990 << stringifyDMAChannelDir(*direction) << " channel "
991 << *channel;
992 } else if (targetModel.hasChannelLocalBdIds(getColumn(), getRow())) {
993 return emitOpError("needs a channel and direction: a BD id on this tile "
994 "names a slot of its channel's BD pool");
995 }
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();
1001 if (oooId < 0 ||
1002 static_cast<uint64_t>(oooId) > targetModel.getMaxOutOfOrderId())
1003 return emitOpError("out_of_order_id must be in [0, ")
1004 << targetModel.getMaxOutOfOrderId() << "].";
1005 if (oooId != 0 && getEnablePacket() == 0)
1006 return emitOpError("out_of_order_id requires a packet-enabled BD");
1007
1008 // Every value on this op is already the hardware-encoded field value (wrap
1009 // fields unbiased, stepsize fields less the step bias, iteration fields
1010 // biased actual-1), so a B-bit field's legal range is [0, 2^B - 1].
1011 AIE::AIETileType tileType = targetModel.getTileType(getColumn(), getRow());
1012 uint32_t wrapBits = targetModel.getDmaBdWrapBits(tileType);
1013 uint32_t stepBits = targetModel.getDmaBdStepBits(tileType);
1014 uint32_t iterBits = targetModel.getDmaBdIterBits(tileType);
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;
1018
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
1023 << "] range.";
1024 // BDs without a d0 step field (all AIE4 BDs) always step d0 by one
1025 // granule, encoded as 0 or as one granule less the bias.
1026 const AIE::DmaBdLayout *layout = targetModel.getDmaBdLayout(tileType);
1027 if (layout && !layout->d0Stride.exists() && getD0Size() > 1 &&
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
1035 << "] range.";
1036 if (getD2Stride() > maxStep)
1037 return emitOpError() << "D2 Stride exceeds the [0:" << maxStep
1038 << "] range.";
1039 if (getIterationSize() > maxIter)
1040 return emitOpError() << "Iteration Size exceeds the [0:" << maxIter
1041 << "] range.";
1042 if (static_cast<uint32_t>(getIterationStride()) > maxStep)
1043 return emitOpError() << "Iteration Stride exceeds the [0:" << maxStep
1044 << "] range.";
1045 // buffer_length is the full 32-bit word on a shim NOC tile but only 17 bits
1046 // on a mem tile and 14 on a core tile, where the packer masks it.
1047 uint64_t maxLen = targetModel.getDmaBdMaxLen(tileType);
1048 if (getBufferLength() > maxLen)
1049 return emitOpError() << "Buffer length exceeds the [0:" << maxLen
1050 << "] range.";
1051 if (targetModel.isShimNOCTile(getColumn(), getRow()) && getD2Size() != 0)
1052 return emitOpError("ShimTile only supports 3 dimensions of sizes.");
1053 // DMABDOp::verify() skips BDs inside aiex.dma_configure_task, so their pads
1054 // are first checked here.
1055 llvm::SmallVector<std::pair<AIE::DmaBdField, AIE::DmaBdField>, 3> padFields;
1056 if (layout)
1057 padFields = layout->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.";
1066 continue;
1067 }
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)
1074 << "] range.";
1075 }
1076
1077 if (!targetModel.isShimNOCTile(getColumn(), getRow()) &&
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());
1083 }
1084 if (!targetModel.isShimNOCTile(getColumn(), getRow()) && getAxcache())
1085 return emitOpError("Only ShimTiles support AxCACHE configuration.");
1086
1087 return success();
1088}
1089
1090uint32_t AIEX::NpuWriteBdOp::getAxcacheOrDefault() {
1091 return getAxcache().value_or(AIE::getTargetModel(*this).getDefaultAxCache());
1092}
1093
1094std::optional<uint32_t> AIEX::getConstantIntOperand(mlir::Value v) {
1095 if (std::optional<uint64_t> cst = getConstantInt64Operand(v))
1096 return static_cast<uint32_t>(*cst);
1097 return std::nullopt;
1098}
1099
1100// Widthwise counterpart of getConstantIntOperand; see createConstantArgPlus.
1101std::optional<uint64_t> AIEX::getConstantInt64Operand(mlir::Value v) {
1102 // An arith.constant is read in place: the generic match folds the op, which
1103 // dominates translating a sequence of a million writes.
1104 if (auto constant = v.getDefiningOp<arith::ConstantOp>())
1105 if (auto attr = dyn_cast<IntegerAttr>(constant.getValue()))
1106 return attr.getValue().getZExtValue();
1107 mlir::APInt cst;
1108 if (!mlir::matchPattern(v, mlir::m_ConstantInt(&cst)))
1109 return std::nullopt;
1110 return cst.getZExtValue();
1111}
1112
1113mlir::Value AIEX::createConstantI32(mlir::OpBuilder &builder,
1114 mlir::Location loc, uint32_t value) {
1115 return arith::ConstantOp::create(
1116 builder, loc, builder.getI32IntegerAttr(static_cast<int32_t>(value)));
1117}
1118
1119mlir::Value AIEX::createConstantArgPlus(mlir::OpBuilder &builder,
1120 mlir::Location loc, uint64_t value) {
1121 if (value <= std::numeric_limits<uint32_t>::max())
1122 return createConstantI32(builder, loc, static_cast<uint32_t>(value));
1123 return arith::ConstantOp::create(
1124 builder, loc,
1125 IntegerAttr::get(builder.getIntegerType(64),
1126 static_cast<int64_t>(value)));
1127}
1128
1129//===----------------------------------------------------------------------===//
1130// Buffer-relative runtime writes
1131//===----------------------------------------------------------------------===//
1132
1133// DataLayout's default queries abort for types without a builtin layout or a
1134// type interface; a legal memref element (such as another memref) need not have
1135// either. Check component types before querying composite builtin layouts too.
1136static bool hasQueryableStorageLayout(Type type) {
1137 if (type.isIntOrFloat() || isa<IndexType, DataLayoutTypeInterface>(type))
1138 return true;
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());
1143 return false;
1144}
1145
1146// Match BufferOp's allocation convention without an unchecked shape product or
1147// a fixed-size conversion of scalable element storage.
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())) {
1154 // The default vector layout uses a signed getNumElements(), then unsigned
1155 // innermost-dimension padding and bit products. Guard that query itself.
1156 if (vector.isScalable() || vector.getRank() == 0)
1157 return std::nullopt;
1158 int64_t elements = 1;
1159 for (int64_t dim : vector.getShape()) {
1160 auto product = llvm::checkedMul(elements, dim);
1161 if (!product)
1162 return std::nullopt;
1163 elements = *product;
1164 }
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;
1172 }
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}))
1177 return 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));
1181 if (!product)
1182 return std::nullopt;
1183 bytes = *product;
1184 }
1185 return bytes;
1186}
1187
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");
1192 return success();
1193}
1194
1195template <typename OpTy>
1196static LogicalResult
1197verifyBufferWrite(OpTy op, std::optional<uint32_t> wordOffset,
1198 uint64_t writeBytes, AIE::NamedOpTableCollection &names) {
1199 auto bufferAttr = op.getBufferAttr();
1200 if (!bufferAttr)
1201 return success();
1202 if (!wordOffset)
1203 return op.emitOpError("address must be constant when buffer is present");
1204 auto device = op->template getParentOfType<AIE::DeviceOp>();
1205 if (!device)
1206 return op.emitOpError("must be inside a device when buffer is present");
1207 // The device's region verifier owns the index and has verified all child
1208 // invariants before dispatching these graph-dependent checks.
1209 auto buffer = names.lookupIn<AIE::BufferOp>(device, bufferAttr.getAttr());
1210 if (!buffer)
1211 return op.emitOpError()
1212 << "buffer '" << bufferAttr.getValue() << "' not found in device";
1213 auto bufferBytes = getStaticMemRefStorageBytes(buffer.getType(),
1214 DataLayout::closest(buffer));
1215 if (!bufferBytes)
1216 return op.emitOpError(
1217 "referenced buffer must have a static, fixed-size storage extent "
1218 "representable in 64 bits");
1219
1220 uint64_t offsetBytes = uint64_t{*wordOffset} * sizeof(uint32_t);
1221 auto end = llvm::checkedAddUnsigned(offsetBytes, writeBytes);
1222 if (!end)
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";
1228
1229 auto tile = buffer.getTileLike();
1230 const auto &targetModel = device.getTargetModel();
1231 uint64_t memoryBytes = tile.isMemTile() ? targetModel.getMemTileSize()
1232 : targetModel.getLocalMemorySize();
1233 uint64_t start = offsetBytes;
1234 if (auto base = buffer.getAddress()) {
1235 if (*base < 0)
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";
1241 }
1242 // An unassigned base can only move the interval upward. Check this necessary
1243 // bound now, and the resolved interval when address assignment runs.
1244 auto memoryEnd = llvm::checkedAddUnsigned(start, writeBytes);
1245 if (!memoryEnd)
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";
1251 return success();
1252}
1253
1254//===----------------------------------------------------------------------===//
1255// NpuWrite32Op
1256//===----------------------------------------------------------------------===//
1257
1258LogicalResult AIEX::NpuWrite32Op::verify() {
1259 return verifyBufferWriteScope(*this);
1260}
1261
1262LogicalResult
1263AIEX::NpuWrite32Op::verifyNamedOpUses(AIE::NamedOpTableCollection &names) {
1264 if (!getBuffer())
1265 return success();
1266 return verifyBufferWrite(*this, getConstantIntOperand(getAddress()),
1267 sizeof(uint32_t), names);
1268}
1269
1270template <typename T>
1271static std::optional<uint32_t>
1272getAbsoluteAddress(T *op, uint32_t addressOffset,
1273 const AIE::NamedOpTable *names) {
1274 AIE::DeviceOp device =
1275 op->getOperation()->template getParentOfType<AIE::DeviceOp>();
1276 if (!device) {
1277 op->emitError("Must be inside a device.");
1278 return std::nullopt;
1279 }
1280 const AIE::AIETargetModel &tm = device.getTargetModel();
1281
1282 uint32_t address = 0;
1283
1284 // If blockwrite references a buffer, the given address is understood to be
1285 // relative to the buffer's start address.
1286 if (auto bufferSym = op->getBuffer()) {
1287 AIE::BufferOp buffer =
1288 names ? names->lookup<AIE::BufferOp>(op->getBufferAttr().getAttr())
1289 : AIE::lookupNamedOpIn<AIE::BufferOp>(device, *bufferSym);
1290 if (!buffer) {
1291 op->emitError() << "buffer '" << *bufferSym << "' not found in device";
1292 return std::nullopt;
1293 }
1294
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;
1301 }
1302
1303 int col = buffer.getTileOp().getCol();
1304 int row = buffer.getTileOp().getRow();
1305 address = tm.getTileAddress(col, row) + tm.getDataMemoryOffset(col, row) +
1306 static_cast<uint32_t>(*bufferAddress) +
1307 addressOffset * sizeof(uint32_t);
1308 } else { // otherwise, the given address is absolute
1309 address = addressOffset;
1310 std::optional<uint32_t> col = op->getColumn();
1311 std::optional<uint32_t> row = op->getRow();
1312 if (col && row) {
1313 // If col and row are set, only the lower 20 bits of the address are
1314 // used, and col and row dictate the upper bits (ignored). The offset thus
1315 // reaches only the first 1 MiB of the tile; AIE4 memtile data memory
1316 // (above 1 MiB of its 5 MiB window) needs a buffer or absolute address.
1317 address = tm.getTileAddress(*col, *row) | (address & 0xfffff);
1318 }
1319 }
1320
1321 return address;
1322}
1323
1324std::optional<uint32_t>
1325AIEX::NpuWrite32Op::getAbsoluteAddress(const AIE::NamedOpTable *names) {
1326 std::optional<uint32_t> addressOffset = getConstantIntOperand(getAddress());
1327 if (!addressOffset)
1328 return std::nullopt;
1329 return ::getAbsoluteAddress(this, *addressOffset, names);
1330}
1331
1332//===----------------------------------------------------------------------===//
1333// NpuAddressPatchOp
1334//===----------------------------------------------------------------------===//
1335
1336LogicalResult AIEX::NpuAddressPatchOp::verify() {
1337 // A runtime register address (addr_val) is meaningful only on the EmitC (C++
1338 // TXN) target; the constant `addr` still carries the fallback / static value.
1339 // The static binary target checks for the operand and diagnoses it there.
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 "
1345 "neither");
1346 return success();
1347}
1348
1349//===----------------------------------------------------------------------===//
1350// NpuUpdateFromScratchpadOp
1351//===----------------------------------------------------------------------===//
1352
1353std::optional<uint32_t> AIEX::NpuUpdateFromScratchpadOp::getAbsoluteAddress(
1354 const AIE::NamedOpTable *names) {
1355 return ::getAbsoluteAddress(this, getAddress(), names);
1356}
1357
1358LogicalResult AIEX::NpuUpdateFromScratchpadOp::verify() {
1359 // StateTable has at most 32 entries (32-bit words).
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) << ").";
1366
1367 // NpuCreateScratchpadOp::verify() bounds the state_table_idx.
1368 return success();
1369}
1370
1371//===----------------------------------------------------------------------===//
1372// NpuCreateScratchpadOp
1373//===----------------------------------------------------------------------===//
1374
1375LogicalResult AIEX::NpuCreateScratchpadOp::verify() {
1376 // Only usage_type == 0 is currently supported by firmware.
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.";
1381 }
1382
1383 // The StateTable layout (usage_type 0) has a max of 32 32-bit-word entries,
1384 // i.e. a maximum total scratchpad size of 128 bytes.
1385 constexpr uint32_t kMaxScratchpadSizeBytes = 128;
1386 if (getSize() == 0) {
1387 return emitOpError("size must be greater than 0.");
1388 }
1389 if (getSize() % 4 != 0) {
1390 return emitOpError("size (")
1391 << getSize() << ") must be a multiple of 4 bytes.";
1392 }
1393 if (getSize() > kMaxScratchpadSizeBytes) {
1394 return emitOpError("size (")
1395 << getSize() << " bytes) exceeds maximum scratchpad size of "
1396 << kMaxScratchpadSizeBytes << " bytes.";
1397 }
1398
1399 // Scratchpads are far rarer than the updates they bound, and an op verifier
1400 // runs after every pass, so the block scan belongs on this side.
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)
1405 continue;
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() << ".";
1411 }
1412 }
1413
1414 // At most one create_scratchpad may appear per runtime sequence. Walk the
1415 // parent RuntimeSequenceOp to check; only report from the duplicate (i.e.
1416 // the op that is NOT the first occurrence) to avoid emitting the same error
1417 // twice.
1418 auto runtimeSeq = getOperation()->getParentOfType<AIE::RuntimeSequenceOp>();
1419 if (!runtimeSeq) {
1420 return success();
1421 }
1422
1423 NpuCreateScratchpadOp firstSeen;
1424 runtimeSeq.walk([&](NpuCreateScratchpadOp op) {
1425 firstSeen = op;
1426 return WalkResult::interrupt();
1427 });
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";
1434 return diag;
1435 }
1436
1437 return success();
1438}
1439
1440//===----------------------------------------------------------------------===//
1441// NpuMaskWrite32Op
1442//===----------------------------------------------------------------------===//
1443
1444LogicalResult AIEX::NpuMaskWrite32Op::verify() {
1445 return verifyBufferWriteScope(*this);
1446}
1447
1448LogicalResult
1449AIEX::NpuMaskWrite32Op::verifyNamedOpUses(AIE::NamedOpTableCollection &names) {
1450 if (!getBuffer())
1451 return success();
1452 return verifyBufferWrite(*this, getConstantIntOperand(getAddress()),
1453 sizeof(uint32_t), names);
1454}
1455
1456std::optional<uint32_t>
1457AIEX::NpuMaskWrite32Op::getAbsoluteAddress(const AIE::NamedOpTable *names) {
1458 std::optional<uint32_t> addressOffset = getConstantIntOperand(getAddress());
1459 if (!addressOffset)
1460 return std::nullopt;
1461 return ::getAbsoluteAddress(this, *addressOffset, names);
1462}
1463
1464//===----------------------------------------------------------------------===//
1465// NpuMaskPollOp
1466//===----------------------------------------------------------------------===//
1467
1468LogicalResult AIEX::NpuMaskPollOp::verify() {
1469 return verifyBufferWriteScope(*this);
1470}
1471
1472LogicalResult
1473AIEX::NpuMaskPollOp::verifyNamedOpUses(AIE::NamedOpTableCollection &names) {
1474 if (!getBuffer())
1475 return success();
1476 return verifyBufferWrite(*this, getConstantIntOperand(getAddress()),
1477 sizeof(uint32_t), names);
1478}
1479
1480std::optional<uint32_t>
1481AIEX::NpuMaskPollOp::getAbsoluteAddress(const AIE::NamedOpTable *names) {
1482 std::optional<uint32_t> addressOffset = getConstantIntOperand(getAddress());
1483 if (!addressOffset)
1484 return std::nullopt;
1485 return ::getAbsoluteAddress(this, *addressOffset, names);
1486}
1487
1488//===----------------------------------------------------------------------===//
1489// NpuBlockWriteOp
1490//===----------------------------------------------------------------------===//
1491
1492LogicalResult AIEX::NpuBlockWriteOp::verify() {
1493 return verifyBufferWriteScope(*this);
1494}
1495
1496LogicalResult
1497AIEX::NpuBlockWriteOp::verifyNamedOpUses(AIE::NamedOpTableCollection &names) {
1498 if (!getBuffer())
1499 return success();
1500 auto type = dyn_cast<MemRefType>(getData().getType());
1501 DataLayout layout = DataLayout::closest(*this);
1502 auto bytes = getStaticMemRefStorageBytes(type, layout);
1503 if (!bytes)
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)
1508 return emitOpError(
1509 "payload must have 32-bit elements when buffer is present");
1510 return verifyBufferWrite(*this, getAddress(), *bytes, names);
1511}
1512
1513std::optional<uint32_t>
1514AIEX::NpuBlockWriteOp::getAbsoluteAddress(const AIE::NamedOpTable *names) {
1515 return ::getAbsoluteAddress(this, getAddress(), names);
1516}
1517
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());
1523 if (width != 32) {
1524 emitWarning("Only 32-bit data type is supported for now");
1525 return nullptr;
1526 }
1527
1528 memref::GetGlobalOp getGlobal = memref.getDefiningOp<memref::GetGlobalOp>();
1529 if (!getGlobal) {
1530 emitError("Only MemRefs from memref.get_global are supported");
1531 return nullptr;
1532 }
1533
1534 auto global = dyn_cast_if_present<memref::GlobalOp>(
1535 (*this)->getParentOfType<AIE::DeviceOp>().lookupSymbol(
1536 getGlobal.getName()));
1537 if (!global) {
1538 emitError("Global symbol not found");
1539 return nullptr;
1540 }
1541
1542 auto initVal = global.getInitialValue();
1543 if (!initVal) {
1544 emitError("Global symbol has no initial value");
1545 return nullptr;
1546 }
1547
1548 auto data = dyn_cast<DenseIntElementsAttr>(*initVal);
1549 if (!data) {
1550 emitError("Global symbol initial value is not a dense int array");
1551 return nullptr;
1552 }
1553
1554 return data;
1555}
1556
1557//===----------------------------------------------------------------------===//
1558// DMAConfigureTaskOp
1559//===----------------------------------------------------------------------===//
1560
1561AIE::DMABDOp AIEX::DMAConfigureTaskOp::getFirstBd() {
1562 Region &body = getBody();
1563 if (body.empty()) {
1564 return nullptr;
1565 }
1566 auto bd_ops = body.front().getOps<AIE::DMABDOp>();
1567 if (bd_ops.empty() && body.front().getNumSuccessors() == 1) {
1568 // Allow the first block to be empty and point to the entry point of the
1569 // chain. This allows for specifying cyclying BD chains (infinite loops)
1570 // within the constraints of MLIR syntax.
1571 Block &chain_entry = *body.front().getSuccessor(0);
1572 bd_ops = chain_entry.getOps<AIE::DMABDOp>();
1573 }
1574 if (bd_ops.empty()) {
1575 return nullptr;
1576 }
1577 return *bd_ops.begin();
1578}
1579
1580LogicalResult
1581AIEX::DMAConfigureTaskOp::canonicalize(AIEX::DMAConfigureTaskOp op,
1582 PatternRewriter &rewriter) {
1583 // Remove blocks that contain nothing but a terminator
1584 Region &body = op.getBody();
1585 bool did_rewrite = false;
1586 for (auto &block : body) {
1587 if (block.empty()) {
1588 continue;
1589 }
1590 auto ops_it = block.without_terminator();
1591 if (std::distance(ops_it.begin(), ops_it.end()) == 0) {
1592 rewriter.eraseOp(block.getTerminator());
1593 did_rewrite = true;
1594 }
1595 }
1596 if (did_rewrite) {
1597 return success();
1598 }
1599 return failure();
1600}
1601
1602// Enforce the per-BD ND access-pattern limit for BDs nested inside a
1603// runtime-sequence DMA task. The AIE::DMABDOp verifier skips these BDs (their
1604// parent is a DMA task op, not a *DMAOp), so this is the only check of the BD
1605// dimension count on the runtime-sequence path.
1606//
1607// Every AIE2/AIE2P DMA BD register file carries getBDMaxDims ND address
1608// dimensions (D0..) plus one separate iteration/repeat dimension: a core/shim
1609// BD has D0..D2 + iteration, a MemTile BD has D0..D3 + iteration. On this path
1610// aiex.shim_dma_single_bd_task hoists the leading tap dimension into that
1611// iteration register, so a shim/core BD may carry one dimension beyond its ND
1612// access limit (3 + 1). A MemTile is not given the +1: AIEDMATasksToNPU maps
1613// the 4th task dimension onto the iteration register for every tile type and
1614// caps the total at 4, which the MemTile's 4 ND dimensions already reach. Both
1615// branches therefore land on the same uniform 4-dimension cap enforced later by
1616// AIEDMATasksToNPU.
1617//
1618// A BD whose sizes and strides are all constant may give more: every dimension
1619// past the third is an iteration dimension, and aie-decompose-large-dma-bd
1620// splits them off into descriptors of 4. With a runtime value among them it
1621// cannot, so the cap applies here.
1622//
1623// A BD's `iteration` attribute claims that iteration register itself, so its
1624// sizes/strides must leave it free: one dimension fewer, with no splitting.
1625static LogicalResult
1626verifyTaskBDDimensions(const AIE::AIETargetModel &targetModel, int col, int row,
1627 Region &body) {
1628 size_t maxNDims = targetModel.getBDMaxDims(col, row);
1629 if (!targetModel.isMemTile(col, row))
1630 ++maxNDims; // leading dim is hoisted into the iteration/repeat register
1631 // A d3 step adds a fourth dimension, which no lowering programs yet.
1632 const AIE::DmaBdLayout *layout = targetModel.getDmaBdLayout(col, row);
1633 bool d3Unsupported = layout && layout->d3Stride.exists();
1634 LogicalResult result = success();
1635 body.walk([&](AIE::DMABDOp bd) {
1636 // The BD's own verifier skips it here, so nothing has yet established that
1637 // its mixed sizes/strides lists are safe to read.
1638 if (failed(bd.verifyMixedSizesAndStrides())) {
1639 result = failure();
1640 return;
1641 }
1642 if (failed(
1643 AIE::verifyDMABDIteration(bd, targetModel.getTileType(col, row)))) {
1644 result = failure();
1645 return;
1646 }
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).";
1655 result = failure();
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 "
1659 "this tile (got "
1660 << std::to_string(numDims)
1661 << " dimensions): its fourth addressing dimension "
1662 "(d3) is not supported yet.";
1663 result = failure();
1664 }
1665 return;
1666 }
1667 auto isConstant = [](OpFoldResult v) {
1668 return getConstantIntValue(v).has_value();
1669 };
1670 if (numDims > maxNDims && llvm::all_of(bd.getMixedSizes(), isConstant) &&
1671 llvm::all_of(bd.getMixedStrides(), isConstant))
1672 return;
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 "
1676 "(got "
1677 << std::to_string(numDims) << " dimensions).";
1678 result = failure();
1679 }
1680 });
1681 return result;
1682}
1683
1684LogicalResult AIEX::DMAConfigureTaskOp::verify() {
1685 if (failed(AIE::verifyDMAChannel(getOperation(), getTileLike(),
1686 getDirection(), getChannel())))
1687 return failure();
1688 const AIE::AIETargetModel &targetModel = AIE::getTargetModel(getOperation());
1689 // Skip the per-BD dimension check on an unplaced (logical) tile: the ND limit
1690 // is a function of the tile's placed coordinates, which are not yet known.
1691 // The verifier runs again on the concrete tile once placement resolves it.
1692 std::optional<int> col = getTileLike().tryGetCol();
1693 std::optional<int> row = getTileLike().tryGetRow();
1694 if (col && row &&
1695 failed(verifyTaskBDDimensions(targetModel, *col, *row, getBody())))
1696 return failure();
1697 Region &body = getBody();
1698 // This is a layering violation on the DMABDOps, but they are never verified
1699 // otherwise Because DMAConfigureTaskOps are not yet merged into the AIE
1700 // dialect. The normal DMABDOp verify operation will skip over any BD inside
1701 // a DMAConfigureTaskOp
1702 if (failed(AIE::verifyAssignedPacket(*this, getPacketAttr())))
1703 return failure();
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()) {
1709 continue;
1710 }
1711 if (block.hasNoPredecessors() && !block.isEntryBlock()) {
1712 auto error = block.getTerminator()->emitError(
1713 "Block ending in this terminator does not form a chain with "
1714 "entry block.");
1715 return failure();
1716 }
1717
1718 const AIE::AIETargetModel &targetModel =
1719 AIE::getTargetModel(getOperation());
1720
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.");
1726 result = failure();
1727 }
1728 // DMABDOp::verify skips task BDs, so validate their packet header and
1729 // out_of_order_id here too.
1730 if (failed(AIE::verifyAssignedPacket(
1731 bd, bd.getPacket().value_or(AIE::PacketInfoAttr()))) ||
1732 failed(AIE::verifyDMABDOutOfOrderId(bd, taskHasPacket)) ||
1733 failed(bd.verifyTransferInBounds()))
1734 result = failure();
1735 bds.push_back(bd);
1736 });
1737 }
1738 // Only a memtile's low-numbered channels reach its neighbors' buffers and
1739 // locks; the rest are local only, as in aie.memtile_dma.
1740 bool onMemTile = col && row && targetModel.isMemTile(*col, *row);
1741 uint32_t adjacentChannels =
1742 onMemTile ? targetModel.getMaxChannelNumForAdjacentMemTile(*col, *row)
1743 : 0;
1744 if (onMemTile && static_cast<uint32_t>(getChannel()) >= adjacentChannels) {
1745 auto isNonLocal = [&](AIE::TileLike tile) {
1746 // Pinned logical and physical tiles can denote the same location. Defer
1747 // the check until placement if the resource's coordinates are unknown.
1748 auto resourceCol = tile.tryGetCol();
1749 auto resourceRow = tile.tryGetRow();
1750 return resourceCol && resourceRow &&
1751 (*resourceCol != *col || *resourceRow != *row);
1752 };
1753 body.walk([&](Operation *op) {
1754 Operation *resource = nullptr;
1755 AIE::TileLike resourceTile;
1756 StringRef what;
1757 if (auto bd = dyn_cast<AIE::DMABDOp>(op)) {
1758 auto buffer = bd.getBuffer().getDefiningOp<AIE::BufferOp>();
1759 if (!buffer)
1760 return;
1761 resource = buffer;
1762 resourceTile = buffer.getTileLike();
1763 what = "buffer";
1764 } else if (auto useLock = dyn_cast<AIE::UseLockOp>(op)) {
1765 auto lock = useLock.getLock().getDefiningOp<AIE::LockOp>();
1766 if (!lock) {
1767 useLock.emitOpError()
1768 << "requires a lock defined by aie.lock in a task on memtile DMA "
1769 "channel "
1770 << getChannel();
1771 result = failure();
1772 return;
1773 }
1774 resource = lock;
1775 resourceTile = lock.getTileLike();
1776 what = "lock";
1777 } else {
1778 return;
1779 }
1780 // aie.buffer and aie.lock reject a tile operand that is not a tile, but
1781 // they may be verified after this task: they can follow the runtime
1782 // sequence, and a buffer can sit inside the task body.
1783 if (!resourceTile) {
1784 op->emitOpError() << "uses a " << what
1785 << " whose tile operand is not a tile";
1786 result = failure();
1787 return;
1788 }
1789 if (!isNonLocal(resourceTile))
1790 return;
1791 InFlightDiagnostic err = op->emitOpError()
1792 << "is in a task on memtile DMA channel "
1793 << getChannel()
1794 << " and attempts to access a non-local " << what
1795 << "; only channels below " << adjacentChannels
1796 << " reach neighboring tiles";
1797 err.attachNote(resource->getLoc()) << what;
1798 result = failure();
1799 });
1800 }
1801 if (getOutOfOrder()) {
1802 // Out-of-order mode rejects task completion token (bits are aliased).
1803 if (getIssueToken()) {
1804 auto err =
1805 emitOpError("out_of_order channel cannot issue a completion token");
1806 err.attachNote() << "set issue_token = false on this out-of-order task";
1807 result = failure();
1808 }
1810 getOperation(), getDirection(), getOutOfOrder(),
1811 llvm::ArrayRef<AIE::DMABDOp>(bds),
1812 /*packetEnabledByContext=*/taskHasPacket)))
1813 result = failure();
1814 }
1815 return result;
1816}
1817
1818LogicalResult AIEX::DMAStartTaskOp::verify() {
1819 if (getRepeatCountAttr() && getRepeatCountVal())
1820 return emitOpError(
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 ")
1824 << rc.getInt();
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, "
1829 "not both");
1830 return success();
1831}
1832
1833std::optional<int64_t> AIEX::DMAConfigureTaskForOp::getStaticBytesStreamed() {
1834 int64_t starts = 0;
1835 for (Operation *user : getResult().getUsers()) {
1836 auto start = dyn_cast<AIEX::DMAStartTaskOp>(user);
1837 if (!start) {
1838 if (isa<AIEX::DMAAwaitTaskOp, AIEX::DMAFreeTaskOp>(user))
1839 continue;
1840 // The task value is forwarded (a branch operand, a call, ...), so its
1841 // starts elsewhere can't be counted.
1842 return std::nullopt;
1843 }
1844 // A start outside the task's own block may run under a loop or a
1845 // mutually-exclusive branch, either of which this static count can't see.
1846 if (start->getBlock() != (*this)->getBlock() ||
1847 start.getRepeatCountAttr() || start.getRepeatCountVal() ||
1848 start.hasRepeatParameter())
1849 return std::nullopt;
1850 ++starts;
1851 }
1852 if (starts == 0)
1853 return 0;
1854 std::optional<int64_t> repeat = getConstantIntValue(getRepeatCountValue());
1855 if (!repeat || *repeat < 0)
1856 return std::nullopt;
1857
1858 Region &body = getBody();
1859 if (body.empty())
1860 return std::nullopt;
1861 // The queue starts the chain at the entry block, so only blocks reachable
1862 // from it stream. A cycle runs indefinitely, and a next_bd_id continues the
1863 // chain outside the body.
1864 std::optional<int64_t> moved = 0;
1865 for (auto scc = llvm::scc_begin(&body.front()); !scc.isAtEnd(); ++scc) {
1866 if (scc.hasCycle())
1867 return std::nullopt;
1868 for (AIE::DMABDOp bd : scc->front()->getOps<AIE::DMABDOp>()) {
1869 // A scratchpad parameter lengthens the BD at run time (AIEOps.td's
1870 // "Runtime length").
1871 std::optional<int64_t> len =
1872 bd.getLengthParameterAttr() || bd.getLengthStateTableIdxAttr()
1873 ? std::nullopt
1874 : bd.getStaticLenInBytes();
1875 if (!len || bd.getIteration() || bd.getNextBdId())
1876 return std::nullopt;
1877 moved = llvm::checkedAdd(*moved, *len);
1878 if (!moved)
1879 return std::nullopt;
1880 }
1881 }
1882 std::optional<int64_t> runs = llvm::checkedAdd(*repeat, int64_t{1});
1883 if (runs)
1884 runs = llvm::checkedMul(*runs, starts);
1885 return runs ? llvm::checkedMul(*moved, *runs) : std::nullopt;
1886}
1887
1888namespace {
1889// A far end's cyclic chain of BDs over one object: each segment's BD, in
1890// order, sent `copies` times in a row.
1891struct BdChain {
1892 SmallVector<int64_t> segmentBytes;
1893 int64_t copies;
1894 int64_t objectBytes;
1895
1896 // Nullopt when the object's bytes overflow or a segment is empty.
1897 static std::optional<BdChain> get(ArrayRef<int64_t> segmentBytes,
1898 int64_t copies) {
1899 if (segmentBytes.size() == 1)
1900 copies = 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);
1907 if (!objectBytes)
1908 return std::nullopt;
1909 }
1910 if (segmentBytes.empty())
1911 return std::nullopt;
1912 return BdChain{SmallVector<int64_t>(segmentBytes), copies, *objectBytes};
1913 }
1914
1915 // True when `bytes` through the chain stop where one of its BDs ends.
1916 bool endsOnBd(int64_t bytes) const {
1917 int64_t rest = bytes % objectBytes;
1918 int64_t start = 0;
1919 for (int64_t segment : segmentBytes) {
1920 if (rest < start + segment * copies)
1921 return (rest - start) % segment == 0;
1922 start += segment * copies;
1923 }
1924 return true;
1925 }
1926
1927 bool operator==(const BdChain &other) const {
1928 return segmentBytes == other.segmentBytes && copies == other.copies;
1929 }
1930};
1931} // namespace
1932
1933std::optional<int64_t> AIEX::NpuDmaMemcpyNdOp::getStaticBytesStreamed() {
1934 if (getLengthParameterAttr() || getLengthStateTableIdxAttr())
1935 return std::nullopt;
1936 uint64_t bits = getElementTypeBitwidth();
1937 if (bits % 8)
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;
1943 }
1944 return bytes;
1945}
1946
1947// The far end of a shim transfer on an objectFIFO receives (or sends) whole
1948// objects through BDs sized by the object type, or by its link pool's
1949// segments, so transfers ending mid-BD never complete it and the fifo hangs.
1950// Several transfers may share an object (concatenating host buffers into it, or
1951// splitting it across them), so it is the runtime sequence's static total
1952// through the fifo that must stop at a BD boundary.
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())
1957 return success();
1958 if (!moved || *moved == 0)
1959 return success();
1960 DataLayout layout = DataLayout::closest(transfer);
1961 // Bytes an object holds, or nullopt when that overflows.
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())));
1967 };
1968 // A linked fifo's far end on the link's shared tile is a chain of BDs over
1969 // the link's pool, one per pool segment, sized by the pool owner whatever
1970 // this fifo's own (or consumer) type. A join's or distribute's combined end
1971 // steps through every segment in order, each small end through its own, and
1972 // a plain link's single segment is the whole pool object. The link's
1973 // repeat_count sends each of its output's segment BDs that many times in a
1974 // row. Every link the fifo meets has an end the transfer must complete,
1975 // one per tile when links on several tiles read a broadcast.
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);
1986 return fifos;
1987 };
1988 auto self = FlatSymbolRefAttr::get(fifo.getSymNameAttr());
1989 if (device)
1990 for (AIE::ObjectFifoLinkOp link : device.getOps<AIE::ObjectFifoLinkOp>()) {
1991 if (!llvm::is_contained(link.getFifoIns(), self) &&
1992 !llvm::is_contained(link.getFifoOuts(), self))
1993 continue;
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)
1998 return success();
1999 linkTiles.push_back(*sharedTile);
2000 AIE::ObjectFifoCreateOp owner = link.getPoolOwner();
2001 MemRefType pool =
2002 cast<AIE::AIEObjectFifoType>(owner.getElemType()).getElementType();
2003 auto width =
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()]};
2010 }
2011 SmallVector<int64_t> segmentBytes;
2012 for (auto [offset, size] : segments) {
2013 std::optional<int64_t> bytes = llvm::checkedMul(size, width);
2014 if (!bytes)
2015 break;
2016 segmentBytes.push_back(*bytes);
2017 }
2018 int64_t copies = llvm::is_contained(outs, fifo)
2019 ? link.getRepeatCount().value_or(1)
2020 : 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);
2026 }
2027 // Every far-end BD chain this transfer must leave at a BD boundary: the
2028 // producer's, for a drain, and each consumer's other than the shim's own. A
2029 // broadcast stalls on its slowest consumer, so a drain bounds what the
2030 // others receive too. An end off every link tile is one BD over its own
2031 // object.
2032 auto addChain = [&](Value tile, Type fifoType) {
2033 if (llvm::is_contained(linkTiles, tile))
2034 return;
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);
2040 };
2041 auto producer =
2042 dyn_cast_or_null<AIE::TileLike>(fifo.getProducerTile().getDefiningOp());
2043 if (!producer)
2044 return success();
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());
2051 }
2052 if (chains.empty())
2053 return success();
2054
2055 // Transfers in a loop or branch have no static count to sum.
2056 auto sequence = transfer->getParentOfType<AIE::RuntimeSequenceOp>();
2057 if (!sequence || transfer->getBlock() != &sequence.getBody().front())
2058 return success();
2059 // A dma_channel_reset_for re-arms the fifo's far ends and drops a partly
2060 // filled object. It doesn't block, so which bytes land before it isn't
2061 // static, and the transfers around it can't be summed.
2062 if (llvm::any_of(transfer->getBlock()->getOps<AIEX::DmaChannelResetForOp>(),
2063 [&](AIEX::DmaChannelResetForOp reset) {
2064 return reset.getObjfifoAttr() == alloc;
2065 }))
2066 return success();
2067 // Bytes `op` moves through the fifo: zero when it moves none or names
2068 // another, nullopt when its count isn't static.
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()
2072 : 0;
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);
2078 return 0;
2079 };
2080 // Segment boundaries don't add up the way whole objects do, so the
2081 // sequence's total is checked whatever this transfer moves, once: by the
2082 // first transfer through the fifo.
2083 for (Operation *prev = transfer->getPrevNode(); prev;
2084 prev = prev->getPrevNode())
2085 if (through(prev) != 0)
2086 return success();
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);
2091 // A transfer that moves nothing, or is never started, shares no object.
2092 if (bytes == 0)
2093 return WalkResult::advance();
2094 if (!bytes || op->getBlock() != transfer->getBlock())
2095 return WalkResult::interrupt();
2096 total = llvm::checkedAdd(*total, *bytes);
2097 if (!total)
2098 return WalkResult::interrupt();
2099 ++sharing;
2100 return WalkResult::advance();
2101 });
2102 if (walk.wasInterrupted())
2103 return success();
2104 const BdChain *partial = llvm::find_if(
2105 chains, [&](const BdChain &chain) { return !chain.endsOnBd(*total); });
2106 if (partial == chains.end())
2107 return success();
2108
2109 InFlightDiagnostic error = transfer->emitOpError()
2110 << "moves " << *moved
2111 << " bytes through objectFIFO @"
2112 << fifo.getSymName() << ", which";
2113 if (sharing > 1)
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
2117 << "-byte objects";
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
2125 << " bytes";
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";
2130}
2131
2132LogicalResult
2133AIEX::DMAConfigureTaskOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2134 FlatSymbolRefAttr alloc = getAllocAttr();
2135 AIE::DeviceOp dev = getOperation()->getParentOfType<AIE::DeviceOp>();
2136 if (!alloc || !dev)
2137 return success();
2138 auto allocation = dyn_cast_or_null<AIE::ShimDMAAllocationOp>(
2139 symbolTable.lookupSymbolIn(dev, alloc.getAttr()));
2140 if (!allocation)
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;
2147 return success();
2148}
2149
2150// Resolving the allocation symbol through the collection keeps the lookup off
2151// the device's linear symbol scan, which a per-op verifier repeats after every
2152// pass.
2153LogicalResult AIEX::DMAConfigureTaskForOp::verifySymbolUses(
2154 SymbolTableCollection &symbolTable) {
2155 AIE::DeviceOp dev = getOperation()->getParentOfType<AIE::DeviceOp>();
2156 if (!dev)
2157 return success();
2158 Operation *target =
2159 symbolTable.lookupSymbolIn(dev, getAlloc().getRootReference());
2160 if (!target)
2161 return emitOpError() << getAlloc() << " does not name a symbol";
2162 // The tile is known once the name is a shim DMA allocation or a route
2163 // endpoint, so the per-BD dimension limit can be enforced before the task
2164 // becomes a concrete dma_configure_task. Before the objectFIFO lowering
2165 // the name is the fifo's own, and the check waits.
2166 Value tileValue;
2167 LogicalResult named =
2168 TypeSwitch<Operation *, LogicalResult>(target)
2169 .Case([&](AIE::ShimDMAAllocationOp alloc) {
2170 tileValue = alloc.getTile();
2171 return success();
2172 })
2173 .Case([&](AIE::RouteEndpointOp endpoint) -> LogicalResult {
2174 tileValue = endpoint.getTile();
2175 if (endpoint.getBundle() == AIE::WireBundle::DMA)
2176 return success();
2177 return emitOpError() << getAlloc() << " names a "
2178 << stringifyWireBundle(endpoint.getBundle())
2179 << " port, not a DMA channel";
2180 })
2181 .Case([&](AIE::ObjectFifoCreateOp fifo) {
2182 return verifyTransferCoversWholeObjects(
2183 *this, getAlloc(), getStaticBytesStreamed(), fifo, symbolTable);
2184 })
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";
2189 });
2190 if (failed(named))
2191 return failure();
2192 // An allocation or endpoint on an unplaced (logical) tile waits for
2193 // placement to substitute a real one.
2194 auto tile = tileValue ? tileValue.getDefiningOp<AIE::TileOp>() : nullptr;
2195 if (!tile)
2196 return success();
2197 const AIE::AIETargetModel &targetModel = AIE::getTargetModel(getOperation());
2198 return verifyTaskBDDimensions(targetModel, tile.getCol(), tile.getRow(),
2199 getBody());
2200}
2201
2202//===----------------------------------------------------------------------===//
2203// DMAStartBdChainOp
2204//===----------------------------------------------------------------------===//
2205
2206AIE::BDChainOp AIEX::DMAStartBdChainOp::getBDChainOp() {
2207 AIE::DeviceOp device = (*this)->getParentOfType<AIE::DeviceOp>();
2208 AIE::BDChainOp chain = device.lookupSymbol<AIE::BDChainOp>(getSymbol());
2209 return chain;
2210}
2211
2212LogicalResult AIEX::DMAStartBdChainOp::verify() {
2213 if (failed(AIE::verifyDMAChannel(getOperation(), getTileLike(),
2214 getDirection(), getChannel())))
2215 return failure();
2216 AIE::BDChainOp chain = getBDChainOp();
2217 if (!chain) {
2218 return emitOpError("symbol does not reference valid BD chain");
2219 }
2220
2221 auto actualArgTypes = getArgs().getTypes();
2222 auto expectedArgTypes = chain.getRegion().getArgumentTypes();
2223 if (actualArgTypes.size() != expectedArgTypes.size()) {
2224 return emitOpError("Number of arguments mismatches.");
2225 }
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];
2231 }
2232 }
2233 return success();
2234}
2235
2236//===----------------------------------------------------------------------===//
2237// NpuControlPacketOp
2238//===----------------------------------------------------------------------===//
2239
2240uint32_t AIEX::NpuControlPacketOp::getRowFromAddr() {
2241 const auto &targetModel = AIE::getTargetModel(*this);
2242 return targetModel.getRowFromAddress(getAddress());
2243}
2244
2245uint32_t AIEX::NpuControlPacketOp::getColumnFromAddr() {
2246 const auto &targetModel = AIE::getTargetModel(*this);
2247 return targetModel.getColumnFromAddress(getAddress());
2248}
2249
2250bool AIEX::NpuControlPacketOp::isOrdinaryWrite() {
2251 return isOrdinaryWrite(AIE::getTargetModel(*this));
2252}
2253
2254bool AIEX::NpuControlPacketOp::isOrdinaryWrite(
2255 const AIE::AIETargetModel &target) {
2256 auto data = getData();
2257 if (getOpcode() != 0 || !data)
2258 return false;
2259 AIE::TileID tile{
2260 static_cast<int>(getAddress() >> target.getColumnShift()),
2261 static_cast<int>(
2262 (getAddress() >> target.getRowShift()) &
2263 ((1u << (target.getColumnShift() - target.getRowShift())) - 1))};
2264 uint32_t offset = getAddress() & ((1u << target.getRowShift()) - 1);
2265 for (size_t index = 0; index < data->size(); ++index)
2266 if (!target.isOrdinaryWriteAddress(tile, offset + 4 * index))
2267 return false;
2268 return true;
2269}
2270
2271LogicalResult AIEX::NpuControlPacketOp::verify() {
2272 // AIE4 control packets have a different header and payload size.
2273 if (isa<AIE::AIE4TargetModel>(AIE::getTargetModel(*this)))
2274 return emitOpError("control packets are not yet supported on AIE4");
2275 // The 2-bit operation field: 0 write, 1 read, 2 write with response, 3
2276 // reserved. A wider value would also spill into the stream ID.
2277 uint32_t opcode = getOpcode();
2278 if (opcode > 2)
2279 return emitOpError("opcode ")
2280 << opcode
2281 << " is reserved; expected 0 (write), 1 (read), or 2 (write with "
2282 "response)";
2283
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())
2289 return emitOpError(
2290 "control packet with a write opcode requires a data payload");
2291
2292 // The word count is encoded as (words - 1), so 0 cannot be represented.
2293 std::optional<uint32_t> words;
2294 if (auto data = getData())
2295 words = data->size();
2296 else
2297 words = getLength();
2298 if (!words)
2299 return emitOpError("read control packet requires a length attribute");
2300 if (*words < 1)
2301 return emitOpError("control packet payload must be at least 1 word");
2302
2303 // Reads are never split, so their length must already fit one packet.
2304 if (isRead && *words > getMaxDataWords())
2305 return emitOpError("read control packet length ")
2306 << *words << " exceeds the maximum of " << getMaxDataWords()
2307 << " 32-bit words";
2308
2309 return success();
2310}
2311
2312AIE::TileID AIEX::NpuControlPacketOp::getTileFromAddr() {
2313 return {static_cast<int>(getColumnFromAddr()),
2314 static_cast<int>(getRowFromAddr())};
2315}
2316
2317uint32_t AIEX::NpuControlPacketOp::getLocalAddress() {
2318 return getAddress() & ((1u << AIE::getTargetModel(*this).getRowShift()) - 1);
2319}
2320
2321//===----------------------------------------------------------------------===//
2322// SetLockOp
2323//===----------------------------------------------------------------------===//
2324
2325LogicalResult AIEX::SetLockOp::verify() {
2326 const auto &targetModel = AIE::getTargetModel(*this);
2327
2328 if (targetModel.getTargetArch() == AIE::AIEArch::AIE1)
2329 return emitOpError("SetLockOp is not supported on AIE1.");
2330
2331 if (!getLock().getDefiningOp<AIE::LockOp>())
2332 return emitOpError("lock operand is not an aie.lock");
2333
2334 if (std::optional<int64_t> value = getConstantIntValue(getValue())) {
2335 if (*value < 0)
2336 return emitOpError("Lock value must be non-negative");
2337 if (*value > targetModel.getMaxLockValue())
2338 return emitOpError("Lock value exceeds the maximum value of " +
2339 std::to_string(targetModel.getMaxLockValue()));
2340 }
2341
2342 auto lockOp = getLockOp();
2343 auto lockIDOpt = getLockOp().getLockID();
2344 // Note that the lockID may not be assigned initially, so lets wait until it
2345 // is to verify the lockID dependent conditions
2346 if (!lockIDOpt) {
2347 return success();
2348 }
2349 // A logical tile with a coordinate still unpinned waits for the
2350 // post-placement re-verify for its range and address checks, as
2351 // UsesAreAccessible's do.
2352 std::optional<int> col = lockOp.getTileLike().tryGetCol();
2353 std::optional<int> row = lockOp.getTileLike().tryGetRow();
2354 if (!col || !row)
2355 return success();
2356
2357 uint32_t lockID = lockOp.getLockIDValue();
2358
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));
2362 }
2363
2364 if (!targetModel.getLocalLockAddress(lockID, AIE::TileID{*col, *row})) {
2365 return emitOpError("Invalid lock ID and tile combination when trying to "
2366 "retrieve the local lock address.");
2367 }
2368
2369 return success();
2370}
2371
2372//===----------------------------------------------------------------------===//
2373// DMABdPoolPopOp / DMABdPoolPushOp
2374//===----------------------------------------------------------------------===//
2375
2376static LogicalResult verifyBdPoolPartition(Operation *op, int col, int row,
2377 uint32_t begin, uint32_t end) {
2378 uint32_t numBds = AIE::getTargetModel(op).getNumBDs(col, row);
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 << ")";
2384 return success();
2385}
2386
2387LogicalResult AIEX::DMABdPoolPopOp::verify() {
2388 if (failed(verifyBdPoolPartition(*this, getColumn(), getRow(), getBdBegin(),
2389 getBdEnd())))
2390 return failure();
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() << ")";
2396 return success();
2397}
2398
2399LogicalResult AIEX::DMABdPoolPushOp::verify() {
2400 return verifyBdPoolPartition(*this, getColumn(), getRow(), getBdBegin(),
2401 getBdEnd());
2402}
2403
2404//===----------------------------------------------------------------------===//
2405// DmaChannelResetOp
2406//===----------------------------------------------------------------------===//
2407
2408LogicalResult AIEX::DmaChannelResetOp::verify() {
2409 const auto &targetModel = AIE::getTargetModel(*this);
2410
2411 auto tile = dyn_cast_or_null<AIE::TileOp>(getTile().getDefiningOp());
2412 if (!tile)
2413 return emitOpError() << "tile operand must be produced by an aie.tile op";
2414 int col = tile.getCol();
2415 int row = tile.getRow();
2416 // Only core and mem tiles have a per-channel DMA reset bit. The shim NOC DMA
2417 // control register has no reset field (aie-codegen's Aie2PShimDmaChProp sets
2418 // Reset.Mask = 0); bit 1 there is PAUSE_MEM, not RESET. Rejecting shim keeps
2419 // the op honest about what it can lower, matching aie-codegen's own
2420 // XAie_DmaChannelReset, which errors on SHIMNOC/SHIMPL tiles.
2421 if (!targetModel.isCoreTile(col, row) && !targetModel.isMemTile(col, row))
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)";
2425
2426 uint32_t numChannels =
2427 targetModel.getNumDMAChannels(col, row, getDirection());
2428 if (getChannel() >= numChannels)
2429 return emitOpError() << "channel " << getChannel()
2430 << " out of range for this tile and direction (tile "
2431 "has "
2432 << numChannels << " DMA channel(s) in this direction)";
2433
2434 return success();
2435}
2436
2437LogicalResult AIEX::DmaChannelResetForOp::verify() {
2438 // Deferring verifier, in the shape of DMAConfigureTaskForOp::verify: the
2439 // referenced symbol is only resolvable once the objectFIFO lowering has run.
2440 // It names an aie.objectfifo, then that fifo's shim endpoint while the
2441 // lowering is in flight, and finally its aie.objectfifo_rearm_binding. If
2442 // none is resolvable yet, defer -- a later pass will resolve it.
2443 AIE::DeviceOp dev = getOperation()->getParentOfType<AIE::DeviceOp>();
2444 if (!dev)
2445 return success();
2446 // The resident re-arm relies on the aie2p behavior that a DMA channel has no
2447 // enable bit, so the only way to restart it is a START_QUEUE push. AIE1 DMA
2448 // channels have an enable bit and are armed differently, so the trio this op
2449 // lowers to would not re-arm them correctly.
2450 if (AIE::getTargetModel(*this).getTargetArch() == AIE::AIEArch::AIE1)
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());
2454 if (!target)
2455 return success(); // symbol resolved during a later pass; defer the check
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)";
2461 return success();
2462}
2463
2464//===----------------------------------------------------------------------===//
2465// CoreResetOp
2466//===----------------------------------------------------------------------===//
2467
2468LogicalResult AIEX::CoreResetOp::verify() {
2469 const auto &targetModel = AIE::getTargetModel(*this);
2470
2471 // The op lowers to an NPU control-packet write; the runtime sequence has no
2472 // meaning on AIE1. Reject it explicitly, as SetLockOp does.
2473 if (targetModel.getTargetArch() == AIE::AIEArch::AIE1)
2474 return emitOpError("aiex.core_reset is not supported on AIE1.");
2475
2476 auto tile = dyn_cast_or_null<AIE::TileOp>(getTile().getDefiningOp());
2477 if (!tile)
2478 return emitOpError() << "tile operand must be produced by an aie.tile op";
2479 int col = tile.getCol();
2480 int row = tile.getRow();
2481 // The tile coordinates are bounded by aie.tile's own verifier, so this op
2482 // does not re-check them for range.
2483
2484 // Only core tiles have a CORE_CONTROL register with a reset bit. Mem and shim
2485 // tiles have no compute core, so there is nothing valid to lower to. This
2486 // matches aie-codegen's XAie_CoreReset, which errors on any tile that is not
2487 // an AIE (core) tile.
2488 if (!targetModel.isCoreTile(col, row))
2489 return emitOpError() << "tile (" << col << ", " << row
2490 << ") has no core to reset (only core tiles have a "
2491 "CORE_CONTROL register)";
2492
2493 return success();
2494}
2495
2496//===----------------------------------------------------------------------===//
2497// BlockFloatingPointType
2498//===----------------------------------------------------------------------===//
2499uint64_t AIEX::BlockFloatType::getTotalSizeInBits() const {
2500 return getBlockSize() * getMantissaBits() + getExponentBits() +
2501 getSubtileShiftBits();
2502}
2503
2504llvm::TypeSize AIEX::BlockFloatType::getTypeSizeInBits(
2505 const mlir::DataLayout &dataLayout,
2506 mlir::DataLayoutEntryListRef params) const {
2507 return llvm::TypeSize::getFixed(getTotalSizeInBits());
2508}
2509
2510uint64_t AIEX::BlockFloatType::getABIAlignment(
2511 const mlir::DataLayout &dataLayout,
2512 mlir::DataLayoutEntryListRef params) const {
2513 // For the purposes of the data movement operations, we want all types to be
2514 // packed <=> ABI alignment is 1.
2515 return 1;
2516}
2517
2518std::optional<AIEX::BlockFloatType::BlockFormat>
2519AIEX::BlockFloatType::getBlockFormat(StringRef blockType) {
2520 static const llvm::StringMap<AIEX::BlockFloatType::BlockFormat>
2521 blockFormatsMap = {
2522 {"v8bfp16ebs8", {8, 8, 8, 0}},
2523 {"v16bfp16ebs16", {16, 8, 8, 0}},
2524 };
2525
2526 auto it = blockFormatsMap.find(blockType);
2527 if (it != blockFormatsMap.end()) {
2528 return it->second;
2529 }
2530
2531 return std::nullopt;
2532}
2533
2534LogicalResult
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.";
2540
2541 return success();
2542}
2543
2544//===----------------------------------------------------------------------===//
2545// ConfigureOp
2546//===----------------------------------------------------------------------===//
2547
2548AIE::DeviceOp AIEX::ConfigureOp::getReferencedDeviceOp() {
2549 ModuleOp moduleOp = this->getOperation()->getParentOfType<ModuleOp>();
2550 if (!moduleOp) {
2551 emitError("aiex.configure must be inside of a module");
2552 return nullptr;
2553 }
2554 Operation *maybeReferencedDevice =
2555 SymbolTable::lookupSymbolIn(moduleOp.getOperation(), getSymbolAttr());
2556 if (!maybeReferencedDevice) {
2557 emitError("No such device: '") << getSymbolAttr() << "'";
2558 return nullptr;
2559 }
2560 AIE::DeviceOp referencedDevice =
2561 llvm::dyn_cast<AIE::DeviceOp>(maybeReferencedDevice);
2562 if (!referencedDevice) {
2563 emitError("Not a device: '") << getSymbolAttr() << "'";
2564 return nullptr;
2565 }
2566 return referencedDevice;
2567}
2568
2569//===----------------------------------------------------------------------===//
2570// ReadScratchpadParameterOp
2571//===----------------------------------------------------------------------===//
2572
2573LogicalResult AIEX::ReadScratchpadParameterOp::verify() {
2574 auto device = (*this)->getParentOfType<AIE::DeviceOp>();
2575 if (!device) {
2576 return emitOpError("must be inside an aie.device");
2577 }
2578 if (!(*this)->getParentOfType<AIE::CoreOp>()) {
2579 return emitOpError("must be inside an aie.core");
2580 }
2581 auto moduleOp = (*this)->getParentOfType<ModuleOp>();
2582 if (!moduleOp ||
2583 !moduleOp.lookupSymbol<AIEX::ScratchpadParameterOp>(getParameter())) {
2584 return emitOpError("references unknown parameter '")
2585 << getParameter()
2586 << "' (aiex.scratchpad_parameter ops are declared at module scope)";
2587 }
2588 if (getResult().getType().isF32()) {
2589 return emitOpError(
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.");
2593 }
2594 return success();
2595}
2596
2597LogicalResult AIEX::WaitScratchpadParametersOp::verify() {
2598 if (!(*this)->getParentOfType<AIE::CoreOp>()) {
2599 return emitOpError("must be inside an aie.core");
2600 }
2601 return success();
2602}
2603
2604LogicalResult AIEX::ConfigureOp::verify() {
2605 AIE::DeviceOp parentDev = getOperation()->getParentOfType<AIE::DeviceOp>();
2606 AIE::DeviceOp referencedDev = getReferencedDeviceOp();
2607 if (!referencedDev) {
2608 return failure();
2609 }
2610 if (parentDev.getDevice() != referencedDev.getDevice()) {
2611 emitError("Device types do not match: '")
2612 << AIE::stringifyAIEDevice(parentDev.getDevice()) << "' vs. '"
2613 << AIE::stringifyAIEDevice(referencedDev.getDevice()) << "'";
2614 return failure();
2615 }
2616 return success();
2617}
2618
2619//===----------------------------------------------------------------------===//
2620// RunOp
2621//===----------------------------------------------------------------------===//
2622
2623AIE::DeviceOp AIEX::RunOp::getCalleeDeviceOp() {
2624 AIEX::ConfigureOp configureOp =
2625 getOperation()->getParentOfType<AIEX::ConfigureOp>();
2626 if (!configureOp) {
2627 return nullptr;
2628 }
2629 AIE::DeviceOp referencedDevice = configureOp.getReferencedDeviceOp();
2630 return referencedDevice;
2631}
2632
2633AIE::RuntimeSequenceOp
2634AIEX::RunOp::getCalleeRuntimeSequenceOp(AIE::NamedOpTableCollection *tables) {
2635 AIEX::ConfigureOp configureOp =
2636 getOperation()->getParentOfType<AIEX::ConfigureOp>();
2637 if (!configureOp) {
2638 return nullptr;
2639 }
2640 AIE::DeviceOp referencedDevice = configureOp.getReferencedDeviceOp();
2641 if (!referencedDevice) {
2642 return nullptr;
2643 }
2644
2645 StringAttr name = getRuntimeSequenceSymbolAttr().getAttr();
2646 if (!tables) {
2647 return AIE::lookupNamedOpIn<AIE::RuntimeSequenceOp>(referencedDevice, name);
2648 }
2649 return tables->lookupIn<AIE::RuntimeSequenceOp>(referencedDevice, name);
2650}
2651
2652//===----------------------------------------------------------------------===//
2653// NpuLoadPdiOp
2654//===----------------------------------------------------------------------===//
2655
2656LogicalResult AIEX::NpuLoadPdiOp::canonicalize(AIEX::NpuLoadPdiOp op,
2657 PatternRewriter &rewriter) {
2658 // Check for back-to-back identical load_pdi ops and remove duplicates
2659 Operation *nextOp = op->getNextNode();
2660 if (!nextOp)
2661 return failure();
2662
2663 // Check if next op is also a NpuLoadPdiOp
2664 auto nextLoadPdi = dyn_cast<AIEX::NpuLoadPdiOp>(nextOp);
2665 if (!nextLoadPdi)
2666 return failure();
2667
2668 // Check if they are identical (all attributes match)
2669 if (op.getDeviceRefAttr() == nextLoadPdi.getDeviceRefAttr() &&
2670 op.getId() == nextLoadPdi.getId() &&
2671 op.getSize() == nextLoadPdi.getSize() &&
2672 op.getAddress() == nextLoadPdi.getAddress()) {
2673 // Erase the first one, keeping the second
2674 rewriter.eraseOp(op);
2675 return success();
2676 }
2677
2678 return failure();
2679}
2680
2681//===----------------------------------------------------------------------===//
2682// NpuWriteConfigOp
2683//===----------------------------------------------------------------------===//
2684
2685static bool writesConfig(Operation *op) {
2686 return isa<AIEX::NpuLoadPdiOp, AIEX::NpuWriteConfigOp,
2687 AIEX::NpuWriteTeardownOp>(op);
2688}
2689
2690// Visits the load_pdi, write_config and write_teardown ops before `op` in its
2691// block, nearest first, then those after it from the block's end, as the host
2692// runs the sequence again on each dispatch, then `op` itself. Returns the first
2693// for which `visit` returns true.
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))
2698 return prev;
2699 for (Operation &next : llvm::reverse(*op->getBlock())) {
2700 if (&next == op)
2701 break;
2702 if (writesConfig(&next) && visit(&next))
2703 return &next;
2704 }
2705 return visit(op) ? op : nullptr;
2706}
2707
2708// The load_pdi that resets the array for `op`, or the write_teardown that
2709// leaves it so, or null.
2710static Operation *precedingReset(Operation *op) {
2711 return findConfigOpBefore(op, [&](Operation *prev) {
2712 return prev != op &&
2713 isa<AIEX::NpuLoadPdiOp, AIEX::NpuWriteTeardownOp>(prev);
2714 });
2715}
2716
2717bool AIEX::NpuLoadPdiOp::loadsSamePdi(NpuLoadPdiOp other) {
2718 return getDeviceRefAttr() == other.getDeviceRefAttr() &&
2719 getId() == other.getId() && getSize() == other.getSize() &&
2720 getAddress() == other.getAddress();
2721}
2722
2723LogicalResult AIEX::NpuWriteConfigOp::verify() {
2724 Operation *found = precedingReset(*this);
2725 if (!found)
2726 return emitOpError("must follow the load_pdi that resets the array");
2727 auto reset = dyn_cast<AIEX::NpuLoadPdiOp>(found);
2728 if (!reset)
2729 return success();
2730 // The firmware skips the load if it loaded the same PDI last. That leaves
2731 // the array as a reset does only if every configuration since is torn down.
2732 bool tornDown = true;
2733 Operation *later = reset;
2734 auto before =
2735 cast<AIEX::NpuLoadPdiOp>(findConfigOpBefore(reset, [&](Operation *op) {
2736 if (isa<AIEX::NpuWriteConfigOp>(op) &&
2737 !isa<AIEX::NpuWriteTeardownOp>(later))
2738 tornDown = false;
2739 later = op;
2740 return isa<AIEX::NpuLoadPdiOp>(op);
2741 }));
2742 if (!before.loadsSamePdi(reset) || tornDown)
2743 return success();
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";
2748 return diag;
2749}
2750
2751LogicalResult
2752AIEX::NpuLoadPdiOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2753 FlatSymbolRefAttr ref = getDeviceRefAttr();
2754 if (!ref)
2755 return success();
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";
2761 return success();
2762}
2763
2764LogicalResult
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))
2774 : nullptr;
2775 // The transaction conversion gives every device a `@configure` sequence; an
2776 // empty one still configures nothing.
2777 if (reset &&
2778 (!empty ||
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(); });
2783 })))
2784 return emitOpError("must follow a load_pdi of an empty device, which "
2785 "resets the array");
2786 return success();
2787}
2788
2789//===----------------------------------------------------------------------===//
2790// NpuWriteTeardownOp
2791//===----------------------------------------------------------------------===//
2792
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";
2801 return success();
2802}
2803
2804LogicalResult
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()));
2809 if (!device)
2810 return emitOpError() << getDeviceRefAttr() << " is not a device";
2811 Operation *shimStart = AIEX::findShimDmaStart(device);
2812 if (!shimStart)
2813 return success();
2814 InFlightDiagnostic diag =
2815 emitOpError() << getDeviceRefAttr()
2816 << " starts a shim DMA channel, which teardown cannot stop";
2817 diag.attachNote(shimStart->getLoc()) << "started here";
2818 return diag;
2819}
2820
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");
2825 return success();
2826}
2827
2828LogicalResult
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";
2834 return success();
2835}
2836
2837llvm::DenseMap<AIE::TileID, AIE::PacketInfoAttr>
2838AIEX::controllerIdsOf(AIE::DeviceOp device) {
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;
2844 return ids;
2845}
2846
2847// Append the BD ids `program` takes, each with the channel that submits it.
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) {
2853 reached.insert(bd);
2854 if (std::optional<uint32_t> id = bd.getBdId())
2855 bds.push_back({channel, *id});
2856 };
2857 Region &body = program.getDmaBody();
2858 // A block-form program's channel submits every BD its chain reaches.
2859 for (Block &block : body)
2860 for (AIE::DMAStartOp start : block.getOps<AIE::DMAStartOp>()) {
2861 Channel channel;
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>())
2871 add(bd, channel);
2872 for (Block *successor : bdBlock->getSuccessors())
2873 if (visited.insert(successor).second)
2874 worklist.push_back(successor);
2875 }
2876 }
2877 // A region-form program names its channel on the aie.dma.
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()));
2883 });
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});
2887 });
2888}
2889
2890SmallVector<AIEX::StaticBd> AIEX::staticBdIds(ArrayRef<AIE::DeviceOp> devices,
2891 AIE::TileID tile) {
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);
2897 return bds;
2898}
2899
2900FailureOr<SmallVector<AIEX::ControlPacketMulticast>>
2901AIEX::controlPacketMulticasts(ModuleOp module, FlatSymbolRefAttr reference) {
2902 SmallVector<ControlPacketMulticast> routes;
2903 auto device = reference ? module.lookupSymbol<AIE::DeviceOp>(reference)
2904 : AIE::DeviceOp{};
2905 auto overlay =
2906 device && device.getOverlayAttr()
2907 ? module.lookupSymbol<AIE::DeviceOp>(device.getOverlayAttr())
2908 : AIE::DeviceOp{};
2909 auto groups =
2910 overlay ? AIE::AIEDialect::CtrlPktMulticastAttrHelper(module.getContext())
2911 .getAttr(overlay)
2912 : ArrayAttr{};
2913 if (!groups)
2914 return routes;
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{};
2920 auto packetId =
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() ||
2926 !llvm::all_of(
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";
2930 return failure();
2931 }
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;
2937 return failure();
2938 }
2939 auto alloc =
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";
2945 return failure();
2946 }
2947 routes.push_back({alloc, static_cast<uint32_t>(packetId.getInt()), tiles});
2948 }
2949 return routes;
2950}
2951
2952Operation *AIEX::findShimDmaStart(AIE::DeviceOp device) {
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();
2958 found = op;
2959 return WalkResult::interrupt();
2960 });
2961 return found;
2962}
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)
Definition AIEDialect.h:179
mlir::Operation * lookup(mlir::StringAttr name) const
Definition AIEDialect.h:153
const V & get(const std::map< K, V > &pa, K k)
Definition d_ary_heap.h:70
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])
Definition BdLowering.h:147
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)
Definition BdLowering.h:67
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)
Definition BdLowering.h:79
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).
Definition AIEEnums.h:19
mlir::LogicalResult verifyDMABDIteration(DMABDOp bd, AIETileType tileType)
WireBundle getDMAChannelBundle(DMAChannelDir dir)
The stream-switch bundle the channels of dir use.
Definition AIEEnums.h:29
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.