MLIR-AIE 1.4.6.dev
AIEDMATasksToNPU.cpp
Go to the documentation of this file.
1//===- AIEDMATasksToNPU.cpp -------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2024 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
8#include <algorithm>
9#include <iterator>
10#include <limits>
11
17
18#include "mlir/Dialect/Arith/IR/Arith.h"
19#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
20#include "mlir/Dialect/MemRef/IR/MemRef.h"
21#include "mlir/Dialect/SCF/IR/SCF.h"
22#include "mlir/Dialect/UB/IR/UBOps.h"
23#include "mlir/Dialect/Utils/StaticValueUtils.h"
24#include "mlir/Interfaces/ControlFlowInterfaces.h"
25#include "mlir/Interfaces/SideEffectInterfaces.h"
26#include "mlir/Pass/Pass.h"
27#include "mlir/Pass/PassManager.h"
28#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
29#include "mlir/Transforms/LoopInvariantCodeMotionUtils.h"
30#include "mlir/Transforms/Passes.h"
31#include "mlir/Transforms/WalkPatternRewriteDriver.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/TypeSwitch.h"
34
35namespace xilinx::AIEX {
36#define GEN_PASS_DEF_AIEDMATASKSTONPU
37#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
38} // namespace xilinx::AIEX
39
40using namespace mlir;
41using namespace xilinx;
42using namespace xilinx::AIEX;
43
44// This pass emits absolute tile coordinates, so it cannot run before placement
45// has substituted a concrete `aie.tile` for an `aie.logical_tile`. Report that
46// instead of calling getTileOp(), which fatally errors on an unplaced tile.
47static LogicalResult emitUnplacedTileError(Operation *op,
48 DMAConfigureTaskOp task_op) {
49 auto err = op->emitOpError(
50 "Cannot lower a DMA task whose tile is not placed; run placement first.");
51 if (task_op.getOperation() != op)
52 err.attachNote(task_op.getLoc()) << "Task configured here.";
53 return err;
54}
55
56struct DMAStartTaskOpPattern : OpRewritePattern<DMAStartTaskOp> {
57 DMAStartTaskOpPattern(MLIRContext *context,
58 llvm::DenseMap<Operation *, bool> &onlyPushedOnce)
60
61 // Whether every start of a configure pushes a constant repeat count of 0.
62 llvm::DenseMap<Operation *, bool> &onlyPushedOnce;
63
64 LogicalResult matchAndRewrite(DMAStartTaskOp op,
65 PatternRewriter &rewriter) const override {
66 DMAConfigureTaskOp task_op = op.getTaskOp();
67 if (!task_op && !op.getTask().getDefiningOp<DMAConfigureTaskForOp>()) {
68 // A task carried through runtime control flow. The push names one head
69 // BD, so it lowers only if every value the task can carry comes from
70 // the same configure.
71 task_op = getUniqueReachableConfigure(op.getTask());
72 if (!task_op)
73 return op.emitOpError(
74 "starts a task carried through control flow that does not come "
75 "from exactly one aiex.dma_configure_task, so its queue push has "
76 "no single buffer descriptor ID. Start the task where it is "
77 "configured.");
78 }
79 if (!task_op) {
80 // Cannot rewrite this; probably points to a DMAStartTaskForOp,
81 // which we will lower once it has been rewritten into a DMAStartTaskOp.
82 return failure();
83 }
84 AIE::TileOp tile = task_op.tryGetTileOp();
85 if (!tile)
86 return emitUnplacedTileError(op, task_op);
87 Location loc = op.getLoc();
88
89 // The bd_id for the queue push: the head BD's runtime pool value if it
90 // carries one, else its static value.
91 AIE::DMABDOp head = task_op.getFirstBd();
92 OpFoldResult idOfr = head ? head.getBdIdValue() : OpFoldResult();
93 if (!idOfr) {
94 auto err = op.emitOpError(
95 "First buffer descriptor in chain has not been assigned an ID");
96 err.attachNote() << "Run the `aie-assign-runtime-buffer-descriptor-ids` "
97 "pass first or manually assign an ID.";
98 return failure();
99 }
100 Value bdIdVal = getAsValue(rewriter, loc, idOfr, rewriter.getI32Type());
101 if (op.getRepeatParameterAttr())
102 return op.emitOpError("has a repeat_parameter; run "
103 "--aie-lower-scratchpad-parameters first");
104 // A runtime repeat count keeps its width so the push lowering can
105 // range-check it before narrowing. A scratchpad one is added to a push
106 // of 0.
107 IntegerAttr repeatIdx = op.getRepeatStateTableIdxAttr();
108 OpFoldResult repeatOfr = repeatIdx ? rewriter.getI32IntegerAttr(0)
109 : op.getPushRepeatCount(task_op);
110 onlyPushedOnce.try_emplace(task_op, true).first->second &=
111 !repeatIdx && isConstantIntValue(repeatOfr, 0);
112 Value repeatCount = dyn_cast<Value>(repeatOfr);
113 if (!repeatCount)
114 repeatCount = getAsValue(rewriter, loc, repeatOfr, rewriter.getI32Type());
115 rewriter.replaceOpWithNewOp<NpuPushQueueOp>(
116 op, tile.getCol(), tile.getRow(), task_op.getDirection(),
117 task_op.getChannel(), op.getPushIssueToken(task_op), repeatCount,
118 bdIdVal, repeatIdx);
119 return success();
120 }
121};
122
123// Resolve a task value to a configure that gives the sync its physical channel.
124// The value is usually a configure result, but under the dynamic BD pool path a
125// task threaded through runtime control flow surfaces as a region-branch
126// successor input instead: an scf.for/scf.if result (the task carried out of
127// the construct), or a loop's own iter_arg block argument (when the task is
128// awaited from inside the loop body rather than after it -- e.g. a
129// software-pipelined sequence awaiting the previous iteration's task before
130// reusing its BD). Every reachable configure targets the same physical channel
131// -- the pool pass verified both branches of an scf.if agree, and a loop's
132// init and per-iteration reconfiguration agree -- so the first one found
133// gives the right channel.
134//
135// getReachableConfigures walks such a value back to its configures through
136// RegionBranchOpInterface, at any nesting depth.
137static DMAConfigureTaskOp resolveConfigureThroughCF(Value task) {
138 SmallVector<DMAConfigureTaskOp> configures;
139 (void)getReachableConfigures(task, configures);
140 return configures.empty() ? nullptr : configures.front();
141}
142
143struct DMAAwaitTaskOpPattern : OpRewritePattern<DMAAwaitTaskOp> {
144 using OpRewritePattern::OpRewritePattern;
145
146 LogicalResult matchAndRewrite(DMAAwaitTaskOp op,
147 PatternRewriter &rewriter) const override {
148 DMAConfigureTaskOp task_op = op.getTaskOp();
149 if (!task_op) {
150 // The awaited task threads through runtime control flow (an scf result),
151 // so it has no directly-defining configure; walk the SSA carry to one.
152 task_op = resolveConfigureThroughCF(op.getTask());
153 }
154 if (!task_op) {
155 return failure();
156 }
157 if (!task_op.getIssueToken()) {
158 auto err = op.emitOpError(
159 "Cannot wait on a BD that is not configured to issue a token.");
160 err.attachNote(task_op.getLoc())
161 << "Consider adding attribute `issue_token=true` here.";
162 return err;
163 }
164 AIE::TileOp tile = task_op.tryGetTileOp();
165 if (!tile)
166 return emitUnplacedTileError(op, task_op);
167 Location loc = op.getLoc();
168 rewriter.replaceOpWithNewOp<NpuSyncOp>(
169 op, createConstantI32(rewriter, loc, tile.getCol()),
170 createConstantI32(rewriter, loc, tile.getRow()),
171 createConstantI32(rewriter, loc, (uint32_t)task_op.getDirection()),
172 createConstantI32(rewriter, loc, task_op.getChannel()),
173 createConstantI32(rewriter, loc, 1),
174 createConstantI32(rewriter, loc, 1));
175 return success();
176 }
177};
178
180 : xilinx::AIEX::impl::AIEDMATasksToNPUBase<AIEDMATasksToNPUPass> {
181
182 // A BD whose aie.next_bd successor draws its id from the dynamic pool, mapped
183 // to that runtime id; hoistNextBdOpsIntoAttrs fills it in place of the
184 // next_bd_id attribute.
185 llvm::DenseMap<AIE::DMABDOp, Value> runtimeNextBdId;
186
187 bool shouldSkipBlock(Block &block) {
188 // Allow blocks in the input IR that contain nothing but a next_bd operation
189 // as the entry block. We will skip these blocks and not lower them to
190 // anything.
191 auto it = block.without_terminator();
192 return block.isEntryBlock() && it.begin() == it.end();
193 }
194
195 LogicalResult verifyBdInBlock(Block &block) {
196 auto bd_ops = block.getOps<AIE::DMABDOp>();
197 // Exactly one BD op per block
198 int n_bd_ops = std::distance(bd_ops.begin(), bd_ops.end());
199 if (n_bd_ops < 1) {
200 auto error = block.getTerminator()->emitError(
201 "Block ending in this terminator does not contain a required "
202 "aie.dma_bd operation.");
203 error.attachNote(block.getParentOp()->getLoc())
204 << "Error encountered while lowering this BD configuration.";
205 return failure();
206 }
207 if (n_bd_ops > 1) {
208 auto error = block.getTerminator()->emitOpError(
209 "This block contains multiple aie.dma_bd operations. Exactly one "
210 " is "
211 "required.");
212 auto it = bd_ops.begin();
213 ++it;
214 for (; it != bd_ops.end(); ++it) {
215 error.attachNote((*it)->getLoc()) << "Extra aie.dma_bd operation here.";
216 }
217 return failure();
218 }
219 AIE::DMABDOp bd_op = *bd_ops.begin();
220 bool hasRuntimeBdId = bd_op.getBdIdVal() != nullptr;
221 if (!hasRuntimeBdId && !bd_op.getBdId().has_value()) {
222 auto error = bd_op.emitOpError(
223 "Cannot lower buffer descriptor without assigned ID.");
224 error.attachNote()
225 << "Run the `--aie-assign-runtime-sequence-bd-ids` pass first or "
226 "manually assign an ID to this buffer descriptor.";
227 error.attachNote(block.getParentOp()->getLoc())
228 << "Error encountered while lowering this BD configuration.";
229 return failure();
230 }
231 return success();
232 }
233
234 // A builder that derives a BD operand from runtime scalars (a width cast, a
235 // transfer-length product, a cf.assert guard) emits that arithmetic where it
236 // is called, inside the BD block. None of it depends on the BD, so hoist it
237 // ahead of the task. What stays (an op with other effects, or one reading a
238 // value only the block defines) is left for verifyNoUnsupportedOpsInBlock to
239 // reject.
240 void hoistScalarOpsOutOfBdBlocks(DMAConfigureTaskOp op) {
241 moveLoopInvariantCode(
242 {&op.getBody()},
243 [](Value v, Region *body) {
244 return !body->isAncestor(v.getParentRegion());
245 },
246 [](Operation *inner, Region *) {
247 return inner->getNumRegions() == 0 &&
248 (isPure(inner) || isa<cf::AssertOp>(inner));
249 },
250 [&](Operation *inner, Region *) { inner->moveBefore(op); });
251 }
252
253 LogicalResult verifyNoUnsupportedOpsInBlock(Block &block) {
254 WalkResult unsupported_ops = block.walk([&](Operation *inner_op) {
255 return llvm::TypeSwitch<Operation *, WalkResult>(inner_op)
256 .Case<AIE::DMABDOp>(
257 [&](AIE::DMABDOp bd_op) { return WalkResult::advance(); })
258 .Case<AIE::UseLockOp>(
259 [&](AIE::UseLockOp lock_op) { return WalkResult::advance(); })
260 .Case<arith::ConstantOp>(
261 [&](arith::ConstantOp const_op) { return WalkResult::advance(); })
262 .Case<AIE::NextBDOp>(
263 [&](AIE::NextBDOp lock_op) { return WalkResult::advance(); })
264 .Case<AIE::EndOp>(
265 [&](AIE::EndOp lock_op) { return WalkResult::advance(); })
266 .Default([&](Operation *inner_op) {
267 auto error = block.getParentOp()->emitOpError(
268 "Unsupported operation within BD block.");
269 error.attachNote(inner_op->getLoc())
270 << "No lowering to NPU instructions available for this "
271 "operation.";
272 return WalkResult::interrupt();
273 });
274 });
275 if (unsupported_ops.wasInterrupted()) {
276 return failure();
277 }
278 return success();
279 }
280
281 AIE::DMABDOp getBdForBlock(Block &block) {
282 auto bd_ops = block.getOps<AIE::DMABDOp>();
283 AIE::DMABDOp bd_op = *bd_ops.begin(); // Dereference first (and only, after
284 // previous checks) bd op iterator
285 return bd_op;
286 }
287
288 /// `lengthField` is the value the BD write gave its length field.
289 LogicalResult setAddressForSingleBD(OpBuilder &builder, AIE::DMABDOp &bd_op,
290 AIE::TileOp &tile, int channel,
291 AIE::DMAChannelDir channelDir,
292 OpFoldResult bdId,
293 OpFoldResult lengthField) {
294 const AIE::AIETargetModel &target_model = AIE::getTargetModel(bd_op);
295 auto buf = bd_op.getBuffer();
296 auto col = tile.getCol();
297 auto row = tile.getRow();
298 const AIE::DmaBdLayout *layout =
299 target_model.getDmaBdLayout(col, row, channelDir);
300 if (!layout)
301 return bd_op->emitOpError("has no buffer descriptor layout on this tile");
302 bool channelLocalIds =
303 target_model.usesChannelLocalBdIds(col, row, channelDir);
304 // A foldable SSA bd_id must name the same register as the block write.
305 // A runtime one is patched via runtimeRegisterAddr; its placeholder id
306 // only has to name a register in the channel's pool.
307 auto constBdId = bdId ? getConstantIntValue(bdId) : std::nullopt;
308 uint32_t placeholderId =
309 channelLocalIds
310 ? target_model.getBdIdRangeForChannel(col, row, channel, channelDir)
311 .first
312 : 0;
313 uint32_t bd_id =
314 constBdId ? *constBdId : bd_op.getBdId().value_or(placeholderId);
315 uint64_t register_addr =
316 (channelLocalIds ? target_model.getDmaBdAddress(col, row, bd_id,
317 channel, channelDir)
318 : target_model.getDmaBdAddress(col, row, bd_id)) +
319 target_model.getDmaBdAddressOffset(col, row);
320 std::optional<uint64_t> staticByteAddress;
321 // On the runtime-bd_id path the patched register (BD buffer-address word)
322 // is itself runtime: getBdRegisterBase(bd_id) + getDmaBdAddressOffset.
323 // Emitted as an SSA operand on the address patch; null keeps the static
324 // constant.
325 Value runtimeRegisterAddr;
326 if (bdId && !getConstantIntValue(bdId)) {
327 Value base = getBdRegisterBase(builder, bd_op.getLoc(), target_model, col,
328 row, bdId, channel, channelDir);
329 runtimeRegisterAddr = arith::AddIOp::create(
330 builder, bd_op.getLoc(), base,
331 createConstantI32(builder, bd_op.getLoc(),
332 target_model.getDmaBdAddressOffset(col, row)));
333 }
334
335 // emitUpdateBdAddressFromOffsetParameter bakes a compile-time register
336 // address into npu.update_from_scratchpad, so pairing it with a BD drawn
337 // from the runtime pool would patch whichever BD that literal names rather
338 // than the one just configured.
339 if (bd_op.getOffsetStateTableIdxAttr() && runtimeRegisterAddr)
340 return bd_op->emitOpError(
341 "offset_state_table_idx is not supported with a runtime bd_id; the "
342 "scratchpad update targets a compile-time BD register address.");
343
344 // A buffer descriptor can refer to a statically allocated aie.buffer, or to
345 // a DDR buffer which will be passed as a runtime argument (block
346 // argument). Try to find the root block argument, either directly or
347 // through supported subview/view/cast chains.
348 mlir::BlockArgument buf_arg = nullptr;
349 int64_t offset = 0;
350
351 if (auto directArg = llvm::dyn_cast<mlir::BlockArgument>(buf)) {
352 buf_arg = directArg;
353 offset = 0;
354 } else if (auto traceResult = traceSubviewToBlockArgument(buf)) {
355 buf_arg = traceResult->rootArg;
356 offset = traceResult->offsetInBytes;
357 }
358
359 if (buf_arg) {
360 if (!target_model.isShimNOCTile(tile.getCol(), tile.getRow())) {
361 return bd_op->emitOpError("DDR memory (runtime input arguments) can "
362 "only be referred to on shim tiles.");
363 }
364
365 std::optional<unsigned> hostIdx = getHostBufferArgIndex(buf_arg);
366 if (!hostIdx)
367 return bd_op->emitOpError(
368 "buffer must resolve to a memref argument of the runtime sequence");
369 unsigned arg_idx = *hostIdx;
370 // arg_plus = buffer byte offset. The dma_bd offset is a single element
371 // offset (stride 1); a constant folds to a constant (byte-identical to
372 // before), a runtime offset operand is built with arith. `offset` here is
373 // the constant subview base in bytes.
374 OpFoldResult offsetOfr =
375 bd_op.getOffset() ? OpFoldResult(bd_op.getOffset())
376 : OpFoldResult(builder.getI32IntegerAttr(
377 bd_op.getConstantOffset().value_or(0)));
378 OpFoldResult oneStride = builder.getI32IntegerAttr(1);
379 Value argPlus =
380 buildArgPlusValue(builder, bd_op.getLoc(), {offsetOfr}, {oneStride},
381 bd_op.getBufferElementTypeWidthInBytes(), offset,
382 target_model.getAddressGenGranularity() / 8);
383 if (!argPlus)
384 return failure();
385 NpuAddressPatchOp::create(builder, bd_op.getLoc(),
386 /*addr*/ register_addr,
387 /*addr_val*/ runtimeRegisterAddr,
388 /*arg_idx*/ arg_idx, argPlus);
389 } else if (AIE::BufferOp buffer =
390 llvm::dyn_cast<AIE::BufferOp>(buf.getDefiningOp())) {
391 std::optional<uint32_t> bufferAddr = buffer.getAddress();
392 if (!bufferAddr.has_value()) {
393 return bd_op->emitOpError(
394 "Cannot lower buffer without associated address. Run pass "
395 "--aie-assign-buffer-addresses first or manually assign an "
396 "address.");
397 }
398 uint64_t buf_addr = *bufferAddr;
399 // A memtile DMA sees neighbour memories via getMemLocalBaseAddress().
400 if (target_model.isMemTile(col, row)) {
401 int memCol = buffer.getTileOp().getCol();
402 int memRow = buffer.getTileOp().getRow();
403 std::optional<uint32_t> addrOffset =
404 target_model.getMemLocalBaseAddress(col, row, memCol, memRow);
405 if (!addrOffset)
406 return bd_op->emitOpError("the memory of tile (")
407 << memCol << ", " << memRow
408 << ") is not reachable from the DMA of memtile (" << col
409 << ", " << row << ")";
410 buf_addr += *addrOffset;
411 }
412
413 const AIE::DmaBdField &addrBits = layout->bufferOffset;
414 uint64_t divisor = getBdAddressUnit(target_model, col, row);
415 uint64_t maxByteAddr = (uint64_t(addrBits.mask()) + 1) * divisor - 1;
416 if (buf_addr > maxByteAddr)
417 return bd_op->emitOpError("buffer address exceeds the tile's DMA "
418 "address field.");
419
420 // getOffsetInBytes() folds a runtime offset to 0, so it may only be read
421 // on the constant path; a runtime offset is added with arith instead.
422 bool constOffset = !bd_op.getOffset() || bd_op.getConstantOffset();
423 Location loc = bd_op.getLoc();
424 Value addrField;
425 if (constOffset) {
426 buf_addr += bd_op.getOffsetInBytes();
427 if (buf_addr > maxByteAddr)
428 return bd_op->emitOpError("buffer address exceeds the tile's DMA "
429 "address field.");
430 staticByteAddress = buf_addr;
431 addrField =
432 createConstantI32(builder, loc, addrBits.place(buf_addr / divisor));
433 } else {
434 Value byteAddr =
435 buildArgPlusValue(builder, loc, {OpFoldResult(bd_op.getOffset())},
436 {OpFoldResult(builder.getI32IntegerAttr(1))},
437 bd_op.getBufferElementTypeWidthInBytes(),
438 (int64_t)buf_addr, divisor);
439 if (!byteAddr)
440 return failure();
441 Type i64 = builder.getI64Type();
442 Value fits = builder.createOrFold<arith::CmpIOp>(
443 loc, arith::CmpIPredicate::ule, byteAddr,
444 arith::ConstantOp::create(builder, loc,
445 IntegerAttr::get(i64, maxByteAddr)));
446 if (failed(emitRuntimeCheck(builder, loc, fits,
447 "a runtime DMA offset puts the buffer "
448 "address past the tile's DMA address "
449 "field")))
450 return failure();
451 if (divisor != 1)
452 byteAddr = arith::DivUIOp::create(
453 builder, loc, byteAddr,
454 arith::ConstantOp::create(builder, loc,
455 IntegerAttr::get(i64, divisor)));
456 addrField = arith::TruncIOp::create(builder, loc, builder.getI32Type(),
457 byteAddr);
458 if (addrBits.shift != 0)
459 addrField = arith::ShLIOp::create(
460 builder, loc, addrField,
461 createConstantI32(builder, loc, addrBits.shift));
462 }
463 // The register holding the address word. A runtime bd_id makes it
464 // runtime too; a pinned one folds to the literal the static path uses.
465 Value regAddrVal =
466 runtimeRegisterAddr
467 ? runtimeRegisterAddr
468 : createConstantI32(builder, loc,
469 static_cast<uint32_t>(register_addr));
470 uint32_t addrMask = addrBits.place(0xFFFFFFFF);
471 if (addrMask == 0xFFFFFFFF)
472 NpuWrite32Op::create(builder, loc, regAddrVal, addrField, nullptr,
473 nullptr, nullptr);
474 else
475 NpuMaskWrite32Op::create(builder, loc, regAddrVal, addrField,
476 createConstantI32(builder, loc, addrMask),
477 nullptr, nullptr, nullptr);
478 } else {
479 return bd_op->emitOpError(
480 "Buffer argument must be a constant aie.buffer, a runtime sequence "
481 "input argument, or a supported chain of memref.subview, "
482 "memref.view, memref.cast, or memref.reinterpret_cast operations "
483 "rooted at a block argument. Subviews must be static and contiguous; "
484 "views must have a constant byte shift and no dynamic result sizes.");
485 }
486
487 // If this BD has an offset_state_table_idx, emit update_from_scratchpad to
488 // add the runtime offset to the BD address register. This is applied after
489 // the base address is set (by either NpuAddressPatchOp for DDR buffers or
490 // NpuMaskWrite32Op/NpuWrite32Op for on-chip buffers), since the hardware
491 // update_from_scratchpad instruction is additive -- it reads the existing
492 // register value and adds a computed delta to it.
493 if (bd_op.getOffsetStateTableIdxAttr()) {
494 auto bufType = llvm::cast<BaseMemRefType>(bd_op.getBuffer().getType());
496 builder, bd_op, bufType, register_addr, target_model, col, row,
497 staticByteAddress, lengthField)))
498 return failure();
499 }
500
501 return success();
502 }
503
504 // The lock / packet / next_bd fields for a BD block. A runtime lock value is
505 // guarded and encoded with `builder`; only the dynamic path reaches that.
506 FailureOr<BdTemplateFields>
507 gatherBdTemplateFields(OpBuilder &builder, Block &block, AIE::DMABDOp bd_op,
508 AIE::TileOp &tile,
509 const AIE::AIETargetModel &target_model,
510 std::optional<xilinx::AIE::PacketInfoAttr> packet,
511 bool outOfOrder = false) {
513 // Out-of-order S2MM ignores Next_BD; the IR chain only lists the receive
514 // BDs. Leave the BDs unchained, as the static AIE-RT lowering does.
515 if (!outOfOrder) {
516 if (std::optional<uint32_t> nextBdId = bd_op.getNextBdId()) {
517 f.next_bd_id = *nextBdId;
518 f.use_next_bd = 1;
519 } else if (Value nextBdIdVal = runtimeNextBdId.lookup(bd_op)) {
520 f.next_bd_id_val = nextBdIdVal;
521 f.use_next_bd = 1;
522 }
523 }
524
525 auto info = bd_op.getPacket().value_or(packet.value_or(nullptr));
526 if (info) {
527 if (!info.isAssigned()) {
528 bd_op.emitOpError("packet has no pkt_id; allocation assigns one, so a "
529 "header at this level must carry it");
530 return failure();
531 }
532 if (failed(verifyBdPacketType(bd_op, target_model, tile.getCol(),
533 tile.getRow(), info.getPktType())))
534 return failure();
535 f.enable_packet = 1;
536 f.packet_type = info.getPktType();
537 f.packet_id = info.assignedId();
538 }
539
540 if (std::optional<int32_t> oooId = bd_op.getOutOfOrderId())
541 f.out_of_order_id = *oooId;
542
543 if (std::optional<AIE::BDIterationAttr> iter = bd_op.getIteration())
544 f.iteration_current = iter->getCurrent();
545
546 // AcquireGreaterEqual is encoded negated, so a runtime one must be >= 1:
547 // a field of 0 would mean "acquire == 0".
548 auto lockValue = [&](AIE::UseLockOp op, int32_t &constOut,
549 Value &valueOut) -> LogicalResult {
550 if (std::optional<int64_t> c = getConstantIntValue(op.getValue())) {
551 constOut = op.acquireGE() ? -static_cast<int32_t>(*c)
552 : static_cast<int32_t>(*c);
553 return success();
554 }
555 Location loc = op.getLoc();
556 int32_t minValue = op.acquireGE() ? 1 : 0;
557 int32_t maxValue = target_model.getMaxLockValue();
558 Value fromMin = builder.createOrFold<arith::SubIOp>(
559 loc, op.getValue(), createConstantI32(builder, loc, minValue));
560 Value inRange = builder.createOrFold<arith::CmpIOp>(
561 loc, arith::CmpIPredicate::ule, fromMin,
562 createConstantI32(builder, loc, maxValue - minValue));
563 if (failed(emitRuntimeCheck(builder, loc, inRange,
564 "a runtime lock value must be in [" +
565 Twine(minValue) + ":" + Twine(maxValue) +
566 "]")))
567 return failure();
568 valueOut = op.getValue();
569 if (op.acquireGE())
570 valueOut = arith::SubIOp::create(
571 builder, loc, createConstantI32(builder, loc, 0), valueOut);
572 return success();
573 };
574
575 AIE::UseLockOp acquire_op, release_op;
576 if (failed(
577 AIE::verifyBdLockPair(block, outOfOrder, acquire_op, release_op)))
578 return failure();
579 // A memtile BD may use locks of its neighbours, so each lock ID is offset
580 // by the base index of the tile that owns that lock, as in AIERT.cpp.
581 auto lockIdFor = [&](AIE::LockOp lock, int32_t id) -> FailureOr<int32_t> {
582 if (!target_model.isMemTile(tile.getCol(), tile.getRow()))
583 return id;
584 std::optional<uint32_t> offset = target_model.getLockLocalBaseIndex(
585 tile.getCol(), tile.getRow(), lock.colIndex(), lock.rowIndex());
586 if (!offset) {
587 bd_op.emitOpError("the locks of tile (")
588 << lock.colIndex() << ", " << lock.rowIndex()
589 << ") are not reachable from the DMA of memtile (" << tile.getCol()
590 << ", " << tile.getRow() << ")";
591 return failure();
592 }
593 return id + static_cast<int32_t>(*offset);
594 };
595 if (release_op) {
596 AIE::LockOp rel_lock = release_op.getLockOp();
597
598 // Acquire is optional under out-of-order (release-only completion).
599 if (acquire_op) {
600 AIE::LockOp acq_lock = acquire_op.getLockOp();
601 if (std::optional<int32_t> acqLockId = acq_lock.getLockID()) {
602 FailureOr<int32_t> id = lockIdFor(acq_lock, *acqLockId);
603 if (failed(id))
604 return failure();
605 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
606 f.lock_acq_id = *id;
607 if (failed(lockValue(acquire_op, f.lock_acq_val, f.lock_acq_val_val)))
608 return failure();
609 f.lock_acq_enable = 1;
610 }
611 }
612
613 if (std::optional<int32_t> relLockId = rel_lock.getLockID()) {
614 FailureOr<int32_t> id = lockIdFor(rel_lock, *relLockId);
615 if (failed(id))
616 return failure();
617 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
618 f.lock_rel_id = *id;
619 if (failed(lockValue(release_op, f.lock_rel_val, f.lock_rel_val_val)))
620 return failure();
621 }
622 }
623 return f;
624 }
625
626 // Dynamic (runtime SSA size/stride/len/bd_id) BD lowering, the dma_task
627 // sibling of DmaToNpuPattern::lowerDynamic. Reaching this function at all
628 // means the design targets the EmitC (C++ TXN) builder, never the static
629 // binary target: a design meant for the binary target is unrolled to
630 // all-constant before this pass runs. Scope (a tile type with a BD register
631 // layout, no padding, realizability) is enforced by the caller;
632 // buildBdWords picks the layout from the tile.
633 LogicalResult
634 rewriteSingleBDDynamic(OpBuilder &builder, Block &block, AIE::DMABDOp bd_op,
635 AIE::TileOp &tile, int channel,
636 AIE::DMAChannelDir channelDir,
637 std::optional<xilinx::AIE::PacketInfoAttr> packet,
638 Value runtimeBdId = nullptr, bool outOfOrder = false) {
639 const auto &target_model = AIE::getTargetModel(bd_op);
640 Location loc = bd_op.getLoc();
641 int col = tile.getCol();
642 int row = tile.getRow();
643
644 auto fieldsOr = gatherBdTemplateFields(builder, block, bd_op, tile,
645 target_model, packet, outOfOrder);
646 if (failed(fieldsOr))
647 return failure();
648 // failed() above guards the deref; FailureOr hides the std::optional base's
649 // has_value(), so the checker cannot see the guard (suppressed below).
650 BdTemplateFields f = *fieldsOr; // NOLINT
651
652 // The bd_id as an OpFoldResult: the runtime pool value if present, else the
653 // pinned constant attribute. On the non-runtime path verifyBdInBlock (run
654 // for every block before any lowering, with hasRuntimeBdId == !runtimeBdId)
655 // has already required the attribute, so the access is guaranteed set here.
656 OpFoldResult bdIdOfr;
657 if (runtimeBdId) {
658 bdIdOfr = runtimeBdId;
659 } else {
660 std::optional<uint32_t> staticBdId = bd_op.getBdId();
661 assert(staticBdId && "static bd_id must be assigned (checked by "
662 "verifyBdInBlock before lowering)");
663 bdIdOfr = builder.getI32IntegerAttr(*staticBdId);
664 }
665
666 // Normalize sizes/strides to a 4-element outermost-first mixed list (the
667 // shared emitter's contract, matching memcpy_nd's always-4D operands),
668 // padding absent leading dims with size 1 / stride 0. dma_bd's mixed lists
669 // are outermost-first and variable-length (0..4 dims). A BD with no dims is
670 // a contiguous scan, so its innermost stride is 1, which keeps it linear
671 // like the static path.
672 SmallVector<OpFoldResult> sizes(bd_op.getMixedSizes());
673 SmallVector<OpFoldResult> strides(bd_op.getMixedStrides());
674 if (sizes.size() > 4 || strides.size() > 4)
675 return bd_op->emitOpError(
676 "At most four data layout transformation dimensions may be "
677 "provided; aie-decompose-large-dma-bd splits a longer one.");
678 OpFoldResult one = builder.getI64IntegerAttr(1);
679 OpFoldResult zeroOfr = builder.getI64IntegerAttr(0);
680 SmallVector<OpFoldResult, 4> sizes4(4, one), strides4(4, zeroOfr);
681 if (strides.empty())
682 strides4.back() = one;
683 for (size_t i = 0; i < sizes.size(); i++) {
684 sizes4[4 - sizes.size() + i] = sizes[i];
685 strides4[4 - strides.size() + i] = strides[i];
686 }
687 // The iteration attribute takes the outermost (iteration) slot, which
688 // verifyTaskBDDimensions has kept free of sizes/strides.
689 if (std::optional<AIE::BDIterationAttr> iter = bd_op.getIteration()) {
690 sizes4.front() = builder.getI64IntegerAttr(iter->getSize());
691 strides4.front() = builder.getI64IntegerAttr(iter->getStride());
692 }
693 // len as OpFoldResult: the runtime operand if present, else the static_len
694 // attr (a constant BD with runtime sizes/strides still reaches here). With
695 // runtime dims and no len, the transfer is their d0*d1*d2 extent; with
696 // constant dims or none, it is the whole buffer, as on the static path.
697 // That default needs a constant offset, or it could run past the buffer.
698 OpFoldResult lenOfr;
699 if (Value lenOperand = bd_op.getLen())
700 lenOfr = lenOperand;
701 else if (std::optional<int32_t> constLen = bd_op.getConstantLen())
702 lenOfr = builder.getI32IntegerAttr(*constLen);
703 else if (bd_op.getSizes().empty() && bd_op.getStrides().empty()) {
704 auto bufTy = cast<BaseMemRefType>(bd_op.getBuffer().getType());
705 if (!bufTy.hasStaticShape() ||
706 (bd_op.getOffset() && !bd_op.getConstantOffset()))
707 return bd_op->emitOpError(
708 "runtime-valued BD requires an explicit transfer length; provide a "
709 "`len` for this buffer descriptor.");
710 lenOfr = builder.getI64IntegerAttr(bufTy.getNumElements());
711 }
712
713 // As on the static path, the lowest three dims (d3 repeats the BD) must
714 // cover a constant length exactly.
715 std::optional<int64_t> constLen =
716 lenOfr ? getConstantIntValue(lenOfr) : std::nullopt;
717 std::optional<int64_t> dimsLen = 1;
718 for (OpFoldResult s : llvm::drop_begin(sizes4)) {
719 std::optional<int64_t> c = getConstantIntValue(s);
720 if (!c) {
721 dimsLen.reset();
722 break;
723 }
724 *dimsLen *= *c;
725 }
726 uint64_t elemWidth =
727 static_cast<uint64_t>(bd_op.getBufferElementTypeWidthInBytes()) * 8;
728 if (!sizes.empty() && constLen && dimsLen && *dimsLen != *constLen) {
729 auto err = bd_op->emitOpError(
730 "Buffer descriptor length does not match length of "
731 "transfer expressed by lowest three dimensions of data "
732 "layout transformation strides/wraps. ")
733 << "BD length is " << (*constLen * elemWidth / 8)
734 << " bytes. Lowest three dimensions of data layout "
735 "transformation would result in transfer of "
736 << (*dimsLen * elemWidth / 8) << " bytes. ";
737 err.attachNote() << "Do not include the highest dimension size in "
738 "transfer length, as this is the BD repeat count.";
739 return failure();
740 }
741
742 // A BD without addressing dims, or whose dims are a unit-stride d0 alone,
743 // is a plain linear transfer of `len` elements (canonicalization strips a
744 // contiguous [1, 1, 1, N] to this form, and the static path encodes it
745 // linear from `len` alone), so give it exactly that shape. With any other
746 // dims, `len` must agree with their d0*d1*d2 extent.
747 bool linear =
748 sizes.empty() ||
749 (lenOfr && isConstantIntValue(strides4[3], 1) &&
750 llvm::all_of(ArrayRef(sizes4).drop_back(),
751 [](OpFoldResult v) { return isConstantIntValue(v, 1); }));
752 if (linear) {
753 sizes4[3] = lenOfr;
754 strides4[3] = one;
755 }
756
757 // The BD-level repeat_count (encoder output) is unused here: the dma_task
758 // queue push is emitted separately by DMAStartTaskOpPattern from the task
759 // op's repeat_count, not the BD's outer dim.
760 SmallVector<Value> bdWords;
761 Value bdRepeatCount;
762 if (failed(buildBdWords(
763 builder, loc, target_model, col, row, f, sizes4, strides4,
764 elemWidth, bd_op.getBurstLength(), bd_op.getAxcacheOrDefault(),
765 linear ? OpFoldResult() : lenOfr, bdRepeatCount, bdWords)))
766 return failure();
767
768 // The walk must stay inside the host buffer it reads or writes.
769 if (auto trace = traceSubviewToBlockArgument(bd_op.getBuffer())) {
770 OpFoldResult offsetOfr =
771 bd_op.getOffset() ? OpFoldResult(bd_op.getOffset())
772 : OpFoldResult(builder.getI32IntegerAttr(
773 bd_op.getConstantOffset().value_or(0)));
774 if (failed(guardWithinHostBuffer(
775 builder, loc, cast<BaseMemRefType>(trace->rootArg.getType()),
776 trace->offsetInBytes, elemWidth / 8, {offsetOfr}, {one}, sizes4,
777 strides4)))
778 return failure();
779 }
780
781 // One blockwrite carries the whole register block for BD configuration.
782 Value bdBase = getBdRegisterBase(builder, loc, target_model, col, row,
783 bdIdOfr, channel, channelDir);
784 NpuBlockWriteValuesOp::create(builder, loc, bdBase, bdWords);
785 const AIE::DmaBdLayout *layout =
786 target_model.getDmaBdLayout(col, row, channelDir);
788 builder, bd_op, tile, channel, channelDir, bdIdOfr,
789 layout ? OpFoldResult(bdWords[layout->bufferLength.word])
790 : OpFoldResult());
791 }
792
793 LogicalResult
794 rewriteSingleBD(OpBuilder &builder, Block &block, AIE::TileOp &tile,
795 int channel, AIE::DMAChannelDir channelDir,
796 std::optional<xilinx::AIE::PacketInfoAttr> packet,
797 bool outOfOrder = false) {
798 AIE::DMABDOp bd_op = getBdForBlock(block);
799 Value runtimeBdId = bd_op.getBdIdVal();
800 const auto &target_model = AIE::getTargetModel(bd_op);
801 if (failed(verifyRuntimeBdTarget(bd_op, target_model, tile.getCol(),
802 tile.getRow(), channelDir)))
803 return failure();
804 // A channel-local BD id names a register only within its channel's pool.
805 if (std::optional<uint32_t> id = bd_op.getBdId();
806 id && target_model.hasChannelLocalBdIds(tile.getCol(), tile.getRow()) &&
807 !target_model.isBdChannelAccessible(tile.getCol(), tile.getRow(), *id,
808 channel, channelDir))
809 return bd_op->emitOpError("BD ID ")
810 << *id << " is not in the BD pool of "
811 << AIE::stringifyDMAChannelDir(channelDir) << " channel "
812 << channel;
813 auto buffer_type = llvm::cast<BaseMemRefType>(bd_op.getBuffer().getType());
814 uint32_t addr_granularity = target_model.getAddressGenGranularity();
815
816 // Runtime (SSA) sizes/strides/len/offset take the dynamic BD-word encoder
817 // path; a runtime bd_id (dynamic free-list pool) also forces it, since the
818 // BD register addresses are then runtime and cannot fold into a blockwrite,
819 // and so does a runtime next_bd, which is a runtime field in the words.
820 // A fully-constant descriptor with a pinned bd_id takes the static path
821 // below unchanged. The encoder covers every tile type that has a BD
822 // register layout (see buildBdWords), so anything the dynamic path can't
823 // represent stays a clean diagnostic.
824 bool runtimeLen = bd_op.getLen() && !bd_op.getConstantLen();
825 bool runtimeOffset = bd_op.getOffset() && !bd_op.getConstantOffset();
826 bool runtimeDims =
827 llvm::any_of(bd_op.getMixedSizes(),
828 [](OpFoldResult s) { return !getConstantIntValue(s); }) ||
829 llvm::any_of(bd_op.getMixedStrides(),
830 [](OpFoldResult s) { return !getConstantIntValue(s); });
831 bool runtimeNextBd = runtimeNextBdId.contains(bd_op);
832 bool runtimeLock =
833 llvm::any_of(block.getOps<AIE::UseLockOp>(), [](AIE::UseLockOp op) {
834 return !getConstantIntValue(op.getValue());
835 });
836 if (runtimeLen || runtimeDims || runtimeOffset || runtimeBdId ||
837 runtimeNextBd || runtimeLock) {
838 // The verifier leaves a runtime offset, bd_id, next_bd or lock value as
839 // the only ways here. An offset that depends on a runtime-sequence loop
840 // is constant by now if the loop was unrolled.
841 if (bd_op.getLengthStateTableIdxAttr())
842 return bd_op->emitOpError("length_parameter requires a constant "
843 "offset, bd_id, next_bd and lock value");
844 int col = tile.getCol(), row = tile.getRow();
845 if (!target_model.isShimNOCTile(col, row) &&
846 !target_model.isMemTile(col, row) &&
847 !target_model.isCoreTile(col, row))
848 return bd_op->emitOpError(
849 "runtime-valued BD size/stride/len/bd_id/next_bd/lock value is "
850 "only supported on tiles with a DMA buffer descriptor layout (shim "
851 "NOC, mem and "
852 "core tiles); use compile-time constants here.");
853 if (bd_op.getPadDimensions().has_value())
854 return bd_op->emitOpError(
855 "zero padding is not supported with runtime sizes/strides/len.");
856 // Realizability of the constant size/stride operands (runtime ones are
857 // guarded at lowering by the shared encoder). Mixed lists are
858 // outermost-first; the helper wants innermost-first.
859 uint64_t elemWidth =
860 static_cast<uint64_t>(bd_op.getBufferElementTypeWidthInBytes()) * 8;
861 SmallVector<OpFoldResult, 4> sizesRev(
862 llvm::reverse(bd_op.getMixedSizes()));
863 SmallVector<OpFoldResult, 4> stridesRev(
864 llvm::reverse(bd_op.getMixedStrides()));
866 bd_op, sizesRev, stridesRev, elemWidth,
867 target_model.getAddressGenGranularity())))
868 return failure();
869 return rewriteSingleBDDynamic(builder, block, bd_op, tile, channel,
870 channelDir, packet, runtimeBdId,
871 outOfOrder);
872 }
873
874 // Static path: bd_id is a pinned attribute (the dynamic/runtime-bd_id path
875 // returned above) and the offset is constant (runtime offset routed above).
876 // verifyBdInBlock (run for every block before lowering, with the static
877 // path implying hasRuntimeBdId == false) has already required the
878 // attribute.
879 std::optional<uint32_t> bdIdAttr = bd_op.getBdId();
880 assert(bdIdAttr && "static bd_id must be assigned (checked by "
881 "verifyBdInBlock before lowering)");
882 uint32_t bd_id = *bdIdAttr;
883 int64_t offset = bd_op.getOffsetInBytes();
884 uint64_t len = bd_op.getLenInBytes();
885 uint64_t len_addr_granularity = len * 8 / addr_granularity;
886
887 if (offset * 8 % addr_granularity != 0) {
888 return bd_op->emitOpError("Offset must be aligned to ")
889 << (addr_granularity / 8) << " byte boundary.";
890 }
891
892 // A runtime length may start from zero: the update below adds to it.
893 if (len < addr_granularity / 8 && !bd_op.getLengthStateTableIdxAttr()) {
894 return bd_op->emitOpError("Transfer size of ")
895 << len << " bytes falls below minimum hardware transfer unit of "
896 << (addr_granularity / 8) << " bytes.";
897 }
898 // The owning storage must outlive the ArrayRef view below.
899 std::optional<llvm::SmallVector<AIE::BDDimLayoutAttr>> dimsStorage =
900 bd_op.getConstantDimensions();
901 if (!dimsStorage)
902 return bd_op->emitOpError("internal error folding BD dimensions");
903 // The iteration attribute rides in the outermost (iteration) slot of the
904 // dimensioned form, so a BD without dims becomes one contiguous dimension.
905 std::optional<AIE::BDIterationAttr> iter = bd_op.getIteration();
906 if (iter && dimsStorage->empty())
907 dimsStorage->push_back(AIE::BDDimLayoutAttr::get(
908 builder.getContext(), len / bd_op.getBufferElementTypeWidthInBytes(),
909 1));
910 std::optional<llvm::ArrayRef<AIE::BDDimLayoutAttr>> dims;
911 if (!dimsStorage->empty())
912 dims = llvm::ArrayRef<AIE::BDDimLayoutAttr>(*dimsStorage);
913 llvm::SmallVector<int64_t, 4> sizes = llvm::SmallVector<int64_t, 4>(4, 0);
914 llvm::SmallVector<int64_t, 4> strides = llvm::SmallVector<int64_t, 4>(4, 0);
915
916 // Padding
917 std::optional<llvm::ArrayRef<AIE::BDPadLayoutAttr>> padDims =
918 bd_op.getPadDimensions();
919 llvm::SmallVector<int64_t, 4> padBefore =
920 llvm::SmallVector<int64_t, 4>(4, 0);
921 llvm::SmallVector<int64_t, 4> padAfter =
922 llvm::SmallVector<int64_t, 4>(4, 0);
923 llvm::fill(padBefore, 0);
924 llvm::fill(padAfter, 0);
925
926 auto d0size = 0;
927 auto d0stride = 0;
928 auto d1size = 0;
929 auto d1stride = 0;
930 auto d2size = 0;
931 auto d2stride = 0;
932 auto iteration_size = 0;
933 auto iteration_stride = 0;
934
935 if (dims && !dims->empty()) {
936 llvm::SmallVector<int64_t, 4> input_sizes =
937 llvm::SmallVector<int64_t, 4>(4, 1);
938 llvm::SmallVector<int64_t, 4> input_strides =
939 llvm::SmallVector<int64_t, 4>(4, 0);
940 if (dims->size() > 4) {
941 return bd_op->emitOpError(
942 "At most four data layout transformation dimensions may be "
943 "provided; aie-decompose-large-dma-bd splits a longer one.");
944 }
945
946 for (size_t i = 0; i < dims->size(); i++) {
947 // Pass down dimensions in reverse order; in the MLIR, this allows
948 // us to specify step sizes/wraps in the same order as we would
949 // access a multi-dim C array, with the highest dimension first.
950 int j = dims->size() - i - 1;
951 input_sizes[i] = (*dims)[j].getSize();
952 input_strides[i] = (*dims)[j].getStride();
953 }
954 if (iter) {
955 input_sizes[3] = iter->getSize();
956 input_strides[3] = iter->getStride();
957 }
958
959 // d3 (repeat) is excluded; a repeated linear transfer is still linear.
960 // A contiguous row-major ND access on a shim NOC tile is also lowered
961 // using the wide buffer_length register, exempt from the 10-bit ND
962 // wrap-size limit. Canonicalization zeroes size-1 strides before this
963 // pass runs, so isContiguousTransfer is sufficient.
964 // A linear transfer leaves the wraps unset, and the pads apply to them.
965 bool treatAsLinear =
966 !padDims.has_value() &&
967 isLinearModeTransfer(target_model, tile.getCol(), tile.getRow(),
968 input_sizes, input_strides);
969 if (!treatAsLinear && bd_op.getLengthStateTableIdxAttr())
970 AIE::placeRuntimeLengthDimension(input_sizes, input_strides);
971
972 if (padDims.has_value()) {
973 const AIE::DmaBdLayout *layout =
974 target_model.getDmaBdLayout(tile.getCol(), tile.getRow());
975 size_t numPadFields = layout ? layout->padFields().size() : 0;
976 if (numPadFields == 0)
977 return bd_op->emitOpError()
978 << "Padding is only supported by memtile dma bds.";
979 if (padDims->size() > dims->size())
980 return bd_op->emitOpError()
981 << "Mismatch number of dimensions between padding(s)"
982 << " and wrap(s) and stride(s).";
983 for (auto [d, pad] : llvm::enumerate(llvm::reverse(*padDims)))
984 if (d >= numPadFields &&
985 (pad.getConstPadBefore() || pad.getConstPadAfter()))
986 return bd_op->emitOpError()
987 << "D" << d
988 << " zero padding is not supported on this tile.";
989 if (channelDir == AIE::DMAChannelDir::MM2S) {
990 for (size_t i = 0; i < padDims->size(); i++) {
991 int j = padDims->size() - i - 1;
992 padBefore[i] = (*padDims)[j].getConstPadBefore();
993 padAfter[i] = (*padDims)[j].getConstPadAfter();
994 }
995 for (size_t i = padDims->size(); i < dims->size(); i++) {
996 padBefore[i] = 0;
997 padAfter[i] = 0;
998 }
999 int64_t elementBytes = bd_op.getBufferElementTypeWidthInBytes();
1000 if ((padBefore[0] * elementBytes) % 4 ||
1001 (padAfter[0] * elementBytes) % 4)
1002 return bd_op->emitOpError()
1003 << "Inner-most padding count must result in padding in "
1004 "32-bit words.";
1005 padBefore[0] = padBefore[0] * elementBytes / 4;
1006 padAfter[0] = padAfter[0] * elementBytes / 4;
1007 } else
1008 return bd_op->emitOpError()
1009 << "supports padding only for MM2S direction on MemTiles.";
1010 }
1011 getHardwareStridesWraps(target_model, bd_op, tile.getCol(), tile.getRow(),
1012 buffer_type, input_sizes, input_strides, sizes,
1013 strides);
1014
1015 if (failed(verifyStridesWraps(
1016 bd_op, [&] { return bd_op->emitOpError(); }, buffer_type,
1017 tile.getCol(), tile.getRow(), input_sizes, input_strides, sizes,
1018 strides, treatAsLinear))) {
1019 return failure();
1020 }
1021
1022 iteration_size = sizes[3];
1023 iteration_stride = strides[3];
1024
1025 if (!treatAsLinear) {
1026 // d0_size, d0_stride
1027 d0size = sizes[0];
1028 d0stride = strides[0];
1029
1030 // d1_size, d1_stride
1031 d1size = sizes[1];
1032 d1stride = strides[1];
1033
1034 // d2_stride
1035 d2stride = strides[2];
1036
1037 // TODO: d2_size is a dead field; AIEDmaToNpu.cpp memtile word-packing
1038 // never writes it (see its `// TODO: D2Size`); the real D2 repeat
1039 // count is carried entirely by buffer_length, same as on shim tiles.
1040 d2size = (target_model.isMemTile(tile.getCol(), tile.getRow()))
1041 ? sizes[2]
1042 : 0;
1043 }
1044 if (input_sizes[3] > 1 && input_strides[3] == 0) {
1045 // We allow users to encode the repeat_count as a dimension 3 stride
1046 // of 0. This must lower to a iteration wrap of 0, so no stride is
1047 // ever added. We then repeat the BD using the repeat_count in
1048 // NpuPushQueueOp.
1049 iteration_size = 0;
1050 iteration_stride = 0;
1051 }
1052
1053 // Ensure the total transfer length and the padded length expressed in the
1054 // lowest three dimensions of strides/wraps agree. (Fourth dimension is
1055 // iteration/repeat count and repeats the whole BD, so should not be
1056 // incorporated in length of a single BD invocation.)
1057 uint64_t len_dims_addr_granularity = 1;
1058 for (size_t i = 0; i < 3; i++) {
1059 len_dims_addr_granularity *= sizes[i] + padBefore[i] + padAfter[i];
1060 }
1061 // A runtime length from zero keeps the pattern for the units it adds.
1062 bool runtimeLengthFromZero =
1063 len_addr_granularity == 0 && bd_op.getLengthStateTableIdxAttr();
1064 if (len_dims_addr_granularity != len_addr_granularity &&
1065 !runtimeLengthFromZero) {
1066 auto err =
1067 bd_op->emitOpError(
1068 "Buffer descriptor length does not match length of transfer "
1069 "expressed by lowest three dimensions of data layout "
1070 "transformation strides/wraps. ")
1071 << "BD length is " << (len_addr_granularity * addr_granularity / 8)
1072 << " bytes. "
1073 << "Lowest three dimensions of data layout transformation would "
1074 "result in transfer of "
1075 << (len_dims_addr_granularity * addr_granularity / 8) << " bytes. ";
1076 err.attachNote() << "Do not include the highest dimension size in "
1077 "transfer length, as this is the BD repeat count.";
1078 return failure();
1079 }
1080 } else {
1081 if (padDims && target_model.isMemTile(tile.getCol(), tile.getRow()) &&
1082 channelDir == AIE::DMAChannelDir::MM2S) {
1083 return bd_op->emitOpError()
1084 << "Padding requires n-d data layouts expressed as "
1085 << "wrap(s) and stride(s).";
1086 }
1087 if (padDims) {
1088 return bd_op->emitOpError()
1089 << " Padding is supported only on MemTiles.";
1090 }
1091 }
1092 auto fieldsOr = gatherBdTemplateFields(builder, block, bd_op, tile,
1093 target_model, packet, outOfOrder);
1094 if (failed(fieldsOr))
1095 return failure();
1096 bool channelLocalIds = target_model.usesChannelLocalBdIds(
1097 tile.getCol(), tile.getRow(), channelDir);
1098 // failed() above guards the deref; see note in rewriteSingleBDDynamic.
1099 BdTemplateFields f = *fieldsOr; // NOLINT
1100
1101 NpuWriteBdOp::create(
1102 builder, bd_op.getLoc(), tile.getCol(), bd_id, len_addr_granularity,
1103 offset,
1104 /*enable_packet=*/f.enable_packet,
1105 /*out_of_order_id=*/f.out_of_order_id,
1106 /*packet_id=*/f.packet_id,
1107 /*packet_type=*/f.packet_type,
1108 /*d0_size=*/d0size, /*d0_stride=*/d0stride,
1109 /*d1_size=*/d1size, /*d1_stride=*/d1stride,
1110 /*d2_size=*/d2size, /*d2_stride=*/d2stride,
1111 /*iteration_current=*/f.iteration_current,
1112 /*iteration_size=*/iteration_size,
1113 /*iteration_stride=*/iteration_stride,
1114 /*next_bd=*/f.next_bd_id,
1115 /*row=*/tile.getRow(),
1116 /*use_next_bd=*/f.use_next_bd,
1117 /*valid_bd=*/1,
1118 /*lock_rel_val=*/f.lock_rel_val, /*lock_rel_id=*/f.lock_rel_id,
1119 /*lock_acq_enable=*/f.lock_acq_enable,
1120 /*lock_acq_val=*/f.lock_acq_val, /*lock_acq_id=*/f.lock_acq_id,
1121 /*d0_zero_before=*/padBefore[0],
1122 /*d1_zero_before=*/padBefore[1], /*d2_zero_before=*/padBefore[2],
1123 /*d0_zero_after=*/padAfter[0], /*d1_zero_after=*/padAfter[1],
1124 /*d2_zero_after=*/padAfter[2],
1125 /*burst_length=*/bd_op.getBurstLength(),
1126 /*axcache=*/
1127 target_model.isShimNOCTile(tile.getCol(), tile.getRow())
1128 ? builder.getI32IntegerAttr(bd_op.getAxcacheOrDefault())
1129 : IntegerAttr(),
1130 // A channel-local BD id needs its channel to name a register.
1131 channelLocalIds ? builder.getI32IntegerAttr(channel) : IntegerAttr(),
1132 channelLocalIds
1133 ? AIE::DMAChannelDirAttr::get(builder.getContext(), channelDir)
1134 : AIE::DMAChannelDirAttr());
1135 if (failed(setAddressForSingleBD(
1136 builder, bd_op, tile, channel, channelDir, {},
1137 builder.getI64IntegerAttr(len_addr_granularity))))
1138 return failure();
1139
1140 // A length_state_table_idx adds the runtime length to the BD's
1141 // Buffer_Length, which the BD write has already set to the static length.
1142 // The verifier requires a length_unit with it.
1143 auto lengthUnit = bd_op.getLengthUnit();
1144 if (bd_op.getLengthStateTableIdxAttr() && lengthUnit)
1146 builder, bd_op, buffer_type, *lengthUnit, target_model, tile.getCol(),
1147 tile.getRow(), bd_id);
1148 return success();
1149 }
1150
1151 LogicalResult hoistNextBdOpsIntoAttrs(DMAConfigureTaskOp op) {
1152 Region &body = op.getBody();
1153 for (auto &block : body) {
1154 if (shouldSkipBlock(block)) {
1155 continue;
1156 }
1157 AIE::DMABDOp bd_op = getBdForBlock(block);
1158 if (AIE::NextBDOp next_bd_op =
1159 llvm::dyn_cast<AIE::NextBDOp>(block.getTerminator())) {
1160 if (bd_op.getNextBdId().has_value()) {
1161 auto error =
1162 bd_op.emitOpError("Cannot specify both next_bd_id attribute and "
1163 "aie.next_bd operation.");
1164 error.attachNote(next_bd_op.getLoc())
1165 << "Potentially conflicting next buffer descriptor ID specified "
1166 "here.";
1167 return failure();
1168 }
1169 Block &next_bd_block = *next_bd_op.getDest();
1170 AIE::DMABDOp next_dma_bd_op = getBdForBlock(next_bd_block);
1171 // verifyBdInBlock has required a pinned or a runtime id on every BD.
1172 if (Value nextBdIdVal = next_dma_bd_op.getBdIdVal())
1173 runtimeNextBdId[bd_op] = nextBdIdVal;
1174 else
1175 bd_op.setNextBdId(next_dma_bd_op.getBdId());
1176 OpBuilder builder(next_bd_op);
1177 AIE::EndOp::create(builder, next_bd_op.getLoc());
1178 next_bd_op.erase();
1179 }
1180 }
1181 return success();
1182 }
1183
1184 LogicalResult emitOutOfOrderChannelEnable(OpBuilder &builder,
1185 DMAConfigureTaskOp op,
1186 AIE::TileOp tile) {
1188 int col = tile.getCol();
1189 int row = tile.getRow();
1190 int channel = op.getChannel();
1191
1192 uint32_t ctrlAddrLocal = tm.getLocalDmaControlAddress(
1193 col, row, channel, AIE::DMAChannelDir::S2MM);
1194
1195 std::string ctrlRegName = "DMA_S2MM_" + std::to_string(channel) + "_Ctrl";
1196 // DMA control regs live in the memory module; memtile ignores isMem, shim
1197 // is rejected by the verifier.
1198 const AIE::RegisterInfo *ctrlReg =
1199 tm.lookupRegister(ctrlRegName, tile.getTileID(), /*isMem=*/true);
1200 if (!ctrlReg)
1201 return op.emitOpError("target has no ")
1202 << ctrlRegName << " register in its register database";
1203 const AIE::BitFieldInfo *oooField =
1204 ctrlReg->getField("Enable_Out_of_Order");
1205 if (!oooField)
1206 return op.emitOpError()
1207 << ctrlRegName
1208 << " has no Enable_Out_of_Order field in the register database";
1209 std::optional<uint32_t> oooMask = tm.getFieldMask(*oooField);
1210 if (!oooMask)
1211 return op.emitOpError()
1212 << ctrlRegName
1213 << " Enable_Out_of_Order field does not fit in a 32-bit register";
1214 std::optional<uint32_t> oooValue = tm.encodeFieldValue(*oooField, 1);
1215 if (!oooValue)
1216 return op.emitOpError()
1217 << ctrlRegName
1218 << " Enable_Out_of_Order field value does not fit in its bit "
1219 "width";
1220
1221 Location loc = op.getLoc();
1222 IntegerAttr colAttr = builder.getI32IntegerAttr(col);
1223 IntegerAttr rowAttr = builder.getI32IntegerAttr(row);
1224 Value addr = createConstantI32(builder, loc, ctrlAddrLocal);
1225 Value val = createConstantI32(builder, loc, *oooValue);
1226 Value mask = createConstantI32(builder, loc, *oooMask);
1227 NpuMaskWrite32Op::create(builder, loc, addr, val, mask, nullptr, colAttr,
1228 rowAttr);
1229 return success();
1230 }
1231
1233 DMAConfigureTaskOp op,
1234 const llvm::DenseMap<Operation *, bool> &onlyPushedOnce) {
1235 OpBuilder builder(op);
1236 AIE::TileOp tile = op.tryGetTileOp();
1237 if (!tile)
1238 return emitUnplacedTileError(op, op);
1239
1240 if (!op.use_empty()) {
1241 auto err = op.emitOpError("Cannot lower while op still has uses.");
1242 mlir::Operation::use_range uses = op.getOperation()->getUses();
1243 for (auto &use : uses) {
1244 err.attachNote(use.getOwner()->getLoc()) << "Used here.";
1245 }
1246 return failure();
1247 }
1248
1249 Region &body = op.getBody();
1251
1252 // Verify each BD block first; subsequent functions rely on them being
1253 // well-formed
1254 for (auto &it : body) {
1255 if (shouldSkipBlock(it)) {
1256 continue;
1257 }
1258 if (failed(verifyNoUnsupportedOpsInBlock(it))) {
1259 return failure();
1260 }
1261 if (failed(verifyBdInBlock(it))) {
1262 return failure();
1263 }
1264 AIE::UseLockOp acquire, release;
1265 if (failed(
1266 AIE::verifyBdLockPair(it, op.getOutOfOrder(), acquire, release)))
1267 return failure();
1268 }
1269
1270 if (op.getOutOfOrder()) {
1271 if (failed(emitOutOfOrderChannelEnable(builder, op, tile)))
1272 return failure();
1273 }
1274
1275 // Hoist next_bd operations into next_bd_id attribute of the dma_bd
1276 runtimeNextBdId.clear();
1277 if (failed(hoistNextBdOpsIntoAttrs(op))) {
1278 return failure();
1279 }
1280
1281 auto channelDir = op.getDirection();
1282 auto packet = op.getPacket();
1283
1284 // One push onto the task queue runs one iteration of a BD's iteration
1285 // dimension; only a push's repeat_count runs the rest. Warn once the
1286 // BDs are known to lower, so an invalid one gets only its error.
1287 SmallVector<std::pair<Location, int64_t>> unrepeatedIterations;
1288 if (onlyPushedOnce.lookup(op)) {
1289 for (auto bd_op : body.getOps<AIE::DMABDOp>()) {
1290 SmallVector<OpFoldResult> sizes = bd_op.getMixedSizes();
1291 std::optional<int64_t> iterations;
1292 if (std::optional<AIE::BDIterationAttr> iter = bd_op.getIteration())
1293 iterations = iter->getSize();
1294 else if (sizes.size() == 4)
1295 iterations = getConstantIntValue(sizes.front());
1296 if (iterations && *iterations > 1)
1297 unrepeatedIterations.emplace_back(bd_op.getLoc(), *iterations);
1298 }
1299 }
1300
1301 // Lower all BDs
1302 for (auto &block : body) {
1303 if (shouldSkipBlock(block)) {
1304 continue;
1305 }
1306 if (failed(rewriteSingleBD(builder, block, tile, op.getChannel(),
1307 channelDir, packet, op.getOutOfOrder()))) {
1308 return failure();
1309 }
1310 }
1311
1312 for (auto [loc, iterations] : unrepeatedIterations)
1313 mlir::emitWarning(loc)
1314 << "iteration dimension of size " << iterations
1315 << " is pushed with repeat_count 0, so only its first iteration "
1316 "runs; set repeat_count = "
1317 << iterations - 1;
1318
1319 op.erase();
1320
1321 return success();
1322 }
1323
1325 AIE::DeviceOp device,
1326 const llvm::DenseMap<Operation *, bool> &onlyPushedOnce) {
1327 WalkResult result = device.walk([&](DMAConfigureTaskOp op) {
1328 if (failed(rewriteSingleDMAConfigureTaskOp(op, onlyPushedOnce))) {
1329 return WalkResult::interrupt();
1330 }
1331 return WalkResult::advance();
1332 });
1333 if (result.wasInterrupted()) {
1334 return failure();
1335 }
1336 return success();
1337 }
1338
1339 // Drop the dead task-index carries left by the dynamic BD pool path once
1340 // awaits have lowered to npu.sync. scf.for/scf.if carry the task value as a
1341 // result purely to hold the await's data dependence on the configure; with
1342 // the await gone that carry is dead but still counts as a use of the
1343 // branch-local configure, blocking its use_empty lowering. scf's own
1344 // canonicalizations remove dead iter-args/results and prune the yields
1345 // feeding them. Run them device-wide but with folding and constant-CSE
1346 // DISABLED, so the static path's byte-golden constant emission is untouched
1347 // -- only the dead scf carries go.
1348 //
1349 // scf's canonicalizations only see one level at a time: a task carried
1350 // through NESTED loops (an outer iter_arg feeding an inner loop's init) is
1351 // never provably dead to either loop in isolation, since each still sees a
1352 // genuine SSA use feeding the other -- even once the whole chain is
1353 // unobserved end to end. RemoveDeadValues performs the cross-region
1354 // liveness analysis (via RegionBranchOpInterface, generic over nesting
1355 // depth) needed to prune that fully; run it as a nested pipeline afterward
1356 // to pick up what the local canonicalizations left behind.
1357 LogicalResult dropDeadTaskCarries(AIE::DeviceOp device) {
1358 // Only a region-carried value can be a dead carry, and a static sequence
1359 // has none; the analysis costs time proportional to the whole device.
1360 if (llvm::none_of(device.getOps<AIE::RuntimeSequenceOp>(), [](auto seq) {
1361 return seq
1362 .walk([](RegionBranchOpInterface) {
1363 return WalkResult::interrupt();
1364 })
1365 .wasInterrupted();
1366 }))
1367 return success();
1368
1369 RewritePatternSet patterns(&getContext());
1370 scf::ForOp::getCanonicalizationPatterns(patterns, &getContext());
1371 scf::IfOp::getCanonicalizationPatterns(patterns, &getContext());
1372 GreedyRewriteConfig config;
1373 config.enableFolding(false).enableConstantCSE(false);
1374 if (failed(applyPatternsGreedily(device, std::move(patterns), config)))
1375 return failure();
1376
1377 OpPassManager pm(AIE::DeviceOp::getOperationName());
1378 pm.addPass(createRemoveDeadValuesPass());
1379 return runPipeline(pm, device);
1380 }
1381
1382 void runOnOperation() override {
1383 AIE::DeviceOp device = getOperation();
1384
1385 // Lower the starts and awaits. Each rewrites one op into ops that need no
1386 // further lowering, so one walk does it.
1387 RewritePatternSet patterns(&getContext());
1388 llvm::DenseMap<Operation *, bool> onlyPushedOnce;
1389 patterns.insert<DMAStartTaskOpPattern>(&getContext(), onlyPushedOnce);
1390 patterns.insert<DMAAwaitTaskOpPattern>(&getContext());
1391 walkAndApplyPatterns(device, std::move(patterns));
1392 // A start or await left unlowered still uses its configure, so lowering
1393 // the configures would only add errors.
1394 bool unlowered = false;
1395 device.walk([&](Operation *op) {
1396 if (isa<DMAStartTaskOp, DMAAwaitTaskOp>(op)) {
1397 op->emitError() << "failed to legalize operation '" << op->getName()
1398 << "'";
1399 unlowered = true;
1400 }
1401 });
1402 if (unlowered)
1403 return signalPassFailure();
1404
1405 // Drop the now-dead task-index carries the awaits held, so the branch-local
1406 // configures they used can reach use_empty and lower below.
1407 if (failed(dropDeadTaskCarries(device)))
1408 signalPassFailure();
1409
1410 // Lower the configuration for the BDs
1411 if (failed(rewriteDMAConfigureTaskOp(device, onlyPushedOnce))) {
1412 signalPassFailure();
1413 }
1414
1415 eraseDeadArith(device);
1416 }
1417};
1418
1419std::unique_ptr<OperationPass<AIE::DeviceOp>>
1421 return std::make_unique<AIEDMATasksToNPUPass>();
1422}
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.
std::optional< uint32_t > encodeFieldValue(const BitFieldInfo &field, uint32_t value) const
Encode a field value with proper bit shifting.
virtual std::optional< uint32_t > getMemLocalBaseAddress(int localCol, int localRow, int memCol, int memRow) const
Return the memory base address (or offset) in the local tile when accessing a neighbor's memory or an...
uint32_t getLocalDmaControlAddress(int col, int row, int channel, AIE::DMAChannelDir direction) const
Return the DMA task-queue register address relative to its tile.
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...
bool isMemTile(int col, int row) const
Return true if the given tile is a Mem tile.
virtual std::optional< uint32_t > getLockLocalBaseIndex(int localCol, int localRow, int lockCol, int lockRow) const
Return the lock base index (or offset) in the local tile when accessing a neighbor's lock or an empty...
std::optional< uint32_t > getFieldMask(const BitFieldInfo &field) const
Compute a 32-bit mask for a register field.
const RegisterInfo * lookupRegister(llvm::StringRef name, TileID tile, bool isMem=false) const
Register Database API - provides access to register and event information for trace configuration and...
virtual uint64_t getDmaBdAddress(int col, int row, uint32_t bd_id, int channel=-1, AIE::DMAChannelDir direction=AIE::DMAChannelDir::MM2S) const =0
Return the array address of the dma buffer descriptor for the given col, row, buffer descriptor id,...
virtual uint32_t getDmaBdAddressOffset(int col, int row) const =0
Return the offset of the base address field within the shim dma buffer descriptor.
bool isShimNOCTile(int col, int row) const
Return true if the given tile is a ShimNOC tile.
virtual uint32_t getMaxLockValue() const =0
Return the maximum value that can be stored in a lock register.
bool usesChannelLocalBdIds(int col, int row, DMAChannelDir direction) const
Control and trace channels always have private, channel-local pools.
virtual uint32_t getAddressGenGranularity() const =0
Return the data bus width of the device.
mlir::LogicalResult verifyRuntimeBdTarget(mlir::Operation *op, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow, xilinx::AIE::DMAChannelDir direction=xilinx::AIE::DMAChannelDir::MM2S)
uint64_t getBdAddressUnit(const AIE::AIETargetModel &targetModel, int col, int row)
Definition AIEUtils.cpp:207
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)
DMAConfigureTaskOp getUniqueReachableConfigure(Value task)
Definition AIEUtils.cpp:563
std::optional< SubviewTraceResult > traceSubviewToBlockArgument(Value value)
Definition AIEUtils.cpp:25
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)
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::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIEDMATasksToNPUPass()
void eraseDeadArith(mlir::Operation *root)
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)
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
bool getReachableConfigures(Value task, SmallVectorImpl< DMAConfigureTaskOp > &configures)
Definition AIEUtils.cpp:527
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)
mlir::LogicalResult verifyBdLockPair(mlir::Block &block, bool outOfOrder, UseLockOp &acquire, UseLockOp &release)
const AIETargetModel & getTargetModel(mlir::Operation *op)
void placeRuntimeLengthDimension(llvm::MutableArrayRef< int64_t > sizes, llvm::MutableArrayRef< int64_t > strides)
void runOnOperation() override
LogicalResult dropDeadTaskCarries(AIE::DeviceOp device)
bool shouldSkipBlock(Block &block)
LogicalResult rewriteSingleBD(OpBuilder &builder, Block &block, AIE::TileOp &tile, int channel, AIE::DMAChannelDir channelDir, std::optional< xilinx::AIE::PacketInfoAttr > packet, bool outOfOrder=false)
void hoistScalarOpsOutOfBdBlocks(DMAConfigureTaskOp op)
LogicalResult rewriteDMAConfigureTaskOp(AIE::DeviceOp device, const llvm::DenseMap< Operation *, bool > &onlyPushedOnce)
LogicalResult verifyNoUnsupportedOpsInBlock(Block &block)
LogicalResult emitOutOfOrderChannelEnable(OpBuilder &builder, DMAConfigureTaskOp op, AIE::TileOp tile)
AIE::DMABDOp getBdForBlock(Block &block)
LogicalResult rewriteSingleBDDynamic(OpBuilder &builder, Block &block, AIE::DMABDOp bd_op, AIE::TileOp &tile, int channel, AIE::DMAChannelDir channelDir, std::optional< xilinx::AIE::PacketInfoAttr > packet, Value runtimeBdId=nullptr, bool outOfOrder=false)
LogicalResult hoistNextBdOpsIntoAttrs(DMAConfigureTaskOp op)
LogicalResult verifyBdInBlock(Block &block)
LogicalResult setAddressForSingleBD(OpBuilder &builder, AIE::DMABDOp &bd_op, AIE::TileOp &tile, int channel, AIE::DMAChannelDir channelDir, OpFoldResult bdId, OpFoldResult lengthField)
lengthField is the value the BD write gave its length field.
llvm::DenseMap< AIE::DMABDOp, Value > runtimeNextBdId
FailureOr< BdTemplateFields > gatherBdTemplateFields(OpBuilder &builder, Block &block, AIE::DMABDOp bd_op, AIE::TileOp &tile, const AIE::AIETargetModel &target_model, std::optional< xilinx::AIE::PacketInfoAttr > packet, bool outOfOrder=false)
LogicalResult rewriteSingleDMAConfigureTaskOp(DMAConfigureTaskOp op, const llvm::DenseMap< Operation *, bool > &onlyPushedOnce)
LogicalResult matchAndRewrite(DMAAwaitTaskOp op, PatternRewriter &rewriter) const override
llvm::DenseMap< Operation *, bool > & onlyPushedOnce
LogicalResult matchAndRewrite(DMAStartTaskOp op, PatternRewriter &rewriter) const override
DMAStartTaskOpPattern(MLIRContext *context, llvm::DenseMap< Operation *, bool > &onlyPushedOnce)
Bit field information for a register.
Bits [shift, shift + width) of register word in a buffer descriptor's register block.
uint32_t place(uint64_t value) const
uint32_t mask() const
The register layout of one tile type's DMA buffer descriptor.
llvm::SmallVector< std::pair< DmaBdField, DmaBdField >, 3 > padFields() const
The (before, after) zero-padding fields, innermost dimension first.
const BitFieldInfo * getField(llvm::StringRef fieldName) const
Lookup a bit field by name, case-insensitively.