MLIR-AIE 1.4.6.dev
AIEMaterializeRuntimeSequences.cpp
Go to the documentation of this file.
1//===- AIEMaterializeRuntimeSequences.cpp -----------------------*- C++ -*-===//
2//
3// Copyright (C) 2025 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
14#include "aie/Targets/AIERT.h"
15
16#include "mlir/Dialect/Arith/IR/Arith.h"
17#include "mlir/Dialect/MemRef/IR/MemRef.h"
18#include "mlir/IR/IRMapping.h"
19#include "mlir/IR/PatternMatch.h"
20#include "mlir/Pass/Pass.h"
21#include "mlir/Transforms/DialectConversion.h"
22#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
23#include "mlir/Transforms/WalkPatternRewriteDriver.h"
24#include "llvm/ADT/STLExtras.h"
25
26namespace xilinx::AIEX {
27#define GEN_PASS_DEF_AIEMATERIALIZERUNTIMESEQUENCES
28#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
29} // namespace xilinx::AIEX
30
31#define DEBUG_TYPE "aie-materialize-runtime-sequence"
32
33using namespace mlir;
34using namespace xilinx;
35using namespace xilinx::AIEX;
36
38 AnalysisManager &analysisManager;
39
40 // if invalid, analysis failed and results should not be considered
41 bool isValid = false;
42
43 // Call graph is cyclic
44 bool isCyclic = false;
45
46 RuntimeCallGraphCyclicityAnalysis(Operation *op, AnalysisManager &am)
47 : analysisManager(am) {
48 AIE::RuntimeSequenceOp runtimeSequenceOp =
49 llvm::dyn_cast<AIE::RuntimeSequenceOp>(op);
50 if (!runtimeSequenceOp) {
51 op->emitError("RuntimeCallGraphCyclicityAnalysis can only be called on "
52 "aiex.runtime_sequence operations.");
53 return;
54 }
55
56 // Use DFS with a stack to detect cycles
57 // A cycle exists if we encounter a sequence already on the current path
58 llvm::DenseSet<AIE::RuntimeSequenceOp> callStack;
59 llvm::DenseSet<AIE::RuntimeSequenceOp> visited;
61
62 std::function<bool(AIE::RuntimeSequenceOp)> hasCycle =
63 [&](AIE::RuntimeSequenceOp seq) -> bool {
64 if (callStack.contains(seq)) {
65 return true; // Found a cycle
66 }
67 if (visited.contains(seq)) {
68 return false; // Already checked this sequence
69 }
70
71 callStack.insert(seq);
72 visited.insert(seq);
73
74 // Check all sequences called by this one
75 bool foundCycle = false;
76 seq.walk([&](RunOp runOp) {
77 if (AIE::RuntimeSequenceOp callee =
78 runOp.getCalleeRuntimeSequenceOp(&calleeNames)) {
79 if (hasCycle(callee)) {
80 foundCycle = true;
81 return WalkResult::interrupt();
82 }
83 }
84 return WalkResult::advance();
85 });
86
87 callStack.erase(seq);
88 return foundCycle;
89 };
90
91 if (hasCycle(runtimeSequenceOp)) {
92 isCyclic = true;
93 isValid = true;
94 return;
95 }
96 isCyclic = false;
97 isValid = true;
98 }
99};
100
101// Turn aie.configure @device into aie.run %.. @configure
102// TODO: add check that liveness of two aie.configures do not overlap
103// (i.e., when we configure A, then configure B, cannot call runtime sequence of
104// A after configuring B)
105// TODO: add code to remove repeated @configure ops
106struct InsertLoadPdiForConfigurePattern : RewritePattern {
107
109 PatternBenefit benefit = 1)
110 : RewritePattern(ConfigureOp::getOperationName(), benefit, context) {}
111
112 LogicalResult matchAndRewrite(Operation *op,
113 PatternRewriter &rewriter) const override {
114 ConfigureOp configureOp = llvm::dyn_cast<ConfigureOp>(op);
115 if (!configureOp) {
116 return failure();
117 }
118
119 // LoadPDI resets the whole device, hence cannot do partial reconfiguration;
120 // therefore, this only supports top-level configure ops
121 if (!llvm::isa<AIE::RuntimeSequenceOp>(configureOp->getParentOp())) {
122 return failure();
123 }
124
125 AIE::DeviceOp referencedDevice = configureOp.getReferencedDeviceOp();
126 if (!referencedDevice) {
127 configureOp.emitError("Referenced symbol is not a device");
128 return failure();
129 }
130
131 Block *configureBlock;
132 if (configureOp.getBody().empty()) {
133 configureBlock = rewriter.createBlock(&configureOp.getBody());
134 } else {
135 configureBlock = &configureOp.getBody().front();
136 }
137
138 rewriter.setInsertionPointToStart(configureBlock);
139 AIEX::NpuLoadPdiOp::create(
140 rewriter, configureOp.getLoc(),
141 FlatSymbolRefAttr::get(referencedDevice.getSymNameAttr()),
142 /*id=*/nullptr, /*size=*/nullptr, /*address=*/nullptr,
143 /*expand_mode=*/configureOp.getExpandModeAttr());
144
145 return success();
146 }
147};
148
149// Collects all external SSA values referenced by an operation (and its nested
150// operations).
151// 1. Collects SSA values from the operation's operands.
152// 2. Recursively walks through all operations in the operation's regions.
153// 3. For each nested operation, collects SSA values from its operands.
154// 4. Skips values that are already in argMap or defined within the operation.
155// 5. For memref.subview operations, traces to the root block argument
156static void
157collectReferencedSSAValues(Operation *op, const IRMapping &argMap,
158 llvm::SetVector<Value> &referencedValues) {
159
160 auto processValue = [&](Value operand) {
161 if (argMap.contains(operand)) {
162 return;
163 }
164
165 // If this is a subview, trace to the root block argument
166 if (auto traceResult = traceSubviewToBlockArgument(operand)) {
167 // Check if the root argument is already mapped
168 if (!argMap.contains(traceResult->rootArg)) {
169 referencedValues.insert(traceResult->rootArg);
170 }
171 return;
172 }
173
174 // Not a subview chain leading to block arg, add as-is
175 referencedValues.insert(operand);
176 };
177
178 // Collect SSA values from the operation's direct operands.
179 for (Value operand : op->getOperands()) {
180 processValue(operand);
181 }
182
183 // Recursively collect SSA values from nested operations in all regions.
184 for (Region &region : op->getRegions()) {
185 region.walk([&](Operation *nestedOp) {
186 for (Value operand : nestedOp->getOperands()) {
187 if (argMap.contains(operand)) {
188 continue;
189 }
190
191 // Check if defined within the parent operation.
192 if (Operation *defOp = operand.getDefiningOp()) {
193 if (op->isProperAncestor(defOp)) {
194 continue;
195 }
196 } else if (auto blockArg = llvm::dyn_cast<BlockArgument>(operand)) {
197 // A block argument has no defining op, so the check above cannot see
198 // it. One belonging to a region nested inside `op` -- an scf.for
199 // induction variable, most commonly -- is nonetheless defined within
200 // `op` and must not be collected as an external reference: it would
201 // reach copyReferencedSSAValues, whose getDefiningOp() is null, and
202 // fail with "Referenced value is not defined by an operation".
203 Operation *owner = blockArg.getOwner()->getParentOp();
204 if (owner && (owner == op || op->isProperAncestor(owner))) {
205 continue;
206 }
207 }
208
209 processValue(operand);
210 }
211 });
212 }
213}
214
215// Returns `base`, or `base_<n>` if the caller device already holds `base`, and
216// records the returned name in `allSymbolNames`.
217static std::string
218uniqueSymbolName(MLIRContext *ctx, llvm::StringRef base,
219 llvm::SetVector<SymbolRefAttr> &allSymbolNames) {
220 std::string uniqueName = base.str();
221 unsigned uniquingCounter = 0;
222 while (allSymbolNames.count(SymbolRefAttr::get(ctx, uniqueName))) {
223 uniqueName = base.str() + "_" + std::to_string(uniquingCounter);
224 uniquingCounter++;
225 }
226 allSymbolNames.insert(SymbolRefAttr::get(ctx, uniqueName));
227 return uniqueName;
228}
229
230// Return the operation in the caller device that stands for `op`, cloning `op`
231// on first use. `clonedDefs` spans the aiex.run calls of one caller device, so
232// several calls that name one definition share one clone and one symbol.
233static Operation *
234getOrClone(PatternRewriter &rewriter, Operation *op, IRMapping &argMap,
235 llvm::DenseMap<Operation *, Operation *> &clonedDefs,
236 mlir::OpBuilder::InsertPoint &insertPoint,
237 llvm::SetVector<SymbolRefAttr> &allSymbolNames) {
238 auto it = clonedDefs.find(op);
239 if (it == clonedDefs.end()) {
240 rewriter.restoreInsertionPoint(insertPoint);
241 Operation *clone = rewriter.clone(*op, argMap);
242 if (auto name = clone->getAttrOfType<StringAttr>(
243 SymbolTable::getSymbolAttrName())) {
244 clone->setAttr(SymbolTable::getSymbolAttrName(),
245 rewriter.getStringAttr(uniqueSymbolName(
246 op->getContext(), name.getValue(), allSymbolNames)));
247 }
248 it = clonedDefs.try_emplace(op, clone).first;
249 insertPoint = rewriter.saveInsertionPoint();
250 }
251 argMap.map(op->getResults(), it->second->getResults());
252 return it->second;
253}
254
255// Copies SSA value definitions into the caller device.
256// Supports `aie.tile`, `aie.lock` and `aie.buffer` operations.
257// Updates argMap to map old values to new/existing values.
258static LogicalResult copyReferencedSSAValues(
259 PatternRewriter &rewriter, const llvm::SetVector<Value> &referencedValues,
260 AIE::DeviceOp callerDevice, IRMapping &argMap,
261 llvm::DenseMap<Operation *, Operation *> &clonedDefs,
262 mlir::OpBuilder::InsertPoint &clonedSSAInsertPoint,
263 llvm::SetVector<SymbolRefAttr> &allSymbolNames, Operation *errorReportOp) {
264
265 llvm::SetVector<Value> referencedValuesToVisit = referencedValues;
266 std::vector<Operation *> referencedOpsToClone = {};
267 while (!referencedValuesToVisit.empty()) {
268 Value referencedValue = referencedValuesToVisit.pop_back_val();
269 Operation *definingOp = referencedValue.getDefiningOp();
270 if (!definingOp) {
271 return errorReportOp->emitError()
272 << "Referenced value is not defined by an operation";
273 }
274 if (llvm::find(referencedOpsToClone, definingOp) !=
275 referencedOpsToClone.end()) {
276 continue;
277 }
278
279 if (auto tileOp = llvm::dyn_cast<AIE::TileOp>(definingOp)) {
280 referencedOpsToClone.insert(referencedOpsToClone.begin(), definingOp);
281 } else if (auto lockOp = llvm::dyn_cast<AIE::LockOp>(definingOp)) {
282 Value lockTile = lockOp.getTile();
283 if (lockTile) {
284 referencedValuesToVisit.insert(lockTile);
285 }
286 referencedOpsToClone.push_back(definingOp);
287 } else if (auto bufferOp = llvm::dyn_cast<AIE::BufferOp>(definingOp)) {
288 referencedValuesToVisit.insert(bufferOp.getTile());
289 referencedOpsToClone.push_back(definingOp);
290 } else {
291 return errorReportOp->emitError()
292 << "Referenced SSA value defined by unsupported operation type: "
293 << definingOp->getName().getStringRef()
294 << ". Currently only aie.tile, aie.lock and aie.buffer "
295 "operations are supported.";
296 }
297 }
298
299 for (Operation *definingOp : referencedOpsToClone) {
300 if (auto tileOp = llvm::dyn_cast<AIE::TileOp>(definingOp)) {
301 int col = tileOp.getCol();
302 int row = tileOp.getRow();
303
304 // A tile is its coordinates, so a tile the caller already declares stands
305 // for the callee's tile.
306 AIE::TileOp existingTile = nullptr;
307 for (AIE::TileOp tile : callerDevice.getOps<AIE::TileOp>()) {
308 if (tile.getCol() == col && tile.getRow() == row) {
309 existingTile = tile;
310 break;
311 }
312 }
313
314 if (existingTile) {
315 // Verify that all attributes match
316 if (tileOp->getAttrDictionary() != existingTile->getAttrDictionary()) {
317 // Filter out result type attributes and symbol attributes for
318 // comparison
319 auto filterAttrs = [](DictionaryAttr dict) -> DictionaryAttr {
320 SmallVector<NamedAttribute> filteredAttrs;
321 for (auto namedAttr : dict) {
322 StringRef name = namedAttr.getName().getValue();
323 if (name != "col" && name != "row" &&
325 filteredAttrs.push_back(namedAttr);
326 }
327 }
328 return DictionaryAttr::get(dict.getContext(), filteredAttrs);
329 };
330
331 DictionaryAttr tileAttrs = filterAttrs(tileOp->getAttrDictionary());
332 DictionaryAttr existingAttrs =
333 filterAttrs(existingTile->getAttrDictionary());
334
335 if (tileAttrs != existingAttrs) {
336 return errorReportOp->emitError()
337 << "aie.tile(" << col << ", " << row
338 << ") already exists in the device with different "
339 "attributes";
340 }
341 }
342 // The callee's sequence ops move here, so the ids they pin do too.
343 SmallVector<AIE::ReservedBdId> calleeIds =
344 AIE::getReservedBdIds(tileOp);
345 if (!calleeIds.empty()) {
346 SmallVector<AIE::ReservedBdId> ids =
347 AIE::getReservedBdIds(existingTile);
348 ids.append(calleeIds);
349 AIE::setReservedBdIds(existingTile, ids);
350 }
351 // Clones go in at the insertion point; the caller's tile moves ahead
352 // of it, so the locks and buffers cloned onto it follow it.
353 Block *block = clonedSSAInsertPoint.getBlock();
354 Block::iterator point = clonedSSAInsertPoint.getPoint();
355 Operation *tile = existingTile.getOperation();
356 if (tile->getBlock() == block && point != block->end()) {
357 if (tile == &*point)
358 clonedSSAInsertPoint = OpBuilder::InsertPoint(block, ++point);
359 else if (!tile->isBeforeInBlock(&*point))
360 tile->moveBefore(&*point);
361 }
362 clonedDefs[definingOp] = tile;
363 }
364 }
365
366 Operation *clonedOp = getOrClone(rewriter, definingOp, argMap, clonedDefs,
367 clonedSSAInsertPoint, allSymbolNames);
368 rewriter.replaceOpUsesWithIf(
369 definingOp, clonedOp->getResult(0), [&](OpOperand &operand) {
370 return operand.getOwner()->getParentOfType<AIE::DeviceOp>() ==
371 callerDevice;
372 });
373 }
374
375 return success();
376}
377
378// Inlines the definitions of all symbols referenced in the given operation
379// at the current insertion point in the given rewriter, unless the symbol
380// definition is in the "previouslyInlinedSymbolMap" map. While inlining,
381// symbols will be renamed to have a unique name.
382// Also copies in SSA values referenced by the inlined symbol definitions.
383static LogicalResult inlineReferencedSymbolDefinitions(
384 PatternRewriter &rewriter, Operation *op, Operation *lookupFrom,
385 IRMapping &argMap,
386 llvm::DenseMap<SymbolRefAttr, SymbolRefAttr> &previouslyInlinedSymbolMap,
387 AIE::DeviceOp callerDevice,
388 llvm::DenseMap<Operation *, Operation *> &clonedDefs,
389 AIE::NamedOpTableCollection &calleeNames,
390 mlir::OpBuilder::InsertPoint &clonedDefOpsInsertionPoint,
391 llvm::SetVector<SymbolRefAttr> &allSymbolNames) {
392 for (NamedAttribute namedAttr : op->getAttrs()) {
393 Attribute attr = namedAttr.getValue();
394 auto newAttr = attr.replace([&](SymbolRefAttr oldSymbolRef) {
395 auto inlined = previouslyInlinedSymbolMap.find(oldSymbolRef);
396 if (inlined != previouslyInlinedSymbolMap.end())
397 return std::make_pair(inlined->second, WalkResult::advance());
398
399 // Add the new symbol definition
400 // First try to look up from the lookupFrom operation (e.g., within the
401 // callee device). If not found, try looking up from the module level
402 // (for cross-device references).
403 // The caller device gains clones as calls are inlined; a callee device
404 // keeps its names while the caller's calls are inlined, so it is indexed
405 // once.
406 Operation *symbolDefOp = nullptr;
407 Operation *calleeTable = SymbolTable::getNearestSymbolTable(lookupFrom);
408 if (calleeTable && calleeTable != callerDevice &&
409 oldSymbolRef.getNestedReferences().empty()) {
410 symbolDefOp = calleeNames.getTable(calleeTable)
411 .lookup(oldSymbolRef.getRootReference());
412 } else {
413 symbolDefOp =
414 SymbolTable::lookupNearestSymbolFrom(lookupFrom, oldSymbolRef);
415 if (!symbolDefOp && oldSymbolRef.getNestedReferences().empty()) {
416 symbolDefOp =
417 AIE::lookupNamedOp(lookupFrom, oldSymbolRef.getRootReference());
418 }
419 }
420 if (!symbolDefOp) {
421 if (ModuleOp moduleOp = lookupFrom->getParentOfType<ModuleOp>()) {
422 symbolDefOp = SymbolTable::lookupSymbolIn(moduleOp, oldSymbolRef);
423 }
424 }
425 if (!symbolDefOp) {
426 return std::make_pair(oldSymbolRef, WalkResult::interrupt());
427 }
428
429 // If the symbol is a device, don't clone it - keep the original
430 // reference. Device ops must stay at module level.
431 if (llvm::isa<AIE::DeviceOp>(symbolDefOp)) {
432 previouslyInlinedSymbolMap[oldSymbolRef] = oldSymbolRef;
433 return std::make_pair(oldSymbolRef, WalkResult::advance());
434 }
435
436 // Collect SSA values referenced by the symbol definition operation
437 llvm::SetVector<Value> symbolReferencedValues;
438 collectReferencedSSAValues(symbolDefOp, argMap, symbolReferencedValues);
439
440 // Copy SSA values referenced by the symbol definition
441 // This updates clonedDefOpsInsertionPoint to be after the copied SSA
442 // values
443 if (failed(copyReferencedSSAValues(
444 rewriter, symbolReferencedValues, callerDevice, argMap,
445 clonedDefs, clonedDefOpsInsertionPoint, allSymbolNames, op))) {
446 return std::make_pair(oldSymbolRef, WalkResult::interrupt());
447 }
448
449 // Insert the cloned symbol at the device level, after its SSA
450 // dependencies. A definition also named by SSA shares that clone.
451 bool cloned = !clonedDefs.contains(symbolDefOp);
452 Operation *clonedSymbolDefOp =
453 getOrClone(rewriter, symbolDefOp, argMap, clonedDefs,
454 clonedDefOpsInsertionPoint, allSymbolNames);
455 SymbolRefAttr newSymbolRef =
456 FlatSymbolRefAttr::get(clonedSymbolDefOp->getAttrOfType<StringAttr>(
457 SymbolTable::getSymbolAttrName()));
458 previouslyInlinedSymbolMap[oldSymbolRef] = newSymbolRef;
459 // A definition may itself name others, as a shim allocation's
460 // consumed_by names its outputs, and the clone must name their clones.
461 if (cloned &&
462 failed(inlineReferencedSymbolDefinitions(
463 rewriter, clonedSymbolDefOp, symbolDefOp, argMap,
464 previouslyInlinedSymbolMap, callerDevice, clonedDefs, calleeNames,
465 clonedDefOpsInsertionPoint, allSymbolNames)))
466 return std::make_pair(oldSymbolRef, WalkResult::interrupt());
467 // A copied consumption proof describes the device it came from.
468 auto allocation = dyn_cast<AIE::ShimDMAAllocationOp>(clonedSymbolDefOp);
469 ArrayAttr proofs = allocation ? allocation.getConsumedByAttr() : nullptr;
470 auto callee = symbolDefOp->getParentOfType<AIE::DeviceOp>();
471 if (cloned && proofs && callee && callee.getSymNameAttr()) {
472 SmallVector<Attribute> stamped;
473 for (auto proof : proofs.getAsRange<AIE::ConsumedByAttr>())
474 stamped.push_back(AIE::ConsumedByAttr::get(
475 proof.getContext(), proof.getOutput(), proof.getInputBytes(),
476 proof.getOutputBytes(), proof.getGranuleBytes(),
477 proof.getDevice()
478 ? proof.getDevice()
479 : FlatSymbolRefAttr::get(callee.getSymNameAttr())));
480 allocation.setConsumedByAttr(rewriter.getArrayAttr(stamped));
481 }
482 return std::make_pair(newSymbolRef, WalkResult::advance());
483 });
484 if (!newAttr) {
485 return failure();
486 }
487 op->setAttr(namedAttr.getName(), newAttr);
488 }
489 return success();
490}
491
492struct InlineRuntimeCallsPattern : RewritePattern {
493
494 mlir::OpBuilder::InsertPoint &ssaDefInsertPoint;
495 mlir::OpBuilder::InsertPoint &symbolDefInsertPoint;
496 llvm::SetVector<SymbolRefAttr> &allSymbolNames;
497 llvm::DenseMap<Operation *, Operation *> &clonedDefs;
499
501 MLIRContext *ctx, mlir::OpBuilder::InsertPoint &ssaDefInsertPoint,
502 mlir::OpBuilder::InsertPoint &symbolDefInsertPoint,
503 llvm::SetVector<SymbolRefAttr> &allSymbolNames,
504 llvm::DenseMap<Operation *, Operation *> &clonedDefs,
506 : RewritePattern(RunOp::getOperationName(), PatternBenefit(1), ctx),
511
512 LogicalResult matchAndRewrite(Operation *op,
513 PatternRewriter &rewriter) const override {
514 llvm::DenseMap<SymbolRefAttr, SymbolRefAttr> previouslyInlinedSymbolMap;
515
516 RunOp runOp = llvm::dyn_cast<RunOp>(op);
517 if (!runOp) {
518 return failure();
519 }
520
521 AIE::DeviceOp calleeDevice = runOp.getCalleeDeviceOp();
522 AIE::RuntimeSequenceOp calleeRuntimeSequence =
523 runOp.getCalleeRuntimeSequenceOp(&calleeNames);
524 if (!calleeDevice || !calleeRuntimeSequence) {
525 return failure();
526 }
527
528 // rewrite logic
529
530 // Get caller and callee bodies. The callee body will be inlined into the
531 // caller body at the point of the RunOp.
532 Region &calleeBody = calleeRuntimeSequence.getBody();
533 AIE::DeviceOp callerDevice =
534 runOp.getOperation()->getParentOfType<AIE::DeviceOp>();
535 if (!callerDevice) {
536 runOp.emitError() << "needs to be in a DeviceOp";
537 return failure();
538 }
539
540 // The argMap maps callee arguments to caller SSA values.
541 IRMapping argMap;
542 ValueRange values = runOp.getArgs();
543 for (unsigned i = 0, n = calleeBody.getNumArguments(); i < n; i++) {
544 BlockArgument arg = calleeBody.getArgument(i);
545 Value val = values[i];
546 argMap.map(arg, val);
547 }
548
549 // The callee body may reference SSA values and symbols that are defined
550 // in the callee device (outside the callee runtime sequence). We will
551 // inline a supported set of these and error otherwise.
552
553 // Collect SSA values referenced in the callee not defined by the callee and
554 // not in the argMap.
555 llvm::SetVector<Value> referencedValues;
556 for (Operation &op : calleeBody.getOps()) {
557 collectReferencedSSAValues(&op, argMap, referencedValues);
558 }
559 llvm::SetVector<Value> filteredValues;
560 for (Value val : referencedValues) {
561 if (val.getParentRegion() != &calleeBody) {
562 filteredValues.insert(val);
563 }
564 }
565 referencedValues = std::move(filteredValues);
566
567 // Copy the operations that define these SSA values into the caller device
568 if (failed(copyReferencedSSAValues(rewriter, referencedValues, callerDevice,
570 allSymbolNames, runOp))) {
571 return failure();
572 }
573
574 // Find the calling runtime sequence so we can hoist certain ops to its
575 // start instead of placing them at the call site.
576 AIE::RuntimeSequenceOp callerRuntimeSequence =
577 runOp.getOperation()->getParentOfType<AIE::RuntimeSequenceOp>();
578 if (!callerRuntimeSequence) {
579 runOp.emitError() << "needs to be (transitively) inside a "
580 "aie.runtime_sequence operation";
581 return failure();
582 }
583 Block &callerBodyBlock = callerRuntimeSequence.getBody().front();
584 mlir::Block::iterator hoistPos = callerBodyBlock.begin();
585
586 // Now, also inline symbol definitions referenced in the callee body;
587 // this may pull in additional SSA values referenced by the symbol
588 // definitions.
589 //
590 // npu.create_scratchpad ops are hoisted to the start of the calling
591 // runtime sequence instead of being placed at the call site, so a single
592 // scratchpad is created per sequence regardless of how many callees were
593 // inlined.
594 rewriter.setInsertionPoint(runOp);
595 mlir::OpBuilder::InsertPoint clonedOpInsertionPoint =
596 rewriter.saveInsertionPoint();
597 for (Operation &op : calleeBody.getOps()) {
598 bool shouldHoist = llvm::isa<NpuCreateScratchpadOp>(&op);
599 if (shouldHoist) {
600 rewriter.setInsertionPoint(&callerBodyBlock, hoistPos);
601 rewriter.clone(op, argMap);
602 continue;
603 }
604
605 rewriter.restoreInsertionPoint(clonedOpInsertionPoint);
606 Operation *clonedOp = rewriter.clone(op, argMap);
607 clonedOpInsertionPoint = rewriter.saveInsertionPoint();
608
609 // Inline symbol references in all nested ops.
610 WalkResult symbolWalk = clonedOp->walk([&](Operation *nestedOp) {
611 if (failed(inlineReferencedSymbolDefinitions(
612 rewriter, nestedOp, calleeRuntimeSequence.getOperation(),
613 argMap, previouslyInlinedSymbolMap, callerDevice, clonedDefs,
615 return WalkResult::interrupt();
616 }
617 return WalkResult::advance();
618 });
619 if (symbolWalk.wasInterrupted()) {
620 return failure();
621 }
622 }
623
624 // The aiex.run op has been inlined; erase it.
625 rewriter.eraseOp(runOp);
626
627 return success();
628 }
629};
630
631/// Validate all aiex.run ops inside a aiex.configure op against the referenced
632/// device. This must be called sequentially (before any parallel pass
633/// execution) because it performs cross-DeviceOp symbol table lookups.
634/// Placing this validation in RunOp::verify() is unsafe: MLIR's pass manager
635/// may invoke op verifiers concurrently on sibling DeviceOps, causing a data
636/// race on the referenced device's symbol table.
637static LogicalResult
638verifyRunOpsInConfigureOp(ConfigureOp configureOp, AIE::DeviceOp referencedDev,
639 AIE::NamedOpTableCollection &referencedDevNames) {
640 if (configureOp.getBody().empty())
641 return success();
642 AIE::NamedOpTable &devNames = referencedDevNames.getTable(referencedDev);
643 for (RunOp runOp : configureOp.getBody().front().getOps<RunOp>()) {
644 auto seqName = runOp.getRuntimeSequenceSymbol();
645 Operation *maybeSeq =
646 devNames.lookup(runOp.getRuntimeSequenceSymbolAttr().getAttr());
647 if (!maybeSeq) {
648 auto err = runOp.emitError()
649 << "No such runtime sequence for device '"
650 << referencedDev.getSymName() << "': '" << seqName << "'";
651 err.attachNote(referencedDev.getLoc())
652 << "This device does not have a '" << seqName << "' runtime sequence";
653 return failure();
654 }
655 auto runtimeSeq = llvm::dyn_cast<AIE::RuntimeSequenceOp>(maybeSeq);
656 if (!runtimeSeq) {
657 return runOp.emitError()
658 << "'" << seqName << "' is not a runtime sequence";
659 }
660
661 // Validate argument count and types against the callee signature.
662 // An empty body region (no blocks) means the sequence takes no arguments.
663 Region &calleeRegion = runtimeSeq.getBody();
664 unsigned numCalleeArgs =
665 calleeRegion.empty() ? 0 : calleeRegion.getNumArguments();
666 ValueRange args = runOp.getArgs();
667 if (numCalleeArgs != args.size())
668 return runOp.emitOpError() << "argument count mismatch: expected "
669 << numCalleeArgs << " but got " << args.size();
670 for (unsigned i = 0; i < numCalleeArgs; i++) {
671 Type expected = calleeRegion.front().getArgument(i).getType();
672 Type actual = args[i].getType();
673 if (expected != actual)
674 return runOp.emitOpError()
675 << "argument " << i << " type mismatch: expected " << expected
676 << " but got " << actual;
677 }
678 }
679 return success();
680}
681
684 AIEMaterializeRuntimeSequencesPass> {
685 using Base::Base;
686
687 // After inlining, a runtime sequence may contain multiple
688 // npu.create_scratchpad ops (one from the sequence itself and one from each
689 // inlined callee). Keep only the first; all must agree on size because the
690 // scratchpad size is a module-level property. Returns failure if a size
691 // mismatch is detected.
692 LogicalResult
693 deduplicateCreateScratchpadOps(AIE::RuntimeSequenceOp runtimeSeqOp) {
694 if (runtimeSeqOp.getBody().empty())
695 return success();
696
697 Block &body = runtimeSeqOp.getBody().front();
698 NpuCreateScratchpadOp firstScratchpad;
699 SmallVector<NpuCreateScratchpadOp> duplicates;
700 for (NpuCreateScratchpadOp scratchpadOp :
701 body.getOps<NpuCreateScratchpadOp>()) {
702 if (!firstScratchpad) {
703 firstScratchpad = scratchpadOp;
704 continue;
705 }
706 if (firstScratchpad.getSize() != scratchpadOp.getSize()) {
707 scratchpadOp.emitError(
708 "create_scratchpad size mismatch after inlining: ")
709 << scratchpadOp.getSize() << " != " << firstScratchpad.getSize();
710 return failure();
711 }
712 duplicates.push_back(scratchpadOp);
713 }
714 for (NpuCreateScratchpadOp dup : duplicates)
715 dup.erase();
716
717 return success();
718 }
719
720 void runOnOperation() override {
721 ModuleOp moduleOp = getOperation();
722
723 AIE::NamedOpTableCollection referencedDevNames;
724
725 // Process each device in the module
726 for (AIE::DeviceOp deviceOp : moduleOp.getOps<AIE::DeviceOp>()) {
727
728 // Verify all runtime sequences before materialization
729 for (AIE::RuntimeSequenceOp runtimeSequenceOp :
730 deviceOp.getOps<AIE::RuntimeSequenceOp>()) {
731 if (failed(runtimeSequenceOp.verifyBeforeMaterialization())) {
732 return signalPassFailure();
733 }
734
735 // Validate aiex.run ops inside aiex.configure ops. This cross-device
736 // check is performed here (sequentially) rather than in RunOp::verify()
737 // to avoid a race condition: MLIR's pass manager runs verifiers on
738 // sibling DeviceOps concurrently, and looking up symbols in a sibling
739 // DeviceOp from a verifier causes a data race on its symbol table.
740 for (ConfigureOp configureOp :
741 runtimeSequenceOp.getOps<ConfigureOp>()) {
742 AIE::DeviceOp referencedDev = configureOp.getReferencedDeviceOp();
743 if (!referencedDev) {
744 // ConfigureOp::verify() already reported the error (no such
745 // device, not a device, or device type mismatch) at parse time;
746 // this is a safety net if verification was disabled.
747 return signalPassFailure();
748 }
749 if (failed(verifyRunOpsInConfigureOp(configureOp, referencedDev,
750 referencedDevNames)))
751 return signalPassFailure();
752 }
753 }
754
755 // Check for cycles in runtime sequence calls
756 for (AIE::RuntimeSequenceOp runtimeSequenceOp :
757 deviceOp.getOps<AIE::RuntimeSequenceOp>()) {
758 AnalysisManager am =
759 getAnalysisManager().nest(deviceOp).nest(runtimeSequenceOp);
761 am.getAnalysis<RuntimeCallGraphCyclicityAnalysis>();
762 if (!cyclicity.isValid) {
763 return signalPassFailure();
764 }
765 if (cyclicity.isCyclic) {
766 runtimeSequenceOp.emitError(
767 "Runtime sequence call graph contains a cycle");
768 return signalPassFailure();
769 }
770 }
771
772 // Greedily inline all runtime sequences that can be inlined;
773 // this will start with runtime sequences that do not call other runtime
774 // sequences (leaves); once their callers inline them, the callers can
775 // be inlined as well, and so on
776 mlir::Block &deviceBodyFirstBlock = deviceOp.getBodyRegion().front();
777 auto runtimeSequenceOps = deviceOp.getOps<AIE::RuntimeSequenceOp>();
778 if (runtimeSequenceOps.begin() == runtimeSequenceOps.end()) {
779 // No runtime sequences to materialize
780 continue;
781 }
782 AIE::RuntimeSequenceOp firstRuntimeSequenceOp =
783 *runtimeSequenceOps.begin();
784 mlir::OpBuilder::InsertPoint ssaDefInsertPoint(
785 &deviceBodyFirstBlock, deviceBodyFirstBlock.begin());
786 mlir::OpBuilder::InsertPoint symbolDefInsertPoint(
787 &deviceBodyFirstBlock, mlir::Block::iterator(firstRuntimeSequenceOp));
788 llvm::SetVector<SymbolRefAttr> allSymbolNames = {};
789 for (Operation &op : deviceBodyFirstBlock) {
790 if (auto symbolName = op.getAttrOfType<StringAttr>(
791 SymbolTable::getSymbolAttrName())) {
792 allSymbolNames.insert(SymbolRefAttr::get(symbolName));
793 }
794 }
795
796 MLIRContext *ctx = &getContext();
797 GreedyRewriteConfig rewriter_config = GreedyRewriteConfig();
798 rewriter_config.setRegionSimplificationLevel(
799 GreedySimplifyRegionLevel::Disabled);
800
801 RewritePatternSet patterns_0(ctx);
802 llvm::DenseMap<Operation *, Operation *> clonedDefs;
803 AIE::NamedOpTableCollection calleeNames;
804 patterns_0.insert<InlineRuntimeCallsPattern>(
805 ctx, ssaDefInsertPoint, symbolDefInsertPoint, allSymbolNames,
806 clonedDefs, calleeNames);
807 if (failed(applyPatternsGreedily(deviceOp, std::move(patterns_0),
808 rewriter_config))) {
809 return signalPassFailure();
810 }
811
812 // Deduplicate create_scratchpad ops that were hoisted during inlining.
813 for (AIE::RuntimeSequenceOp runtimeSeqOp :
814 deviceOp.getOps<AIE::RuntimeSequenceOp>()) {
815 if (failed(deduplicateCreateScratchpadOps(runtimeSeqOp)))
816 return signalPassFailure();
817 }
818
819 // Insert LoadPDI ops for each aiex.configure op
820 RewritePatternSet patterns_1(ctx);
821 patterns_1.insert<InsertLoadPdiForConfigurePattern>(ctx);
822 walkAndApplyPatterns(deviceOp, std::move(patterns_1));
823
824 // Canonicalize to remove duplicate back-to-back load_pdi ops, visiting
825 // only the load_pdi ops rather than every op of the sequences.
826 RewritePatternSet canonicalize_patterns(ctx);
827 AIEX::NpuLoadPdiOp::getCanonicalizationPatterns(canonicalize_patterns,
828 ctx);
829 SmallVector<Operation *> loadPdis;
830 deviceOp.walk([&](NpuLoadPdiOp op) { loadPdis.push_back(op); });
831 GreedyRewriteConfig loadPdiConfig = rewriter_config;
832 loadPdiConfig.setStrictness(GreedyRewriteStrictness::ExistingOps);
833 if (failed(applyOpPatternsGreedily(
834 loadPdis, std::move(canonicalize_patterns), loadPdiConfig))) {
835 return signalPassFailure();
836 }
837
838 // Flatten the IR: hoist all operations inside aiex.configure to be direct
839 // children of the runtime sequence, preserving order
840 for (AIE::RuntimeSequenceOp runtimeSequenceOp :
841 deviceOp.getOps<AIE::RuntimeSequenceOp>()) {
842 SmallVector<ConfigureOp> configureOps;
843
844 for (ConfigureOp configureOp :
845 runtimeSequenceOp.getOps<ConfigureOp>()) {
846 configureOps.push_back(configureOp);
847 }
848
849 IRRewriter rewriter(ctx);
850 for (ConfigureOp configureOp : configureOps) {
851 Block &configureBlock = configureOp.getBody().front();
852
853 // Collect all operations in the configure block
854 SmallVector<Operation *> opsToHoist;
855 for (Operation &op : configureBlock) {
856 opsToHoist.push_back(&op);
857 }
858
859 // Hoist operations to be right before the configure op
860 rewriter.setInsertionPoint(configureOp);
861 for (Operation *op : opsToHoist) {
862 op->moveBefore(configureOp);
863 }
864
865 // Erase the now-empty configure op
866 rewriter.eraseOp(configureOp);
867 }
868 }
869
870 } // end for each device
871 }
872};
873
874std::unique_ptr<OperationPass<ModuleOp>>
876 return std::make_unique<AIEMaterializeRuntimeSequencesPass>();
877}
NamedOpTable & getTable(mlir::Operation *symbolTableOp)
Definition AIEDialect.h:175
mlir::Operation * lookup(mlir::StringAttr name) const
Definition AIEDialect.h:153
std::optional< SubviewTraceResult > traceSubviewToBlockArgument(Value value)
Definition AIEUtils.cpp:25
std::unique_ptr< mlir::OperationPass< mlir::ModuleOp > > createAIEMaterializeRuntimeSequencesPass()
void setReservedBdIds(TileOp tile, llvm::ArrayRef< ReservedBdId > ids)
bool isReservedBdIdsAttr(llvm::StringRef name)
mlir::Operation * lookupNamedOp(mlir::Operation *from, mlir::StringAttr name)
llvm::SmallVector< ReservedBdId > getReservedBdIds(TileOp tile)
LogicalResult deduplicateCreateScratchpadOps(AIE::RuntimeSequenceOp runtimeSeqOp)
LogicalResult matchAndRewrite(Operation *op, PatternRewriter &rewriter) const override
mlir::OpBuilder::InsertPoint & ssaDefInsertPoint
InlineRuntimeCallsPattern(MLIRContext *ctx, mlir::OpBuilder::InsertPoint &ssaDefInsertPoint, mlir::OpBuilder::InsertPoint &symbolDefInsertPoint, llvm::SetVector< SymbolRefAttr > &allSymbolNames, llvm::DenseMap< Operation *, Operation * > &clonedDefs, AIE::NamedOpTableCollection &calleeNames)
llvm::DenseMap< Operation *, Operation * > & clonedDefs
mlir::OpBuilder::InsertPoint & symbolDefInsertPoint
llvm::SetVector< SymbolRefAttr > & allSymbolNames
AIE::NamedOpTableCollection & calleeNames
InsertLoadPdiForConfigurePattern(MLIRContext *context, PatternBenefit benefit=1)
LogicalResult matchAndRewrite(Operation *op, PatternRewriter &rewriter) const override
RuntimeCallGraphCyclicityAnalysis(Operation *op, AnalysisManager &am)