MLIR-AIE 1.4.6.dev
AIETargetNPU.cpp
Go to the documentation of this file.
1//===- AIETargetNPU.cpp -----------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2023-2025 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
9
17
18#include "mlir/Dialect/Arith/IR/Arith.h"
19#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
20#include "mlir/Dialect/Func/IR/FuncOps.h"
21#include "mlir/Dialect/MemRef/IR/MemRef.h"
22#include "mlir/IR/SymbolTable.h"
23#include "mlir/Interfaces/DataLayoutInterfaces.h"
24#include "mlir/Interfaces/SideEffectInterfaces.h"
25
26#include "mlir/Tools/mlir-translate/MlirTranslateMain.h"
27#include "llvm/ADT/DenseMap.h"
28
29#include "mlir/Dialect/Utils/StaticValueUtils.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/TypeSwitch.h"
32#include "llvm/Support/Format.h"
33#include "llvm/Support/FormatVariadic.h"
34#include "llvm/Support/JSON.h"
35#include "llvm/Support/raw_ostream.h"
36
37#include <memory>
38#include <vector>
39
40using namespace mlir;
41using namespace xilinx;
42using namespace xilinx::AIE;
43using namespace xilinx::AIEX;
44
45namespace {
46
47// Example:
48// - instructions = {3,4,5}
49// - tailSize = 2
50// instructions becomes {3,4,5,0,0} and
51// a mutable reference to the tail {0,0} is returned.
52llvm::MutableArrayRef<uint32_t>
53reserveAndGetTail(std::vector<uint32_t> &instructions, uint64_t tailSize) {
54 auto oldSize = instructions.size();
55 auto newSize = oldSize + tailSize;
56 instructions.resize(newSize, 0);
57 return llvm::MutableArrayRef<uint32_t>(instructions.data() + oldSize,
58 tailSize);
59}
60
61// Thin wrappers that extract MLIR attributes and delegate to TxnEncoding.h,
62// the single source of truth for the TXN word layout.
63
64LogicalResult appendSync(std::vector<uint32_t> &instructions, NpuSyncOp op) {
65 std::optional<uint32_t> column = AIEX::getConstantIntOperand(op.getColumn());
66 std::optional<uint32_t> row = AIEX::getConstantIntOperand(op.getRow());
67 std::optional<uint32_t> direction =
68 AIEX::getConstantIntOperand(op.getDirection());
69 std::optional<uint32_t> channel =
70 AIEX::getConstantIntOperand(op.getChannel());
71 std::optional<uint32_t> columnNum =
72 AIEX::getConstantIntOperand(op.getColumnNum());
73 std::optional<uint32_t> rowNum = AIEX::getConstantIntOperand(op.getRowNum());
74 if (!column || !row || !direction || !channel || !columnNum || !rowNum)
75 return op.emitOpError("Cannot translate sync with non-constant operands to "
76 "a static TXN binary");
77 aie_runtime::txn_append_sync(instructions, *column, *row, *direction,
78 *channel, *columnNum, *rowNum);
79 return success();
80}
81
82LogicalResult appendWrite32(std::vector<uint32_t> &instructions,
83 NpuWrite32Op op) {
84 if (op.getBuffer())
85 return op.emitOpError("Cannot translate symbolic address");
86 std::optional<uint32_t> address = op.getAbsoluteAddress();
87 std::optional<uint32_t> value = AIEX::getConstantIntOperand(op.getValue());
88 if (!address || !value)
89 return op.emitOpError(
90 "Cannot translate write32 with non-constant address or value "
91 "to a static TXN binary");
92 aie_runtime::txn_append_write32(instructions, *address, *value);
93 return success();
94}
95
96LogicalResult appendMaskWrite32(std::vector<uint32_t> &instructions,
97 NpuMaskWrite32Op op) {
98 if (op.getBuffer())
99 return op.emitOpError("Cannot translate symbolic address");
100 std::optional<uint32_t> address = op.getAbsoluteAddress();
101 std::optional<uint32_t> value = AIEX::getConstantIntOperand(op.getValue());
102 std::optional<uint32_t> mask = AIEX::getConstantIntOperand(op.getMask());
103 if (!address || !value || !mask)
104 return op.emitOpError("Cannot translate maskwrite32 with non-constant "
105 "address, value, or mask to a static TXN binary");
106 aie_runtime::txn_append_maskwrite32(instructions, *address, *value, *mask);
107 return success();
108}
109
110LogicalResult appendMaskPoll(std::vector<uint32_t> &instructions,
111 NpuMaskPollOp op) {
112 if (op.getBuffer())
113 return op.emitOpError("Cannot translate symbolic address");
114 std::optional<uint32_t> address = op.getAbsoluteAddress();
115 std::optional<uint32_t> value = AIEX::getConstantIntOperand(op.getValue());
116 std::optional<uint32_t> mask = AIEX::getConstantIntOperand(op.getMask());
117 if (!address || !value || !mask)
118 return op.emitOpError("Cannot translate maskpoll with non-constant "
119 "address, value, or mask to a static TXN binary");
120 aie_runtime::txn_append_maskpoll32(instructions, *address, *value, *mask);
121 return success();
122}
123
124void appendLoadPdi(std::vector<uint32_t> &instructions, NpuLoadPdiOp op) {
125 aie_runtime::txn_append_loadpdi(instructions, op.getId(), op.getSize(),
126 op.getAddress());
127}
128
129LogicalResult appendAddressPatch(std::vector<uint32_t> &instructions,
130 NpuAddressPatchOp op, bool foldDDRAddrOffset) {
131 if (op.getAddrVal())
132 return op.emitOpError("Cannot translate address_patch with a runtime "
133 "register address (addr_val) to a static TXN binary; "
134 "the runtime-bd_id pool path targets the C++ TXN "
135 "target only");
136 std::optional<uint64_t> argPlus =
137 AIEX::getConstantInt64Operand(op.getArgPlus());
138 if (!argPlus)
139 return op.emitOpError("Cannot translate address_patch with non-constant "
140 "arg_plus to a static TXN binary");
141 std::optional<uint32_t> argIdx = op.getArgIdx();
142 if (!argIdx)
143 return op.emitOpError("address_patch still names its host buffer by SSA "
144 "value; run -aie-resolve-address-patch-buffers");
145 aie_runtime::txn_append_arg_patch(instructions, op.getAddr(), *argIdx,
146 *argPlus, foldDDRAddrOffset);
147 return success();
148}
149
150// Cached resolution of NpuBlockWriteOp's data words.
151// NpuBlockWriteOp::getDataWords() resolves the data memref.global via
152// device.lookupSymbol (a LINEAR symbol scan over the device's symbols) +
153// global.getInitialValue() on EVERY call — perf shows this
154// (SymbolTable::lookupSymbolIn + memref::GlobalOp::getInherentAttr) is ~47% of
155// AIETranslateNpuToBinary on a B=128 runtime sequence (~10^5 block-writes),
156// i.e. O(block-writes x globals). Resolve via a prebuilt per-device SymbolTable
157// (O(1)) and memoize per global symbol (the B-unroll's streams reuse the same
158// data globals), so the returned attribute is byte-identical but the work
159// collapses. Falls back to the canonical method on any non-global memref /
160// lookup miss (identical behavior).
161static DenseIntElementsAttr cachedBlockWriteData(
162 NpuBlockWriteOp op, mlir::SymbolTable &symTab,
163 llvm::DenseMap<mlir::StringAttr, DenseIntElementsAttr> &cache) {
164 auto getGlobal = op.getData().getDefiningOp<mlir::memref::GetGlobalOp>();
165 if (!getGlobal)
166 return op.getDataWords();
167 // A hit already passed the width check: get_global's type is its global's.
168 mlir::StringAttr key = getGlobal.getNameAttr().getRootReference();
169 auto it = cache.find(key);
170 if (it != cache.end())
171 return it->second;
172 // Honor getDataWords()'s 32-bit-element contract exactly: a non-32-bit memref
173 // must take the canonical path (which emits "Only 32-bit data type is
174 // supported" + returns nullptr), not the cached fast path.
175 mlir::DataLayout dataLayout = mlir::DataLayout::closest(op);
176 if (dataLayout.getTypeSizeInBits(
177 mlir::cast<mlir::MemRefType>(op.getData().getType())
178 .getElementType()) != 32)
179 return op.getDataWords();
180 DenseIntElementsAttr data;
181 if (auto global =
182 dyn_cast_if_present<mlir::memref::GlobalOp>(symTab.lookup(key)))
183 if (auto initVal = global.getInitialValue())
184 data = dyn_cast<DenseIntElementsAttr>(*initVal);
185 if (!data)
186 data = op.getDataWords(); // preserve original error/edge behavior exactly
187 cache[key] = data;
188 return data;
189}
190
191LogicalResult appendBlockWrite(
192 std::vector<uint32_t> &instructions, NpuBlockWriteOp op,
193 std::optional<uint32_t> address, mlir::SymbolTable &symTab,
194 llvm::DenseMap<mlir::StringAttr, DenseIntElementsAttr> &dataCache) {
195 if (!address)
196 return op.emitOpError(
197 "Cannot translate blockwrite with unresolved address to a static TXN "
198 "binary");
199 DenseIntElementsAttr data = cachedBlockWriteData(op, symTab, dataCache);
200
201 // Resolve the payload words via the (cached) data attribute, then hand off to
202 // the encoder which owns the word layout.
203 std::vector<uint32_t> payload;
204 payload.reserve(data.size());
205 if (auto words = data.tryGetValues<uint32_t>(); succeeded(words))
206 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
207 payload.assign(words->begin(), words->end());
208 else
209 for (auto d : data)
210 payload.push_back(d.getZExtValue());
211
212 // The col/row word is only populated when BOTH are present (matching the
213 // historical behavior); otherwise it stays 0 (a flat address).
214 auto col = op.getColumn();
215 auto row = op.getRow();
216 uint32_t colVal = 0, rowVal = 0;
217 if (col && row) {
218 colVal = *col;
219 rowVal = *row;
220 }
221 aie_runtime::txn_append_blockwrite(instructions, *address, payload.data(),
222 payload.size(), colVal, rowVal);
223 return success();
224}
225
226void appendPreempt(std::vector<uint32_t> &instructions, NpuPreemptOp op) {
227 aie_runtime::txn_append_preempt(instructions, op.getLevel());
228}
229
230void appendCreateScratchpad(std::vector<uint32_t> &instructions,
231 NpuCreateScratchpadOp op) {
232 // TXN_OPC_CREATE_SCRATCHPAD encoding (4 words = 16 bytes):
233 // Byte 0: Opcode (10)
234 // Byte 1: Usage Type
235 // Bytes 2-3: padding
236 // Bytes 4-7: Size
237 // Bytes 8-15: DDR Address (patched at runtime by XRT)
238 auto words = reserveAndGetTail(instructions, 4);
239
241 words[0] |= (static_cast<uint32_t>(op.getUsageType()) << 8);
242 words[1] = op.getSize();
243 // DDR address words[2] and words[3] are left as 0;
244 // they will be patched at runtime by XRT/aiebu based on the
245 // .ctrl.scratchpad section.
246 words[2] = 0;
247 words[3] = 0;
248}
249
250LogicalResult appendUpdateRegFromScratchpad(std::vector<uint32_t> &instructions,
251 NpuUpdateFromScratchpadOp op,
252 const NamedOpTable &names) {
253 std::optional<uint32_t> address = op.getAbsoluteAddress(&names);
254 if (!address)
255 return op.emitOpError("Cannot translate update_from_scratchpad with "
256 "unresolved address to a static TXN binary");
257 // TXN_OPC_UPDATE_REG encoding (3 words = 12 bytes):
258 // Byte 0: Opcode (12)
259 // Byte 1: StateTableIdx
260 // Byte 2: Func
261 // Byte 3: padding
262 // Bytes 4-7: FuncArg
263 // Bytes 8-11: RegOff (absolute offset from AIE array base to register pair)
264 auto words = reserveAndGetTail(instructions, 3);
265
267 words[0] |= (static_cast<uint32_t>(op.getStateTableIdx()) << 8);
268 words[0] |= (static_cast<uint32_t>(op.getFunc()) << 16);
269 words[1] = op.getFuncArg();
270 words[2] = *address;
271 return success();
272}
273
274} // namespace
275
276namespace {
277
278// Lazy-loaded regdb for register-name decoration, once per process and
279// architecture; nullptr if the JSON files cannot be located.
280static const xilinx::AIE::RegisterDatabase *getRegDB(const AIETargetModel &tm) {
281 if (tm.getTargetArch() == AIEArch::AIE4) {
282 static std::unique_ptr<xilinx::AIE::RegisterDatabase> db =
284 return db.get();
285 }
286 static std::unique_ptr<xilinx::AIE::RegisterDatabase> db =
288 return db.get();
289}
290
291// Decompose an absolute device address into (col, row, offset) using the
292// target model's tile address map, then derive the regdb module name from
293// the row's tile type. Looks the (module, offset) up in regdb. Returns the
294// register name on success and writes the module name to *outModule. On any
295// failure returns empty StringRef.
296static llvm::StringRef
297lookupRegisterByAddress(uint64_t address, const AIETargetModel &tm,
299 std::string &outModule) {
300 outModule.clear();
301 if (!regdb)
302 return {};
303 if (address > UINT32_MAX)
304 return {};
305 int col = tm.getColumnFromAddress(address);
306 int row = tm.getRowFromAddress(address);
307 uint32_t offset = address - tm.getTileAddress(col, row);
308
309 // Determine module from tile type. Module names must match the JSON keys in
310 // aie_registers_<arch>.json: "core", "memory", "memory_tile", "shim".
311 StringRef moduleName;
312 if (tm.isShimNOCTile(col, row) || tm.isShimPLTile(col, row)) {
313 moduleName = "shim";
314 } else if (tm.isMemTile(col, row)) {
315 moduleName = "memory_tile";
316 } else {
317 // For aie tiles, regdb has both core and memory modules. The offset alone
318 // disambiguates. Try core first then memory.
319 if (auto *r = regdb->lookupRegisterByOffset(offset, "core")) {
320 outModule = "core";
321 return r->name;
322 }
323 if (auto *r = regdb->lookupRegisterByOffset(offset, "memory")) {
324 outModule = "memory";
325 return r->name;
326 }
327 return {};
328 }
329 if (auto *r = regdb->lookupRegisterByOffset(offset, moduleName)) {
330 outModule = moduleName.str();
331 return r->name;
332 }
333 return {};
334}
335
336static void pushLocEntry(std::vector<TxnLocEntry> *locmap,
337 uint32_t byteOffsetBefore, uint32_t byteOffsetAfter,
338 StringRef opcodeName, StringRef sourceOpName,
339 std::optional<uint64_t> address, mlir::Operation *op,
340 const AIETargetModel &tm) {
341 if (!locmap)
342 return;
343 TxnLocEntry e;
344 e.byteOffset = byteOffsetBefore;
345 e.byteSize = byteOffsetAfter - byteOffsetBefore;
346 e.opcodeName = opcodeName.str();
347 e.sourceOpName = sourceOpName.str();
348 e.address = address;
349 e.loc = op->getLoc();
350 if (address) {
351 if (auto regName = lookupRegisterByAddress(*address, tm, getRegDB(tm),
353 !regName.empty()) {
354 e.registerName = regName.str();
355 }
356 }
357 locmap->push_back(std::move(e));
358}
359
360// Appends the TXN encoding of a runtime sequence's ops, one op at a time.
361struct TxnEncoder {
362 TxnEncoder(DeviceOp device, std::vector<uint32_t> &instructions,
363 std::vector<TxnLocEntry> *locmap, bool foldDDRAddrOffset,
364 NpuConfigCache &configs)
365 : device(device), tm(device.getTargetModel()),
366 symTab(device.getOperation()), names(device.getOperation()),
367 configs(configs), instructions(instructions), locmap(locmap),
368 foldDDRAddrOffset(foldDDRAddrOffset) {}
369
370 void encode(Operation &o);
371 LogicalResult encodeConfig(DeviceOp configured, bool teardown,
372 NpuConfigCache::Config &config);
373 void appendConfig(Operation *op, FlatSymbolRefAttr deviceRef, bool teardown);
374
375 DeviceOp device;
376 const AIETargetModel &tm;
377 // Built once, with a per-global data cache, so block-write data resolution
378 // is O(1)+memoized instead of a per-op linear symbol scan
379 // (cachedBlockWriteData). ~47% of the translation on a B=128 sequence.
380 mlir::SymbolTable symTab;
381 NamedOpTable names;
382 llvm::DenseMap<mlir::StringAttr, DenseIntElementsAttr> blockWriteDataCache;
383 NpuConfigCache &configs;
384 std::vector<uint32_t> &instructions;
385 std::vector<TxnLocEntry> *locmap;
386 bool foldDDRAddrOffset;
387 uint32_t count = 0;
388 // Accumulates failure from the per-op append helpers (e.g. a non-constant
389 // operand that cannot be encoded into a static TXN binary). The walk
390 // finishes so every offending op is diagnosed, then the translation fails
391 // rather than emit a silently incomplete binary.
392 LogicalResult result = success();
393};
394
395// Generates `configured`'s configuration ops, or with `teardown` its teardown
396// ops, as the expand-load-pdi pass would inline them, in a scratch device of
397// its own, and encodes them as a sequence's own ops are.
398LogicalResult TxnEncoder::encodeConfig(DeviceOp configured, bool teardown,
399 NpuConfigCache::Config &config) {
400 MLIRContext *ctx = device.getContext();
401 ctx->getOrLoadDialect<arith::ArithDialect>();
402 ctx->getOrLoadDialect<memref::MemRefDialect>();
403 OpBuilder builder(ctx);
404 OwningOpRef<ModuleOp> scratch = ModuleOp::create(device.getLoc());
405 builder.setInsertionPointToStart(scratch->getBody());
406 auto holder =
407 DeviceOp::create(builder, device.getLoc(), configured.getDevice(),
408 configured.getSymName(), nullptr);
409 holder.getRegion().emplaceBlock();
410 DeviceOp::ensureTerminator(holder.getBodyRegion(), builder, device.getLoc());
411 builder.setInsertionPointToStart(holder.getBody());
412 auto seq = RuntimeSequenceOp::create(
413 builder, device.getLoc(), builder.getStringAttr("configure"), BoolAttr{},
414 TraceBufferAttr{}, ArrayAttr{}, ArrayAttr{});
415 Block *body = new Block;
416 seq.getBody().push_back(body);
417 builder.setInsertionPointToStart(body);
418 BlockwriteData payloads(holder, teardown ? "teardown_" : "loadpdi_");
419 if (teardown
420 ? failed(generateAndInsertTeardownOps(builder, configured, payloads))
421 : failed(generateAndInsertConfigOps(builder, configured, payloads)))
422 return failure();
423 // The locmap is kept whether or not this translation writes one: another
424 // sharing the cache may.
425 TxnEncoder encoder(holder, config.words, &config.locmap, foldDDRAddrOffset,
426 configs);
427 for (Operation &op : *body)
428 encoder.encode(op);
429 config.count = encoder.count;
430 return encoder.result;
431}
432
433void TxnEncoder::appendConfig(Operation *op, FlatSymbolRefAttr deviceRef,
434 bool teardown) {
435 auto configured = dyn_cast_or_null<DeviceOp>(
436 SymbolTable::lookupSymbolIn(device->getParentOp(), deviceRef));
437 const NpuConfigCache::Config *config =
438 configured
439 ? configs.getOrEncode(configured, teardown,
440 [&](NpuConfigCache::Config &c) {
441 return encodeConfig(configured, teardown, c);
442 })
443 : nullptr;
444 if (!config) {
445 op->emitOpError(teardown ? "cannot generate the teardown of "
446 : "cannot generate the configuration of ")
447 << deviceRef;
448 result = failure();
449 return;
450 }
451 uint32_t base = static_cast<uint32_t>(instructions.size() * sizeof(uint32_t));
452 llvm::append_range(instructions, config->words);
453 count += config->count;
454 if (locmap)
455 for (TxnLocEntry entry : config->locmap) {
456 entry.byteOffset += base;
457 locmap->push_back(std::move(entry));
458 }
459}
460
461void TxnEncoder::encode(Operation &o) {
462 auto byteOffset = [&]() -> uint32_t {
463 return static_cast<uint32_t>(instructions.size() * sizeof(uint32_t));
464 };
465 llvm::TypeSwitch<Operation *>(&o)
466 .Case<cf::AssertOp>([&](auto op) {
467 // A static sequence only ever carries a constant-true guard
468 // (canonicalization erases it); a constant-false one failed at
469 // compile time, and anything unresolved means a runtime value
470 // reached the binary path.
471 auto c = getConstantIntValue(op.getArg());
472 if (c && *c == 0) {
473 op.emitOpError("is violated at compile time: ") << op.getMsg();
474 result = failure();
475 } else if (!c) {
476 op.emitOpError("runtime check cannot be encoded in a static TXN "
477 "binary; use the C++ builder (--aie-npu-to-cpp) "
478 "or specialize the value: ")
479 << op.getMsg();
480 result = failure();
481 }
482 })
483 .Case<NpuSyncOp>([&](auto op) {
484 count++;
485 uint32_t before = byteOffset();
486 if (failed(appendSync(instructions, op)))
487 result = failure();
488 pushLocEntry(locmap, before, byteOffset(), "TCT",
489 op->getName().getStringRef(), std::nullopt, op, tm);
490 })
491 .Case<NpuWrite32Op>([&](auto op) {
492 count++;
493 uint32_t before = byteOffset();
494 uint64_t addr = op.getAbsoluteAddress().value_or(0);
495 if (failed(appendWrite32(instructions, op)))
496 result = failure();
497 pushLocEntry(locmap, before, byteOffset(), "WRITE32",
498 op->getName().getStringRef(), addr, op, tm);
499 })
500 .Case<NpuBlockWriteOp>([&](auto op) {
501 count++;
502 uint32_t before = byteOffset();
503 std::optional<uint32_t> addr = op.getAbsoluteAddress(&names);
504 if (failed(appendBlockWrite(instructions, op, addr, symTab,
505 blockWriteDataCache)))
506 result = failure();
507 pushLocEntry(locmap, before, byteOffset(), "BLOCKWRITE",
508 op->getName().getStringRef(), addr.value_or(0), op, tm);
509 })
510 .Case<NpuBlockWriteValuesOp>([&](auto op) {
511 // A runtime-computed blockwrite payload has no static encoding;
512 // this op only reaches the EmitC (C++ TXN) target.
513 op.emitOpError("cannot translate a runtime-valued blockwrite "
514 "payload to a static TXN binary; this op is "
515 "supported only by the C++ TXN target "
516 "(--aie-npu-to-cpp)");
517 result = failure();
518 })
519 .Case<NpuMaskWrite32Op>([&](auto op) {
520 count++;
521 uint32_t before = byteOffset();
522 uint64_t addr = op.getAbsoluteAddress().value_or(0);
523 if (failed(appendMaskWrite32(instructions, op)))
524 result = failure();
525 pushLocEntry(locmap, before, byteOffset(), "MASKWRITE",
526 op->getName().getStringRef(), addr, op, tm);
527 })
528 .Case<NpuMaskPollOp>([&](auto op) {
529 count++;
530 uint32_t before = byteOffset();
531 uint64_t addr = op.getAbsoluteAddress().value_or(0);
532 if (failed(appendMaskPoll(instructions, op)))
533 result = failure();
534 pushLocEntry(locmap, before, byteOffset(), "MASKPOLL",
535 op->getName().getStringRef(), addr, op, tm);
536 })
537 .Case<NpuLoadPdiOp>([&](auto op) {
538 count++;
539 uint32_t before = byteOffset();
540 appendLoadPdi(instructions, op);
541 pushLocEntry(locmap, before, byteOffset(), "LOAD_PDI",
542 op->getName().getStringRef(), std::nullopt, op, tm);
543 })
544 .Case<NpuAddressPatchOp>([&](auto op) {
545 count++;
546 uint32_t before = byteOffset();
547 if (failed(appendAddressPatch(instructions, op, foldDDRAddrOffset)))
548 result = failure();
549 pushLocEntry(locmap, before, byteOffset(), "ADDRESS_PATCH",
550 op->getName().getStringRef(), op.getAddr(), op, tm);
551 })
552 .Case<NpuPreemptOp>([&](auto op) {
553 count++;
554 uint32_t before = byteOffset();
555 appendPreempt(instructions, op);
556 pushLocEntry(locmap, before, byteOffset(), "PREEMPT",
557 op->getName().getStringRef(), std::nullopt, op, tm);
558 })
559 .Case<NpuCreateScratchpadOp>([&](auto op) {
560 count++;
561 uint32_t before = byteOffset();
562 appendCreateScratchpad(instructions, op);
563 pushLocEntry(locmap, before, byteOffset(), "CREATE_SCRATCHPAD",
564 op->getName().getStringRef(), std::nullopt, op, tm);
565 })
566 .Case<NpuUpdateFromScratchpadOp>([&](auto op) {
567 count++;
568 uint32_t before = byteOffset();
569 if (failed(appendUpdateRegFromScratchpad(instructions, op, names)))
570 result = failure();
571 pushLocEntry(locmap, before, byteOffset(), "UPDATE_FROM_SCRATCHPAD",
572 op->getName().getStringRef(), std::nullopt, op, tm);
573 })
574 .Case<NpuWriteConfigOp>([&](auto op) {
575 appendConfig(op, op.getDeviceRefAttr(), /*teardown=*/false);
576 })
577 .Case<NpuWriteTeardownOp>([&](auto op) {
578 appendConfig(op, op.getDeviceRefAttr(), /*teardown=*/true);
579 })
580 .Default([&](Operation *op) {
581 // Pure values (constants, the operands above) need no encoding;
582 // control packets have their own translation.
583 // Anything else would be dropped from the binary without a trace.
584 if (isMemoryEffectFree(op) || op->hasTrait<OpTrait::IsTerminator>() ||
585 isa<NpuControlPacketOp, SetDeviceOp>(op))
586 return;
587 op->emitOpError("has no static TXN encoding");
588 result = failure();
589 });
590}
591
592} // namespace
593
595 Operation *device, bool teardown,
596 llvm::function_ref<LogicalResult(Config &)> encode) {
597 std::lock_guard<std::mutex> lock(mutex);
598 auto [it, inserted] = configs[teardown].try_emplace(device);
599 if (inserted) {
600 auto config = std::make_unique<Config>();
601 if (succeeded(encode(*config)))
602 it->second = std::move(config);
603 }
604 return it->second.get();
605}
606
608 mlir::ModuleOp moduleOp, std::vector<uint32_t> &instructions,
609 StringRef deviceName, StringRef sequenceName,
610 std::vector<TxnLocEntry> *locmap, bool foldDDRAddrOffset,
611 NpuConfigCache *configs) {
612
613 DeviceOp deviceOp =
614 DeviceOp::getForSymbolInModuleOrError(moduleOp, deviceName);
615 if (!deviceOp) {
616 return failure();
617 }
618
619 const AIETargetModel &tm = deviceOp.getTargetModel();
620
621 // Reserve the 4-word header up front; finalized in-place by
622 // txn_prepend_header once all instructions are appended.
623 aie_runtime::txn_init(instructions);
624
626 txnDeviceGen(tm), tm.rows(), tm.columns(), tm.getNumMemTileRows());
627
628 AIE::RuntimeSequenceOp seq =
629 AIE::RuntimeSequenceOp::getForSymbolInDeviceOrError(deviceOp,
630 sequenceName);
631 if (!seq) {
632 return failure();
633 }
634
635 SmallVector<AIEX::ConfigStep> steps;
636 for (Block &block : seq.getBody())
637 for (Operation &o : block) {
638 if (auto loadPdiOp = dyn_cast<NpuLoadPdiOp>(o)) {
639 FlatSymbolRefAttr ref = loadPdiOp.getDeviceRefAttr();
640 steps.push_back(
641 {&o, loadPdiOp, false,
642 ref ? moduleOp.lookupSymbol<AIE::DeviceOp>(ref) : nullptr});
643 } else if (auto writeConfigOp = dyn_cast<NpuWriteConfigOp>(o)) {
644 steps.push_back({&o, nullptr, false,
645 moduleOp.lookupSymbol<AIE::DeviceOp>(
646 writeConfigOp.getDeviceRefAttr())});
647 }
648 }
649 if (failed(AIEX::checkResidentsSurvive(seq, steps)))
650 return failure();
651
652 NpuConfigCache ownConfigs;
653 TxnEncoder encoder(deviceOp, instructions, locmap, foldDDRAddrOffset,
654 configs ? *configs : ownConfigs);
655 for (Block &block : seq.getBody())
656 for (Operation &o : block)
657 encoder.encode(o);
658 if (failed(encoder.result))
659 return failure();
660
661 // Finalize the TXN header (overwrites the 4 reserved words).
662 aie_runtime::txn_prepend_header(instructions, encoder.count, devInfo);
663 return success();
664}
665
667 ModuleOp module, std::vector<uint32_t> &instructions, StringRef deviceName,
668 StringRef sequenceName, std::vector<TxnLocEntry> *locmap) {
669 DeviceOp deviceOp =
670 AIE::DeviceOp::getForSymbolInModuleOrError(module, deviceName);
671 if (!deviceOp) {
672 return failure();
673 }
674 AIE::RuntimeSequenceOp seq =
675 AIE::RuntimeSequenceOp::getForSymbolInDeviceOrError(deviceOp,
676 sequenceName);
677 if (!seq) {
678 return failure();
679 }
680
681 const AIETargetModel &tm = deviceOp.getTargetModel();
682 llvm::DenseMap<TileID, AIE::PacketInfoAttr> controllerIds =
683 AIEX::controllerIdsOf(deviceOp);
684 SmallVector<AIEX::ControlPacketMulticast> multicasts;
685 for (Operation &operation : seq.getBody().getOps()) {
686 if (auto context = dyn_cast<AIEX::SetDeviceOp>(operation)) {
687 std::optional<SmallVector<AIEX::ControlPacketMulticast>> groups =
688 AIEX::controlPacketMulticasts(module, context.getDeviceRefAttr());
689 if (!groups)
690 return failure();
691 multicasts = std::move(*groups);
692 } else if (isa<AIEX::NpuLoadPdiOp>(operation)) {
693 multicasts.clear();
694 }
695 auto packetOp = dyn_cast<AIEX::NpuControlPacketOp>(operation);
696 if (!packetOp)
697 continue;
698
699 // The C API and Python callers can pass ops that were never verified,
700 // and the encoding below relies on the verifier's checks.
701 if (failed(packetOp.verify()))
702 return failure();
703
704 uint32_t before =
705 static_cast<uint32_t>(instructions.size() * sizeof(uint32_t));
706
707 uint32_t size = 0;
708 auto data = packetOp.getData();
709 if (data)
710 size = data->size();
711
712 // Emit: stream_header (1 word) + ctrl_header (1 word) + data (size words).
713 // The stream header contains the routing pkt_id so the stream switch can
714 // route each control packet to the correct tile's TileControl port.
715 // The DMA BD does NOT use enable_packet -- it sends raw data, and the
716 // stream switch parses the embedded packet headers from the data stream.
717 auto words = reserveAndGetTail(instructions, 2 + size);
718
719 std::optional<uint32_t> length = packetOp.getLength();
720 if (!data && length)
721 size = *length;
722
723 auto parity = [](uint32_t n) {
724 uint32_t p = 0;
725 while (n) {
726 p += n & 1;
727 n >>= 1;
728 }
729 return (p % 2) == 0;
730 };
731
732 // `beats` gets two bits, directly above the address, so an oversized
733 // payload corrupts the address instead of truncating. The verifier
734 // rejects empty payloads and long reads; a long write is legal until
735 // --aie-legalize-control-packet splits it, so it is caught here.
736 if (size > AIEX::NpuControlPacketOp::getMaxDataWords())
737 return packetOp.emitOpError()
738 << "payload is " << size
739 << " words; a control packet carries at most "
740 << AIEX::NpuControlPacketOp::getMaxDataWords()
741 << " on the wire. Run --aie-legalize-control-packet before "
742 "translating.";
743
744 // A tile without a controller_id has no unicast route.
745 uint32_t hdr = 0;
746 if (std::optional<uint32_t> id = packetOp.getMulticastId()) {
747 if (*id >= multicasts.size())
748 return packetOp.emitOpError("multicast_id ")
749 << *id << " has no declaration in the active overlay";
750 hdr = multicasts[*id].packetId;
751 } else {
752 TileID tile = packetOp.getTileFromAddr();
753 AIE::PacketInfoAttr info = controllerIds.lookup(tile);
754 if (!info)
755 return packetOp.emitOpError("targets tile (")
756 << tile.col << ", " << tile.row
757 << "), which has no controller_id to route it by";
758 hdr = (info.getPktType() & 0x7) << 12 | (info.assignedId() & 0xff);
759 }
760 words[0] = hdr | (0x1 & parity(hdr)) << 31;
761
762 uint32_t addr = packetOp.getAddress() & 0xFFFFF;
763 uint32_t beats = size - 1;
764 uint32_t opc = packetOp.getOpcode();
765 uint32_t id = packetOp.getStreamId();
766 hdr = id << 24 | opc << 22 | beats << 20 | addr;
767 words[1] = hdr | (0x1 & parity(hdr)) << 31;
768
769 // configuration data
770 if (data && (opc == 0x0 || opc == 0x2)) {
771 for (unsigned i = 0; i < size; i++)
772 words[i + 2] = (*data)[i];
773 }
774
775 uint32_t after =
776 static_cast<uint32_t>(instructions.size() * sizeof(uint32_t));
777 pushLocEntry(locmap, before, after, "CONTROL_PACKET",
778 packetOp->getName().getStringRef(), packetOp.getAddress(),
779 packetOp, tm);
780 }
781 return success();
782}
783
784// Render an mlir::Location as a JSON object, recursing into NameLoc, FusedLoc,
785// and CallSiteLoc so a consumer can reconstruct the file:line:col + named
786// location structure carried by the source op.
787static llvm::json::Value locToJSON(mlir::Location loc) {
788 using namespace llvm;
789 if (auto f = dyn_cast<mlir::FileLineColLoc>(loc))
790 return json::Value(json::Object{
791 {"kind", "file"},
792 {"file", f.getFilename().str()},
793 {"line", static_cast<int64_t>(f.getLine())},
794 {"col", static_cast<int64_t>(f.getColumn())},
795 });
796 if (auto n = dyn_cast<mlir::NameLoc>(loc)) {
797 json::Object o{{"kind", "name"}, {"name", n.getName().str()}};
798 o["child"] = locToJSON(n.getChildLoc());
799 return json::Value(std::move(o));
800 }
801 if (auto fused = dyn_cast<mlir::FusedLoc>(loc)) {
802 json::Array children;
803 for (mlir::Location c : fused.getLocations())
804 children.push_back(locToJSON(c));
805 return json::Value(
806 json::Object{{"kind", "fused"}, {"children", std::move(children)}});
807 }
808 if (auto cs = dyn_cast<mlir::CallSiteLoc>(loc))
809 return json::Value(json::Object{
810 {"kind", "callsite"},
811 {"callee", locToJSON(cs.getCallee())},
812 {"caller", locToJSON(cs.getCaller())},
813 });
814 if (isa<mlir::OpaqueLoc>(loc))
815 return json::Value(json::Object{{"kind", "opaque"}});
816 return json::Value(json::Object{{"kind", "unknown"}});
817}
818
819void xilinx::AIE::emitNpuLocmapJSON(llvm::raw_ostream &output,
820 llvm::StringRef deviceName,
821 llvm::StringRef binaryName,
822 const std::vector<TxnLocEntry> &locmap) {
823 llvm::json::Object root;
824 root["version"] = 1;
825 root["device"] = deviceName.str();
826 root["binary"] = binaryName.str();
827
828 llvm::json::Array opsArr;
829 for (const auto &e : locmap) {
830 llvm::json::Object o;
831 o["byte_offset"] = static_cast<int64_t>(e.byteOffset);
832 o["byte_size"] = static_cast<int64_t>(e.byteSize);
833 o["opcode"] = e.opcodeName;
834 o["source_op"] = e.sourceOpName;
835 if (e.address)
836 o["address"] = llvm::formatv("{0:X}", *e.address).str();
837 if (!e.registerName.empty()) {
838 o["register"] = e.registerName;
839 o["register_module"] = e.registerModule;
840 }
841 if (e.loc)
842 o["loc"] = locToJSON(*e.loc);
843 opsArr.push_back(std::move(o));
844 }
845 root["operations"] = std::move(opsArr);
846
847 output << llvm::formatv("{0:2}\n", llvm::json::Value(std::move(root)));
848}
virtual uint32_t getTileAddress(int col, int row) const
Return the base address of the tile's window.
virtual AIEArch getTargetArch() const =0
Return the target architecture.
bool isMemTile(int col, int row) const
Return true if the given tile is a Mem tile.
uint32_t getColumnFromAddress(uint32_t address) const
virtual uint32_t getRowFromAddress(uint32_t address) const
Inverse of getTileAddress() for any address in the tile's window.
bool isShimPLTile(int col, int row) const
Return true if the given tile is a ShimPL tile.
virtual int rows() const =0
Return the number of rows in the device.
bool isShimNOCTile(int col, int row) const
Return true if the given tile is a ShimNOC tile.
virtual int columns() const =0
Return the number of columns in the device.
virtual uint32_t getNumMemTileRows() const =0
const Config * getOrEncode(mlir::Operation *device, bool teardown, llvm::function_ref< mlir::LogicalResult(Config &)> encode)
Register and event database for a specific architecture.
static std::unique_ptr< RegisterDatabase > loadAIE2()
Load database for AIE2 architecture.
static std::unique_ptr< RegisterDatabase > loadAIE4()
Load database for AIE4 architecture.
const RegisterInfo * lookupRegisterByOffset(uint32_t offset, llvm::StringRef module) const
Lookup register by tile-relative offset and module name.
void txn_append_maskpoll32(std::vector< uint32_t > &txn, uint32_t addr, uint32_t val, uint32_t mask)
void txn_append_loadpdi(std::vector< uint32_t > &txn, uint32_t id, uint32_t size, uint64_t addr)
void txn_append_write32(std::vector< uint32_t > &txn, uint32_t addr, uint32_t val)
void txn_init(std::vector< uint32_t > &txn)
void txn_append_sync(std::vector< uint32_t > &txn, uint32_t col, uint32_t row, uint32_t dir, uint32_t chan, uint32_t ncol, uint32_t nrow)
void txn_append_preempt(std::vector< uint32_t > &txn, uint32_t level)
void txn_append_arg_patch(std::vector< uint32_t > &txn, uint32_t addr, int32_t arg_idx, uint64_t arg_plus, bool fold_ddr_addr_offset)
TxnDeviceInfo txn_device_info(uint8_t dev_gen, uint8_t num_rows, uint8_t num_cols, uint8_t num_memtile_rows)
@ TXN_OPC_CREATE_SCRATCHPAD
Definition TxnEncoding.h:53
void txn_append_maskwrite32(std::vector< uint32_t > &txn, uint32_t addr, uint32_t val, uint32_t mask)
void txn_append_blockwrite(std::vector< uint32_t > &txn, uint32_t addr, const uint32_t *data, size_t count, uint32_t col=0, uint32_t row=0)
void txn_prepend_header(std::vector< uint32_t > &txn, uint32_t op_count, TxnDeviceInfo info={})
mlir::FailureOr< llvm::SmallVector< ControlPacketMulticast > > controlPacketMulticasts(mlir::ModuleOp module, mlir::FlatSymbolRefAttr reference)
llvm::DenseMap< AIE::TileID, AIE::PacketInfoAttr > controllerIdsOf(AIE::DeviceOp device)
LogicalResult checkResidentsSurvive(AIE::RuntimeSequenceOp seq, ArrayRef< ConfigStep > steps)
Definition AIEUtils.cpp:396
std::optional< uint64_t > getConstantInt64Operand(mlir::Value v)
std::optional< uint32_t > getConstantIntOperand(mlir::Value v)
void emitNpuLocmapJSON(llvm::raw_ostream &output, llvm::StringRef deviceName, llvm::StringRef binaryName, const std::vector< TxnLocEntry > &locmap)
uint8_t txnDeviceGen(const AIETargetModel &tm)
Device generation ID written into the TXN header (aie_runtime::TxnDeviceInfo::devGen).
mlir::LogicalResult AIETranslateControlPacketsToUI32Vec(mlir::ModuleOp, std::vector< uint32_t > &, llvm::StringRef deviceName="", llvm::StringRef sequenceName="", std::vector< TxnLocEntry > *locmap=nullptr)
mlir::LogicalResult AIETranslateNpuToBinary(mlir::ModuleOp, std::vector< uint32_t > &, llvm::StringRef deviceName="", llvm::StringRef sequenceName="", std::vector< TxnLocEntry > *locmap=nullptr, bool foldDDRAddrOffset=true, NpuConfigCache *configs=nullptr)
mlir::LogicalResult generateAndInsertConfigOps(mlir::OpBuilder &builder, xilinx::AIE::DeviceOp device, xilinx::AIEX::BlockwriteData &blockwriteData, llvm::StringRef clElfDir="", AIEToConfigurationOutputType outputType=AIEToConfigurationOutputType::Transaction, bool skipCtrlPktOverlay=false)
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)
mlir::LogicalResult generateAndInsertTeardownOps(mlir::OpBuilder &builder, xilinx::AIE::DeviceOp device, xilinx::AIEX::BlockwriteData &blockwriteData, AIEToConfigurationOutputType outputType=AIEToConfigurationOutputType::Transaction, bool skipCtrlPktOverlay=false)
std::vector< uint32_t > words
Definition AIETargets.h:80
std::vector< TxnLocEntry > locmap
Definition AIETargets.h:83
std::optional< uint64_t > address
Definition AIETargets.h:46
std::string registerModule
Definition AIETargets.h:49
std::optional< mlir::Location > loc
Definition AIETargets.h:50