38#include "mlir/Dialect/Arith/IR/Arith.h"
39#include "mlir/Dialect/SCF/IR/SCF.h"
40#include "mlir/Dialect/Utils/StaticValueUtils.h"
41#include "mlir/Pass/Pass.h"
42#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/DenseSet.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/Support/MathExtras.h"
46#include "llvm/Support/Threading.h"
54#define GEN_PASS_DEF_AIEASSIGNRUNTIMESEQUENCEBDIDS
55#define GEN_PASS_DEF_AIENORMALIZEDMATASKGROUPS
56#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
65static DMAAwaitTaskOp taskTripleAwait(Operation *operation) {
66 auto configure = dyn_cast_or_null<DMAConfigureTaskLike>(operation);
67 if (!configure || !configure.getBody().hasOneBlock() ||
68 configure.getRepeatCount() || configure.getRepeatCountVal() ||
69 !configure.getIssueToken() || !operation->getResult(0).hasNUses(2))
71 if (
auto concrete = dyn_cast<DMAConfigureTaskOp>(operation);
72 concrete && concrete.getOutOfOrder())
74 auto start = dyn_cast_or_null<DMAStartTaskOp>(operation->getNextNode());
75 auto await = start ? dyn_cast_or_null<DMAAwaitTaskOp>(start->getNextNode())
77 if (!start || !await || start.getTask() != operation->getResult(0) ||
78 await.getTask() != operation->getResult(0) || start.getRepeatCount() ||
79 start.getRepeatCountVal() || start.getNoToken() ||
80 start.hasRepeatParameter())
82 Block &body = configure.getBody().front();
83 if (body.getNumArguments() || body.getOperations().size() != 2 ||
84 !isa<AIE::DMABDOp>(body.front()) || !isa<AIE::EndOp>(body.back()))
86 auto bd = cast<AIE::DMABDOp>(body.front());
87 return bd.getBdId() || bd.getNextBdId() ? DMAAwaitTaskOp() : await;
90struct AIENormalizeDMATaskGroupsPass
91 : xilinx::AIEX::impl::AIENormalizeDMATaskGroupsBase<
92 AIENormalizeDMATaskGroupsPass> {
93 void runOnOperation()
override {
94 getOperation().walk([](DMAAwaitTaskOp await) {
95 if (await.getDeferCompletion() &&
96 (taskTripleAwait(await.getTask().getDefiningOp()) != await ||
97 !taskTripleAwait(await->getNextNode())))
98 await.removeDeferCompletionAttr();
103struct AIEAssignRuntimeSequenceBDIDsPass
104 : xilinx::AIEX::impl::AIEAssignRuntimeSequenceBDIDsBase<
105 AIEAssignRuntimeSequenceBDIDsPass> {
106 using Base = xilinx::AIEX::impl::AIEAssignRuntimeSequenceBDIDsBase<
107 AIEAssignRuntimeSequenceBDIDsPass>;
108 AIEAssignRuntimeSequenceBDIDsPass() =
default;
109 AIEAssignRuntimeSequenceBDIDsPass(
110 const AIEAssignRuntimeSequenceBDIDsOptions &options)
113 llvm::DenseMap<AIE::TileID, BdIdGenerator> gens;
116 static constexpr llvm::StringLiteral kWaitForToken =
117 "wait for it (aiex.npu.sync or aiex.npu.dma_wait on its channel, "
118 "consuming its token).";
119 static constexpr llvm::StringLiteral kNoTokenAdvice =
120 "it issues no token: set issue_token = true and wait for it, or await "
121 "a later token-issuing transfer on its channel.";
125 static bool writesQueue(Operation *op,
126 ArrayRef<DmaQueueModel::ChannelKey> keys) {
127 std::optional<uint32_t> first;
129 if (
auto write = dyn_cast<NpuWrite32Op>(op)) {
130 if (write.getBuffer())
132 first = write.getAbsoluteAddress();
133 }
else if (
auto write = dyn_cast<NpuMaskWrite32Op>(op)) {
134 if (write.getBuffer())
136 first = write.getAbsoluteAddress();
137 }
else if (
auto write = dyn_cast<NpuBlockWriteOp>(op)) {
138 if (write.getBuffer())
140 first = write.getAbsoluteAddress();
141 auto data = dyn_cast<MemRefType>(write.getData().getType());
142 if (!data || !data.hasStaticShape())
144 bytes = data.getNumElements() * data.getElementTypeBitWidth() / 8;
150 const AIETargetModel &tm =
154 key[0], key[1], key[3],
static_cast<AIE::DMAChannelDir
>(key[2]));
155 return queue >= *first && queue < *first + bytes;
159 AIE::DeviceOp configuredDevice;
171 void reserveStaticBds(
AIE::TileID tile, BdIdGenerator &gen) {
172 SmallVector<AIE::DeviceOp, 3> devices{getOperation()};
173 for (AIE::DeviceOp device : {loadedDevice, configuredDevice})
175 devices.push_back(device);
180 gen.
reserveBdId(bd.channel->first, bd.channel->second, bd.id);
189 BdIdGenerator &getGeneratorForTile(AIE::TileOp tile) {
191 auto it = gens.find(
id);
192 if (it == gens.end()) {
193 AIE::DeviceOp device = tile->getParentOfType<AIE::DeviceOp>();
194 it = gens.insert({id, BdIdGenerator(tile.getCol(), tile.getRow(),
195 device.getTargetModel())})
197 reserveStaticBds(
id, it->second);
202 void noteConfigured(SetDeviceOp context) {
203 llvm::SmallPtrSet<Operation *, 16> pending;
204 for (
const auto &entry : liveByTile)
205 for (DMAConfigureTaskOp task : entry.second)
206 if (pushCounts.lookup(task).running)
207 pending.insert(task);
208 for (
const auto &entry : loadState.holdsOn)
209 for (
const auto &hold : entry.second)
210 pending.insert(hold.second.copy);
211 if (!pending.empty()) {
212 SmallVector<Operation *> transfers(pending.begin(), pending.end());
213 llvm::sort(transfers, [](Operation *left, Operation *right) {
214 return left->isBeforeInBlock(right);
217 mlir::emitWarning(context.getLoc())
218 <<
"configures a device while runtime DMA transfers may still be in "
219 "flight; await their completion before reconfiguration";
220 diagnostic.attachNote(transfers.front()->getLoc())
221 <<
"unfinished transfer (" << transfers.size() <<
" pending)";
223 FlatSymbolRefAttr ref = context.getDeviceRefAttr();
224 auto device = SymbolTable::lookupNearestSymbolFrom<AIE::DeviceOp>(
225 getOperation()->getParentOp(), ref);
226 if (!device || device == configuredDevice)
228 configuredDevice = device;
229 for (
auto &[tile, tileGen] : gens) {
230 BdIdGenerator &gen = tileGen;
231 reserveStaticBds(tile, gen);
232 for (DMAConfigureTaskOp task : liveByTile.lookup(tile)) {
233 if (releasedTasks.contains(task) || knownComplete.contains(task) ||
234 provenFinished.contains(task))
236 std::optional<uint32_t> held;
237 task.walk([&](AIE::DMABDOp bd) {
238 if (!held && bd.getBdId() &&
239 gen.
isReserved(task.getChannel(), task.getDirection(),
241 held = *bd.getBdId();
245 auto diag = mlir::emitWarning(context.getLoc())
246 <<
"configures " << ref
247 <<
", whose static DMAs take buffer descriptor ID " << *held
248 <<
" on tile (" << tile.col <<
"," << tile.row
249 <<
"), which a transfer not known to be finished holds";
250 diag.attachNote(task.getLoc()) <<
"the transfer is configured here";
256 llvm::DenseMap<Operation *,
257 std::map<DmaQueueModel::ChannelKey, AIE::DMAStartOp>>
260 std::set<DmaQueueModel::ChannelKey> resetChannels;
262 std::map<DmaQueueModel::ChannelKey, AIE::DMAStartOp> &
263 loopingStartsOf(AIE::DeviceOp device) {
264 auto [it, inserted] = loopingStarts.try_emplace(device);
265 auto &starts = it->second;
268 for (AIE::DmaBody program : device.getOps<AIE::DmaBody>()) {
270 program->walk([&](AIE::DMAStartOp start) {
271 if (start.getEndpoint())
273 llvm::SmallPtrSet<Block *, 8> visited;
274 Block *bd = start.getDest();
275 while (bd && visited.insert(bd).second)
276 bd = bd->getNumSuccessors() == 1 ? bd->getSuccessor(0) :
nullptr;
278 starts.try_emplace({tile.col, tile.row,
279 static_cast<int>(start.getChannelDir()),
280 start.getChannelIndex()},
290 LogicalResult checkNotBehindLoop(DMAStartTaskOp start,
291 DMAConfigureTaskOp cfg) {
295 if (resetChannels.count(key))
298 loopingStartsOf(loadedDevice ? loadedDevice : getOperation());
299 auto it = starts.find(key);
300 if (it == starts.end())
302 InFlightDiagnostic diag =
303 start.emitOpError(
"starts a task on a channel whose static DMA "
304 "program loops forever, so the task never runs; "
305 "end that program's BD chain, or reset the channel "
306 "with aiex.dma_channel_reset first");
307 diag.attachNote(it->second.getLoc()) <<
"the program starts here";
314 AIE::DeviceOp loadedDevice;
316 NpuLoadPdiOp opaqueLoad;
318 llvm::SmallPtrSet<Operation *, 16> unloaded;
322 void noteLoadPdi(NpuLoadPdiOp load) {
323 loadedDevice = loadedBy(load);
324 opaqueLoad = loadedDevice ? NpuLoadPdiOp() : load;
325 configuredDevice = {};
326 resetChannels.clear();
327 for (
auto &[tile, tasks] : liveByTile)
328 for (DMAConfigureTaskOp task : tasks)
329 unloaded.insert(task);
332 pendingAwaitReleases.clear();
333 freedInFlight.clear();
340 LogicalResult rejectRuntimeControlFlow(AIE::RuntimeSequenceOp seq) {
341 WalkResult wr = seq.walk([&](Operation *op) -> WalkResult {
342 if (isa<scf::ForOp, scf::IfOp, scf::WhileOp>(op)) {
344 "Runtime-valued control flow in a runtime sequence is not "
345 "supported by this static BD-ID allocation pass. Either pass "
346 "only constant-valued predicates to scf.for and scf.if so "
347 "`aie-unroll-runtime-sequence-loops` can unroll/fold them, or "
348 "use the dynamic EmitC path instead.");
349 return WalkResult::interrupt();
351 return WalkResult::advance();
353 return failure(wr.wasInterrupted());
367 LogicalResult verifyChannelUsage(AIE::RuntimeSequenceOp seq) {
370 const AIETargetModel &tm =
373 std::map<ChannelKey, int> avail;
376 WalkResult wr = seq.walk([&](Operation *op) -> WalkResult {
377 if (
auto start = dyn_cast<DMAStartTaskOp>(op)) {
378 DMAConfigureTaskOp cfg = start.getTaskOp();
380 return WalkResult::advance();
382 AIE::TileOp tile = cfg.getTileOp();
384 tile.getCol(), tile.getRow(), cfg.getChannel(), cfg.getDirection());
387 bool issuesToken = start.getPushIssueToken(cfg);
388 queue.
push(key, issuesToken);
391 }
else if (
auto await = dyn_cast<DMAAwaitTaskOp>(op)) {
392 DMAConfigureTaskOp cfg = await.getTaskOp();
395 if (!cfg || !cfg.getIssueToken())
396 return WalkResult::advance();
398 int &tokens = avail[key];
401 "awaits a task-completion token on a channel where no "
402 "outstanding token is guaranteed to have been produced; the "
403 "runtime sequence would block here forever. Ensure a prior "
404 "issue_token dma_start_task on the same tile, direction and "
405 "channel reaches this await");
406 return WalkResult::interrupt();
410 }
else if (QueueEffect raw =
rawQueueEffect(op, *deviceState.symbols);
411 raw.
kind == QueueEffect::Kind::Await) {
415 avail[raw.key] = std::max(0, avail[raw.key] - 1);
417 }
else if (raw.kind == QueueEffect::Kind::Push) {
418 avail[raw.key] += raw.issuesToken;
419 queue.
push(raw.key, raw.issuesToken);
421 return WalkResult::advance();
423 return failure(wr.wasInterrupted());
426 LogicalResult validate(AIE::RuntimeSequenceOp seq) {
427 if (!seq.getBody().hasOneBlock())
428 return seq.emitOpError(
429 "requires a single block for static BD allocation");
430 WalkResult unplaced = seq.walk([](DMAConfigureTaskOp cfg) {
431 if (cfg.getTile().getDefiningOp<AIE::TileOp>())
432 return WalkResult::advance();
433 cfg.emitOpError(
"Cannot assign buffer descriptor ids to a DMA task "
434 "whose tile is not placed; run placement first.");
435 return WalkResult::interrupt();
437 if (unplaced.wasInterrupted())
441 if (failed(rejectRuntimeControlFlow(seq)))
443 if (failed(verifyChannelUsage(seq)))
448 LogicalResult allocateConfigure(DMAConfigureTaskOp op) {
449 AIE::TileOp tile = op.getTileOp();
450 BdIdGenerator &gen = getGeneratorForTile(tile);
452 const AIETargetModel &targetModel =
454 uint32_t pool = targetModel.
getBdPoolId(tile.getCol(), tile.getRow(),
455 op.getChannel(), op.getDirection());
458 WalkResult result = op.walk<WalkOrder::PreOrder>([&](AIE::DMABDOp bd_op) {
459 if (bd_op.getBdId().has_value()) {
461 tile.getCol(), tile.getRow(), bd_op.getBdId().value(),
462 op.getChannel(), op.getDirection())) {
463 InFlightDiagnostic diag = bd_op.emitOpError(
"Buffer descriptor ID ")
464 << bd_op.getBdId().value()
465 <<
" cannot be submitted on channel "
468 bool dataDir = op.getDirection() == DMAChannelDir::MM2S ||
469 op.getDirection() == DMAChannelDir::S2MM;
471 targetModel.
getBdPoolId(tile.getCol(), tile.getRow(),
472 op.getChannel(), DMAChannelDir::MM2S) ==
473 targetModel.
getBdPoolId(tile.getCol(), tile.getRow(),
475 DMAChannelDir::S2MM)) {
476 diag <<
" of tile (" << tile.getCol() <<
"," << tile.getRow()
477 <<
"), which partitions its buffer descriptors by channel "
478 "parity: an even channel reaches only the low half of the "
479 "ids and an odd channel only the high half.";
480 return WalkResult::interrupt();
483 tile.getCol(), tile.getRow(), op.getChannel(), op.getDirection());
484 diag <<
" (" << stringifyDMAChannelDir(op.getDirection())
485 <<
") of tile (" << tile.getCol() <<
"," << tile.getRow()
486 <<
"), whose BD pool holds ids " << first <<
" to " << last - 1
488 return WalkResult::interrupt();
490 if (
const HeldBy *held =
491 copyHolding(tile.getTileID(), pool, bd_op.getBdId().value())) {
492 InFlightDiagnostic diag =
493 op.emitOpError(
"Specified buffer descriptor ID ")
494 << bd_op.getBdId().value()
495 <<
" is the one an aiex.npu.dma_memcpy_nd on this tile "
496 "programs, and that copy may still be in flight here. Give "
497 "the task another ID, or retire the copy first: ";
498 diag << (held->issuesToken ? kWaitForToken : kNoTokenAdvice);
499 diag.attachNote(held->copy->getLoc()) <<
"the copy is here";
500 return WalkResult::interrupt();
503 bd_op.getBdId().value()) ||
504 gen.
isReserved(op.getChannel(), op.getDirection(),
505 bd_op.getBdId().value())) {
506 op.emitOpError(
"Specified buffer descriptor ID ")
507 << bd_op.getBdId().value()
508 <<
" is already in use. Release the earlier task first: "
509 "aiex.dma_await_task waits for hardware completion before its "
510 "BDs are reusable. aiex.dma_free_task also releases them but "
511 "does NOT wait, so it is only safe when some other "
512 "synchronization already guarantees that task has finished "
513 "(see programming_guide/section-2/section-2d/DMATasks.md).";
514 return WalkResult::interrupt();
516 checkReallocation(tile, op.getChannel(), op.getDirection(),
517 bd_op.getBdId().value(), bd_op.getLoc());
518 gen.
assignBdId(op.getChannel(), op.getDirection(),
519 bd_op.getBdId().value());
521 return WalkResult::advance();
523 if (result.wasInterrupted())
526 AIE::DMABDOp head = op.getFirstBd();
527 uint32_t headAlignment = DMAStartTaskOp::headBdIdAlignment(op.getResult());
531 SmallVector<int32_t> blocked;
533 auto it = forbidden.find(op);
534 if (it == forbidden.end())
536 for (
auto [
id, copy] : it->second)
538 gen.
assignBdId(op.getChannel(), op.getDirection(),
id);
539 blocked.push_back(
id);
543 unsigned tookBack = 0;
546 result = op.walk<WalkOrder::PreOrder>([&](AIE::DMABDOp bd_op) {
547 if (bd_op.getBdId().has_value())
548 return WalkResult::advance();
551 "needs a buffer descriptor ID, but the aiex.npu.load_pdi "
552 "before it does not name a device in this module, so the "
553 "compiler cannot tell which ids the loaded PDI's static "
554 "DMAs use. Name the loaded device with device_ref = "
555 "@<device>, or give this aie.dma_bd a bd_id that the PDI "
557 .attachNote(opaqueLoad.getLoc())
558 <<
"the PDI is loaded here";
559 return WalkResult::interrupt();
561 uint32_t alignment = bd_op == head ? headAlignment : 1;
562 std::optional<int32_t> next_id =
563 gen.
nextBdId(op.getChannel(), op.getDirection(), alignment);
564 while (!next_id && reclaimBds && succeeded(reclaimFor(op))) {
567 next_id = gen.
nextBdId(op.getChannel(), op.getDirection(), alignment);
572 <<
"Too many simultaneously active buffer descriptors on tile ("
573 << tile.getCol() <<
"," << tile.getRow()
574 <<
"), which supports up to "
579 SmallVector<std::tuple<int32_t, Operation *, bool>> copied;
580 if (
auto it = forbidden.find(op); it != forbidden.end())
581 for (
auto [
id, copy] : it->second)
582 if (llvm::is_contained(blocked,
id))
583 copied.push_back({id, copy,
true});
584 for (
auto [owner, heldPool,
id] : loadState.copyOwned)
585 if (owner == tile.getTileID() && heldPool == pool)
587 {id, copyHolding(tile.getTileID(), pool,
id)->copy,
false});
589 if (!copied.empty()) {
590 diag <<
" Of those, aiex.npu.dma_memcpy_nd ops program "
591 << (copied.size() > 1 ?
"ids " :
"id ");
592 llvm::interleaveComma(
593 copied, diag, [&](
auto &entry) { diag << std::get<0>(entry); });
594 diag <<
" while this task may run (see the notes).";
599 bool otherLiveTask = llvm::any_of(
600 liveByTile[tile.getTileID()],
601 [&](DMAConfigureTaskOp t) { return !releasedTasks.contains(t); });
603 diag <<
" Emit an aiex.dma_await_task to free BDs for reuse; it "
604 "waits for hardware completion, so the recycled ids are no "
605 "longer in flight. aiex.dma_free_task also recycles ids but "
606 "does NOT wait for completion -- using it before the task "
607 "has finished is a race -- so reach for it only when some "
608 "other synchronization already guarantees completion (see "
609 "programming_guide/section-2/section-2d/DMATasks.md).";
610 if (reclaimBds && tookBack)
611 diag <<
" The ids the compiler took back did not cover it, and "
612 "it could not take more: every other task holding one is "
613 "not started yet, is started again later, waits on a "
614 "lock this or a later task releases, or runs on a "
615 "channel whose status it cannot poll.";
617 diag <<
" The compiler could not take any back either: every "
618 "task holding one is not started yet, is started again "
619 "later, waits on a lock this or a later task releases, "
620 "or runs on a channel whose status it cannot poll.";
622 diag <<
" Or let the compiler poll for finished tasks and take "
623 "their ids (reclaim-bds, aiecc --reclaim-runtime-bds), "
624 "provided no task depends on a push issued after it.";
625 }
else if (!copied.empty()) {
626 diag <<
" Every id in use here is an aiex.npu.dma_memcpy_nd copy "
627 "(reclaim-bds does not consider those); retire the ones "
628 "the notes name, or give this task's buffer descriptors "
631 for (
auto [
id, copyOp, isForbidden] : copied) {
632 auto copy = cast<NpuDmaMemcpyNdOp>(copyOp);
633 Diagnostic ¬e = diag.attachNote(copy.getLoc());
634 note <<
"this copy " << (isForbidden ?
"reprograms" :
"holds")
635 <<
" buffer descriptor ID " <<
id
636 << (isForbidden ?
" while the task may run; "
637 :
" until it is retired: ");
642 return WalkResult::interrupt();
644 checkReallocation(tile, op.getChannel(), op.getDirection(), *next_id,
646 bd_op.setBdId(next_id);
647 roundState.assignedHere.push_back(bd_op);
648 return WalkResult::advance();
650 for (int32_t
id : blocked)
651 gen.
freeBdId(op.getChannel(), op.getDirection(),
id);
652 if (result.wasInterrupted())
655 liveByTile[tile.getTileID()].push_back(op);
663 DMAConfigureTaskOp task;
673 struct ChannelPushes {
674 SmallVector<StartedTask, 8> tasks;
677 std::map<DmaQueueModel::ChannelKey, ChannelPushes> startedOnChannel;
678 uint64_t pushCount = 0;
683 unsigned started = 0;
684 unsigned running = 0;
685 uint64_t lastPushOrder = 0;
687 llvm::DenseMap<Operation *, PushCounts> pushCounts;
690 DMAConfigureTaskOp configure;
691 DMAStartTaskOp start;
692 DMAAwaitTaskOp await;
694 struct TaskSchedule {
697 SmallVector<SmallVector<TaskTriple>> chains;
698 SmallVector<std::pair<size_t, bool>> events;
701 static std::optional<TaskTriple> taskTriple(Operation *operation) {
702 auto configure = dyn_cast_or_null<DMAConfigureTaskOp>(operation);
703 auto await = configure ? taskTripleAwait(operation) : DMAAwaitTaskOp();
706 return TaskTriple{configure, cast<DMAStartTaskOp>(configure->getNextNode()),
710 bool fitsNow(DMAConfigureTaskOp configure) {
713 BdIdGenerator available = getGeneratorForTile(configure.getTileOp());
714 for (
auto [
id, copy] : forbidden.lookup(configure))
715 available.
reserveBdId(configure.getChannel(), configure.getDirection(),
718 .
nextBdId(configure.getChannel(), configure.getDirection(),
719 DMAStartTaskOp::headBdIdAlignment(configure.getResult()))
724 allocateDeferredTasks(ArrayRef<TaskTriple> tasks,
725 llvm::function_ref<WalkResult(Operation *)> visit) {
726 std::map<DmaQueueModel::ChannelKey, SmallVector<TaskTriple>> channels;
727 for (TaskTriple task : tasks)
729 TaskSchedule schedule{tasks.front().configure->getBlock(),
730 tasks.back().await->getNextNode(),
733 std::map<DmaQueueModel::ChannelKey, size_t> next;
734 std::map<DmaQueueModel::ChannelKey, std::deque<size_t>> pending;
735 std::map<DmaQueueModel::ChannelKey, size_t> windows;
736 uint32_t depth = getOperation().getTargetModel().getDmaTaskQueueDepth();
737 for (
const auto &[key, list] : channels) {
738 const ChannelPushes &channel = startedOnChannel[key];
740 chainTasks ? 1 : depth - (channel.tasks.size() - channel.finished);
742 auto retire = [&](std::deque<size_t> &queue) -> LogicalResult {
743 size_t index = queue.front();
744 for (TaskTriple task : schedule.chains[index])
745 if (visit(task.await).wasInterrupted())
748 chainTasks ? 1 : depth;
749 schedule.events.emplace_back(index,
true);
753 size_t remaining = tasks.size();
755 bool progress =
false;
756 for (
auto &[key, list] : channels) {
757 size_t &position = next[key];
758 if (position == list.size())
760 auto &queue = pending[key];
761 if (queue.size() >= windows[key] && failed(retire(queue)))
763 SmallVector<TaskTriple> chain;
764 while (position < list.size() && fitsNow(list[position].configure)) {
765 TaskTriple task = list[position];
766 if (!chain.empty() &&
767 (task.configure->getAttrDictionary() !=
768 chain.front().configure->getAttrDictionary() ||
769 task.configure.getPacketAttr() !=
770 chain.front().configure.getPacketAttr()))
772 if (visit(task.configure).wasInterrupted())
774 chain.push_back(task);
782 for (TaskTriple task : chain)
783 if (visit(task.start).wasInterrupted())
785 size_t index = schedule.chains.size();
786 schedule.chains.push_back(std::move(chain));
787 schedule.events.emplace_back(index,
false);
788 queue.push_back(index);
792 auto waiting = llvm::find_if(
793 pending, [](
const auto &entry) {
return !entry.second.empty(); });
794 if (waiting == pending.end() || failed(retire(waiting->second)))
798 for (
auto &[key, queue] : pending)
799 while (!queue.empty())
800 if (failed(retire(queue)))
802 roundState.schedules.push_back(std::move(schedule));
806 static void commitSchedule(TaskSchedule &schedule) {
807 for (
auto &chain : schedule.chains) {
808 TaskTriple first = chain.front();
809 for (TaskTriple task : llvm::drop_begin(chain)) {
810 Operation *end = first.configure.getBody().back().getTerminator();
811 OpBuilder builder(end);
812 AIE::NextBDOp::create(builder, end->getLoc(),
813 &task.configure.getBody().front());
815 first.configure.getBody().getBlocks().splice(
816 first.configure.getBody().end(),
817 task.configure.getBody().getBlocks());
820 task.configure.erase();
824 schedule.after ? schedule.after->getIterator() : schedule.block->end();
825 for (
auto [index, await] : schedule.events) {
826 TaskTriple first = schedule.chains[index].front();
828 first.await.removeDeferCompletionAttr();
829 first.await->moveBefore(schedule.block, insertion);
831 first.configure->moveBefore(schedule.block, insertion);
832 first.start->moveBefore(schedule.block, insertion);
838 bool issuesToken, Operation *origin,
839 AIE::ShimDMAAllocationOp allocation,
840 std::optional<Volume> moved) {
841 uint64_t order = pushCount++;
842 startedOnChannel[key].tasks.push_back({task, origin, issuesToken, order});
844 PushCounts &counts = pushCounts[task];
847 counts.lastPushOrder = order;
851 auto &pushes = loadState.pushesByAllocation[allocation];
852 std::optional<Volume> through =
853 pushes.empty() ?
Volume() : pushes.back().through;
854 if (through && moved)
855 for (
auto [term, bytes] : *moved)
856 (*through)[term] += bytes;
858 through = std::nullopt;
859 pushes.push_back({order, through});
862 llvm::SmallPtrSet<Operation *, 16> knownComplete;
866 llvm::SmallPtrSet<Operation *, 16> provenFinished;
868 llvm::SmallPtrSet<Operation *, 16> reclaimed;
870 llvm::SmallPtrSet<Operation *, 16> releasedTasks;
877 llvm::DenseMap<Operation *, unsigned> positionOf;
878 llvm::DenseMap<Value, unsigned> lastReleaseOf;
879 bool reallocate =
false;
881 SmallVector<AIE::DMABDOp> assignedHere;
882 SmallVector<Operation *> insertedHere;
883 SmallVector<TaskSchedule> schedules;
885 RoundState roundState;
887 void indexLockReleases(AIE::RuntimeSequenceOp seq) {
888 unsigned position = 0;
889 for (Operation &op : seq.getBody().getOps()) {
890 roundState.positionOf[&op] = position++;
891 DMAConfigureTaskOp cfg = dyn_cast<DMAConfigureTaskOp>(op);
892 if (
auto start = dyn_cast<DMAStartTaskOp>(op))
893 cfg = start.getTaskOp();
896 cfg.walk([&](AIE::UseLockOp lock) {
898 roundState.lastReleaseOf[lock.getLock()] = roundState.positionOf[&op];
904 llvm::DenseMap<AIE::TileID, SmallVector<DMAConfigureTaskOp, 16>> liveByTile;
916 using TileBdId = std::tuple<AIE::TileID, uint32_t, int32_t>;
918 NpuDmaMemcpyNdOp copy;
923 llvm::DenseMap<Operation *, SmallVector<std::pair<int32_t, Operation *>>>
927 const HeldBy *copyHolding(
AIE::TileID tile, uint32_t pool, int32_t
id)
const {
928 if (!loadState.copyOwned.contains({tile, pool, id}))
930 return &loadState.holdsOn.find({tile, pool,
id})->second.begin()->second;
934 void releaseTaskBdId(
AIE::TileID tile, BdIdGenerator &gen,
935 DMAConfigureTaskOp task, int32_t
id) {
936 gen.
freeBdId(task.getChannel(), task.getDirection(),
id);
938 gen.
col, gen.
row, task.getChannel(), task.getDirection());
939 if (!loadState.holdsOn.contains({tile, pool, id}))
941 gen.
assignBdId(task.getChannel(), task.getDirection(),
id);
942 loadState.copyOwned.insert({tile, pool,
id});
945 static DMAStartTaskOp startAfter(DMAConfigureTaskOp task, Operation *op) {
946 DMAStartTaskOp first;
947 for (Operation *user : task.getResult().getUsers())
948 if (
auto start = dyn_cast<DMAStartTaskOp>(user);
949 start && start->getBlock() == op->getBlock() &&
950 op->isBeforeInBlock(start) &&
951 (!first || start->isBeforeInBlock(first)))
958 LogicalResult holdCopy(NpuDmaMemcpyNdOp copy,
961 AIE::ShimDMAAllocationOp allocation = allocationOf(copy);
962 AIE::TileOp tile = allocation.getTileOp();
964 auto id =
static_cast<int32_t
>(copy.getId());
965 auto staticConflict = [&]() -> LogicalResult {
966 InFlightDiagnostic diag =
967 copy.emitOpError(
"programs buffer descriptor ID ")
968 <<
id <<
", which a static DMA program on tile (" << tile.getCol()
969 <<
"," << tile.getRow() <<
") already uses; give the copy another ID";
970 SmallVector<AIE::DeviceOp, 3> devices{getOperation()};
971 for (AIE::DeviceOp device : {loadedDevice, configuredDevice})
972 if (device && !llvm::is_contained(devices, device))
973 devices.push_back(device);
974 for (AIE::DeviceOp device : devices)
975 for (AIE::DmaBody program : device.getOps<AIE::DmaBody>())
976 if (program.getTileID() == tileId)
977 program.getDmaBody().walk([&](AIE::DMABDOp bd) {
978 if (bd.getBdId() ==
id)
979 diag.attachNote(bd.getLoc())
980 <<
"the static program's buffer descriptor is here";
984 int channel = allocation.getChannelIndex();
985 AIE::DMAChannelDir dir = allocation.getChannelDir();
986 BdIdGenerator &gen = getGeneratorForTile(tile);
988 return staticConflict();
990 if (
auto held = loadState.holdsOn.find({tileId, pool, id});
991 held != loadState.holdsOn.end() && warnUnsafeBdReuse) {
992 const HeldBy &earlier = held->second.begin()->second;
993 auto [entry, inserted] = copiesOverCopies.try_emplace(
995 CopyOverCopy{id, tile.getCol(), tile.getRow(), earlier.copy->getLoc(),
996 earlier.issuesToken});
997 entry->second.tiles.insert({tile.getCol(), tile.getRow()});
998 entry->second.count++;
1000 loadState.holdsByChannel[key].push_back({order, tileId, pool,
id});
1001 loadState.holdsOn[{tileId, pool,
id}][order] = {copy, issuesToken};
1003 checkReallocation(tile, channel, dir,
id, copy.getLoc());
1005 loadState.copyOwned.insert({tileId, pool,
id});
1008 if (loadState.copyOwned.contains({tileId, pool, id}))
1010 for (DMAConfigureTaskOp task : liveByTile[tileId]) {
1011 if (releasedTasks.contains(task) || unloaded.contains(task))
1015 task.getDirection()) != pool)
1018 task.walk([&](AIE::DMABDOp bd) {
1019 if (bd.getBdId() ==
id)
1024 bool running = pushCounts.lookup(task).running;
1027 bool everStarted = pushCounts.contains(task);
1028 DMAStartTaskOp restart = startAfter(task, copy);
1029 if (!running && !restart)
1031 if (!llvm::is_contained(roundState.assignedHere, held)) {
1032 InFlightDiagnostic diag =
1033 task.emitOpError(
"Specified buffer descriptor ID ") << id;
1035 diag <<
" is the one an aiex.npu.dma_memcpy_nd on this tile "
1036 "programs while this task may be in flight. Give the task "
1037 "another ID, or await it before the copy.";
1038 else if (everStarted)
1039 diag <<
" is the one an aiex.npu.dma_memcpy_nd on this tile "
1040 "programs before this task is started again, so the "
1041 "restart would run the copy's descriptor. Give the task "
1042 "another ID, or configure a new task after the copy.";
1044 diag <<
" is the one an aiex.npu.dma_memcpy_nd on this tile "
1045 "programs after this task's own configure wrote it, so "
1046 "starting the task would launch the copy's descriptor "
1047 "instead of its own. Give the task another ID, or start it "
1049 diag.attachNote(copy.getLoc()) <<
"the copy is here";
1051 diag.attachNote(restart.getLoc())
1052 << (everStarted ?
"the task is started again here"
1053 :
"the task starts here, after the copy");
1056 assert(llvm::none_of(forbidden[task],
1057 [&](
auto &entry) {
return entry.first == id; }) &&
1058 "a forbidden id was handed out again");
1059 forbidden[task].push_back({id, copy});
1060 roundState.reallocate =
true;
1065 return staticConflict();
1069 auto holds = loadState.holdsByChannel.find(key);
1070 if (holds == loadState.holdsByChannel.end())
1072 const ChannelPushes &channel = startedOnChannel[key];
1073 std::optional<uint64_t> oldest;
1074 if (channel.finished < channel.tasks.size())
1075 oldest = channel.tasks[channel.finished].order;
1076 while (!holds->second.empty() &&
1077 (!oldest || holds->second.front().order < *oldest)) {
1078 CopyHold hold = holds->second.front();
1079 holds->second.pop_front();
1080 auto on = loadState.holdsOn.find({hold.tile, hold.pool, hold.id});
1081 on->second.erase(hold.order);
1082 if (!on->second.empty())
1084 loadState.holdsOn.erase(on);
1085 if (loadState.copyOwned.erase({hold.tile, hold.pool, hold.id}))
1086 gens.find(hold.tile)->second.freeBdId(
1087 key[3],
static_cast<AIE::DMAChannelDir
>(key[2]), hold.id);
1093 struct ReleasedTask {
1094 DMAConfigureTaskOp configure;
1097 std::map<std::pair<int, int>,
1098 std::map<std::pair<uint32_t, uint32_t>, ReleasedTask>>
1105 ChannelPushes &channel = startedOnChannel[key];
1106 auto &started = channel.tasks;
1107 auto *it = llvm::find_if(
1108 started, [](
const StartedTask &s) {
return s.issuesToken; });
1109 if (it == started.end())
1111 size_t retired = std::distance(started.begin(), it) + 1;
1112 for (
size_t i = 0; i < retired; ++i)
1113 if (DMAConfigureTaskOp task = started[i].task) {
1114 --pushCounts[task].started;
1115 if (i >= channel.finished)
1116 --pushCounts[task].running;
1118 for (
size_t i = 0; i < retired; ++i)
1119 if (DMAConfigureTaskOp task = started[i].task)
1120 if (pushCounts.lookup(task).started == 0)
1121 knownComplete.insert(task);
1124 SmallVector<std::pair<AIE::ShimDMAAllocationOp, uint64_t>> newest;
1125 for (
const StartedTask &push :
1126 llvm::reverse(llvm::make_range(started.begin(), std::next(it))))
1127 if (AIE::ShimDMAAllocationOp output =
1128 push.task ? allocationOf(push.task)
1129 : allocationOf(dyn_cast<NpuDmaMemcpyNdOp>(push.origin)))
1130 if (llvm::none_of(newest,
1131 [&](
auto &seen) {
return seen.first == output; }))
1132 newest.push_back({output, push.order});
1133 started.erase(started.begin(), std::next(it));
1134 channel.finished -= std::min(channel.finished, retired);
1135 for (
auto [output, order] : newest)
1136 creditInputs(output, order);
1137 releaseRetiredCopies(key);
1144 ChannelPushes &channel = startedOnChannel[key];
1145 if (channel.tasks.size() <= unfinished)
1147 for (
size_t done = channel.tasks.size() - unfinished;
1148 channel.finished < done; ++channel.finished)
1149 if (DMAConfigureTaskOp task = channel.tasks[channel.finished].task)
1150 if (--pushCounts[task].running == 0)
1151 provenFinished.insert(task);
1152 releaseRetiredCopies(key);
1158 AIE::ConsumedByAttr proof) {
1159 int64_t granule = proof.getGranuleBytes();
1160 Volume counted = received;
1162 counted[-1] -= granule - 1;
1170 bool nonNegative(AIE::RuntimeSequenceOp seq, int64_t index) {
1171 auto [it, inserted] = deviceState.nonNegativeByIndex.try_emplace(
1172 {seq.getOperation(), index},
false);
1175 auto module = getOperation()->getParentOfType<ModuleOp>();
1178 ArrayAttr reads = seq.getScratchpadParametersAttr();
1179 bool found =
false, held =
true;
1180 for (
auto parameter : module.getOps<ScratchpadParameterOp>()) {
1181 if (parameter.getStateTableIdx() != index ||
1183 !llvm::is_contained(reads.getAsValueRange<FlatSymbolRefAttr>(),
1184 parameter.getSymName())))
1186 std::optional<int32_t> min = parameter.getMinValue();
1188 held &= min && *min >= 0;
1190 it->second = found && held;
1197 std::optional<Volume> pushVolume(DMAStartTaskOp start,
1198 DMAConfigureTaskOp cfg) {
1199 std::optional<int64_t> repeat =
1200 start.hasRepeatParameter()
1202 : getConstantIntValue(start.getPushRepeatCount(cfg));
1203 Region &body = cfg.getBody();
1204 if (!repeat || *repeat < 0 || body.empty())
1205 return std::nullopt;
1207 llvm::SmallPtrSet<Block *, 8> seen;
1208 for (Block *block = &body.front(); block;) {
1209 if (!seen.insert(block).second)
1210 return std::nullopt;
1211 for (AIE::DMABDOp bd : block->getOps<AIE::DMABDOp>()) {
1212 std::optional<int64_t> len = bd.getStaticLenInBytes();
1213 if (!len || bd.getIteration() || bd.getNextBdId() ||
1214 bd.getLengthParameterAttr())
1215 return std::nullopt;
1216 int64_t width = bd.getBufferElementTypeWidthInBytes();
1218 if (std::optional<uint8_t> index = bd.getLengthStateTableIdx()) {
1219 std::optional<int32_t> unit = bd.getLengthUnit();
1221 !nonNegative(start->getParentOfType<AIE::RuntimeSequenceOp>(),
1223 return std::nullopt;
1224 bytes[*index] +=
static_cast<int64_t
>(*unit) * width;
1227 auto next = dyn_cast<AIE::NextBDOp>(block->getTerminator());
1228 block = next ? next.getDest() :
nullptr;
1230 for (
auto &[key, coefficient] : bytes)
1231 if (llvm::MulOverflow(coefficient, *repeat + 1, coefficient))
1232 return std::nullopt;
1238 static std::optional<Volume> copyVolume(NpuDmaMemcpyNdOp copy) {
1239 std::optional<int64_t> bytes = copy.getStaticBytesStreamed();
1241 return std::nullopt;
1243 volume[-1] = *bytes;
1250 struct DeviceState {
1253 std::optional<SymbolTable> symbols;
1257 SmallVector<std::pair<AIE::ShimDMAAllocationOp, AIE::ConsumedByAttr>>>
1262 llvm::DenseMap<std::pair<Operation *, Operation *>,
bool> balancedPairs;
1264 llvm::DenseMap<std::pair<Operation *, int64_t>,
bool> nonNegativeByIndex;
1266 DeviceState deviceState;
1269 AIE::ShimDMAAllocationOp allocationOf(DMAConfigureTaskOp cfg) {
1270 FlatSymbolRefAttr alloc = cfg.getAllocAttr();
1272 return alloc ? deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
1278 AIE::ShimDMAAllocationOp allocationOf(NpuDmaMemcpyNdOp copy) {
1282 return deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
1283 copy.getMetadata().getRootReference());
1289 struct AllocationPush {
1291 std::optional<Volume> through;
1297 std::optional<Volume> through;
1298 uint64_t pushesBefore;
1303 llvm::DenseMap<Operation *, SmallVector<AllocationPush>> pushesByAllocation;
1306 llvm::DenseMap<std::pair<Operation *, Operation *>,
size_t> creditedPushes;
1307 llvm::DenseMap<Operation *, Awaited> awaitedThrough;
1308 std::map<DmaQueueModel::ChannelKey, std::deque<CopyHold>> holdsByChannel;
1309 llvm::DenseMap<TileBdId, std::map<uint64_t, HeldBy>> holdsOn;
1310 llvm::DenseSet<TileBdId> copyOwned;
1312 LoadState loadState;
1322 bool leavesNothing(AIE::ShimDMAAllocationOp input,
1323 AIE::ShimDMAAllocationOp output,
1324 AIE::ConsumedByAttr proof) {
1325 auto entry = deviceState.balancedPairs.try_emplace({input, output},
true);
1327 entry.first->second = llvm::all_of(
1328 getOperation().getOps<AIE::RuntimeSequenceOp>(),
1329 [&](AIE::RuntimeSequenceOp seq) {
1330 return stretchesUnbalanced(seq,
nullptr, proofDevice(proof), input,
1331 output, {input}, {output},
1332 proof) == Unbalanced::No;
1334 return entry.first->second;
1339 AIE::DeviceOp proofDevice(AIE::ConsumedByAttr proof) {
1340 FlatSymbolRefAttr device = proof.getDevice();
1341 Operation *module = getOperation()->getParentOp();
1343 return getOperation();
1344 return module ? SymbolTable::lookupNearestSymbolFrom<AIE::DeviceOp>(module,
1350 AIE::DeviceOp loadedBy(NpuLoadPdiOp load) {
1351 FlatSymbolRefAttr ref = load.getDeviceRefAttr();
1352 Operation *module = getOperation()->getParentOp();
1353 return ref && module ? SymbolTable::lookupNearestSymbolFrom<AIE::DeviceOp>(
1368 Operation *where =
nullptr;
1372 AIE::RuntimeSequenceOp seq, Operation *from, AIE::DeviceOp target,
1373 AIE::ShimDMAAllocationOp input, AIE::ShimDMAAllocationOp output,
1374 ArrayRef<AIE::ShimDMAAllocationOp> inputs,
1375 ArrayRef<AIE::ShimDMAAllocationOp> outputs, AIE::ConsumedByAttr proof,
1376 bool byChannel =
false, Verdict *at =
nullptr) {
1379 auto fromLoad = dyn_cast_or_null<NpuLoadPdiOp>(from);
1380 AIE::DeviceOp loaded = fromLoad ? loadedBy(fromLoad) : getOperation();
1381 bool counting = !from;
1384 seq.walk([&](Operation *op) {
1387 return WalkResult::advance();
1390 return WalkResult::advance();
1391 if (
auto load = dyn_cast<NpuLoadPdiOp>(op)) {
1392 if (target && loaded == target)
1394 if (why != Unbalanced::No) {
1396 *at = {op, in, out};
1397 return WalkResult::interrupt();
1401 loaded = loadedBy(load);
1402 return WalkResult::advance();
1404 if (!target || loaded != target)
1405 return WalkResult::advance();
1406 auto start = dyn_cast<DMAStartTaskOp>(op);
1407 DMAConfigureTaskOp cfg = start ? start.getTaskOp() :
nullptr;
1408 auto copy = dyn_cast<NpuDmaMemcpyNdOp>(op);
1409 AIE::ShimDMAAllocationOp allocation =
1410 cfg ? allocationOf(cfg) : allocationOf(copy);
1411 std::optional<DmaQueueModel::ChannelKey> channel;
1414 else if (QueueEffect raw =
rawQueueEffect(op, *deviceState.symbols);
1415 raw.
kind == QueueEffect::Kind::Push)
1417 bool circuit = byChannel && allocation && !allocation.getPacket();
1419 llvm::is_contained(inputs, allocation) ||
1420 (circuit && channel && *channel == inKey && !input.getPacket());
1422 llvm::is_contained(outputs, allocation) ||
1423 (circuit && channel && *channel == outKey && !output.getPacket());
1424 if ((channel && ((*channel == inKey && !isInput) ||
1425 (*channel == outKey && !isOutput))) ||
1426 writesQueue(op, {inKey, outKey})) {
1427 why = Unbalanced::Traffic;
1429 *at = {op, in, out};
1430 return WalkResult::interrupt();
1432 if (!allocation || (!isInput && !isOutput))
1433 return WalkResult::advance();
1436 std::optional<Volume> moved = op->getParentOp() != seq ? std::nullopt
1437 : cfg ? pushVolume(start, cfg)
1440 why = Unbalanced::Unsized;
1442 *at = {op, in, out};
1443 return WalkResult::interrupt();
1445 for (
auto [key, bytes] : *moved)
1446 (isInput ? in : out)[key] += bytes;
1447 return WalkResult::advance();
1449 if (why == Unbalanced::No && target && loaded == target)
1451 if (at && why != Unbalanced::No && !at->where)
1452 *at = {nullptr, in, out};
1461 LogicalResult checkForeignTail(AIE::RuntimeSequenceOp seq) {
1463 for (
auto load : seq.getOps<NpuLoadPdiOp>())
1465 AIE::DeviceOp loaded = last ? loadedBy(last) : AIE::DeviceOp();
1466 if (!loaded || loaded == getOperation())
1468 SmallVector<std::tuple<AIE::ShimDMAAllocationOp, AIE::ShimDMAAllocationOp,
1471 for (
auto input : loaded.getOps<AIE::ShimDMAAllocationOp>()) {
1472 ArrayAttr proofs = input.getConsumedByAttr();
1475 for (auto proof : proofs.getAsRange<AIE::ConsumedByAttr>()) {
1476 auto output = AIE::ShimDMAAllocationOp::getForSymbol(
1477 loaded, proof.getOutput().getValue());
1478 if (!output || proof.getDevice())
1480 SmallVector<AIE::ShimDMAAllocationOp> inputs, outputs;
1481 for (auto copy : getOperation().getOps<AIE::ShimDMAAllocationOp>()) {
1482 ArrayAttr copied = copy.getConsumedByAttr();
1484 DmaQueueModel::keyOf(copy) != DmaQueueModel::keyOf(input))
1486 for (auto cp : copied.getAsRange<AIE::ConsumedByAttr>()) {
1487 if (proofDevice(cp) != loaded)
1490 auto out = deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
1491 cp.getOutput().getAttr());
1493 DmaQueueModel::keyOf(out) == DmaQueueModel::keyOf(output)) {
1494 inputs.push_back(copy);
1495 outputs.push_back(out);
1499 Unbalanced why = stretchesUnbalanced(seq, last, loaded, input, output,
1500 inputs, outputs, proof,
1502 if (why != Unbalanced::No)
1503 unbalanced.push_back({input, output, why});
1507 llvm::stable_sort(unbalanced, [&](
const auto &a,
const auto &b) {
1513 for (
auto [input, output, why] : unbalanced) {
1514 auto diag = last.emitOpError()
1515 <<
"leaves " << last.getDeviceRefAttr()
1516 <<
" loaded, and its next dispatch, whose proof that @"
1517 << input.getSymName() <<
" is consumed by @"
1518 << output.getSymName()
1519 <<
" counts on a clean start, finds what this "
1520 "sequence's last stretch left: it ";
1521 if (why == Unbalanced::Excess)
1522 diag <<
"moves more through that input than the output proves "
1524 else if (why == Unbalanced::PartGranule)
1525 diag <<
"may end with the output partway through an object of the "
1526 "join the proof passes";
1527 else if (why == Unbalanced::Traffic)
1528 diag <<
"has other traffic on their channels";
1530 diag <<
"moves bytes on their channels whose count is not known, "
1531 "so cannot be proven balanced";
1532 diag <<
". Balance them before the sequence ends, or load this "
1533 "device's PDI again.";
1535 return failure(!unbalanced.empty());
1540 void creditInputs(AIE::ShimDMAAllocationOp output, uint64_t order) {
1541 auto outPushes = loadState.pushesByAllocation.find(output);
1542 auto proofs = deviceState.proofsByOutput.find(output);
1543 if (outPushes == loadState.pushesByAllocation.end() ||
1544 proofs == deviceState.proofsByOutput.end())
1546 auto byOrder = [](
const auto &push, uint64_t bound) {
1547 return push.order < bound;
1549 const AllocationPush *done =
1550 llvm::lower_bound(outPushes->second, order, byOrder);
1551 if (done == outPushes->second.end() || done->order != order)
1553 loadState.awaitedThrough[output] = {done->through, pushCount};
1556 AIE::DeviceOp configured = opaqueLoad ? AIE::DeviceOp()
1557 : loadedDevice ? loadedDevice
1559 for (
auto [input, proof] : proofs->second) {
1560 if (!configured || proofDevice(proof) != configured)
1562 auto inPushes = loadState.pushesByAllocation.find(input);
1563 DmaQueueModel::ChannelKey key = DmaQueueModel::keyOf(input);
1564 if (inPushes == loadState.pushesByAllocation.end() ||
1565 !leavesNothing(input, output, proof))
1567 ArrayRef<AllocationPush> pushes = inPushes->second;
1568 size_t &credited = loadState.creditedPushes[{input, output}];
1569 size_t covered = credited;
1570 Volume counted = countedOutput(*done->through, proof);
1571 for (; covered < pushes.size(); ++covered) {
1572 const std::optional<Volume> &through = pushes[covered].through;
1573 if (!through || !
atMost(*through, proof.getOutputBytes(), counted,
1574 proof.getInputBytes()))
1577 if (covered == credited)
1580 auto &tasks = startedOnChannel[key].tasks;
1581 const StartedTask *at =
1582 llvm::lower_bound(tasks, pushes[covered - 1].order, byOrder);
1583 if (at != tasks.end() && at->order == pushes[covered - 1].order)
1584 noteDrained(key, tasks.end() - at - 1);
1592 void notePoll(NpuMaskPollOp poll) {
1593 std::optional<uint32_t> address = poll.getAbsoluteAddress();
1600 if (!address || !mask || !value || !field)
1602 for (
const auto &[key, channel] : startedOnChannel) {
1604 static_cast<AIE::DMAChannelDir
>(key[2])) !=
1607 if (idle && (*mask & idle) == idle && (*value & idle) == 0)
1608 return noteDrained(key, 0);
1609 unsigned shift = llvm::countr_zero(field);
1611 for (uint32_t size = 0; size <= field >> shift; ++size)
1612 if (((size << shift) & *mask & field) == (*value & *mask & field))
1614 return noteDrained(key, bound + 1);
1621 void noteFreedInFlight(DMAConfigureTaskOp cfg, Operation *freeOp) {
1622 if (!pushCounts.lookup(cfg).started)
1624 AIE::TileOp tile = cfg.getTileOp();
1625 auto &ids = freedInFlight[{tile.getCol(), tile.getRow()}];
1627 tile.getCol(), tile.getRow(), cfg.getChannel(), cfg.getDirection());
1628 cfg.walk([&](AIE::DMABDOp bd) {
1629 if (bd.getBdId().has_value())
1630 ids[{pool, bd.getBdId().value()}] = {cfg, freeOp};
1636 void printVolume(llvm::raw_ostream &os,
const Volume &bytes, int64_t scale,
1637 AIE::RuntimeSequenceOp seq) {
1638 auto constant = bytes.find(-1);
1639 int64_t constantValue =
1640 constant == bytes.end() ? 0 : constant->second * scale;
1641 bool hasTerm = llvm::any_of(
1642 bytes, [](
const auto &term) {
return term.first >= 0 && term.second; });
1643 bool printed =
false;
1644 if (constantValue || !hasTerm) {
1645 os << constantValue;
1648 for (
const auto &term : bytes) {
1649 if (term.first < 0 || !term.second)
1653 int64_t coefficient = term.second * scale;
1654 if (coefficient != 1)
1655 os << coefficient <<
"*";
1656 printParameter(os, term.first, seq);
1661 void printParameter(llvm::raw_ostream &os, int64_t index,
1662 AIE::RuntimeSequenceOp seq) {
1663 auto module = getOperation()->getParentOfType<ModuleOp>();
1664 ArrayAttr reads = seq.getScratchpadParametersAttr();
1666 for (
auto parameter : module.getOps<ScratchpadParameterOp>())
1667 if (parameter.getStateTableIdx() == index &&
1669 llvm::is_contained(reads.getAsValueRange<FlatSymbolRefAttr>(),
1670 parameter.getSymName()))) {
1671 os <<
"@" << parameter.getSymName();
1674 os <<
"parameter " << index;
1680 void explainUnproven(DMAConfigureTaskOp task,
1681 SmallVectorImpl<std::string> &why,
1682 SmallVectorImpl<std::pair<Location, std::string>> &at) {
1683 AIE::ShimDMAAllocationOp input = allocationOf(task);
1684 ArrayAttr proofs = input ? input.getConsumedByAttr() : ArrayAttr();
1686 why.push_back(
"it names no shim allocation, so no output's progress "
1687 "can prove it consumed");
1690 if (!proofs || proofs.empty()) {
1693 llvm::raw_string_ostream os(clause);
1694 os <<
"aie-objectfifo-verify found no output whose progress proves @"
1695 << input.getSymName() <<
" consumed";
1697 why.push_back(std::move(clause));
1700 auto seq = task->getParentOfType<AIE::RuntimeSequenceOp>();
1701 AIE::DeviceOp configured = opaqueLoad ? AIE::DeviceOp()
1702 : loadedDevice ? loadedDevice
1705 SmallVector<std::pair<int64_t, AIE::RuntimeSequenceOp>> exceeding;
1706 auto explainProof = [&](AIE::ConsumedByAttr proof, llvm::raw_ostream &os) {
1707 auto output = deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
1708 proof.getOutput().getAttr());
1709 os <<
"through " << proof.getOutput() <<
", ";
1711 os <<
"that output is not in this device";
1714 if (!configured || proofDevice(proof) != configured) {
1715 os <<
"the proof describes the array of "
1716 << (proof.getDevice()
1718 : FlatSymbolRefAttr::get(getOperation().getSymNameAttr()))
1719 <<
", which is not the one loaded";
1722 if (!leavesNothing(input, output, proof)) {
1723 for (
auto other : getOperation().getOps<AIE::RuntimeSequenceOp>()) {
1726 other,
nullptr, proofDevice(proof), input, output, {input},
1727 {output}, proof,
false, &verdict);
1728 Operation *where = verdict.where;
1733 os <<
"another transfer shares their channels, which the "
1734 "counts do not describe";
1735 note =
"the other transfer";
1737 os <<
"a stretch of @" << other.getSymName()
1738 <<
" may end with the output partway through an object of "
1739 "the join the proof passes ("
1740 << proof.getGranuleBytes()
1741 <<
" output bytes), whose later segments it has then taken "
1743 note =
"the stretch ends here";
1745 os <<
"a transfer on them moves a byte count the compiler "
1746 "cannot follow (a BD chain, a loop, or a length "
1747 "parameter without min_value >= 0)";
1748 note =
"the transfer";
1750 bool scaled = proof.getInputBytes() != proof.getOutputBytes();
1751 os <<
"a stretch of @" << other.getSymName()
1752 <<
" can end having moved more through the input than the "
1753 "output proves taken, so the next dispatch's counts do "
1754 "not start clean (input bytes";
1756 os <<
" times " << proof.getOutputBytes();
1758 printVolume(os, verdict.in, proof.getOutputBytes(), other);
1759 os <<
", against output bytes";
1761 os <<
" times " << proof.getInputBytes();
1763 printVolume(os, verdict.out, proof.getInputBytes(), other);
1766 for (
const auto &term : verdict.in) {
1767 int64_t index = term.first;
1768 auto taken = verdict.out.find(index);
1770 term.second * proof.getOutputBytes() >
1771 (taken == verdict.out.end() ? 0 : taken->second) *
1772 proof.getInputBytes() &&
1773 llvm::none_of(exceeding, [&](
const auto &seen) {
1774 return seen.first == index;
1776 exceeding.push_back({index, other});
1778 note =
"the stretch ends here";
1780 std::pair<Location, std::string> pointer = {
1781 where ? where->getLoc() : other.getLoc(), note};
1782 if (!llvm::is_contained(at, pointer))
1783 at.push_back(pointer);
1787 auto pushes = loadState.pushesByAllocation.find(input);
1788 auto order = pushCounts.find(task);
1789 const AllocationPush *push =
1790 pushes == loadState.pushesByAllocation.end() ||
1791 order == pushCounts.end()
1793 : llvm::find_if(pushes->second, [&](
const AllocationPush &p) {
1794 return p.order == order->second.lastPushOrder;
1796 if (!push || push == pushes->second.end() || !push->through) {
1797 os <<
"the bytes the input has moved up to this transfer are not "
1801 auto awaited = loadState.awaitedThrough.find(output);
1802 if (awaited == loadState.awaitedThrough.end()) {
1803 os <<
"no await on it has retired a transfer yet";
1806 if (awaited->second.pushesBefore <= push->order) {
1807 os <<
"no await on it has retired a transfer since this one was "
1811 const std::optional<Volume> &taken = awaited->second.through;
1813 os <<
"the bytes its awaited transfers moved are not known";
1816 Volume counted = countedOutput(*taken, proof);
1817 if (
atMost(*push->through, proof.getOutputBytes(), counted,
1818 proof.getInputBytes())) {
1819 os <<
"its awaited transfers cover this transfer's bytes, but "
1820 "not those of every push of this task";
1823 bool scaled = proof.getInputBytes() != proof.getOutputBytes();
1824 os <<
"the bytes its awaited transfers moved";
1826 os <<
", less the part of an object of the join the proof passes ("
1827 << proof.getGranuleBytes() <<
" bytes) they may end in,";
1829 os <<
" times " << proof.getInputBytes();
1831 printVolume(os, counted, proof.getInputBytes(), seq);
1832 os <<
", fall short of the bytes the input moved up to this "
1835 os <<
" times " << proof.getOutputBytes();
1837 printVolume(os, *push->through, proof.getOutputBytes(), seq);
1838 auto isParameter = [](
auto term) {
return term.first >= 0; };
1839 if (llvm::any_of(counted, isParameter) ||
1840 llvm::any_of(*push->through, isParameter))
1841 os <<
", for some parameter values";
1843 for (AIE::ConsumedByAttr proof : proofs.getAsRange<AIE::ConsumedByAttr>()) {
1846 llvm::raw_string_ostream os(clause);
1847 explainProof(proof, os);
1849 why.push_back(std::move(clause));
1851 if (proofs.size() > 1 && excess == proofs.size()) {
1854 llvm::raw_string_ostream os(clause);
1855 os <<
"no one output's proof covers the input: it moves more than "
1856 "each proves alone";
1857 if (!exceeding.empty()) {
1858 os <<
", by how much depending on the runtime parameter";
1859 if (exceeding.size() > 1)
1862 llvm::interleaveComma(exceeding, os, [&](const auto ¶meter) {
1863 printParameter(os, parameter.first, parameter.second);
1867 why.push_back(std::move(clause));
1873 void checkReallocation(AIE::TileOp tile,
int channel, AIE::DMAChannelDir dir,
1874 uint32_t
id, Location at) {
1875 if (!warnUnsafeBdReuse)
1877 auto tileIt = freedInFlight.find({tile.getCol(), tile.getRow()});
1878 if (tileIt == freedInFlight.end())
1881 tile.getCol(), tile.getRow(), channel, dir);
1882 auto idIt = tileIt->second.find({pool,
id});
1883 if (idIt == tileIt->second.end())
1885 ReleasedTask released = idIt->second;
1886 tileIt->second.erase(idIt);
1887 if (knownComplete.contains(released.configure) ||
1888 provenFinished.contains(released.configure))
1890 auto [entry, inserted] = unsafeReuses.try_emplace(
1891 at, UnsafeReuse{id, tile.getCol(), tile.getRow(), {}});
1892 UnsafeReuse &reuse = entry->second;
1894 explainUnproven(released.configure, reuse.why, reuse.notes);
1895 if (!llvm::is_contained(reuse.freeLocs, released.freeOp->getLoc()))
1896 reuse.freeLocs.push_back(released.freeOp->getLoc());
1897 reuse.tiles.insert({tile.getCol(), tile.getRow()});
1906 struct UnsafeReuse {
1909 SmallVector<Location> freeLocs;
1910 std::set<std::pair<int, int>> tiles = {};
1912 SmallVector<std::string> why = {};
1913 SmallVector<std::pair<Location, std::string>> notes = {};
1915 llvm::MapVector<Location, UnsafeReuse> unsafeReuses;
1918 struct CopyOverCopy {
1922 bool earlierIssuesToken;
1923 std::set<std::pair<int, int>> tiles = {};
1926 llvm::MapVector<Location, CopyOverCopy> copiesOverCopies;
1928 void emitUnsafeReuses() {
1929 for (
auto &[loc, reuse] : unsafeReuses) {
1933 mlir::emitWarning(loc)
1934 <<
"reuses buffer descriptor ID " << reuse.id <<
" on tile ("
1935 << reuse.col <<
"," << reuse.row
1936 <<
") after it was released by an aiex.dma_free_task that had no "
1937 "completion guarantee, so the DMA it belonged to may still be "
1938 "running and this reprograms it underneath. Consume the "
1939 "outstanding tokens on the same tile, direction and channel "
1940 "through a task queued at or after this transfer -- each await "
1941 "consumes the oldest token, regardless of the task it names.";
1942 for (
const std::string &why : reuse.why)
1943 diag.attachNote() <<
"not proven finished: " << why;
1944 for (Location freeLoc : reuse.freeLocs)
1945 diag.attachNote(freeLoc) <<
"released here";
1946 for (
auto &[noteLoc, text] : reuse.notes)
1947 diag.attachNote(noteLoc) << text;
1948 if (reuse.count > 1) {
1949 Diagnostic ¬e = diag.attachNote();
1950 note <<
"and " << reuse.count - 1
1951 <<
" more times from this transfer, on tile"
1952 << (reuse.tiles.size() > 1 ?
"s " :
" ");
1953 llvm::interleaveComma(reuse.tiles, note, [&](
auto tile) {
1954 note <<
"(" << tile.first <<
"," << tile.second <<
")";
1958 unsafeReuses.clear();
1959 for (
auto &[loc, reuse] : copiesOverCopies) {
1960 auto diag = mlir::emitWarning(loc)
1961 <<
"reuses buffer descriptor ID " << reuse.id <<
" on tile ("
1962 << reuse.col <<
"," << reuse.row
1963 <<
") while an earlier aiex.npu.dma_memcpy_nd of that ID may "
1964 "still be in flight, so this reprograms it underneath. "
1965 "Give this copy another ID, or retire the earlier copy "
1967 diag << (reuse.earlierIssuesToken ? kWaitForToken : kNoTokenAdvice);
1968 diag.attachNote(reuse.earlier) <<
"the earlier copy is here";
1969 if (reuse.count > 1) {
1970 Diagnostic ¬e = diag.attachNote();
1971 note <<
"and " << reuse.count - 1
1972 <<
" more times from this copy, on tile"
1973 << (reuse.tiles.size() > 1 ?
"s " :
" ");
1974 llvm::interleaveComma(reuse.tiles, note, [&](
auto tile) {
1975 note <<
"(" << tile.first <<
"," << tile.second <<
")";
1979 copiesOverCopies.clear();
1987 llvm::SmallPtrSet<Operation *, 8> awaitedConfigures;
1989 llvm::SmallPtrSet<Operation *, 8> pendingAwaitReleases;
1995 LogicalResult recycle(DMAConfigureTaskOp task_op, Operation *freeOp,
1997 pendingAwaitReleases.erase(task_op);
2000 if (awaitedConfigures.contains(task_op) || reclaimed.contains(task_op) ||
2001 unloaded.contains(task_op))
2003 BdIdGenerator &gen = getGeneratorForTile(task_op.getTileOp());
2004 WalkResult result = task_op.walk<WalkOrder::PreOrder>([&](AIE::DMABDOp bd) {
2005 if (!bd.getBdId().has_value()) {
2006 bd.emitOpError(
"Free called on BD chain with unassigned IDs.");
2007 return WalkResult::interrupt();
2010 bd.getBdId().value()) &&
2011 !loadState.copyOwned.contains(
2012 {task_op.getTileOp().getTileID(),
2013 gen.targetModel.getBdPoolId(gen.col, gen.row,
2014 task_op.getChannel(),
2015 task_op.getDirection()),
2016 bd.getBdId().value()})) {
2017 releaseTaskBdId(task_op.getTileOp().getTileID(), gen, task_op,
2018 bd.getBdId().value());
2020 freeOp->emitOpError(
"frees buffer descriptor ID ")
2021 << bd.getBdId().value()
2022 <<
", which is not currently in use; it was already completed by "
2024 "earlier aiex.dma_free_task or aiex.dma_await_task";
2025 return WalkResult::interrupt();
2027 return WalkResult::advance();
2029 if (result.wasInterrupted())
2031 releasedTasks.insert(task_op);
2033 awaitedConfigures.insert(task_op);
2035 noteFreedInFlight(task_op, freeOp);
2042 LogicalResult recycleTask(Value task, Operation *op,
bool isAwait) {
2043 auto cfg = dyn_cast_or_null<DMAConfigureTaskOp>(task.getDefiningOp());
2045 auto err = op->emitOpError(
2046 "does not reference a valid configure_task operation.");
2047 if (Operation *def = task.getDefiningOp()) {
2048 if (isa<DMAStartBdChainOp>(def))
2049 err.attachNote(def->getLoc())
2050 <<
"Lower this operation first using the "
2051 "--aie-materialize-bd-chains pass.";
2052 if (isa<DMAConfigureTaskForOp>(def))
2053 err.attachNote(def->getLoc())
2054 <<
"Lower this operation first using the "
2055 "--aie-substitute-shim-dma-allocations pass.";
2060 return recycle(cfg, op,
false);
2061 pendingAwaitReleases.insert(cfg);
2062 return recycleCompletedTasks(op);
2065 LogicalResult recycleCompletedTasks(Operation *op) {
2066 SmallVector<Operation *, 8> pending(pendingAwaitReleases.begin(),
2067 pendingAwaitReleases.end());
2068 for (Operation *pendingOp : pending) {
2069 auto pendingCfg = cast<DMAConfigureTaskOp>(pendingOp);
2072 if (!knownComplete.contains(pendingCfg))
2075 if (llvm::any_of(pendingCfg.getResult().getUsers(), [&](Operation *user) {
2076 return isa<DMAStartTaskOp>(user) &&
2077 user->getBlock() == op->getBlock() &&
2078 op->isBeforeInBlock(user);
2081 if (failed(recycle(pendingCfg, op,
true)))
2098 LogicalResult reclaimFor(DMAConfigureTaskOp op) {
2099 AIE::TileOp tile = op.getTileOp();
2102 auto isCandidate = [&](DMAConfigureTaskOp task) {
2103 if (releasedTasks.contains(task) || startAfter(task, op))
2105 if (tm.
getBdPoolId(tile.getCol(), tile.getRow(), task.getChannel(),
2106 task.getDirection()) !=
2107 tm.
getBdPoolId(tile.getCol(), tile.getRow(), op.getChannel(),
2110 bool usable =
false;
2111 task.walk([&](AIE::DMABDOp bd) {
2112 usable |= bd.getBdId() &&
2114 *bd.getBdId(), op.getChannel(),
2119 auto take = [&](DMAConfigureTaskOp task) {
2121 task.walk([&](AIE::DMABDOp bd) {
2122 releaseTaskBdId(tile.getTileID(), gen, task, *bd.getBdId());
2124 reclaimed.insert(task);
2125 releasedTasks.insert(task);
2126 pendingAwaitReleases.erase(task);
2129 ArrayRef<DMAConfigureTaskOp> live = liveByTile[tile.getTileID()];
2130 for (DMAConfigureTaskOp task : live)
2131 if ((knownComplete.contains(task) || provenFinished.contains(task)) &&
2132 isCandidate(task)) {
2137 unsigned at = roundState.positionOf.lookup(op);
2138 auto waitsOnLater = [&](DMAConfigureTaskOp task) {
2140 task.walk([&](AIE::UseLockOp lock) {
2141 auto last = roundState.lastReleaseOf.find(lock.getLock());
2142 waits |= (lock.acquire() || lock.acquireGE()) &&
2143 last != roundState.lastReleaseOf.end() && last->second >= at;
2150 DMAConfigureTaskOp victim;
2151 size_t victimQueuedBehind = 0;
2152 uint64_t victimOrder = 0;
2153 for (DMAConfigureTaskOp task : live) {
2154 if (!isCandidate(task) || waitsOnLater(task))
2158 static_cast<AIE::DMAChannelDir
>(key[2])))
2160 const ChannelPushes &channel = startedOnChannel[key];
2161 ArrayRef<StartedTask> started = channel.tasks;
2163 llvm::find_if(llvm::reverse(started),
2164 [&](
const StartedTask &s) {
return s.task == task; });
2165 size_t queuedBehind = std::distance(started.rbegin(), last);
2167 if (last == started.rend() ||
2168 started.size() - 1 - queuedBehind < channel.finished)
2170 if (queuedBehind == 0 ? !idle : !field)
2173 if (victim && std::make_pair(queuedBehind == 0, last->order) >=
2174 std::make_pair(victimQueuedBehind == 0, victimOrder))
2177 victimQueuedBehind = queuedBehind;
2178 victimOrder = last->order;
2185 key[0], key[1], key[3],
static_cast<AIE::DMAChannelDir
>(key[2]));
2188 uint32_t mask = idle;
2189 size_t unfinished = 0;
2190 if (victimQueuedBehind > 0) {
2191 unsigned shift = llvm::countr_zero(field);
2193 std::min<uint32_t>(llvm::bit_floor(victimQueuedBehind),
2194 llvm::bit_floor((field >> shift) + 1) / 2) -
2196 mask = field & ~(bound << shift);
2197 unfinished = bound + 1;
2200 auto cst = [&](uint32_t v) {
2201 auto constant = arith::ConstantOp::create(b, op.getLoc(), b.getI32Type(),
2202 b.getI32IntegerAttr(v));
2203 roundState.insertedHere.push_back(constant);
2204 return constant.getResult();
2206 Value maskValue = cst(mask);
2207 for (TaskSchedule &schedule : roundState.schedules)
2208 if (schedule.after == op.getOperation())
2209 schedule.after = maskValue.getDefiningOp();
2210 Value compareValue = cst(0);
2211 Value statusValue = cst(*status);
2212 auto poll = NpuMaskPollOp::create(b, op.getLoc(), statusValue, compareValue,
2216 roundState.insertedHere.push_back(poll);
2217 SmallVector<int32_t> ids;
2218 victim.walk([&](AIE::DMABDOp bd) { ids.push_back(*bd.getBdId()); });
2221 auto remark = mlir::emitRemark(poll.getLoc())
2222 <<
"tile (" << tile.getCol() <<
"," << tile.getRow()
2223 <<
") has no free buffer descriptor id, so this poll waits "
2224 << (victimQueuedBehind > 0
2225 ?
"until the queue behind an earlier task is short "
2226 "enough to prove it finished"
2227 :
"until the channel of an earlier task is idle")
2228 <<
" and takes back its ids ";
2229 llvm::interleaveComma(ids, remark);
2230 remark.attachNote(victim.getLoc()) <<
"the task it waits for";
2231 noteDrained(key, unfinished);
2242 void resetPerSequenceState() {
2244 awaitedConfigures.clear();
2245 pendingAwaitReleases.clear();
2246 startedOnChannel.clear();
2249 knownComplete.clear();
2250 provenFinished.clear();
2252 releasedTasks.clear();
2254 freedInFlight.clear();
2256 configuredDevice = {};
2259 resetChannels.clear();
2264 void warnLeaks(AIE::RuntimeSequenceOp sequence) {
2265 if (!warnUnreleasedTransfers)
2267 for (
const auto &[key, channel] : startedOnChannel) {
2268 SmallVector<Operation *> outstanding;
2269 for (
const StartedTask &push :
2270 llvm::drop_begin(channel.tasks, channel.finished))
2271 if (!push.task || (!releasedTasks.contains(push.task) &&
2272 !unloaded.contains(push.task)))
2273 outstanding.push_back(push.origin);
2274 if (outstanding.empty())
2276 auto diag = mlir::emitWarning(sequence.getLoc())
2277 <<
"may exit with " << outstanding.size()
2278 <<
" DMA transfer(s) neither awaited nor freed on tile ("
2279 << key[0] <<
"," << key[1] <<
") "
2280 << AIE::stringifyDMAChannelDir(
2281 static_cast<AIE::DMAChannelDir
>(key[2]))
2282 <<
" channel " << key[3]
2283 <<
"; runtime sequences called by aiex.run must finish using "
2284 "their channels before returning. Await completion, or "
2285 "free tasks whose completion is guaranteed indirectly";
2286 diag.attachNote(outstanding.front()->getLoc())
2287 <<
"first outstanding transfer starts here";
2291 void runOnOperation()
override {
2292 AIE::DeviceOp device = getOperation();
2293 loopingStarts.clear();
2295 deviceState.symbols.emplace(device);
2296 for (
auto input : device.getOps<AIE::ShimDMAAllocationOp>())
2297 if (ArrayAttr proofs = input.getConsumedByAttr())
2298 for (
auto proof : proofs.getAsRange<AIE::ConsumedByAttr>())
2300 deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
2301 proof.getOutput().getAttr()))
2302 deviceState.proofsByOutput[output].push_back({input, proof});
2304 WalkResult wr = device.walk([&](AIE::RuntimeSequenceOp seq) -> WalkResult {
2305 if (seq.getBody().empty())
2306 return WalkResult::advance();
2307 if (failed(checkForeignTail(seq)))
2308 return WalkResult::interrupt();
2313 bool dynamicPool =
false;
2314 bool hasTasks =
false;
2315 bool hasControlFlow =
false;
2316 seq.walk([&](Operation *op) {
2317 dynamicPool |= isa<DMABdPoolPopOp>(op);
2318 hasControlFlow |= isa<scf::ForOp, scf::IfOp, scf::WhileOp>(op);
2320 isa<DMAConfigureTaskOp, DMAConfigureTaskForOp, DMAStartBdChainOp,
2321 DMAStartTaskOp, DMAAwaitTaskOp, DMAFreeTaskOp>(op);
2323 if (dynamicPool || (!hasTasks && hasControlFlow))
2324 return WalkResult::advance();
2326 if (hasTasks && failed(validate(seq)))
2327 return WalkResult::interrupt();
2334 SmallVector<DMAFreeTaskOp> frees;
2335 auto visit = [&](Operation *op) -> WalkResult {
2336 if (
auto cfg = dyn_cast<DMAConfigureTaskOp>(op)) {
2337 if (failed(allocateConfigure(cfg)))
2338 return WalkResult::interrupt();
2339 }
else if (
auto start = dyn_cast<DMAStartTaskOp>(op)) {
2340 if (DMAConfigureTaskOp cfg = start.getTaskOp()) {
2341 if (unloaded.contains(cfg)) {
2343 "starts a task configured before an aiex.npu.load_pdi, "
2344 "which reconfigured the array; its buffer descriptor ids "
2345 "may now belong to the loaded device's static DMAs. "
2346 "Configure the task after the load_pdi instead.");
2347 return WalkResult::interrupt();
2353 if (releasedTasks.contains(cfg)) {
2355 "starts a task whose buffer descriptors an earlier "
2356 "aiex.dma_free_task released; their ids may already be "
2357 "reprogrammed for another task. Free the task after its "
2358 "last start instead.");
2359 return WalkResult::interrupt();
2361 if (failed(checkNotBehindLoop(start, cfg)))
2362 return WalkResult::interrupt();
2363 knownComplete.erase(cfg);
2364 provenFinished.erase(cfg);
2366 start.getPushIssueToken(cfg), start, allocationOf(cfg),
2367 pushVolume(start, cfg));
2369 }
else if (
auto load = dyn_cast<NpuLoadPdiOp>(op)) {
2371 }
else if (
auto context = dyn_cast<SetDeviceOp>(op)) {
2372 noteConfigured(context);
2373 }
else if (
auto reset = dyn_cast<DmaChannelResetOp>(op)) {
2375 reset.getTileOp(), reset.getDirection(), reset.getChannel()));
2376 }
else if (
auto poll = dyn_cast<NpuMaskPollOp>(op)) {
2378 }
else if (
auto await = dyn_cast<DMAAwaitTaskOp>(op)) {
2379 if (DMAConfigureTaskOp cfg = await.getTaskOp())
2380 if (cfg.getIssueToken())
2382 if (failed(recycleTask(await.getTask(), await,
true)))
2383 return WalkResult::interrupt();
2384 }
else if (
auto freeOp = dyn_cast<DMAFreeTaskOp>(op)) {
2385 if (failed(recycleTask(freeOp.getTask(), freeOp,
false)))
2386 return WalkResult::interrupt();
2387 frees.push_back(freeOp);
2390 noteAwaited(raw.key);
2391 if (failed(recycleCompletedTasks(op)))
2392 return WalkResult::interrupt();
2394 auto copy = dyn_cast<NpuDmaMemcpyNdOp>(op);
2395 AIE::ShimDMAAllocationOp allocation = allocationOf(copy);
2396 notePush(raw.key, DMAConfigureTaskOp{}, raw.issuesToken, op,
2397 allocation, copy ? copyVolume(copy) : std::nullopt);
2399 if (failed(holdCopy(copy, raw.key, pushCount - 1, raw.issuesToken)))
2400 return WalkResult::interrupt();
2401 if (roundState.reallocate)
2402 return WalkResult::interrupt();
2405 return WalkResult::advance();
2412 auto reusesBefore = unsafeReuses;
2413 auto copiesBefore = copiesOverCopies;
2414 WalkResult r = WalkResult::advance();
2415 std::vector<Diagnostic> held;
2417 resetPerSequenceState();
2421 indexLockReleases(seq);
2425 uint64_t thread = llvm::get_threadid();
2426 ScopedDiagnosticHandler hold(&getContext(), [&](Diagnostic &diag) {
2427 if (llvm::get_threadid() != thread)
2429 held.push_back(std::move(diag));
2432 r = WalkResult::advance();
2433 auto &body = seq.getBody().front();
2434 for (
auto iterator = body.begin(); iterator != body.end();) {
2435 Operation *operation = &*iterator++;
2436 SmallVector<TaskTriple> tasks;
2437 auto triple = taskTriple(operation);
2439 tasks.push_back(*triple);
2440 if (!triple->await.getDeferCompletion())
2442 triple = taskTriple(triple->await->getNextNode());
2445 tasks.size() > 1 && tasks.front().await.getDeferCompletion() &&
2446 llvm::all_of(tasks, [&](TaskTriple task) {
2447 const auto &channel =
2449 return fitsNow(task.configure) &&
2450 channel.tasks.size() - channel.finished <
2453 .getDmaTaskQueueDepth() &&
2456 [](
const StartedTask &push) {
2457 return push.issuesToken;
2461 iterator = std::next(tasks.back().await->getIterator());
2462 if (failed(allocateDeferredTasks(tasks, visit))) {
2463 r = WalkResult::interrupt();
2466 }
else if (operation->walk(visit).wasInterrupted()) {
2467 r = WalkResult::interrupt();
2472 if (!roundState.reallocate)
2474 for (AIE::DMABDOp bd : roundState.assignedHere)
2475 bd.removeBdIdAttr();
2476 for (Operation *inserted : llvm::reverse(roundState.insertedHere))
2478 unsafeReuses = reusesBefore;
2479 copiesOverCopies = copiesBefore;
2481 for (Diagnostic &diag : held)
2482 getContext().getDiagEngine().emit(std::move(diag));
2483 if (r.wasInterrupted())
2484 return WalkResult::interrupt();
2486 for (TaskSchedule &schedule : roundState.schedules)
2487 commitSchedule(schedule);
2488 for (
auto await : seq.getOps<DMAAwaitTaskOp>())
2489 await.removeDeferCompletionAttr();
2490 for (DMAFreeTaskOp freeOp : frees)
2492 for (
auto context : llvm::make_early_inc_range(seq.getOps<SetDeviceOp>()))
2494 return WalkResult::advance();
2497 if (wr.wasInterrupted())
2498 return signalPassFailure();
2504std::unique_ptr<OperationPass<AIE::DeviceOp>>
2506 return std::make_unique<AIENormalizeDMATaskGroupsPass>();
2509std::unique_ptr<OperationPass<AIE::DeviceOp>>
2511 return std::make_unique<AIEAssignRuntimeSequenceBDIDsPass>();
2514std::unique_ptr<OperationPass<AIE::DeviceOp>>
2516 const AIEAssignRuntimeSequenceBDIDsOptions &options) {
2517 return std::make_unique<AIEAssignRuntimeSequenceBDIDsPass>(options);
static void push(ChannelState &q, bool issuesToken)
Record a push.
static void awaitToken(ChannelState &q)
Retire what a task-completion-token await proves has drained.
std::array< int, 4 > ChannelKey
{col, row, direction, channel}.
static bool wouldOverflow(const ChannelState &q, uint32_t depth)
True when a push would land on a full queue.
static ChannelKey keyOf(AIE::TileOp tile, AIE::DMAChannelDir direction, int64_t channel)
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.
virtual uint32_t getDmaChannelIdleMask() const
Return the bits of the getDmaStatusAddress() register that are all clear exactly when the channel has...
uint32_t getNumBDsForChannel(int col, int row, int channel, DMAChannelDir dir) const
virtual uint32_t getBdPoolId(int col, int row, int channel, DMAChannelDir dir) const
Return the pool channel in direction dir draws its BDs from.
virtual uint32_t getDmaTaskQueueDepth() const =0
Return how many DMA tasks a single channel's task queue holds (unsupported = 0).
bool isBdChannelAccessible(int col, int row, uint32_t bd_id, int channel, DMAChannelDir dir) const
virtual uint32_t getDmaTaskQueueSizeMask() const
Return the mask selecting the live task-queue occupancy field within the getDmaStatusAddress() regist...
uint32_t getDmaQueueAddress(int col, int row, int channel, AIE::DMAChannelDir direction) const
Return the array address of the task queue register a push writes, the word after the channel's contr...
virtual std::optional< uint32_t > getDmaStatusAddress(int, int, int, AIE::DMAChannelDir) const
Return the address of the DMA status register for a channel, or nullopt when this target's layout has...
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....
std::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIENormalizeDMATaskGroupsPass()
bool atMost(const Volume &a, int64_t scaleA, const Volume &b, int64_t scaleB)
llvm::SmallVector< StaticBd > staticBdIds(llvm::ArrayRef< AIE::DeviceOp > devices, AIE::TileID tile)
void guardQueueOverflow(DmaQueueModel &queue, mlir::Operation *push, const AIE::AIETargetModel &tm, const DmaQueueModel::ChannelKey &key, uint32_t depth, bool enforce)
Handle a push on key that would land on a full queue: poll where one can be emitted,...
bool wholeGranules(const Volume &bytes, int64_t granule)
std::optional< uint32_t > getConstantIntOperand(mlir::Value v)
std::map< int64_t, int64_t > Volume
std::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIEAssignRuntimeSequenceBDIDsPass()
Unbalanced balanceUnder(AIE::ConsumedByAttr proof, const Volume &in, const Volume &out)
struct TileID { friend std::ostream &operator<<(std::ostream &os, const TileID &s) { os<< "TileID("<< s.col<< ", "<< s.row<< ")"; return os; } friend std::string to_string(const TileID &s) { std::ostringstream ss; ss<< s; return ss.str(); } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const TileID &s) { os<< to_string(s); return os; } inline bool operator<(const TileID &rhs) const { return std::tie(col, row)< std::tie(rhs.col, rhs.row); } bool operator==(const TileID &rhs) const { return std::tie(col, row)==std::tie(rhs.col, rhs.row); } bool operator!=(const TileID &rhs) const { return !(*this==rhs);} int col, row;} TileID
const AIETargetModel & getTargetModel(mlir::Operation *op)
bool isReserved(int channelIndex, DMAChannelDir dir, uint32_t bdId) const
const AIETargetModel & targetModel
std::set< std::pair< uint32_t, uint32_t > > reserved
void reserveBdId(int channelIndex, DMAChannelDir dir, uint32_t bdId)
std::optional< uint32_t > nextBdId(int channelIndex, DMAChannelDir dir, uint32_t alignment=1)
void freeBdId(int channelIndex, DMAChannelDir dir, uint32_t bdId)
void assignBdId(int channelIndex, DMAChannelDir dir, uint32_t bdId)
bool bdIdAlreadyAssigned(int channelIndex, DMAChannelDir dir, uint32_t bdId)
What one op in a loop body does to a channel queue.