MLIR-AIE 1.4.6.dev
AIELowerDynamicBDPool.cpp
Go to the documentation of this file.
1//===- AIELowerDynamicBDPool.cpp --------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// The dynamic counterpart to AIEAssignRuntimeSequenceBDIDs: where that pass
9// rejects a runtime-bound scf.for, this keeps the loop rolled and draws bd_ids
10// from a runtime free-list pool per tile and BD partition. Each configure gets
11// a dma_bd_pool_pop (its SSA id feeding bd_id_val); each free gets a
12// dma_bd_pool_push. An await is only a completion sync (npu_sync), never a
13// push.
14//
15// A popped id must be reachable at its push. Since a task value can cross a
16// loop back edge and exit as a result, the ids are carried in lockstep: every
17// task iter_arg gets parallel i32 id iter_args, and a push looks up the paired
18// ids.
19//
20// A multi-BD chain pops one id per BD, in body order, all from the channel's
21// partition. AIEDMATasksToNPU links each BD's next_bd to its successor's
22// runtime id. The ids share the task's lifetime, so a free pushes all of them.
23//
24//===----------------------------------------------------------------------===//
25
30
31#include "mlir/Dialect/Arith/IR/Arith.h"
32#include "mlir/Dialect/SCF/IR/SCF.h"
33#include "mlir/Pass/Pass.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/DenseSet.h"
36#include "llvm/ADT/SetVector.h"
37
38#include <set>
39
40namespace xilinx::AIEX {
41#define GEN_PASS_DEF_AIELOWERDYNAMICBDPOOL
42#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
43} // namespace xilinx::AIEX
44
45using namespace mlir;
46using namespace xilinx;
47using namespace xilinx::AIEX;
48
49namespace {
50
51struct AIELowerDynamicBDPoolPass
52 : xilinx::AIEX::impl::AIELowerDynamicBDPoolBase<AIELowerDynamicBDPoolPass> {
53 using Base =
54 xilinx::AIEX::impl::AIELowerDynamicBDPoolBase<AIELowerDynamicBDPoolPass>;
55 AIELowerDynamicBDPoolPass() = default;
56 AIELowerDynamicBDPoolPass(const AIELowerDynamicBDPoolOptions &options)
57 : Base(options) {}
58
59 // Maps a task value (the Index result of a configure, or any Index the carry
60 // propagates it into) to the i32 pool ids available at that same program
61 // point, one per BD of the task's chain in body order.
62 llvm::DenseMap<Value, SmallVector<Value, 2>> pairedId;
63 // The (col,row) of the tile each task's id belongs to, so a push names the
64 // right pool even when the id is a loop result rather than a direct pop.
65 llvm::DenseMap<Value, std::pair<int, int>> tileForTask;
66 // A representative (loop-invariant) configure per task, so a post-loop await
67 // on a loop result -- which has no defining configure -- can be redirected to
68 // one with the right (tile,dir,channel).
69 llvm::DenseMap<Value, DMAConfigureTaskOp> originConfigure;
70
71 // Every SSA value that carries a DMA task: configure results plus everything
72 // the task flows into (for iter_args/results, if results). Computed by
73 // forward closure from configures, so it is independent of the order in which
74 // control flow is later rewritten.
75 llvm::DenseSet<Value> taskValues;
76 // The number of ids each task value carries (its chain length). Known for
77 // every task value up front, unlike pairedId, whose entry for an scf
78 // result/iter_arg only exists once that op is grown.
79 llvm::DenseMap<Value, unsigned> taskIdCount;
80
81 // A grown scf.for/scf.if whose appended i32 yield operands are still
82 // placeholders. carried[i] is the original task position whose idCount[i]
83 // ids were appended, laid out contiguously from nOrig; the yields are wired
84 // once every position is paired.
85 struct Fixup {
86 Operation *op;
87 SmallVector<unsigned> carried;
88 SmallVector<unsigned> idCount;
89 unsigned nOrig;
90 SmallVector<Operation *> placeholders; // dead consts to erase (scf.if only)
91 };
92 SmallVector<Fixup> fixups;
93
94 // The BD ids a configure's channel can submit. Pools are keyed by this range,
95 // so channels that share a partition share a pool. Private BD pools that
96 // reuse the same ids also share one, which is conservative.
97 static std::pair<uint32_t, uint32_t> bdPartition(DMAConfigureTaskOp cfg) {
98 AIE::TileOp tile = cfg.getTileOp();
100 tile.getCol(), tile.getRow(), cfg.getChannel(), cfg.getDirection());
101 }
102
103 // The BDs of a configure's body, in block order: the order their ids are
104 // popped and carried.
105 static SmallVector<AIE::DMABDOp, 2> chainBds(DMAConfigureTaskOp cfg) {
106 SmallVector<AIE::DMABDOp, 2> bds;
107 cfg.walk([&](AIE::DMABDOp bd) { bds.push_back(bd); });
108 return bds;
109 }
110
111 void markTask(Value v, unsigned idCount, SmallVectorImpl<Value> &worklist) {
112 if (taskValues.insert(v).second) {
113 taskIdCount[v] = idCount;
114 worklist.push_back(v);
115 }
116 }
117
118 // Forward-propagate task-ness from every configure result through scf.for
119 // (init -> iter_arg, yield -> result) and scf.if (yield -> result). A value
120 // that is never derived from a configure (e.g. an unrelated index yielded on
121 // one branch) stays out of the set, which is what lets the divergent-yield
122 // check below reject it.
123 void computeTaskValues(AIE::RuntimeSequenceOp seq) {
124 taskValues.clear();
125 taskIdCount.clear();
126 SmallVector<Value> worklist;
127 seq.walk([&](DMAConfigureTaskOp c) {
128 markTask(c.getResult(), chainBds(c).size(), worklist);
129 });
130 while (!worklist.empty()) {
131 Value v = worklist.pop_back_val();
132 unsigned idCount = taskIdCount.lookup(v);
133 for (OpOperand &use : v.getUses()) {
134 Operation *user = use.getOwner();
135 if (auto f = dyn_cast<scf::ForOp>(user)) {
136 for (unsigned k = 0; k < f.getInitArgs().size(); ++k)
137 if (f.getInitArgs()[k] == v)
138 markTask(f.getRegionIterArg(k), idCount, worklist);
139 } else if (isa<scf::YieldOp>(user)) {
140 unsigned k = use.getOperandNumber();
141 Operation *parent = user->getParentOp();
142 if (auto pf = dyn_cast<scf::ForOp>(parent))
143 markTask(pf.getResult(k), idCount, worklist);
144 else if (auto pi = dyn_cast<scf::IfOp>(parent))
145 markTask(pi.getResult(k), idCount, worklist);
146 }
147 }
148 }
149 }
150
151 // Every position a task flows through carries one fixed number of ids, so
152 // both branches of an scf.if, and an scf.for's init and per-iteration yield,
153 // must agree on the chain length.
154 LogicalResult verifyChainLengths(AIE::RuntimeSequenceOp seq) {
155 auto agree = [&](Operation *op, Value a, Value b,
156 StringRef what) -> LogicalResult {
157 if (!taskValues.contains(a) || !taskValues.contains(b) ||
158 taskIdCount.lookup(a) == taskIdCount.lookup(b))
159 return success();
160 return op->emitOpError()
161 << what << " a " << taskIdCount.lookup(a) << "-BD chain and a "
162 << taskIdCount.lookup(b)
163 << "-BD chain at the same position; a pool-allocated task "
164 "carries one buffer descriptor id per BD, so every task "
165 "flowing through one position must have the same chain length";
166 };
167 WalkResult wr = seq.walk([&](Operation *op) -> WalkResult {
168 if (auto ifOp = dyn_cast<scf::IfOp>(op)) {
169 if (ifOp.getNumResults() == 0 || ifOp.elseBlock() == nullptr)
170 return WalkResult::advance();
171 auto thenYield = cast<scf::YieldOp>(ifOp.thenBlock()->getTerminator());
172 auto elseYield = cast<scf::YieldOp>(ifOp.elseBlock()->getTerminator());
173 for (unsigned k = 0; k < ifOp.getNumResults(); ++k)
174 if (failed(agree(ifOp, thenYield.getOperand(k),
175 elseYield.getOperand(k),
176 "yields from its branches")))
177 return WalkResult::interrupt();
178 } else if (auto forOp = dyn_cast<scf::ForOp>(op)) {
179 auto yield = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
180 for (unsigned k = 0; k < forOp.getInitArgs().size(); ++k)
181 if (failed(agree(forOp, forOp.getInitArgs()[k], yield.getOperand(k),
182 "carries from its init and its yield")))
183 return WalkResult::interrupt();
184 }
185 return WalkResult::advance();
186 });
187 return failure(wr.wasInterrupted());
188 }
189
190 LogicalResult lowerConfigure(DMAConfigureTaskOp cfg) {
191 SmallVector<AIE::DMABDOp, 2> bds = chainBds(cfg);
192 if (llvm::any_of(bds, [](AIE::DMABDOp bd) { return bd.getBdIdVal(); }))
193 return success(); // already lowered
194
195 // The pool owns all id allocation here, so a hand-pinned bd_id would
196 // collide with a runtime pop. Allocation is all-pool or all-static (for a
197 // straight-line sequence), never mixed.
198 for (AIE::DMABDOp bd : bds)
199 if (bd.getBdId().has_value())
200 return bd.emitOpError(
201 "pins a buffer descriptor ID inside a runtime-bound "
202 "sequence that draws IDs from the dynamic pool; a pinned "
203 "ID would collide with a runtime-allocated one. Allocate "
204 "every BD in this sequence from the pool (drop the "
205 "bd_id), or make the sequence straight-line so the static "
206 "allocator assigns all IDs.");
207
208 AIE::TileOp tile = cfg.getTileOp();
209 auto [begin, end] = bdPartition(cfg);
210 if (bds.size() > end - begin)
211 return cfg.emitOpError()
212 << "chains " << bds.size() << " buffer descriptors, but channel "
213 << cfg.getChannel() << " of tile (" << tile.getCol() << ","
214 << tile.getRow() << ") draws from a pool of only " << end - begin
215 << " ids";
216 OpBuilder b(cfg);
217 SmallVector<Value, 2> ids;
218 for (AIE::DMABDOp bd : bds) {
219 Value bdId =
220 DMABdPoolPopOp::create(b, cfg.getLoc(), b.getI32Type(), tile.getCol(),
221 tile.getRow(), begin, end, /*id=*/nullptr)
222 .getBdId();
223 bd.getBdIdValMutable().assign(bdId);
224 ids.push_back(bdId);
225 }
226 pairedId[cfg.getResult()] = ids;
227 return success();
228 }
229
230 // Grow an scf.for with a parallel i32 iter_arg for every task-carrying
231 // iter_arg, so the popped id can flow in lockstep with the task Index. The
232 // yields are left as placeholders (the new id block arg itself) and wired to
233 // the real per-iteration id later, once every position is paired -- a body
234 // may yield an id defined by a not-yet-grown inner op. Pairs the new
235 // iter_args/results in `pairedId` and records a Fixup.
236 scf::ForOp carryIdsThroughLoop(scf::ForOp forOp) {
237 SmallVector<unsigned> carried; // iter_arg positions carrying a task
238 SmallVector<unsigned> idCount; // ids per carried position (chain length)
239 SmallVector<Value> newInits;
240 for (unsigned k = 0; k < forOp.getInitArgs().size(); ++k) {
241 Value init = forOp.getInitArgs()[k];
242 if (!taskValues.contains(init))
243 continue;
244 SmallVector<Value, 2> ids = pairedId.lookup(init);
245 assert(ids.size() == taskIdCount.lookup(init) &&
246 "for init carries a task but its ids are not all paired");
247 carried.push_back(k);
248 idCount.push_back(ids.size());
249 newInits.append(ids.begin(), ids.end());
250 }
251 if (carried.empty())
252 return forOp;
253
254 unsigned nOrig = forOp.getInitArgs().size();
255 IRRewriter rewriter(forOp);
256 auto newYields = [&](OpBuilder &b, Location loc,
257 ArrayRef<BlockArgument> newBBArgs) {
258 // Placeholder: yield each new id iter_arg straight back. Same type,
259 // dominates the yield, and is a no-op for an identity (task-reuse) carry.
260 // wireFixups overwrites it with the real per-iteration id.
261 return SmallVector<Value>(newBBArgs.begin(), newBBArgs.end());
262 };
263
264 FailureOr<LoopLikeOpInterface> newLoop = forOp.replaceWithAdditionalYields(
265 rewriter, newInits,
266 /*replaceInitOperandUsesInLoop=*/false, newYields);
267 assert(succeeded(newLoop) && "scf.for additional-yields rewrite failed");
268 // The assert above already guards this; the checker just doesn't
269 // associate succeeded() with FailureOr's std::optional base.
270 auto newFor = cast<scf::ForOp>(
271 newLoop->getOperation()); // NOLINT(bugprone-unchecked-optional-access)
272
273 unsigned off = nOrig;
274 for (auto [i, k] : llvm::enumerate(carried)) {
275 // The rewrite gave the loop new block args/results; migrate task-ness
276 // onto them so a later-grown consumer of this loop's result still sees a
277 // task.
278 taskValues.insert(newFor.getRegionIterArg(k));
279 taskValues.insert(newFor.getResult(k));
280 taskIdCount[newFor.getRegionIterArg(k)] = idCount[i];
281 taskIdCount[newFor.getResult(k)] = idCount[i];
282 SmallVector<Value, 2> argIds, resIds;
283 for (unsigned j = 0; j < idCount[i]; ++j) {
284 argIds.push_back(newFor.getRegionIterArg(off + j));
285 resIds.push_back(newFor.getResult(off + j));
286 }
287 pairedId[newFor.getRegionIterArg(k)] = argIds;
288 pairedId[newFor.getResult(k)] = resIds;
289 off += idCount[i];
290 }
291 fixups.push_back({newFor, carried, idCount, nOrig, {}});
292 return newFor;
293 }
294
295 // Grow an scf.if with a parallel i32 result per task it yields out (its
296 // branch-local id), so a task freed after the if finds its id. Yields start
297 // as placeholders, wired later. A result carries a task iff BOTH branches
298 // yield one; a divergent yield (only one branch) is rejected -- no id to push
299 // on the other path.
300 LogicalResult carryIdsThroughIf(scf::IfOp ifOp) {
301 if (ifOp.getNumResults() == 0 || ifOp.elseBlock() == nullptr)
302 return success();
303
304 auto thenYield = cast<scf::YieldOp>(ifOp.thenBlock()->getTerminator());
305 auto elseYield = cast<scf::YieldOp>(ifOp.elseBlock()->getTerminator());
306
307 SmallVector<unsigned> carried; // result positions carrying a task
308 SmallVector<unsigned> idCount; // ids per carried position (chain length)
309 for (unsigned k = 0; k < ifOp.getNumResults(); ++k) {
310 bool thenT = taskValues.contains(thenYield.getOperand(k));
311 bool elseT = taskValues.contains(elseYield.getOperand(k));
312 if (thenT && elseT) {
313 carried.push_back(k);
314 idCount.push_back(taskIdCount.lookup(thenYield.getOperand(k)));
315 } else if (thenT || elseT)
316 return ifOp.emitOpError(
317 "yields a pool-allocated task on only one branch of an scf.if; "
318 "both "
319 "branches must yield the task (and its buffer descriptor id) so it "
320 "can be freed after the if");
321 }
322 if (carried.empty())
323 return success();
324
325 unsigned nOrig = ifOp.getNumResults();
326 OpBuilder b(ifOp);
327 SmallVector<Type> resultTypes(ifOp.getResultTypes());
328 unsigned numIds = llvm::sum_of(idCount);
329 resultTypes.append(numIds, b.getI32Type());
330
331 auto newIf =
332 scf::IfOp::create(b, ifOp.getLoc(), resultTypes, ifOp.getCondition(),
333 /*withElseRegion=*/true);
334 newIf.getThenRegion().takeBody(ifOp.getThenRegion());
335 newIf.getElseRegion().takeBody(ifOp.getElseRegion());
336
337 // Append a placeholder i32 per carried id to each branch's yield;
338 // wireFixups replaces them with the branch's real ids (which may be defined
339 // by a not-yet-grown inner op). The placeholders are dead constants erased
340 // during wiring.
341 SmallVector<Operation *> placeholders;
342 auto appendPlaceholders = [&](scf::YieldOp y) {
343 OpBuilder yb(y);
344 SmallVector<Value> ids;
345 for (unsigned j = 0; j < numIds; ++j) {
346 auto c =
347 arith::ConstantOp::create(yb, y.getLoc(), yb.getI32IntegerAttr(0));
348 placeholders.push_back(c);
349 ids.push_back(c);
350 }
351 y->insertOperands(y->getNumOperands(), ids);
352 };
353 appendPlaceholders(cast<scf::YieldOp>(newIf.thenBlock()->getTerminator()));
354 appendPlaceholders(cast<scf::YieldOp>(newIf.elseBlock()->getTerminator()));
355
356 unsigned off = nOrig;
357 for (auto [i, k] : llvm::enumerate(carried)) {
358 // Migrate task-ness onto the rebuilt result so a later-grown consumer of
359 // this if's result still sees a task.
360 taskValues.insert(newIf.getResult(k));
361 taskIdCount[newIf.getResult(k)] = idCount[i];
362 SmallVector<Value, 2> resIds;
363 for (unsigned j = 0; j < idCount[i]; ++j)
364 resIds.push_back(newIf.getResult(off + j));
365 pairedId[newIf.getResult(k)] = resIds;
366 off += idCount[i];
367 }
368 for (unsigned k = 0; k < nOrig; ++k)
369 ifOp.getResult(k).replaceAllUsesWith(newIf.getResult(k));
370 ifOp.erase();
371 fixups.push_back({newIf, carried, idCount, nOrig, placeholders});
372 return success();
373 }
374
375 // Sweep 2: with every position paired, set each grown op's appended yield
376 // operand(s) to the real id yielded at that position. Runs after all growth,
377 // so an id defined by an inner op (grown later than its enclosing op) is
378 // resolvable, and an identity carry resolves to its own iter_arg's id.
379 void wireFixups() {
380 for (Fixup &fx : fixups) {
381 SmallVector<scf::YieldOp, 2> yields;
382 if (auto forOp = dyn_cast<scf::ForOp>(fx.op)) {
383 yields.push_back(cast<scf::YieldOp>(forOp.getBody()->getTerminator()));
384 } else {
385 auto ifOp = cast<scf::IfOp>(fx.op);
386 for (Block *blk : {ifOp.thenBlock(), ifOp.elseBlock()})
387 yields.push_back(cast<scf::YieldOp>(blk->getTerminator()));
388 }
389 for (scf::YieldOp yield : yields) {
390 unsigned off = fx.nOrig;
391 for (auto [i, k] : llvm::enumerate(fx.carried)) {
392 SmallVector<Value, 2> ids = pairedId.lookup(yield.getOperand(k));
393 assert(ids.size() == fx.idCount[i] &&
394 "carried task yields the wrong number of ids");
395 for (auto [j, id] : llvm::enumerate(ids))
396 yield.setOperand(off + j, id);
397 off += fx.idCount[i];
398 }
399 }
400 }
401 for (Fixup &fx : fixups)
402 for (Operation *p : fx.placeholders)
403 p->erase();
404 }
405
406 // Sweep 3: over the final IR, give every task value its tile (for the push)
407 // and a representative origin configure (for an await that names a loop
408 // result with no defining configure -- a loop's pre-loop init, which
409 // dominates a post-loop await). Order-independent forward closure:
410 // - scf.for: the init's tile/origin flow to the iter_arg AND the result, so
411 // a result takes the loop-invariant init configure (which dominates a
412 // post-loop await), not the per-iteration body configure.
413 // - scf.if: the then-branch yield's tile/origin flow to the result.
414 // A push only reads the tile, so both branches must agree; a genuinely
415 // cross-tile scf.if is rejected, and so is a for-loop whose per-iteration
416 // reconfiguration disagrees with its init.
417 LogicalResult computeMetadata(AIE::RuntimeSequenceOp seq) {
418 tileForTask.clear();
419 originConfigure.clear();
420 SmallVector<Value> worklist;
421 auto setMeta = [&](Value v, std::pair<int, int> tile,
422 DMAConfigureTaskOp origin) {
423 if (tileForTask.count(v))
424 return;
425 tileForTask[v] = tile;
426 originConfigure[v] = origin;
427 worklist.push_back(v);
428 };
429 seq.walk([&](DMAConfigureTaskOp c) {
430 AIE::TileOp t = c.getTileOp();
431 setMeta(c.getResult(), {t.getCol(), t.getRow()}, c);
432 });
433 while (!worklist.empty()) {
434 Value v = worklist.pop_back_val();
435 auto tile = tileForTask[v];
436 DMAConfigureTaskOp origin = originConfigure[v];
437 for (OpOperand &use : v.getUses()) {
438 Operation *user = use.getOwner();
439 if (auto f = dyn_cast<scf::ForOp>(user)) {
440 for (unsigned k = 0; k < f.getInitArgs().size(); ++k)
441 if (f.getInitArgs()[k] == v) {
442 setMeta(f.getRegionIterArg(k), tile, origin);
443 setMeta(f.getResult(k), tile, origin);
444 }
445 } else if (isa<scf::YieldOp>(user)) {
446 auto ifOp = dyn_cast<scf::IfOp>(user->getParentOp());
447 if (ifOp && user->getBlock() == ifOp.thenBlock())
448 setMeta(ifOp.getResult(use.getOperandNumber()), tile, origin);
449 }
450 }
451 }
452 // A task carried out of an scf.if and freed after it resolves to one BD id
453 // and one push, so both branches must agree on the full physical channel
454 // (tile,dir,channel) -- otherwise the single push would be ambiguous.
455 WalkResult wr = seq.walk([&](scf::IfOp ifOp) -> WalkResult {
456 if (ifOp.getNumResults() == 0 || ifOp.elseBlock() == nullptr)
457 return WalkResult::advance();
458 auto thenYield = cast<scf::YieldOp>(ifOp.thenBlock()->getTerminator());
459 auto elseYield = cast<scf::YieldOp>(ifOp.elseBlock()->getTerminator());
460 for (unsigned k = 0; k < ifOp.getNumResults(); ++k)
461 if (failed(checkChannelAgreement(
462 ifOp, thenYield.getOperand(k), elseYield.getOperand(k),
463 "yields tasks on different physical channels "
464 "(tile/direction/channel) from its two branches at "
465 "the same result; a pooled buffer descriptor id and "
466 "its completion sync belong to one channel")))
467 return WalkResult::interrupt();
468 return WalkResult::advance();
469 });
470 if (wr.wasInterrupted())
471 return failure();
472
473 // A task carried around an scf.for must likewise agree on the physical
474 // channel between the loop's init and its per-iteration reconfiguration
475 // -- the push after the loop uses the loop-invariant init's tile
476 // (computeMetadata never adopts the body's), and an await reachable
477 // through the loop (resolveConfigureThroughCF in AIEDMATasksToNPU) may
478 // resolve to either one.
479 WalkResult forWr = seq.walk([&](scf::ForOp forOp) -> WalkResult {
480 auto yield = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
481 for (unsigned k = 0; k < forOp.getInitArgs().size(); ++k)
482 if (failed(checkChannelAgreement(
483 forOp, forOp.getInitArgs()[k], yield.getOperand(k),
484 "carries a task on different physical channels "
485 "(tile/direction/channel) between its init and its "
486 "per-iteration reconfiguration; a pooled buffer "
487 "descriptor id and its completion sync belong to one "
488 "channel")))
489 return WalkResult::interrupt();
490 return WalkResult::advance();
491 });
492 return forWr.wasInterrupted() ? failure() : success();
493 }
494
495 // If both `a` and `b` resolve (via originConfigure) to a configure, and
496 // those configures target different physical channels, emit `msg` on `op`
497 // and return failure. Shared by the scf.if and scf.for channel-agreement
498 // checks in computeMetadata -- only the pair of values being compared
499 // differs between them.
500 LogicalResult checkChannelAgreement(Operation *op, Value a, Value b,
501 StringRef msg) {
502 DMAConfigureTaskOp originA = originConfigure.lookup(a);
503 DMAConfigureTaskOp originB = originConfigure.lookup(b);
504 if (originA && originB &&
505 DmaQueueModel::keyOf(originA) != DmaQueueModel::keyOf(originB)) {
506 op->emitOpError(msg);
507 return failure();
508 }
509 return success();
510 }
511
512 // Every value that may carry `task`'s BD id after it: the region arguments
513 // and results it is forwarded to, including the next iteration of a loop
514 // that yields it. The forward counterpart of getReachableConfigures.
515 static llvm::SetVector<Value> aliasesAfter(Value task) {
516 llvm::SetVector<Value> aliases;
517 aliases.insert(task);
518 for (unsigned i = 0; i < aliases.size(); ++i) {
519 for (OpOperand &use : aliases[i].getUses()) {
520 Operation *user = use.getOwner();
521 auto branch = dyn_cast<RegionBranchOpInterface>(user);
522 if (!branch && user->hasTrait<OpTrait::IsTerminator>())
523 branch =
524 dyn_cast_or_null<RegionBranchOpInterface>(user->getParentOp());
525 if (!branch)
526 continue;
527 RegionBranchSuccessorMapping mapping;
528 branch.getSuccessorOperandInputMapping(mapping);
529 aliases.insert_range(mapping.lookup(&use));
530 }
531 }
532 return aliases;
533 }
534
535 // A start that can run after `freeOp` pushes an id the pool may already
536 // have handed to another task: one later in the block the two share, or one
537 // in a loop around both whose next iteration still names the freed id.
538 static LogicalResult verifyNoStartAfterFree(Value task, Operation *freeOp) {
539 llvm::SetVector<Value> aliases = aliasesAfter(task);
540 auto startsAfterFree = [&](DMAStartTaskOp start) {
541 for (Block *block = freeOp->getBlock(); block;
542 block = block->getParentOp()->getBlock()) {
543 Operation *startAt = block->findAncestorOpInBlock(*start);
544 if (!startAt)
545 continue;
546 Operation *freeAt = block->findAncestorOpInBlock(*freeOp);
547 if (freeAt != startAt && freeAt->isBeforeInBlock(startAt))
548 return true;
549 break;
550 }
551 Value started = start.getTask();
552 for (auto loop = freeOp->getParentOfType<scf::ForOp>(); loop;
553 loop = loop->getParentOfType<scf::ForOp>()) {
554 if (!loop->isAncestor(start))
555 continue;
556 if (!loop.getBody()->getParent()->isAncestor(started.getParentRegion()))
557 return true;
558 auto arg = dyn_cast<BlockArgument>(started);
559 if (arg && arg.getOwner() == loop.getBody() &&
560 arg.getArgNumber() >= loop.getNumInductionVars()) {
561 unsigned k = arg.getArgNumber() - loop.getNumInductionVars();
562 if (aliases.contains(loop.getYieldedValues()[k]))
563 return true;
564 }
565 }
566 return false;
567 };
568 for (Value alias : aliases)
569 for (Operation *user : alias.getUsers()) {
570 auto start = dyn_cast<DMAStartTaskOp>(user);
571 if (!start || !startsAfterFree(start))
572 continue;
573 auto diag = start.emitOpError(
574 "starts a task whose buffer descriptor ID was already returned "
575 "to the runtime pool; the pool may have handed it to another "
576 "task. Free the task after its last start instead.");
577 diag.attachNote(freeOp->getLoc()) << "returned here";
578 return diag;
579 }
580 return success();
581 }
582
583 LogicalResult lowerRelease(Value task, Operation *op) {
584 SmallVector<Value, 2> ids = pairedId.lookup(task);
585 if (ids.empty())
586 return op->emitOpError(
587 "does not resolve to a task allocated from the runtime pool; cannot "
588 "return its buffer descriptor ID");
589 if (failed(verifyNoStartAfterFree(task, op)))
590 return failure();
591 auto tile = tileForTask.lookup(task);
592 auto [begin, end] = bdPartition(originConfigure.lookup(task));
593 OpBuilder b(op);
594 for (Value id : ids)
595 DMABdPoolPushOp::create(b, op->getLoc(), tile.first, tile.second, begin,
596 end, id);
597 return success();
598 }
599
600 // Guard pushes that can land on a full task queue, and (opt-in) warn at a
601 // dma_free_task whose own push is not yet proven complete. Must run before
602 // frees are erased below -- it is the only point where this pass still has
603 // both the dma_free_task ops and the origin-configure metadata they resolve
604 // through.
605 //
606 // A sequence lowered here keeps its scf.for rolled, so the static allocator
607 // skips it. Guard while task metadata is available; aie-dma-to-npu later
608 // checks the combined pushes from tasks, memcpy and channel rearm operations.
609 void guardQueueDepth(AIE::RuntimeSequenceOp seq, SymbolTable &symbols) {
610 const AIE::AIETargetModel &tm =
611 seq->getParentOfType<AIE::DeviceOp>().getTargetModel();
612
613 auto effectOf = [&](Operation *op) -> QueueEffect {
614 if (isa<NpuPushQueueOp, NpuSyncOp, NpuDmaMemcpyNdOp, NpuDmaWaitOp>(op))
615 return rawQueueEffect(op, symbols);
616 DMAConfigureTaskOp cfg;
617 Value task;
618 bool isConfigure = false;
619 bool isPush = false;
620 bool issuesToken = false;
621 if (auto start = dyn_cast<DMAStartTaskOp>(op)) {
622 task = start.getTask();
623 cfg = originConfigure.lookup(task);
624 isPush = true;
625 issuesToken = cfg && start.getPushIssueToken(cfg);
626 } else if (auto configure = dyn_cast<DMAConfigureTaskOp>(op)) {
627 if (!warnUnsafeBdReuse)
628 return {};
629 cfg = configure;
630 task = configure.getResult();
631 isConfigure = true;
632 } else if (auto await = dyn_cast<DMAAwaitTaskOp>(op)) {
633 cfg = originConfigure.lookup(await.getTask());
634 // Only a token-issuing await retires anything.
635 if (cfg && !cfg.getIssueToken())
636 return {};
637 } else if (auto freeOp = dyn_cast<DMAFreeTaskOp>(op)) {
638 if (!warnUnsafeBdReuse)
639 return {};
640 cfg = originConfigure.lookup(freeOp.getTask());
641 if (!cfg)
642 return {};
643 if (!cfg.tryGetTileOp())
644 return {};
645 return QueueEffect::free(DmaQueueModel::keyOf(cfg), freeOp.getTask());
646 } else {
647 return {};
648 }
649 if (!cfg)
650 return {};
651 if (!cfg.tryGetTileOp())
652 return {};
654 if (isConfigure)
655 return QueueEffect::configure(key, task);
656 return isPush ? QueueEffect::push(key, issuesToken,
657 warnUnsafeBdReuse ? task : Value{})
658 : QueueEffect::await(key);
659 };
660
661 DmaQueueModel queue;
662 guardSequenceQueueDepth(seq.getBody(), queue, tm, enforceQueueDepth,
663 warnUnsafeBdReuse, effectOf);
664 }
665
666 // A static DMA program or an aiex.npu.dma_memcpy_nd programs its BD id on
667 // its tile outside the pool, so every pool of that tile holding the id gives
668 // it up for the sequence.
669 void reserveTakenIds(AIE::RuntimeSequenceOp seq, SymbolTable &symbols) {
670 std::set<std::tuple<int, int, uint32_t, uint32_t>> pools;
671 std::set<std::tuple<int, int, uint32_t>> reserved;
672 seq.walk([&](DMABdPoolPopOp pop) {
673 pools.insert(
674 {pop.getColumn(), pop.getRow(), pop.getBdBegin(), pop.getBdEnd()});
675 if (std::optional<uint32_t> id = pop.getId())
676 reserved.insert({pop.getColumn(), pop.getRow(), *id});
677 });
678 if (pools.empty())
679 return;
680 std::set<std::tuple<int, int, uint32_t>> taken;
681 for (AIE::DmaBody program : getOperation().getOps<AIE::DmaBody>())
682 for (uint32_t id : AIE::getAssignedBdIds(program))
683 taken.insert({program.getTileID().col, program.getTileID().row, id});
684 seq.walk([&](NpuDmaMemcpyNdOp copy) {
685 auto allocation = symbols.lookup<AIE::ShimDMAAllocationOp>(
686 copy.getMetadata().getRootReference());
687 if (AIE::TileOp tile = allocation ? allocation.getTileOp() : nullptr)
688 taken.insert({tile.getCol(), tile.getRow(),
689 static_cast<uint32_t>(copy.getId())});
690 });
691 OpBuilder b = OpBuilder::atBlockBegin(&seq.getBody().front());
692 for (auto [col, row, begin, end] : pools)
693 for (auto [takenCol, takenRow, id] : taken)
694 if (takenCol == col && takenRow == row && id >= begin && id < end &&
695 !reserved.count({col, row, id}))
696 DMABdPoolPopOp::create(b, seq.getLoc(), b.getI32Type(), col, row,
697 begin, end, b.getI32IntegerAttr(id));
698 }
699
700 void runOnOperation() override {
701 AIE::DeviceOp device = getOperation();
702 SymbolTable symbols(device);
703
704 WalkResult wr = device.walk([&](AIE::RuntimeSequenceOp seq) -> WalkResult {
705 // A pop with an id withholds a taken BD id from the pool. Every exit
706 // from this sequence's body runs it, whether or not the lowering below
707 // grew new pools (carryIdsThroughLoop, computeMetadata) for it to see.
708 auto finish = [&](WalkResult result) {
709 reserveTakenIds(seq, symbols);
710 return result;
711 };
712
713 bool hasRuntimeCF = false;
714 seq.walk([&](Operation *op) {
715 if (isa<scf::ForOp, scf::IfOp, scf::WhileOp>(op))
716 hasRuntimeCF = true;
717 });
718 if (!hasRuntimeCF)
719 return finish(WalkResult::advance());
720
721 // Idempotency: a sequence already carrying pool pops has been lowered by
722 // a prior run of this pass. Its awaits may have dropped their task
723 // operand (sync_* attrs) and its scf ops already carry i32 ids, so
724 // re-running the carry logic would misfire. Skip it.
725 bool alreadyLowered = false;
726 seq.walk([&](DMABdPoolPopOp) { alreadyLowered = true; });
727 if (alreadyLowered)
728 return finish(WalkResult::advance());
729
730 // scf.while has no bounded trip count, so a BD id popped in its body has
731 // no place to be pushed back deterministically; only scf.for and scf.if
732 // are supported.
733 WalkResult whileCheck = seq.walk([&](scf::WhileOp w) {
734 w.emitOpError("scf.while in a runtime sequence is not supported by the "
735 "dynamic BD pool path; only scf.for and scf.if are "
736 "supported");
737 return WalkResult::interrupt();
738 });
739 if (whileCheck.wasInterrupted())
740 return finish(WalkResult::interrupt());
741
742 pairedId.clear();
743 tileForTask.clear();
744 originConfigure.clear();
745 fixups.clear();
746
747 // 1. Every configure pops an id (program order: a pop dominates every use
748 // of its id).
749 WalkResult r = seq.walk([&](DMAConfigureTaskOp cfg) -> WalkResult {
750 return failed(lowerConfigure(cfg)) ? WalkResult::interrupt()
751 : WalkResult::advance();
752 });
753 if (r.wasInterrupted())
754 return finish(WalkResult::interrupt());
755
756 // 2. Thread the id alongside the task everywhere the task flows. The task
757 // Index already threads (it is valid IR); shadowing every position it
758 // occupies with a parallel i32 makes the id in-scope at every push.
759 // a. Task closure: which SSA values carry a task (order-independent).
760 // b. Grow structure outermost-first (pre-order): an enclosing op's new
761 // iter_arg/result exists before an inner op yields through it. A
762 // divergent scf.if is rejected here.
763 // c. Wire the placeholder yields now that every position is paired --
764 // handles both siblings (producer grown before consumer) and
765 // parent-defines/child-consumes (inner id resolvable after growth).
766 computeTaskValues(seq);
767 if (failed(verifyChainLengths(seq)))
768 return finish(WalkResult::interrupt());
769 SmallVector<Operation *> cf;
770 seq.walk<WalkOrder::PreOrder>([&](Operation *o) {
771 if (isa<scf::ForOp, scf::IfOp>(o))
772 cf.push_back(o);
773 });
774 for (Operation *o : cf) {
775 if (auto f = dyn_cast<scf::ForOp>(o)) {
776 carryIdsThroughLoop(f);
777 } else if (failed(carryIdsThroughIf(cast<scf::IfOp>(o)))) {
778 return finish(WalkResult::interrupt());
779 }
780 }
781 wireFixups();
782
783 // 3. Metadata over the final IR: each task's tile (for the push) and a
784 // dominating origin configure (for an await on a loop/if result).
785 if (failed(computeMetadata(seq)))
786 return finish(WalkResult::interrupt());
787
788 // 4. Return ids to the pool. A free is the ONLY push: it returns the id
789 // to the free-list. An await is a TCT sync (npu_sync), never a release
790 // -- it emits no push. In the rolled pool one physical id is live
791 // across iterations, so the static path's "await = release" (safe only
792 // because unrolling gives each await a distinct id) would push the
793 // same live id once per iteration and corrupt the free-list. Leaving a
794 // task unfreed is valid: the pool is stack-local and re-initialized
795 // every invocation, so an unfreed id merely holds a slot for the rest
796 // of this one run (the await-only idiom, live BDs <= pool size).
797 //
798 // The await keeps its natural SSA operand -- the task value it names,
799 // whether that is a direct configure, a loop result, or an scf.if
800 // result (the phi of the task in flight, whichever branch ran). The
801 // npu_sync lowering (AIEDMATasksToNPU) walks that value to the
802 // physical channel; both branches of an scf.if were verified to agree
803 // on it (computeMetadata). This preserves the sync's data dependence
804 // on the task rather than breaking it.
805 SmallVector<Operation *> toErase;
806 r = seq.walk([&](Operation *op) -> WalkResult {
807 if (auto freeOp = dyn_cast<DMAFreeTaskOp>(op)) {
808 if (failed(lowerRelease(freeOp.getTask(), freeOp)))
809 return WalkResult::interrupt();
810 toErase.push_back(freeOp);
811 }
812 return WalkResult::advance();
813 });
814 if (r.wasInterrupted())
815 return finish(WalkResult::interrupt());
816 // Only once this sequence has lowered cleanly: guarding or reporting a
817 // queue on a design that is already being rejected just buries the
818 // error. Guard before erasing the frees above -- it still needs to see
819 // them, resolved through originConfigure, to check reuse safety.
820 guardQueueDepth(seq, symbols);
821 for (Operation *op : toErase)
822 op->erase();
823 return finish(WalkResult::advance());
824 });
825 if (wr.wasInterrupted())
826 return signalPassFailure();
827 }
828};
829
830} // namespace
831
832std::unique_ptr<OperationPass<AIE::DeviceOp>>
834 return std::make_unique<AIELowerDynamicBDPoolPass>();
835}
836
837std::unique_ptr<OperationPass<AIE::DeviceOp>>
839 const AIELowerDynamicBDPoolOptions &options) {
840 return std::make_unique<AIELowerDynamicBDPoolPass>(options);
841}
std::array< int, 4 > ChannelKey
{col, row, direction, channel}.
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.
std::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIELowerDynamicBDPoolPass()
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....
void guardSequenceQueueDepth(mlir::Region &body, DmaQueueModel &queue, const AIE::AIETargetModel &tm, bool enforce, bool warnUnsafeBdReuse, EffectFn effectOf)
Guard every push in a runtime sequence that can land on a full queue, and (when warnUnsafeBdReuse) wa...
llvm::SmallVector< uint32_t > getAssignedBdIds(DmaBody program)
const AIETargetModel & getTargetModel(mlir::Operation *op)
static QueueEffect await(DmaQueueModel::ChannelKey key)
static QueueEffect configure(DmaQueueModel::ChannelKey key, mlir::Value task)
static QueueEffect free(DmaQueueModel::ChannelKey key, mlir::Value task)
static QueueEffect push(DmaQueueModel::ChannelKey key, bool issuesToken, mlir::Value task={})