MLIR-AIE 1.4.6.dev
AIEDmaToNpu.cpp
Go to the documentation of this file.
1//===- AIEDmaToNpu.cpp ------------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2023 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
15
16#include "mlir/Dialect/Arith/IR/Arith.h"
17#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
18#include "mlir/Dialect/MemRef/IR/MemRef.h"
19#include "mlir/Dialect/SCF/IR/SCF.h"
20#include "mlir/Pass/Pass.h"
21#include "mlir/Transforms/DialectConversion.h"
22#include "llvm/Support/MathExtras.h"
23#include <algorithm>
24#include <cstdint>
25
26namespace xilinx::AIEX {
27#define GEN_PASS_DEF_AIEDMATONPU
28#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
29} // namespace xilinx::AIEX
30
31using namespace mlir;
32using namespace xilinx;
33using namespace xilinx::AIEX;
34
35namespace {
36
37struct Write32SymToAddr : OpConversionPattern<NpuWrite32Op> {
38 using OpConversionPattern::OpConversionPattern;
39
40 Write32SymToAddr(MLIRContext *context, const AIE::NamedOpTable &names)
41 : OpConversionPattern(context), names(names) {}
42
43 const AIE::NamedOpTable &names;
44
45 LogicalResult
46 matchAndRewrite(NpuWrite32Op op, OpAdaptor adaptor,
47 ConversionPatternRewriter &rewriter) const override {
48
49 if (!op.getBuffer())
50 return failure();
51
52 std::optional<uint32_t> address = op.getAbsoluteAddress(&names);
53 if (!address.has_value()) {
54 return failure();
55 }
56
57 Value addressVal = createConstantI32(rewriter, op->getLoc(), *address);
58 rewriter.replaceOpWithNewOp<NpuWrite32Op>(
59 op, addressVal, adaptor.getValue(), nullptr, nullptr, nullptr);
60 return success();
61 }
62};
63
64struct BlockWriteSymToAddr : OpConversionPattern<NpuBlockWriteOp> {
65 using OpConversionPattern::OpConversionPattern;
66
67 BlockWriteSymToAddr(MLIRContext *context, const AIE::NamedOpTable &names)
68 : OpConversionPattern(context), names(names) {}
69
70 const AIE::NamedOpTable &names;
71
72 LogicalResult
73 matchAndRewrite(NpuBlockWriteOp op, OpAdaptor adaptor,
74 ConversionPatternRewriter &rewriter) const override {
75
76 if (!op.getBuffer())
77 return failure();
78
79 std::optional<uint32_t> address = op.getAbsoluteAddress(&names);
80 if (!address.has_value()) {
81 return failure();
82 }
83 rewriter.replaceOpWithNewOp<NpuBlockWriteOp>(op, *address, op.getData(),
84 nullptr, nullptr, nullptr);
85 return success();
86 }
87};
88
89struct MaskWrite32SymToAddr : OpConversionPattern<NpuMaskWrite32Op> {
90 using OpConversionPattern::OpConversionPattern;
91
92 MaskWrite32SymToAddr(MLIRContext *context, const AIE::NamedOpTable &names)
93 : OpConversionPattern(context), names(names) {}
94
95 const AIE::NamedOpTable &names;
96
97 LogicalResult
98 matchAndRewrite(NpuMaskWrite32Op op, OpAdaptor adaptor,
99 ConversionPatternRewriter &rewriter) const override {
100
101 if (!op.getBuffer())
102 return failure();
103
104 std::optional<uint32_t> absoluteAddress = op.getAbsoluteAddress(&names);
105 if (!absoluteAddress.has_value()) {
106 return failure();
107 }
108
109 Value addressVal =
110 createConstantI32(rewriter, op->getLoc(), *absoluteAddress);
111 rewriter.replaceOpWithNewOp<NpuMaskWrite32Op>(
112 op, addressVal, adaptor.getValue(), adaptor.getMask(), nullptr, nullptr,
113 nullptr);
114 return success();
115 }
116};
117
118struct MaskPollSymToAddr : OpConversionPattern<NpuMaskPollOp> {
119 using OpConversionPattern::OpConversionPattern;
120
121 MaskPollSymToAddr(MLIRContext *context, const AIE::NamedOpTable &names)
122 : OpConversionPattern(context), names(names) {}
123
124 const AIE::NamedOpTable &names;
125
126 LogicalResult
127 matchAndRewrite(NpuMaskPollOp op, OpAdaptor adaptor,
128 ConversionPatternRewriter &rewriter) const override {
129 if (!op.getBuffer())
130 return failure();
131
132 std::optional<uint32_t> absoluteAddress = op.getAbsoluteAddress(&names);
133 if (!absoluteAddress)
134 return failure();
135
136 Value addressVal =
137 createConstantI32(rewriter, op->getLoc(), *absoluteAddress);
138 rewriter.replaceOpWithNewOp<NpuMaskPollOp>(
139 op, addressVal, adaptor.getValue(), adaptor.getMask(), nullptr, nullptr,
140 nullptr);
141 return success();
142 }
143};
144
145struct RtpToWrite32Pattern : OpConversionPattern<NpuWriteRTPOp> {
146 using OpConversionPattern::OpConversionPattern;
147
148 RtpToWrite32Pattern(MLIRContext *context, const AIE::NamedOpTable &names)
149 : OpConversionPattern(context), names(names) {}
150
151 const AIE::NamedOpTable &names;
152
153 LogicalResult
154 matchAndRewrite(NpuWriteRTPOp op, OpAdaptor adaptor,
155 ConversionPatternRewriter &rewriter) const override {
156
157 auto buffer = names.lookup<AIE::BufferOp>(op.getBufferAttr().getAttr());
158 if (!buffer) {
159 op->emitError("buffer '" + op.getBuffer() + "' not found in device");
160 return failure();
161 }
162
163 auto bufferAddress = buffer.getAddress();
164 if (!bufferAddress) {
165 op->emitError("buffer must have address assigned");
166 return failure();
167 }
168 AIE::TileOp tile = buffer.getTileOp();
169
170 // On AIE4 a tile-relative offset reaches only the first 1 MiB of the
171 // tile, below memtile data memory, so keep the buffer reference.
172 if (isa<AIE::AIE4TargetModel>(AIE::getTargetModel(op))) {
173 rewriter.replaceOpWithNewOp<NpuWrite32Op>(
174 op, createConstantI32(rewriter, op->getLoc(), op.getIndex()),
175 adaptor.getValue(), op.getBufferAttr(), nullptr, nullptr);
176 return success();
177 }
178
179 uint32_t idx = op.getIndex() * sizeof(uint32_t);
180 uint32_t address = *bufferAddress + idx;
181
182 NpuWrite32Op::create(rewriter, op->getLoc(),
183 createConstantI32(rewriter, op->getLoc(), address),
184 adaptor.getValue(), nullptr,
185 rewriter.getI32IntegerAttr(tile.getCol()),
186 rewriter.getI32IntegerAttr(tile.getRow()));
187
188 rewriter.eraseOp(op);
189 return success();
190 }
191};
192
193struct PushQueuetoWrite32Pattern : OpConversionPattern<NpuPushQueueOp> {
194
195public:
196 using OpConversionPattern::OpConversionPattern;
197
198 PushQueuetoWrite32Pattern(MLIRContext *context, PatternBenefit benefit = 1)
199 : OpConversionPattern(context, benefit) {}
200
201 LogicalResult
202 matchAndRewrite(NpuPushQueueOp op, OpAdaptor adaptor,
203 ConversionPatternRewriter &rewriter) const override {
204
205 const auto &tm = AIE::getTargetModel(op);
206 uint32_t ctrl_offset = tm.getDmaControlAddress(
207 op.getColumn(), op.getRow(), op.getChannel(), op.getDirection());
208
209 // control packet for issuing token
210 if (op.getIssueToken()) {
211 // set the task-complete-token controller ID field in the dma control
212 // register
213 AIE::TileOp shimTile = AIE::TileOp::getOrCreate(
214 rewriter, op->getParentOfType<AIE::DeviceOp>(), op.getColumn(),
215 op.getRow());
216 if (shimTile->hasAttr("controller_id")) {
217 AIE::PacketInfoAttr controller_id_attr =
218 shimTile->getAttrOfType<AIE::PacketInfoAttr>("controller_id");
219 uint32_t data = controller_id_attr.assignedId() << 8;
220 uint32_t mask = 0x00001F00;
221 NpuMaskWrite32Op::create(
222 rewriter, op->getLoc(),
223 createConstantI32(rewriter, op->getLoc(), ctrl_offset),
224 createConstantI32(rewriter, op->getLoc(), data),
225 createConstantI32(rewriter, op->getLoc(), mask), nullptr, nullptr,
226 nullptr);
227 }
228 }
229
230 uint32_t queue_offset = tm.getDmaQueueAddress(
231 op.getColumn(), op.getRow(), op.getChannel(), op.getDirection());
232
233 // Command word: bd_id in the START_BD_ID field, repeat_count based at bit
234 // 16, issue-token bit [31]. START_BD_ID is as wide as the tile's BD ids.
235 // bd_id and repeat_count may be runtime SSA; all-constant folds to one
236 // constant (byte-identical to the static path), else built with arith.
237 Location loc = op->getLoc();
238 auto i32ty = rewriter.getIntegerType(32);
239 uint32_t bdIdMask =
240 (1u << llvm::Log2_32_Ceil(tm.getNumBDs(op.getColumn(), op.getRow()))) -
241 1;
242 // AIE4 shim BD banks number from 0: bank-1 ids 16-31 are written as id-16.
243 if (isa<AIE::AIE4TargetModel>(tm) &&
244 tm.isShimNOCTile(op.getColumn(), op.getRow()))
245 bdIdMask = 0xFu;
246 // getMaxRepeatCount() is the repeat field's all-ones value.
247 uint32_t repeatMask =
248 tm.getMaxRepeatCount() ? tm.getMaxRepeatCount() : 0xFFu;
249 std::optional<uint32_t> bd_id = getConstantIntOperand(op.getBdId());
250 std::optional<uint64_t> repeat_cnt =
251 getConstantInt64Operand(op.getRepeatCount());
252 uint32_t issueBit = op.getIssueToken() ? 0x80000000 : 0;
253
254 // A scratchpad repeat count: the host writes it already shifted into the
255 // repeat field, and the update adds it to the rest of the command word.
256 // The verifier holds bd_id to a constant multiple of 4, which the
257 // update's clearing of bits [1:0] keeps.
258 if (IntegerAttr idx = op.getRepeatStateTableIdxAttr()) {
259 NpuUpdateFromScratchpadOp::create(
260 rewriter, loc, static_cast<uint8_t>(idx.getUInt()),
261 StateTableFunc::Incr,
262 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
263 /*func_arg=*/(*bd_id & bdIdMask) | issueBit,
264 /*address=*/queue_offset, /*buffer=*/nullptr, /*column=*/nullptr,
265 /*row=*/nullptr);
266 rewriter.eraseOp(op);
267 return success();
268 }
269
270 Value cmdVal;
271 if (bd_id && repeat_cnt) {
272 cmdVal = createConstantI32(
273 rewriter, loc,
274 (*bd_id & bdIdMask) | ((*repeat_cnt & repeatMask) << 16) | issueBit);
275 } else {
276 // Built with arith (constant fields fold). A runtime repeat_count is
277 // masked to its field below, so an out-of-range value would silently wrap
278 // to a different number of
279 // executions. Refuse the dispatch instead (host-side guard); the
280 // unsigned compare also rejects a negative count (zero executions).
281 Value repeat;
282 if (repeat_cnt) {
283 repeat = createConstantI32(rewriter, loc, *repeat_cnt);
284 } else {
285 Value repeat64 =
286 getAsI64(rewriter, loc, OpFoldResult(op.getRepeatCount()));
287 if (!repeat64)
288 return failure();
289 uint32_t maxRepeat = tm.getMaxRepeatCount();
290 Value inRange = arith::CmpIOp::create(
291 rewriter, loc, arith::CmpIPredicate::ule, repeat64,
292 arith::ConstantOp::create(rewriter, loc,
293 rewriter.getI64IntegerAttr(maxRepeat)));
294 if (failed(emitRuntimeCheck(
295 rewriter, loc, inRange,
296 "a runtime DMA repeat count exceeds the task queue's [0:" +
297 Twine(maxRepeat) + "] range (at most " +
298 Twine(maxRepeat + 1) + " executions)")))
299 return failure();
300 repeat = rewriter.createOrFold<arith::TruncIOp>(loc, i32ty, repeat64);
301 }
302 Value cmd = createConstantI32(rewriter, loc, issueBit);
303 Value bdField = rewriter.createOrFold<arith::AndIOp>(
304 loc, getAsValue(rewriter, loc, op.getBdId(), i32ty),
305 createConstantI32(rewriter, loc, bdIdMask));
306 cmd = rewriter.createOrFold<arith::OrIOp>(loc, cmd, bdField);
307 Value masked = rewriter.createOrFold<arith::AndIOp>(
308 loc, repeat, createConstantI32(rewriter, loc, repeatMask));
309 Value shifted = rewriter.createOrFold<arith::ShLIOp>(
310 loc, masked, createConstantI32(rewriter, loc, 16));
311 cmdVal = rewriter.createOrFold<arith::OrIOp>(loc, cmd, shifted);
312 }
313
314 NpuWrite32Op::create(
315 rewriter, op->getLoc(),
316 createConstantI32(rewriter, op->getLoc(), queue_offset), cmdVal,
317 nullptr, nullptr, nullptr);
318 rewriter.eraseOp(op);
319 return success();
320 }
321};
322
323struct DmaToNpuPattern : OpConversionPattern<NpuDmaMemcpyNdOp> {
324 using OpConversionPattern::OpConversionPattern;
325
326public:
327 DmaToNpuPattern(MLIRContext *context, PatternBenefit benefit = 1)
328 : OpConversionPattern(context, benefit) {}
329
330 LogicalResult
331 matchAndRewrite(NpuDmaMemcpyNdOp op, OpAdaptor adaptor,
332 ConversionPatternRewriter &rewriter) const override {
333 // Any runtime (SSA) offset/size/stride takes the dynamic path; a
334 // fully-constant descriptor takes the static path below. The op verifier
335 // has already enforced the supported scope for the dynamic case (shim NOC,
336 // no padding, realizable/in-range constants).
337 bool allOffsetsConstant =
338 llvm::all_of(op.getMixedOffsets(),
339 [](OpFoldResult s) { return getConstantIntValue(s); });
340 bool allSizesConstant =
341 llvm::all_of(op.getMixedSizes(),
342 [](OpFoldResult s) { return getConstantIntValue(s); });
343 bool allStridesConstant =
344 llvm::all_of(op.getMixedStrides(),
345 [](OpFoldResult s) { return getConstantIntValue(s); });
346 if (!allOffsetsConstant || !allSizesConstant || !allStridesConstant)
347 return lowerDynamic(op, adaptor, rewriter);
348
349 const auto &targetModel = AIE::getTargetModel(op);
350 BaseMemRefType bufferType = op.getMemref().getType();
351 auto *ctx = op->getContext();
352 auto i32ty = IntegerType::get(ctx, 32);
353 auto zero = IntegerAttr::get(i32ty, 0);
354
355 auto dev = op->getParentOfType<AIE::DeviceOp>();
356 if (!dev)
357 return failure();
358
359 auto infoOp = AIE::ShimDMAAllocationOp::getForSymbol(
360 dev, op.getMetadata().getRootReference());
361 if (!infoOp) {
362 return op->emitOpError("couldn't find shim_dma_allocation op.");
363 }
364
365 AIE::TileOp shimTile = infoOp.getTileOp();
366 if (!shimTile) {
367 return op->emitOpError(
368 "shim_dma_allocation op must reference a valid TileOp.");
369 }
370
371 auto channelDir = infoOp.getChannelDir();
372 bool isMM2S = AIE::isMM2S(channelDir);
373 int tileCol = shimTile.getCol();
374 int tileRow = shimTile.getRow();
375 if (failed(verifyRuntimeBdTarget(op, targetModel, tileCol, tileRow,
376 channelDir)))
377 return failure();
378
379 // initialize fields to zero
380 auto column = zero;
381 auto bd_id = zero;
382 auto buffer_length = zero;
383 auto buffer_offset = zero;
384 auto enable_packet = zero;
385 auto out_of_order_id = zero;
386 auto packet_id = zero;
387 auto packet_type = zero;
388 auto d0_size = zero;
389 auto d0_stride = zero;
390 auto d1_size = zero;
391 auto d1_stride = zero;
392 auto d2_size = zero;
393 auto d2_stride = zero;
394 auto iteration_current = zero;
395 auto iteration_size = zero;
396 auto iteration_stride = zero;
397 auto next_bd = zero;
398 auto row = zero;
399 auto use_next_bd = zero;
400 auto valid_bd = zero;
401 auto lock_rel_val = zero;
402 auto lock_rel_id = zero;
403 auto lock_acq_enable = zero;
404 auto lock_acq_val = zero;
405 auto lock_acq_id = zero;
406 auto d0_zero_before = zero;
407 auto d1_zero_before = zero;
408 auto d2_zero_before = zero;
409 auto d0_zero_after = zero;
410 auto d1_zero_after = zero;
411 auto d2_zero_after = zero;
412 auto burst_length = zero;
413 auto axcache = zero;
414
415 auto issue_token = BoolAttr::get(ctx, false);
416 auto repeat_count = zero;
417 llvm::SmallVector<int64_t, 4> inputSizes = llvm::map_to_vector(
418 llvm::reverse(op.getMixedSizes()),
419 [](OpFoldResult s) { return getConstantIntValue(s).value(); });
420 llvm::SmallVector<int64_t, 4> inputStrides = llvm::map_to_vector(
421 llvm::reverse(op.getMixedStrides()),
422 [](OpFoldResult s) { return getConstantIntValue(s).value(); });
423 // A contiguous row-major ND access on a shim NOC tile is lowered to linear
424 // mode (d0_size=d1_size=0) just like an already-canonical linear transfer.
425 // This allows naturally-expressed multidimensional transfers (e.g., a 2D
426 // image as [height, width]) without hitting the 10-bit ND wrap-size limit.
427 bool isLinear = isLinearModeTransfer(targetModel, tileCol, tileRow,
428 inputSizes, inputStrides);
429 if (!isLinear && op.getLengthStateTableIdxAttr())
430 AIE::placeRuntimeLengthDimension(inputSizes, inputStrides);
431 llvm::SmallVector<int64_t, 4> sizes(4);
432 llvm::SmallVector<int64_t, 4> strides(4);
433 getHardwareStridesWraps(targetModel, op, tileCol, tileRow, bufferType,
434 inputSizes, inputStrides, sizes, strides);
435
436 // column
437 column = IntegerAttr::get(i32ty, tileCol);
438
439 // row
440 row = IntegerAttr::get(i32ty, tileRow);
441
442 if (failed(verifyStridesWraps(
443 op, [&] { return op->emitOpError(); }, bufferType, tileCol, tileRow,
444 inputSizes, inputStrides, sizes, strides, isLinear))) {
445 return failure();
446 }
447
448 // bd_id
449 bd_id = IntegerAttr::get(i32ty, op.getId());
450
451 // buffer_length
452 uint64_t buffer_length_val = inputSizes[0] * op.getElementTypeBitwidth() /
453 targetModel.getAddressGenGranularity();
454 if (inputSizes.size() > 1) {
455 for (size_t i = 1; i < std::min(inputSizes.size(), (size_t)3); i++) {
456 buffer_length_val *= inputSizes[i];
457 }
458 }
459 buffer_length = IntegerAttr::get(i32ty, buffer_length_val);
460
461 // buffer_offset - zero because the complete address is set by the patch op
462 buffer_offset = IntegerAttr::get(i32ty, 0);
463
464 // enable_packet
465 if (auto packetInfo =
466 op.getPacket() ? op.getPacket() : infoOp.getPacket()) {
467 if (failed(verifyBdPacketType(op, targetModel, tileCol, tileRow,
468 packetInfo->getPktType())))
469 return failure();
470 enable_packet = IntegerAttr::get(i32ty, 1);
471 packet_type = IntegerAttr::get(i32ty, packetInfo->getPktType());
472 packet_id = IntegerAttr::get(i32ty, packetInfo->assignedId());
473 }
474
475 // out_of_order_id - stays 0; senders stamp it via aie.dma_bd,
476 // dma_configure_task, or npu.writebd
477
478 if (!isLinear) {
479 // d0_size, d0_stride
480 d0_size = IntegerAttr::get(i32ty, sizes[0]);
481 d0_stride = IntegerAttr::get(i32ty, strides[0]);
482
483 // d1_size, d1_stride
484 d1_size = IntegerAttr::get(i32ty, sizes[1]);
485 d1_stride = IntegerAttr::get(i32ty, strides[1]);
486
487 // d2_stride
488 d2_stride = IntegerAttr::get(i32ty, strides[2]);
489
490 // d2_size
491 if (targetModel.isMemTile(tileCol, 0)) // Need to be any row
492 d2_size = IntegerAttr::get(i32ty, sizes[2]);
493 else
494 d2_size = IntegerAttr::get(i32ty, 0);
495 }
496 // iteration_current, iteration_size, iteration_stride, repeat_count
497 if (inputSizes[3] > 1) {
498 if (inputStrides[3] > 0) {
499 iteration_size = IntegerAttr::get(i32ty, sizes[3]);
500 iteration_stride = IntegerAttr::get(i32ty, strides[3]);
501 } else {
502 // We allow users to encode the repeat_count as a dimension 3 stride
503 // of 0. This must lower to a iteration wrap of 0, so no stride is
504 // ever added. We then repeat the BD using the repeat_count in
505 // NpuPushQueueOp.
506 iteration_size = zero;
507 iteration_stride = zero;
508 }
509 }
510 repeat_count = IntegerAttr::get(i32ty, sizes[3]);
511
512 // next_bd
513
514 // use_next_bd
515
516 // valid_bd
517 valid_bd = IntegerAttr::get(i32ty, 1);
518
519 // lock_rel_val
520
521 // lock_rel_id
522
523 // lock_acq_enable
524
525 // lock_acq_val
526
527 // lock_acq_id
528
529 // d0_zero_before
530 d0_zero_before = IntegerAttr::get(i32ty, op.getD0ZeroBefore());
531
532 // d1_zero_before
533 d1_zero_before = IntegerAttr::get(i32ty, op.getD1ZeroBefore());
534
535 // d2_zero_before
536 d2_zero_before = IntegerAttr::get(i32ty, op.getD2ZeroBefore());
537
538 // d0_zero_after
539 d0_zero_after = IntegerAttr::get(i32ty, op.getD0ZeroAfter());
540
541 // d1_zero_after
542 d1_zero_after = IntegerAttr::get(i32ty, op.getD1ZeroAfter());
543
544 // d2_zero_after
545 d2_zero_after = IntegerAttr::get(i32ty, op.getD2ZeroAfter());
546
547 // burst_size
548 burst_length = IntegerAttr::get(i32ty, op.getBurstLength());
549
550 // axcache; only meaningful on the AXI-MM side, so left unset elsewhere to
551 // match the dma_task path (and NpuWriteBdOp's verifier).
552 if (targetModel.isShimNOCTile(tileCol, tileRow))
553 axcache = IntegerAttr::get(i32ty, op.getAxcacheOrDefault());
554 else
555 axcache = IntegerAttr();
556
557 // Set the issue_token
558 issue_token = BoolAttr::get(ctx, op.getIssueToken());
559 // Earlier, all S2MM channels were implicitly assumed to issue a token.
560 // This logic is kept for now for backward compatibility.
561 if (!isMM2S)
562 issue_token = BoolAttr::get(ctx, true);
563
564 if (targetModel.isMemTile(tileCol, tileRow) && (!isMM2S) &&
565 (op.getD0ZeroBefore() != 0 || op.getD0ZeroAfter() != 0 ||
566 op.getD1ZeroBefore() != 0 || op.getD1ZeroAfter() != 0 ||
567 op.getD2ZeroBefore() != 0 || op.getD2ZeroAfter() != 0)) {
568 op->emitOpError("MemTile supports zero padding only on MM2S direction");
569 return failure();
570 }
571
572 // write the buffer descriptor to the array
573 bool channelLocalIds =
574 targetModel.usesChannelLocalBdIds(tileCol, tileRow, channelDir);
575 NpuWriteBdOp::create(
576 rewriter, op->getLoc(), column, bd_id, buffer_length, buffer_offset,
577 enable_packet, out_of_order_id, packet_id, packet_type, d0_size,
578 d0_stride, d1_size, d1_stride, d2_size, d2_stride, iteration_current,
579 iteration_size, iteration_stride, next_bd, row, use_next_bd, valid_bd,
580 lock_rel_val, lock_rel_id, lock_acq_enable, lock_acq_val, lock_acq_id,
581 d0_zero_before, d1_zero_before, d2_zero_before, d0_zero_after,
582 d1_zero_after, d2_zero_after, burst_length, axcache,
583 // Channel-local BD ids need the channel to name a register.
584 channelLocalIds ? IntegerAttr::get(i32ty, infoOp.getChannelIndex())
585 : IntegerAttr(),
586 channelLocalIds ? infoOp.getChannelDirAttr()
587 : AIE::DMAChannelDirAttr());
588
589 // Resolve the buffer's runtime-sequence arg and emit the address patch
590 // (plus any offset-state update).
591 int arg_idx = -1;
592 if (failed(emitBufferAddressPatch(op, adaptor, rewriter, infoOp, tileCol,
593 tileRow, arg_idx)))
594 return failure();
595
596 // A length_state_table_idx adds the runtime length to the BD's
597 // Buffer_Length, after the BD write above has set the static length. The
598 // verifier requires a length_unit with it.
599 auto lengthUnit = op.getLengthUnit();
600 if (op.getLengthStateTableIdxAttr() && lengthUnit) {
601 if (failed(emitUpdateBdLengthFromParameter(rewriter, op, bufferType,
602 *lengthUnit, targetModel,
603 tileCol, tileRow, op.getId())))
604 return failure();
605 }
606
607 // push the patched bd onto the dma task queue. bd_id and repeat_count are
608 // SSA operands; materialize them as constants here (the static path).
609 NpuPushQueueOp::create(
610 rewriter, op->getLoc(), column, row, infoOp.getChannelDirAttr(),
611 infoOp.getChannelIndexAttr(), issue_token,
612 createConstantI32(rewriter, op->getLoc(),
613 static_cast<uint32_t>(repeat_count.getInt())),
614 createConstantI32(rewriter, op->getLoc(),
615 static_cast<uint32_t>(bd_id.getInt())),
616 /*repeat_state_table_idx=*/nullptr);
617
618 rewriter.eraseOp(op);
619 return success();
620 }
621
622 // Resolve the runtime-sequence argument index the descriptor's buffer traces
623 // back to, and emit the address-patch (plus an offset-state update, if the op
624 // carries one) that binds the runtime buffer pointer into the BD. Shared by
625 // the static and dynamic lowering paths, which are otherwise identical here.
626 // A walk with any runtime offset, size or stride also gets a host-side check
627 // that it stays inside the host buffer. On success `argIdx` receives the
628 // resolved index.
629 LogicalResult emitBufferAddressPatch(NpuDmaMemcpyNdOp op, OpAdaptor adaptor,
630 ConversionPatternRewriter &rewriter,
631 AIE::ShimDMAAllocationOp infoOp,
632 int tileCol, int tileRow,
633 int &argIdx) const {
634 AIE::RuntimeSequenceOp seqOp =
635 op->getParentOfType<AIE::RuntimeSequenceOp>();
636 if (!seqOp)
637 return op->emitOpError("NpuDmaMemcpyNdOps must have RuntimeSequenceOp "
638 "parent at time of lowering.");
639 auto traceResult = traceSubviewToBlockArgument(adaptor.getMemref());
640 if (!traceResult)
641 return op->emitOpError(
642 "memref must be a block argument or subview/cast/reinterpret_cast of "
643 "a block argument with static offsets, sizes, and strides");
644 std::optional<unsigned> hostIdx =
645 getHostBufferArgIndex(traceResult->rootArg);
646 if (!hostIdx || traceResult->rootArg.getOwner() != &seqOp.getBody().front())
647 return failure();
648 argIdx = static_cast<int>(*hostIdx);
649
650 const auto &targetModel = AIE::getTargetModel(op);
651 int channel = infoOp.getChannelIndex();
652 AIE::DMAChannelDir dir = infoOp.getChannelDir();
653 // Only the pool is checked; the allocation verifies the channel exists.
654 if (!targetModel.isBdInChannelPool(tileCol, tileRow, op.getId(), channel,
655 dir))
656 return op->emitOpError("BD ID ")
657 << op.getId() << " is not in the BD pool of "
658 << AIE::stringifyDMAChannelDir(dir) << " channel " << channel;
659 uint64_t patchAddr = targetModel.getDmaBdAddress(tileCol, tileRow,
660 op.getId(), channel, dir) +
661 targetModel.getDmaBdAddressOffset(tileCol, tileRow);
662
663 // arg_plus is the buffer byte offset. Constant offsets fold to a constant
664 // (byte-identical to the static path); a runtime offset operand is built
665 // with arith so it flows into the patch instead of being rejected. The
666 // subview trace contributes a constant base byte offset.
667 SmallVector<OpFoldResult> offsets = op.getMixedOffsets();
668 SmallVector<OpFoldResult> strides = op.getMixedStrides();
669 int64_t elemBytes = op.getElementTypeBitwidth() / 8;
670 SmallVector<OpFoldResult> sizes = op.getMixedSizes();
671 bool isRuntime =
672 llvm::any_of(llvm::concat<OpFoldResult>(offsets, sizes, strides),
673 [](OpFoldResult v) { return !getConstantIntValue(v); });
674 if (isRuntime && failed(guardWithinHostBuffer(
675 rewriter, op->getLoc(),
676 cast<BaseMemRefType>(traceResult->rootArg.getType()),
677 traceResult->offsetInBytes, elemBytes, offsets,
678 strides, sizes, strides)))
679 return failure();
680 Value argPlus = buildArgPlusValue(
681 rewriter, op->getLoc(), offsets, strides, elemBytes,
682 traceResult->offsetInBytes, targetModel.getAddressGenGranularity() / 8);
683 if (!argPlus)
684 return failure();
685 NpuAddressPatchOp::create(rewriter, op->getLoc(), patchAddr,
686 /*addr_val=*/Value(), argIdx, argPlus);
687
688 // If this DMA op has an offset_state_table_idx, emit an
689 // update_from_scratchpad to add the runtime offset to the BD address
690 // register (additive; applied after the base patch above).
691 if (op.getOffsetStateTableIdxAttr()) {
692 auto bufType = cast<BaseMemRefType>(op.getMemref().getType());
694 rewriter, op, bufType, patchAddr, targetModel, tileCol, tileRow)))
695 return failure();
696 }
697 return success();
698 }
699
700 // Lower a shim-NOC dma_memcpy_nd carrying runtime (SSA) offsets/sizes/
701 // strides. The encoder runs the same arithmetic as the static path, so a
702 // runtime value equal to a constant yields the same word. aiebu requires the
703 // block-write to precede the address patch and cover the patched word.
704 LogicalResult lowerDynamic(NpuDmaMemcpyNdOp op, OpAdaptor adaptor,
705 ConversionPatternRewriter &rewriter) const {
706 const auto &targetModel = AIE::getTargetModel(op);
707 auto *ctx = op->getContext();
708 auto i32ty = IntegerType::get(ctx, 32);
709 Location loc = op->getLoc();
710
711 auto dev = op->getParentOfType<AIE::DeviceOp>();
712 if (!dev)
713 return failure();
714 auto infoOp = AIE::ShimDMAAllocationOp::getForSymbol(
715 dev, op.getMetadata().getRootReference());
716 if (!infoOp)
717 return op->emitOpError("couldn't find shim_dma_allocation op.");
718 AIE::TileOp shimTile = infoOp.getTileOp();
719 if (!shimTile)
720 return op->emitOpError(
721 "shim_dma_allocation op must reference a valid TileOp.");
722 auto channelDir = infoOp.getChannelDir();
723 bool isMM2S = AIE::isMM2S(channelDir);
724 int tileCol = shimTile.getCol();
725 int tileRow = shimTile.getRow();
726 if (failed(verifyRuntimeBdTarget(op, targetModel, tileCol, tileRow,
727 channelDir)))
728 return failure();
729
730 // Packet / token setup (identical to the static path).
731 auto column = IntegerAttr::get(i32ty, tileCol);
732 auto row = IntegerAttr::get(i32ty, tileRow);
733 BdTemplateFields fields;
734 if (auto packetInfo =
735 op.getPacket() ? op.getPacket() : infoOp.getPacket()) {
736 if (failed(verifyBdPacketType(op, targetModel, tileCol, tileRow,
737 packetInfo->getPktType())))
738 return failure();
739 fields.enable_packet = 1;
740 fields.packet_type = packetInfo->getPktType();
741 fields.packet_id = packetInfo->assignedId();
742 }
743 auto issue_token = BoolAttr::get(ctx, op.getIssueToken());
744 if (!isMM2S)
745 issue_token = BoolAttr::get(ctx, true);
746
747 // buffer_length is the size-product here, hence no explicit length; the
748 // encoder returns the hw repeat_count for the queue push.
749 SmallVector<Value> words;
750 Value repeatCount;
751 if (failed(buildBdWords(rewriter, loc, targetModel, tileCol, tileRow,
752 fields, op.getMixedSizes(), op.getMixedStrides(),
753 op.getElementTypeBitwidth(), op.getBurstLength(),
754 op.getAxcacheOrDefault(),
755 /*lenElems=*/OpFoldResult(), repeatCount, words)))
756 return failure();
757 Value bdBase =
758 getBdRegisterBase(rewriter, loc, targetModel, tileCol, tileRow,
759 rewriter.getI32IntegerAttr(op.getId()));
760 NpuBlockWriteValuesOp::create(rewriter, loc, bdBase, words);
761
762 // Address patch for the buffer pointer; emitBufferAddressPatch folds a
763 // constant offset or builds a runtime arg_plus with arith as needed.
764 int arg_idx = -1;
765 if (failed(emitBufferAddressPatch(op, adaptor, rewriter, infoOp, tileCol,
766 tileRow, arg_idx)))
767 return failure();
768
769 NpuPushQueueOp::create(
770 rewriter, loc, column, row, infoOp.getChannelDirAttr(),
771 infoOp.getChannelIndexAttr(), issue_token, repeatCount,
772 createConstantI32(rewriter, loc, op.getId()),
773 /*repeat_state_table_idx=*/nullptr);
774
775 rewriter.eraseOp(op);
776 return success();
777 }
778};
779
780/// Convert NpuDmaWaitOp into NpuSyncOp by retrieving the necessary
781/// information from the ShimDMAAllocationOp referenced through the
782/// symbol argument of this op.
783struct DmaWaitToSyncPattern : OpConversionPattern<NpuDmaWaitOp> {
784
785public:
786 using OpConversionPattern::OpConversionPattern;
787
788 DmaWaitToSyncPattern(MLIRContext *context, PatternBenefit benefit = 1)
789 : OpConversionPattern(context, benefit) {}
790
791 LogicalResult
792 matchAndRewrite(NpuDmaWaitOp op, OpAdaptor adaptor,
793 ConversionPatternRewriter &rewriter) const override {
794 AIE::DeviceOp dev = op->getParentOfType<AIE::DeviceOp>();
795 if (!dev)
796 return op->emitError("couldn't find parent of type DeviceOp");
797
798 AIE::ShimDMAAllocationOp shimDmaAllocOp =
799 AIE::ShimDMAAllocationOp::getForSymbol(dev, op.getSymbol());
800 if (!shimDmaAllocOp) {
801 return op->emitError("couldn't find shim_dma_allocation op");
802 }
803
804 AIE::TileOp shimTile = shimDmaAllocOp.getTileOp();
805 if (!shimTile) {
806 return op->emitError(
807 "shim_dma_allocation op must reference a valid TileOp");
808 }
809
810 // Create with `column_num == 1` and `row_num == 1` to check for a single
811 // column and row.
812 Location loc = op->getLoc();
813 (void)rewriter.replaceOpWithNewOp<NpuSyncOp>(
814 op, createConstantI32(rewriter, loc, shimTile.getCol()),
815 createConstantI32(rewriter, loc, shimTile.getRow()),
817 rewriter, loc,
818 static_cast<uint32_t>(shimDmaAllocOp.getChannelDir())),
819 createConstantI32(rewriter, loc, shimDmaAllocOp.getChannelIndex()),
820 createConstantI32(rewriter, loc, 1),
821 createConstantI32(rewriter, loc, 1));
822
823 return success();
824 }
825};
826
827struct WriteBdToBlockWritePattern : OpConversionPattern<NpuWriteBdOp> {
828 using OpConversionPattern::OpConversionPattern;
829
830public:
831 WriteBdToBlockWritePattern(MLIRContext *context,
832 BlockwriteData &blockwriteData,
833 PatternBenefit benefit = 1)
834 : OpConversionPattern(context, benefit), blockwriteData(blockwriteData) {}
835
836 BlockwriteData &blockwriteData;
837
838 LogicalResult
839 matchAndRewrite(NpuWriteBdOp op, OpAdaptor adaptor,
840 ConversionPatternRewriter &rewriter) const override {
841
842 AIE::DeviceOp dev = op->getParentOfType<AIE::DeviceOp>();
843 const AIE::AIETargetModel &tm = dev.getTargetModel();
844 int col = op.getColumn();
845 int row = op.getRow();
846
847 std::optional<AIE::DMAChannelDir> dir = op.getDirection();
848 if (failed(verifyRuntimeBdTarget(op, tm, col, row,
849 dir.value_or(AIE::DMAChannelDir::MM2S))))
850 return failure();
851 const AIE::DmaBdLayout *layout = tm.getDmaBdLayout(col, row);
852 if (!layout)
853 return op->emitOpError("has no buffer descriptor layout on this tile");
854 if (op.getPacketType() && !layout->packetType.exists())
855 return op->emitOpError("the buffer descriptors of this tile have no "
856 "packet type field: it is a DMA channel setting");
857 if (!tm.isMemTile(col, row) &&
858 (op.getD0ZeroBefore() || op.getD1ZeroBefore() || op.getD2ZeroBefore() ||
859 op.getD0ZeroAfter() || op.getD1ZeroAfter() || op.getD2ZeroAfter()))
860 return op->emitOpError("Zero padding is only available on MemTile");
861
862 std::vector<uint32_t> words(layout->numWords, 0);
863 auto set = [&](const AIE::DmaBdField &field, uint64_t value) {
864 if (field.exists())
865 words[field.word] |= field.place(value);
866 };
867 uint64_t bufferOffset = op.getBufferOffset();
868 if (tm.isCoreTile(col, row))
869 bufferOffset /= 4;
870 set(layout->bufferLength, op.getBufferLength());
871 set(layout->bufferOffset, bufferOffset);
872 set(layout->enablePacket, op.getEnablePacket());
873 set(layout->packetType, op.getPacketType());
874 set(layout->packetId, op.getPacketId());
875 set(layout->outOfOrderId, op.getOutOfOrderId());
876 set(layout->d0Size, op.getD0Size());
877 set(layout->d0Stride, op.getD0Stride());
878 set(layout->d1Size, op.getD1Size());
879 set(layout->d1Stride, op.getD1Stride());
880 set(layout->d2Stride, op.getD2Stride());
881 set(layout->iterationCurrent, op.getIterationCurrent());
882 set(layout->iterationSize, op.getIterationSize());
883 set(layout->iterationStride, op.getIterationStride());
884 set(layout->d0ZeroBefore, op.getD0ZeroBefore());
885 set(layout->d1ZeroBefore, op.getD1ZeroBefore());
886 set(layout->d2ZeroBefore, op.getD2ZeroBefore());
887 set(layout->d0ZeroAfter, op.getD0ZeroAfter());
888 set(layout->d1ZeroAfter, op.getD1ZeroAfter());
889 set(layout->d2ZeroAfter, op.getD2ZeroAfter());
890 if (layout->burstLength.exists())
891 set(layout->burstLength,
892 getShimBurstLengthEncoding(tm, op.getBurstLength()));
893 set(layout->axcache, op.getAxcacheOrDefault());
894 set(layout->nextBd, op.getNextBd());
895 set(layout->useNextBd, op.getUseNextBd());
896 set(layout->validBd, op.getValidBd());
897 set(layout->lockRelValue, op.getLockRelVal());
898 set(layout->lockRelId, op.getLockRelId());
899 set(layout->lockAcqEnable, op.getLockAcqEnable());
900 set(layout->lockAcqValue, op.getLockAcqVal());
901 set(layout->lockAcqId, op.getLockAcqId());
902
903 // The verifier has required a channel where the BD id is channel-local.
904 uint32_t bd_id = op.getBdId();
905 std::optional<uint32_t> channel = op.getChannel();
906 uint64_t bd_addr = channel && dir
907 ? tm.getDmaBdAddress(col, row, bd_id, *channel, *dir)
908 : tm.getDmaBdAddress(col, row, bd_id);
909
910 memref::GlobalOp global = nullptr;
911 {
912 OpBuilder::InsertionGuard guard(rewriter);
913 rewriter.setInsertionPoint(op->getParentOfType<AIE::RuntimeSequenceOp>());
914 global = blockwriteData.getOrCreate(rewriter, op.getLoc(), words);
915 }
916 auto memref = memref::GetGlobalOp::create(
917 rewriter, op.getLoc(), global.getType(), global.getName());
918
919 (void)rewriter.replaceOpWithNewOp<NpuBlockWriteOp>(
920 op, rewriter.getUI32IntegerAttr(bd_addr), memref.getResult(), nullptr,
921 nullptr, nullptr);
922 return success();
923 }
924};
925
926// Count all task starts at their common representation, after memcpy lowering
927// but before pushes become register writes. This includes starts lowered by
928// dma-tasks-to-npu and compiler-generated channel rearm pushes, and so every
929// path's tokens: no sequence may leave one on a channel any of them awaits.
930static LogicalResult checkQueueDepth(AIE::DeviceOp device,
931 bool enforceQueueDepth) {
932 const AIE::AIETargetModel &tm = device.getTargetModel();
933 SymbolTable symbols(device);
934 auto queueEffectOf = [&](Operation *op) {
935 return rawQueueEffect(op, symbols);
936 };
937 std::set<DmaQueueModel::ChannelKey> awaited;
938 SmallVector<SyncCover> mayAwait;
939 device.walk([&](Operation *op) {
940 QueueEffect e = queueEffectOf(op);
942 awaited.insert(e.key);
943 else if (auto sync = dyn_cast<NpuSyncOp>(op))
944 mayAwait.push_back(syncCover(sync));
945 });
946 bool consumed = true;
947 device.walk([&](AIE::RuntimeSequenceOp seq) {
948 DmaQueueModel queue;
949 // No dma_free_task survives to this lowering stage; nothing to check here.
950 guardSequenceQueueDepth(seq.getBody(), queue, tm, enforceQueueDepth,
951 /*warnUnsafeBdReuse=*/false, queueEffectOf);
952 seq->removeAttr(queueDiagnosedAttr);
953 consumed &=
954 succeeded(checkTokensConsumed(seq, awaited, mayAwait, queueEffectOf));
955 });
956 return success(consumed);
957}
958
959struct AIEDmaToNpuPass : xilinx::AIEX::impl::AIEDmaToNpuBase<AIEDmaToNpuPass> {
960 using Base = xilinx::AIEX::impl::AIEDmaToNpuBase<AIEDmaToNpuPass>;
961 AIEDmaToNpuPass() = default;
962 AIEDmaToNpuPass(const AIEDmaToNpuOptions &options) : Base(options) {}
963
964 void runOnOperation() override {
965
966 AIE::DeviceOp device = getOperation();
967
968 ConversionTarget target(getContext());
969 target.addLegalDialect<AIEXDialect>();
970 target.addLegalDialect<memref::MemRefDialect>();
971 target.addLegalDialect<arith::ArithDialect>();
972 target.addLegalOp<cf::AssertOp>();
973 target.addLegalOp<AIE::BufferOp>();
974 target.addLegalOp<AIE::ShimDMAAllocationOp>();
975 target.addLegalOp<AIE::TileOp>();
976
977 target.addIllegalOp<NpuDmaMemcpyNdOp>();
978 target.addIllegalOp<NpuDmaWaitOp>();
979 target.addIllegalOp<NpuWriteRTPOp>();
980 target.addIllegalOp<NpuWriteBdOp>();
981 target.addDynamicallyLegalOp<NpuWrite32Op>(
982 [&](NpuWrite32Op op) { return !op.getBuffer(); });
983 target.addDynamicallyLegalOp<NpuBlockWriteOp>(
984 [&](NpuBlockWriteOp op) { return !op.getBuffer(); });
985 target.addDynamicallyLegalOp<NpuMaskWrite32Op>(
986 [&](NpuMaskWrite32Op op) { return !op.getBuffer(); });
987 target.addDynamicallyLegalOp<NpuMaskPollOp>(
988 [&](NpuMaskPollOp op) { return !op.getBuffer(); });
989
990 BlockwriteData blockwriteData(device, "blockwrite_data_");
991 AIE::NamedOpTable names(device);
992
993 RewritePatternSet patterns(&getContext());
994 patterns.insert<BlockWriteSymToAddr>(&getContext(), names);
995 patterns.insert<DmaToNpuPattern>(&getContext());
996 patterns.insert<DmaWaitToSyncPattern>(&getContext());
997 patterns.insert<MaskWrite32SymToAddr>(&getContext(), names);
998 patterns.insert<MaskPollSymToAddr>(&getContext(), names);
999 patterns.insert<RtpToWrite32Pattern>(&getContext(), names);
1000 patterns.insert<Write32SymToAddr>(&getContext(), names);
1001 patterns.insert<WriteBdToBlockWritePattern>(&getContext(), blockwriteData);
1002
1003 // The driver converts the illegal ops alone; started from the device, it
1004 // would visit every op of the runtime sequences.
1005 SmallVector<Operation *> illegal;
1006 device.walk([&](Operation *op) {
1007 if (target.isIllegal(op))
1008 illegal.push_back(op);
1009 });
1010 ConversionConfig config;
1011 config.foldingMode = DialectConversionFoldingMode::Never;
1012 config.allowPatternRollback = false;
1013 if (failed(applyPartialConversion(illegal, target, std::move(patterns),
1014 config))) {
1015 signalPassFailure();
1016 return;
1017 }
1018
1019 if (failed(checkQueueDepth(device, enforceQueueDepth))) {
1020 signalPassFailure();
1021 return;
1022 }
1023
1024 target.addIllegalOp<NpuPushQueueOp>();
1025 RewritePatternSet pushPatterns(&getContext());
1026 pushPatterns.insert<PushQueuetoWrite32Pattern>(&getContext());
1027 SmallVector<Operation *> pushes;
1028 device.walk([&](NpuPushQueueOp op) { pushes.push_back(op); });
1029 if (failed(applyPartialConversion(pushes, target, std::move(pushPatterns),
1030 config)))
1031 signalPassFailure();
1032
1033 eraseDeadArith(device);
1034 }
1035};
1036
1037} // namespace
1038
1039std::unique_ptr<OperationPass<AIE::DeviceOp>> AIEX::createAIEDmaToNpuPass() {
1040 return std::make_unique<AIEDmaToNpuPass>();
1041}
1042
1043std::unique_ptr<OperationPass<AIE::DeviceOp>>
1044AIEX::createAIEDmaToNpuPass(const AIEDmaToNpuOptions &options) {
1045 return std::make_unique<AIEDmaToNpuPass>(options);
1046}
Tracks, per DMA channel, the pushes not yet known to have completed along one execution path.
mlir::LogicalResult verifyRuntimeBdTarget(mlir::Operation *op, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, xilinx::AIE::DMAChannelDir direction=xilinx::AIE::DMAChannelDir::MM2S)
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::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIEDmaToNpuPass()
std::optional< SubviewTraceResult > traceSubviewToBlockArgument(Value value)
Definition AIEUtils.cpp:25
QueueEffect rawQueueEffect(mlir::Operation *op, mlir::SymbolTable &symbols)
What a push or an await that names no task does to its channel: an aiex.npu.push_queue; an aiex....
constexpr llvm::StringLiteral queueDiagnosedAttr
mlir::Value buildArgPlusValue(mlir::OpBuilder &builder, mlir::Location loc, llvm::ArrayRef< mlir::OpFoldResult > elementOffsets, llvm::ArrayRef< mlir::OpFoldResult > strides, int64_t elemWidthBytes, int64_t baseByteOffset, uint32_t granuleBytes)
std::optional< uint64_t > getConstantInt64Operand(mlir::Value v)
mlir::LogicalResult checkTokensConsumed(AIE::RuntimeSequenceOp sequence, const std::set< DmaQueueModel::ChannelKey > &awaited, llvm::ArrayRef< SyncCover > mayAwait, EffectFn effectOf)
Check that sequence ends, on every path, with no task-completion token outstanding on a channel some ...
SyncCover syncCover(NpuSyncOp sync)
mlir::Value getAsValue(mlir::OpBuilder &builder, mlir::Location loc, mlir::OpFoldResult ofr, mlir::Type intType)
mlir::Value getBdRegisterBase(mlir::OpBuilder &builder, mlir::Location loc, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, mlir::OpFoldResult bdId, int channel=-1, xilinx::AIE::DMAChannelDir direction=xilinx::AIE::DMAChannelDir::MM2S)
mlir::LogicalResult guardWithinHostBuffer(mlir::OpBuilder &builder, mlir::Location loc, mlir::BaseMemRefType hostBufferType, int64_t baseByteOffset, int64_t elemWidthBytes, llvm::ArrayRef< mlir::OpFoldResult > offsets, llvm::ArrayRef< mlir::OpFoldResult > offsetStrides, llvm::ArrayRef< mlir::OpFoldResult > sizes, llvm::ArrayRef< mlir::OpFoldResult > strides)
mlir::LogicalResult buildBdWords(mlir::OpBuilder &builder, mlir::Location loc, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, const BdTemplateFields &fields, llvm::ArrayRef< mlir::OpFoldResult > mixedSizes, llvm::ArrayRef< mlir::OpFoldResult > mixedStrides, uint64_t elemWidth, uint32_t burstLength, uint32_t axcache, mlir::OpFoldResult lenElems, mlir::Value &repeatCountOut, llvm::SmallVectorImpl< mlir::Value > &wordsOut)
LogicalResult emitUpdateBdAddressFromOffsetParameter(OpBuilder &builder, Operation *bdOp, BaseMemRefType bufType, uint64_t registerAddr, const AIE::AIETargetModel &targetModel, int col, int row, std::optional< uint64_t > staticByteAddress=std::nullopt, OpFoldResult lengthField={})
Definition AIEUtils.cpp:214
std::optional< uint32_t > getConstantIntOperand(mlir::Value v)
mlir::Value getAsI64(mlir::OpBuilder &builder, mlir::Location loc, mlir::OpFoldResult ofr)
void eraseDeadArith(mlir::Operation *root)
void guardSequenceQueueDepth(mlir::Region &body, DmaQueueModel &queue, const AIE::AIETargetModel &tm, bool enforce, bool warnUnsafeBdReuse, EffectFn effectOf)
Guard every push in a runtime sequence that can land on a full queue, and (when warnUnsafeBdReuse) wa...
bool isLinearModeTransfer(const AIE::AIETargetModel &targetModel, int col, int row, llvm::ArrayRef< int64_t > sizes, llvm::ArrayRef< int64_t > strides)
mlir::LogicalResult emitRuntimeCheck(mlir::OpBuilder &builder, mlir::Location loc, mlir::Value cond, const llvm::Twine &message)
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)
LogicalResult emitUpdateBdLengthFromParameter(OpBuilder &builder, Operation *bdOp, BaseMemRefType bufType, int64_t lengthUnit, const AIE::AIETargetModel &targetModel, int col, int row, int bdId)
Definition AIEUtils.cpp:296
mlir::LogicalResult verifyBdPacketType(mlir::Operation *op, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, uint32_t packetType)
std::optional< unsigned > getHostBufferArgIndex(BlockArgument arg)
Definition AIEUtils.cpp:149
mlir::Value createConstantI32(mlir::OpBuilder &builder, mlir::Location loc, uint32_t value)
uint32_t getShimBurstLengthEncoding(const AIE::AIETargetModel &tm, uint32_t burstLength)
const AIETargetModel & getTargetModel(mlir::Operation *op)
void placeRuntimeLengthDimension(llvm::MutableArrayRef< int64_t > sizes, llvm::MutableArrayRef< int64_t > strides)
bool isMM2S(DMAChannelDir dir)
True if dir moves data out of memory onto a stream (MM2S, ControlMM2S).
Definition AIEEnums.h:19
What one op in a loop body does to a channel queue.
DmaQueueModel::ChannelKey key
uint32_t place(uint64_t value) const
DmaBdField d0Size
Without a d0Stride field the innermost dimension is contiguous.