MLIR-AIE 1.4.6.dev
AIEToConfiguration.cpp
Go to the documentation of this file.
1//===- AIEToConfiguration.h -------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2024 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
8#include "../PassDetail.h"
9#include "TransactionBinary.h"
10
15#include "aie/Targets/AIERT.h"
16
17#include "mlir/Dialect/Arith/IR/Arith.h"
18#include "mlir/Dialect/Func/IR/FuncOps.h"
19#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
20#include "mlir/Dialect/MemRef/IR/MemRef.h"
21#include "mlir/IR/IRMapping.h"
22#include "mlir/IR/Matchers.h"
23#include "mlir/Interfaces/CallInterfaces.h"
24
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/DenseSet.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/Support/Debug.h"
30
31extern "C" {
32#include "aie_codegen.h"
33}
34
35#include <algorithm>
36#include <array>
37#include <cstring>
38#include <map>
39#include <optional>
40#include <set>
41#include <tuple>
42#include <utility>
43#include <vector>
44
45namespace xilinx {
46#define GEN_PASS_DEF_AIEANNOTATECORELOCKACQUIRES
47#define GEN_PASS_DEF_CONVERTAIETOCONTROLPACKETS
48#define GEN_PASS_DEF_CONVERTAIETOTRANSACTION
49#include "aie/Conversion/Passes.h.inc"
50} // namespace xilinx
51
52#define DEBUG_TYPE "aie-convert-to-config"
53
54using namespace mlir;
55using namespace xilinx;
56using namespace xilinx::AIE;
57
58namespace {
59
60constexpr size_t kTxnHeaderBytes = 16;
61
62struct TxnPreemptHeader {
63 uint8_t opcode;
64 uint8_t level;
65 uint16_t reserved;
66};
67
68struct TxnLoadPdiHeader {
69 uint8_t opcode;
70 uint8_t padding;
71 uint16_t id;
72 uint32_t size;
73 uint64_t address;
74};
75} // namespace
76
77// Parse a TXN binary blob. On success return the number of columns from the
78// header and a vector of parsed operations. On failure return std::nullopt.
80 const std::vector<uint8_t> &data,
81 std::vector<TransactionBinaryOperation> &ops) {
82
83 if (data.size() < kTxnHeaderBytes) {
84 llvm::errs() << "Transaction binary is too small for header\n";
85 return std::nullopt;
86 }
87
88 uint32_t major = data[0];
89 uint32_t minor = data[1];
90 uint32_t num_cols = data[4];
91
92 uint32_t num_ops, txn_size;
93 std::memcpy(&num_ops, &data[8], 4);
94 std::memcpy(&txn_size, &data[12], 4);
95
96 LLVM_DEBUG(llvm::dbgs() << "Major: " << major << "\n");
97 LLVM_DEBUG(llvm::dbgs() << "Minor: " << minor << "\n");
98 LLVM_DEBUG(llvm::dbgs() << "DevGen: " << data[2] << "\n");
99 LLVM_DEBUG(llvm::dbgs() << "NumRows: " << data[3] << "\n");
100 LLVM_DEBUG(llvm::dbgs() << "NumCols: " << num_cols << "\n");
101 LLVM_DEBUG(llvm::dbgs() << "NumMemTileRows: " << data[5] << "\n");
102 LLVM_DEBUG(llvm::dbgs() << "NumOps: " << num_ops << "\n");
103 LLVM_DEBUG(llvm::dbgs() << "TxnSize: " << txn_size << " bytes\n");
104
105 size_t i = kTxnHeaderBytes;
106
107 auto requireBytes = [&](size_t offset, size_t length) -> bool {
108 if (offset + length > data.size()) {
109 llvm::errs() << "Transaction binary truncated while parsing opcode\n";
110 return false;
111 }
112 return true;
113 };
114
115 auto read32 = [&](size_t offset) -> uint32_t {
116 uint32_t value;
117 std::memcpy(&value, data.data() + offset, sizeof(uint32_t));
118 return value;
119 };
120
121 // Convert opcode from uint8 to a validated opcode byte
122 auto convertOpcode = [](uint8_t opc) -> std::optional<uint8_t> {
123 switch (opc) {
124 case static_cast<uint8_t>(XAie_TxnOpcode::XAIE_IO_WRITE):
125 case static_cast<uint8_t>(XAie_TxnOpcode::XAIE_IO_BLOCKWRITE):
126 case static_cast<uint8_t>(XAie_TxnOpcode::XAIE_IO_MASKWRITE):
127 case static_cast<uint8_t>(XAie_TxnOpcode::XAIE_IO_MASKPOLL):
128 case 0x6: // XAie_TxnOpcode::XAIE_IO_PREEMPT
129 case 0x8: // XAie_TxnOpcode::XAIE_IO_LOAD_PDI
130 case static_cast<uint8_t>(XAie_TxnOpcode::XAIE_IO_CUSTOM_OP_TCT):
131 case static_cast<uint8_t>(XAie_TxnOpcode::XAIE_IO_CUSTOM_OP_DDR_PATCH):
132 return opc;
133 default:
134 llvm::errs() << "Unhandled opcode: " << std::to_string(opc) << "\n";
135 return std::nullopt;
136 }
137 };
138
139 // Parse the binary blob. There are two versions supported, 0.1 and 1.0.
140 // For both versions, build a list of TransactionBinaryOperation objects
141 // representing the parsed operations.
142 if (major == 0 && minor == 1) {
143 while (i < data.size()) {
144 auto maybeOpcode = convertOpcode(data[i]);
145 if (!maybeOpcode)
146 return std::nullopt;
147 XAie_TxnOpcode opcode = static_cast<XAie_TxnOpcode>(*maybeOpcode);
148 LLVM_DEBUG(llvm::dbgs() << "opcode: " + std::to_string(opcode) << "\n");
149
151 op.cmd.Opcode = opcode;
152
153 switch (opcode) {
154 case XAie_TxnOpcode::XAIE_IO_WRITE: {
155 LLVM_DEBUG(llvm::dbgs() << "opcode: WRITE (0x00)\n");
156 if (!requireBytes(i, 24))
157 return std::nullopt;
158 uint32_t addrLo = read32(i + 8);
159 uint32_t addrHi = read32(i + 12);
160 uint32_t value = read32(i + 16);
161 uint32_t opSize = read32(i + 20);
162 if (!requireBytes(i, opSize))
163 return std::nullopt;
164 uint64_t addr = (static_cast<uint64_t>(addrHi) << 32) | addrLo;
165 op.cmd.RegOff = addr;
166 op.cmd.Value = value;
167 op.cmd.Size = 0;
168 i += opSize;
169 break;
170 }
171 case XAie_TxnOpcode::XAIE_IO_BLOCKWRITE: {
172 LLVM_DEBUG(llvm::dbgs() << "opcode: BLOCKWRITE (0x01)\n");
173 if (!requireBytes(i, 16))
174 return std::nullopt;
175 uint32_t addr = read32(i + 8);
176 uint32_t opSize = read32(i + 12);
177 if (opSize < 16 || !requireBytes(i, opSize))
178 return std::nullopt;
179 const uint8_t *payload = data.data() + i + 16;
180 uint32_t payloadBytes = opSize - 16;
181 op.cmd.RegOff = addr;
182 op.cmd.DataPtr = reinterpret_cast<uint64_t>(payload);
183 op.cmd.Size = payloadBytes;
184 i += opSize;
185 break;
186 }
187 // MASKPOLL has the same word layout as MASKWRITE (aie-codegen's
188 // XAie_MaskPoll32Hdr matches XAie_MaskWrite32Hdr); the poll timeout is
189 // not serialized.
190 case XAie_TxnOpcode::XAIE_IO_MASKWRITE:
191 case XAie_TxnOpcode::XAIE_IO_MASKPOLL: {
192 LLVM_DEBUG(llvm::dbgs() << "opcode: MASKWRITE (0x03) or MASKPOLL "
193 "(0x04)\n");
194 if (!requireBytes(i, 28))
195 return std::nullopt;
196 uint32_t addrLo = read32(i + 8);
197 uint32_t addrHi = read32(i + 12);
198 uint32_t value = read32(i + 16);
199 uint32_t mask = read32(i + 20);
200 uint32_t opSize = read32(i + 24);
201 if (opSize < 28) {
202 llvm::errs() << "Transaction op size " << opSize
203 << " is smaller than its 28-byte header\n";
204 return std::nullopt;
205 }
206 if (!requireBytes(i, opSize))
207 return std::nullopt;
208 uint64_t addr = (static_cast<uint64_t>(addrHi) << 32) | addrLo;
209 op.cmd.RegOff = addr;
210 op.cmd.Value = value;
211 op.cmd.Mask = mask;
212 op.cmd.Size = opSize;
213 i += opSize;
214 break;
215 }
216 case XAie_TxnOpcode::XAIE_IO_CUSTOM_OP_TCT: {
217 uint32_t opSize = read32(i + 4);
218 if (opSize < 16 || !requireBytes(i, opSize))
219 return std::nullopt;
220 uint32_t descriptor = read32(i + 8);
221 uint32_t config = read32(i + 12);
223 /*column=*/static_cast<int32_t>((descriptor >> 16) & 0xff),
224 /*row=*/static_cast<int32_t>((descriptor >> 8) & 0xff),
225 /*direction=*/static_cast<int32_t>(descriptor & 0xff),
226 /*channel=*/static_cast<int32_t>((config >> 24) & 0xff),
227 /*columnCount=*/static_cast<int32_t>((config >> 16) & 0xff),
228 /*rowCount=*/static_cast<int32_t>((config >> 8) & 0xff)};
229 op.sync = payload;
230 op.cmd.Size = opSize;
231 i += opSize;
232 break;
233 }
234 // Not in the vendored third_party/aie-codegen enum (though the driver
235 // protocol defines it); can't add it without forking upstream.
236 case 0x8: { // NOLINT(clang-diagnostic-switch):
237 // XAie_TxnOpcode::XAIE_IO_LOAD_PDI
238 LLVM_DEBUG(llvm::dbgs() << "opcode: LOAD_PDI (0x08)\n");
239 constexpr size_t opSize = sizeof(TxnLoadPdiHeader);
240 if (!requireBytes(i, opSize))
241 return std::nullopt;
242 TxnLoadPdiHeader header;
243 std::memcpy(&header, data.data() + i, opSize);
245 header.id, header.size, header.address};
246 op.loadPdi = payload;
247 op.cmd.Size = opSize;
248 i += opSize;
249 break;
250 }
251 case XAie_TxnOpcode::XAIE_IO_CUSTOM_OP_DDR_PATCH: {
252 uint32_t opSize = read32(i + 4);
253 if (opSize < 44 || !requireBytes(i, opSize))
254 return std::nullopt;
255 uint32_t action = read32(i + 20);
256 uint32_t addr = read32(i + 24);
257 int32_t argIdx = static_cast<int32_t>(read32(i + 32));
258 uint64_t argPlus = static_cast<uint64_t>(read32(i + 40)) |
259 (static_cast<uint64_t>(read32(i + 44)) << 32);
261 action, addr, argIdx, argPlus};
262 op.addressPatch = payload;
263 op.cmd.Size = opSize;
264 i += opSize;
265 break;
266 }
267 case 0x6: { // XAie_TxnOpcode::XAIE_IO_PREEMPT
268 LLVM_DEBUG(llvm::dbgs() << "opcode: PREEMPT (0x06)\n");
269 constexpr size_t opSize = sizeof(TxnPreemptHeader);
270 if (!requireBytes(i, opSize))
271 return std::nullopt;
272 const auto *header =
273 reinterpret_cast<const TxnPreemptHeader *>(data.data() + i);
274 op.cmd.Value = header->level;
275 op.cmd.Size = opSize;
276 i += opSize;
277 break;
278 }
279 default:
280 llvm::errs() << "Unhandled opcode: " << std::to_string(opcode)
281 << " for v0.1 transaction\n";
282 return std::nullopt;
283 }
284
285 ops.push_back(op);
286 }
287 } else if (major == 1 && minor == 0) {
288 while (i < data.size()) {
289 auto maybeOpcode = convertOpcode(data[i]);
290 if (!maybeOpcode)
291 return std::nullopt;
292 XAie_TxnOpcode opcode = static_cast<XAie_TxnOpcode>(*maybeOpcode);
293 LLVM_DEBUG(llvm::dbgs() << "opcode: " + std::to_string(opcode) << "\n");
294
296 op.cmd.Opcode = opcode;
297
298 switch (opcode) {
299 case XAie_TxnOpcode::XAIE_IO_WRITE: {
300 LLVM_DEBUG(llvm::dbgs() << "opcode: WRITE (0x00)\n");
301 if (!requireBytes(i, 12))
302 return std::nullopt;
303 uint32_t addr = read32(i + 4);
304 uint32_t value = read32(i + 8);
305 op.cmd.RegOff = addr;
306 op.cmd.Value = value;
307 op.cmd.Size = 0;
308 i += 12;
309 break;
310 }
311 case XAie_TxnOpcode::XAIE_IO_BLOCKWRITE: {
312 LLVM_DEBUG(llvm::dbgs() << "opcode: BLOCKWRITE (0x01)\n");
313 if (!requireBytes(i, 12))
314 return std::nullopt;
315 uint32_t addr = read32(i + 4);
316 uint32_t opSize = read32(i + 8);
317 if (opSize < 12 || !requireBytes(i, opSize))
318 return std::nullopt;
319 const uint8_t *payload = data.data() + i + 12;
320 uint32_t payloadBytes = opSize - 12;
321 op.cmd.RegOff = addr;
322 op.cmd.DataPtr = reinterpret_cast<uint64_t>(payload);
323 op.cmd.Size = payloadBytes;
324 i += opSize;
325 break;
326 }
327 case XAie_TxnOpcode::XAIE_IO_MASKWRITE:
328 case XAie_TxnOpcode::XAIE_IO_MASKPOLL: {
329 LLVM_DEBUG(llvm::dbgs() << "opcode: MASKWRITE (0x03) or MASKPOLL "
330 "(0x04)\n");
331 if (!requireBytes(i, 16))
332 return std::nullopt;
333 uint32_t addr = read32(i + 4);
334 uint32_t value = read32(i + 8);
335 uint32_t mask = read32(i + 12);
336 op.cmd.RegOff = addr;
337 op.cmd.Value = value;
338 op.cmd.Mask = mask;
339 op.cmd.Size = 0;
340 i += 16;
341 break;
342 }
343 case XAie_TxnOpcode::XAIE_IO_CUSTOM_OP_TCT: {
344 uint32_t opSize = read32(i + 4);
345 if (opSize < 16 || !requireBytes(i, opSize))
346 return std::nullopt;
347 uint32_t descriptor = read32(i + 8);
348 uint32_t config = read32(i + 12);
350 /*column=*/static_cast<int32_t>((descriptor >> 16) & 0xff),
351 /*row=*/static_cast<int32_t>((descriptor >> 8) & 0xff),
352 /*direction=*/static_cast<int32_t>(descriptor & 0xff),
353 /*channel=*/static_cast<int32_t>((config >> 24) & 0xff),
354 /*columnCount=*/static_cast<int32_t>((config >> 16) & 0xff),
355 /*rowCount=*/static_cast<int32_t>((config >> 8) & 0xff)};
356 op.sync = payload;
357 op.cmd.Size = opSize;
358 i += opSize;
359 break;
360 }
361 // LOAD_PDI is matched by value here too; see the first switch.
362 case 0x8: { // NOLINT(clang-diagnostic-switch):
363 // XAie_TxnOpcode::XAIE_IO_LOAD_PDI
364 LLVM_DEBUG(llvm::dbgs() << "opcode: LOAD_PDI (0x08)\n");
365 constexpr size_t opSize = sizeof(TxnLoadPdiHeader);
366 if (!requireBytes(i, opSize))
367 return std::nullopt;
368 TxnLoadPdiHeader header;
369 std::memcpy(&header, data.data() + i, opSize);
371 header.id, header.size, header.address};
372 op.loadPdi = payload;
373 op.cmd.Size = opSize;
374 i += opSize;
375 break;
376 }
377 case XAie_TxnOpcode::XAIE_IO_CUSTOM_OP_DDR_PATCH: {
378 uint32_t opSize = read32(i + 4);
379 if (opSize < 44 || !requireBytes(i, opSize))
380 return std::nullopt;
381 uint32_t action = read32(i + 20);
382 uint32_t addr = read32(i + 24);
383 int32_t argIdx = static_cast<int32_t>(read32(i + 32));
384 uint64_t argPlus = static_cast<uint64_t>(read32(i + 40)) |
385 (static_cast<uint64_t>(read32(i + 44)) << 32);
387 action, addr, argIdx, argPlus};
388 op.addressPatch = payload;
389 op.cmd.Size = opSize;
390 i += opSize;
391 break;
392 }
393 case 0x6: { // XAie_TxnOpcode::XAIE_IO_PREEMPT
394 LLVM_DEBUG(llvm::dbgs() << "opcode: PREEMPT (0x06)\n");
395 constexpr size_t opSize = sizeof(TxnPreemptHeader);
396 if (!requireBytes(i, opSize))
397 return std::nullopt;
398 const auto *header =
399 reinterpret_cast<const TxnPreemptHeader *>(data.data() + i);
400 op.cmd.Value = header->level;
401 op.cmd.Size = opSize;
402 i += opSize;
403 break;
404 }
405 default:
406 llvm::errs() << "Unhandled opcode: " << std::to_string(opcode)
407 << " for v1.0 transaction\n";
408 return std::nullopt;
409 }
410
411 ops.push_back(op);
412 }
413 } else {
414 llvm::errs() << "Unsupported TXN binary version: " << major << "." << minor
415 << "\n";
416 return std::nullopt;
417 }
418
419 return num_cols;
420}
421
422// Translate vector of TransactionBinaryOperation to a sequence of transaction
423// ops (npu.write32, npu.maskwrite32, npu.maskpoll, npu.blockwrite). Each
424// emitted op gets the per-op `sourceLoc` from AIERT's instruction-range
425// bracketing if available; otherwise it falls back to `fallbackLoc` (typically
426// the device location).
427static LogicalResult
428emitTransactionOps(OpBuilder &builder, Location fallbackLoc,
429 std::vector<TransactionBinaryOperation> &operations,
430 std::vector<memref::GlobalOp> &global_data) {
431
432 // One constant per distinct value. They all land in the same block through
433 // `builder`, so the first use dominates every later one.
434 //
435 // Because the first use is what creates the op, callers must bind the
436 // operands to locals rather than call this inside an argument list: the
437 // evaluation order of function arguments is unspecified, and it decides the
438 // order the constants are emitted in.
439 llvm::DenseMap<uint32_t, Value> constantCache;
440 auto constant = [&](Location loc, uint32_t value) {
441 Value &cached = constantCache[value];
442 if (!cached)
443 cached = AIEX::createConstantI32(builder, loc, value);
444 return cached;
445 };
446
447 // create the txn ops
448 for (auto [op, payload] : llvm::zip(operations, global_data)) {
449 Location loc = op.sourceLoc.value_or(fallbackLoc);
450
451 if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_WRITE) {
452 Value address = constant(loc, op.cmd.RegOff);
453 Value value = constant(loc, op.cmd.Value);
454 AIEX::NpuWrite32Op::create(builder, loc, address, value, nullptr, nullptr,
455 nullptr);
456 } else if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_BLOCKWRITE) {
457 auto memref = memref::GetGlobalOp::create(builder, loc, payload.getType(),
458 payload.getName());
459 AIEX::NpuBlockWriteOp::create(
460 builder, loc, builder.getUI32IntegerAttr(op.cmd.RegOff),
461 memref.getResult(), nullptr, nullptr, nullptr);
462 } else if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_MASKWRITE) {
463 Value address = constant(loc, op.cmd.RegOff);
464 Value value = constant(loc, op.cmd.Value);
465 Value mask = constant(loc, op.cmd.Mask);
466 AIEX::NpuMaskWrite32Op::create(builder, loc, address, value, mask,
467 nullptr, nullptr, nullptr);
468 } else if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_MASKPOLL) {
469 Value address = constant(loc, op.cmd.RegOff);
470 Value value = constant(loc, op.cmd.Value);
471 Value mask = constant(loc, op.cmd.Mask);
472 AIEX::NpuMaskPollOp::create(builder, loc, address, value, mask,
473 /*buffer=*/nullptr, /*column=*/nullptr,
474 /*row=*/nullptr);
475 } else if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_CUSTOM_OP_TCT) {
476 if (!op.sync) {
477 llvm::errs() << "Missing sync payload while emitting transaction\n";
478 return failure();
479 }
480 const TransactionBinaryOperation::SyncPayload &sync = *op.sync;
481 Value column = constant(loc, sync.column);
482 Value row = constant(loc, sync.row);
483 Value direction = constant(loc, sync.direction);
484 Value channel = constant(loc, sync.channel);
485 Value columnCount = constant(loc, sync.columnCount);
486 Value rowCount = constant(loc, sync.rowCount);
487 AIEX::NpuSyncOp::create(builder, loc, column, row, direction, channel,
488 columnCount, rowCount);
489 } else if (op.cmd.Opcode == 0x8 /* XAie_TxnOpcode::XAIE_IO_LOAD_PDI */) {
490 if (!op.loadPdi) {
491 llvm::errs() << "Missing load_pdi payload while emitting transaction\n";
492 return failure();
493 }
495 *op.loadPdi;
496 auto idAttr =
497 builder.getI32IntegerAttr(static_cast<int32_t>(payloadInfo.id));
498 IntegerAttr sizeAttr =
499 builder.getI32IntegerAttr(static_cast<int32_t>(payloadInfo.size));
500
501 auto ui64Ty =
502 IntegerType::get(builder.getContext(), 64, IntegerType::Unsigned);
503 IntegerAttr addressAttr =
504 IntegerAttr::get(ui64Ty, llvm::APInt(64, payloadInfo.address));
505
506 AIEX::NpuLoadPdiOp::create(builder, loc, /*device_ref=*/nullptr, idAttr,
507 sizeAttr, addressAttr,
508 /*expand_mode=*/nullptr);
509 } else if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_CUSTOM_OP_DDR_PATCH) {
510 if (!op.addressPatch) {
511 llvm::errs()
512 << "Missing address_patch payload while emitting transaction\n";
513 return failure();
514 }
516 *op.addressPatch;
517 AIEX::NpuAddressPatchOp::create(
518 builder, loc, patch.addr,
519 /*addr_val=*/mlir::Value(), static_cast<int32_t>(patch.argIdx),
520 AIEX::createConstantArgPlus(builder, loc, patch.argPlus));
521 } else if (op.cmd.Opcode == 0x6 /* XAie_TxnOpcode::XAIE_IO_PREEMPT */) {
522 auto ui8Ty =
523 IntegerType::get(builder.getContext(), 8, IntegerType::Unsigned);
524 auto levelAttr = IntegerAttr::get(ui8Ty, llvm::APInt(8, op.cmd.Value));
525 AIEX::NpuPreemptOp::create(builder, loc, levelAttr);
526 } else {
527 llvm::errs() << "Unhandled txn opcode: " << op.cmd.Opcode << "\n";
528 return failure();
529 }
530 }
531 return success();
532}
533
534// Scans back from the insertion point to the last PDI load, which reprograms
535// the array.
536static llvm::DenseMap<uint32_t, uint32_t>
537registersWrittenSinceLoad(OpBuilder &builder) {
538 llvm::DenseMap<uint32_t, uint32_t> registers;
539 Block *block = builder.getInsertionBlock();
540 if (!block)
541 return registers;
542 Block::iterator it = builder.getInsertionPoint();
543 while (it != block->begin()) {
544 Operation &op = *--it;
545 if (isa<AIEX::NpuLoadPdiOp>(op))
546 break;
547 auto packet = dyn_cast<AIEX::NpuControlPacketOp>(op);
548 std::optional<ArrayRef<int32_t>> data =
549 packet ? packet.getData() : std::nullopt;
550 if (!data)
551 continue;
552 for (auto [i, word] : llvm::enumerate(*data))
553 registers.try_emplace(packet.getAddress() + i * sizeof(int32_t), word);
554 }
555 return registers;
556}
557
558// Translate vector of TransactionBinaryOperation to a sequence of control
559// packet ops. Each emitted op gets the per-op `sourceLoc` from AIERT's
560// instruction-range bracketing if available; otherwise it falls back to
561// `fallbackLoc`.
562static LogicalResult emitControlPacketOps(
563 OpBuilder &builder, Location fallbackLoc,
564 std::vector<TransactionBinaryOperation> &operations,
565 std::vector<memref::GlobalOp> &global_data,
566 const llvm::DenseMap<uint32_t, uint32_t> &initialRegisters) {
567
568 auto *ctx = builder.getContext();
569
570 // A control packet writes whole words, so a masked write becomes a write of
571 // the value the register would hold after it.
572 llvm::DenseMap<uint32_t, uint32_t> registers =
573 registersWrittenSinceLoad(builder);
574 for (auto [address, value] : initialRegisters)
575 registers.try_emplace(address, value);
576
577 // create the control packet ops
578 for (auto [op, payload] : llvm::zip(operations, global_data)) {
579 Location loc = op.sourceLoc.value_or(fallbackLoc);
580
581 if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_WRITE) {
582 registers[op.cmd.RegOff] = op.cmd.Value;
583 AIEX::NpuControlPacketOp::create(
584 builder, loc, builder.getUI32IntegerAttr(op.cmd.RegOff), nullptr,
585 /*opcode*/ builder.getI32IntegerAttr(0),
586 /*stream_id*/ builder.getI32IntegerAttr(0),
587 DenseI32ArrayAttr::get(ctx, ArrayRef<int32_t>(op.cmd.Value)));
588 } else if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_BLOCKWRITE) {
589 auto initialValue = payload.getInitialValue();
590 if (!initialValue)
591 continue;
592 auto blockWriteData = dyn_cast<DenseIntElementsAttr>(*initialValue);
593 if (!blockWriteData) {
594 payload.emitError(
595 "Global symbol initial value is not a dense int array");
596 break;
597 }
598 auto blockWriteDataValues = blockWriteData.getValues<int32_t>();
599 // Split block write data into beats of 4 or less, in int32_t.
600 int currAddr = op.cmd.RegOff;
601 for (size_t i = 0; i < blockWriteDataValues.size(); i += 4) {
602 auto last = std::min(blockWriteDataValues.size(), i + 4);
603 SmallVector<int32_t> splitData =
604 SmallVector<int32_t>(blockWriteDataValues.begin() + i,
605 blockWriteDataValues.begin() + last);
606 for (auto [j, word] : llvm::enumerate(splitData))
607 registers[currAddr + j * sizeof(int32_t)] = word;
608 AIEX::NpuControlPacketOp::create(
609 builder, loc, builder.getUI32IntegerAttr(currAddr), nullptr,
610 /*opcode*/ builder.getI32IntegerAttr(0),
611 /*stream_id*/ builder.getI32IntegerAttr(0),
612 DenseI32ArrayAttr::get(ctx, ArrayRef<int32_t>(splitData)));
613 currAddr += splitData.size() * sizeof(int32_t);
614 }
615
616 } else if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_MASKWRITE) {
617 uint32_t &reg = registers[op.cmd.RegOff];
618 reg = (reg & ~op.cmd.Mask) | (op.cmd.Value & op.cmd.Mask);
619 int32_t value = reg;
620 AIEX::NpuControlPacketOp::create(
621 builder, loc, builder.getUI32IntegerAttr(op.cmd.RegOff), nullptr,
622 /*opcode*/ builder.getI32IntegerAttr(0),
623 /*stream_id*/ builder.getI32IntegerAttr(0),
624 DenseI32ArrayAttr::get(ctx, ArrayRef<int32_t>(value)));
625 } else if (op.cmd.Opcode == XAie_TxnOpcode::XAIE_IO_MASKPOLL) {
626 llvm::errs() << "control-packet configuration cannot express a mask "
627 "poll\n";
628 return failure();
629 } else {
630 llvm::errs() << "Unhandled txn opcode: " << op.cmd.Opcode << "\n";
631 return failure();
632 }
633 }
634 return success();
635}
636
637// Take transaction operations and insert them at the _current_ insertion point
638// of the supplied builder.
639static LogicalResult convertTransactionOpsToMLIR(
640 OpBuilder builder, AIE::AIEToConfigurationOutputType outputType,
641 std::vector<TransactionBinaryOperation> &operations,
642 AIEX::BlockwriteData &blockwriteData,
643 const llvm::DenseMap<uint32_t, uint32_t> &initialRegisters = {}) {
644
645 // for each blockwrite in the binary, find or create a GlobalOp with the data
646 // at the device level
647 std::vector<memref::GlobalOp> global_data;
648 DeviceOp device = blockwriteData.getDevice();
649 Location loc = device.getLoc();
650 {
651 OpBuilder::InsertionGuard guard(builder);
652 builder.setInsertionPointToStart(device.getBody());
653 for (auto &op : operations) {
654 if (op.cmd.Opcode != XAIE_IO_BLOCKWRITE) {
655 global_data.emplace_back(nullptr);
656 continue;
657 }
658 const uint32_t *d = reinterpret_cast<const uint32_t *>(op.cmd.DataPtr);
659 global_data.push_back(blockwriteData.getOrCreate(
660 builder, loc, ArrayRef<uint32_t>(d, op.cmd.Size / 4)));
661 }
662 }
663
664 // create the txn ops
666 if (failed(emitTransactionOps(builder, loc, operations, global_data)))
667 return failure();
668 } else if (outputType == AIE::AIEToConfigurationOutputType::ControlPacket) {
669 if (failed(emitControlPacketOps(builder, loc, operations, global_data,
670 initialRegisters)))
671 return failure();
672 } else {
673 llvm_unreachable("bad output type");
674 }
675
676 return success();
677}
678
679// Convert (disassemble) a transaction binary to MLIR. On success return a new
680// ModuleOp containing a DeviceOp containing a runtime sequence with the
681// transaction binary encoded as a sequence of npu.write32, npu.maskwrite32,
682// npu.maskpoll and npu.blockwrite operations. On failure return std::nullopt.
683std::optional<mlir::ModuleOp>
685 std::vector<uint8_t> &binary) {
686
687 // parse the binary
688 std::vector<TransactionBinaryOperation> operations;
689 auto c = parseTransactionBinary(binary, operations);
690 if (!c) {
691 llvm::errs() << "Failed to parse binary\n";
692 return std::nullopt;
693 }
694 int columns = *c;
695
696 // write32/maskwrite32/sync/address_patch now carry their integer fields as
697 // SSA operands materialized via arith.constant, so ensure the dialect is
698 // loaded before emitting them.
699 ctx->getOrLoadDialect<mlir::arith::ArithDialect>();
700
701 auto loc = mlir::UnknownLoc::get(ctx);
702
703 // create a new ModuleOp and set the insertion point
704 auto module = ModuleOp::create(loc);
705 OpBuilder builder(module.getBodyRegion());
706 builder.setInsertionPointToStart(module.getBody());
707
708 // create aie.device
709 std::vector<AIEDevice> devices{AIEDevice::npu1_1col, AIEDevice::npu1_2col,
710 AIEDevice::npu1_3col, AIEDevice::npu1};
711 auto device = DeviceOp::create(builder, loc, devices[columns - 1],
712 DeviceOp::getDefaultDeviceName(), nullptr);
713 device.getRegion().emplaceBlock();
714 DeviceOp::ensureTerminator(device.getBodyRegion(), builder, loc);
715 builder.setInsertionPointToStart(device.getBody());
716
717 // convert the parsed ops to MLIR
718 AIEX::BlockwriteData blockwriteData(device, "config_blockwrite_data_");
719 if (failed(convertTransactionOpsToMLIR(
721 blockwriteData)))
722 return std::nullopt;
723
724 return module;
725}
726
727// Insert the ops of the transaction `ctl` recorded, as `outputType`.
728static LogicalResult
729insertRecordedTransaction(AIERTControl &ctl, OpBuilder &builder,
731 AIEX::BlockwriteData &blockwriteData,
732 DeviceOp configured = {}) {
733 // Export the transactions to a binary buffer
734 std::vector<uint8_t> txn_data = ctl.exportSerializedTransaction();
735
736 // parse the binary data
737 std::vector<TransactionBinaryOperation> operations;
738 if (!parseTransactionBinary(txn_data, operations)) {
739 llvm::errs() << "Failed to parse binary\n";
740 return failure();
741 }
742
743 // Attach per-op source locations from AIERT's instruction-range bracketing.
744 // AIERTControl already projected those onto the serialized transaction's
745 // operations, so the indices line up with what the parser reproduced here.
746 // Ops with no bracketed location keep std::nullopt and inherit the device
747 // fallback location at emit time.
748 const std::vector<mlir::Location> &opLocs = ctl.getTxnOpLocs();
749 // Sharp edge: that projection models how aie-codegen's serializer maps
750 // recorded commands to binary operations. A count disagreement means the
751 // model has drifted from the pinned aie-codegen and every index past the
752 // divergence is mislabeled -- fail loudly instead of silently. An empty
753 // vector just means nothing was bracketed.
754 assert((opLocs.empty() || opLocs.size() == operations.size()) &&
755 "txn loc/op count mismatch: AIERTControl's command-to-operation "
756 "projection disagrees with the transaction parser; aie-codegen's "
757 "serializer has drifted from projectCmdLocsOntoSerializedOps");
758 for (size_t i = 0, e = std::min(opLocs.size(), operations.size()); i < e; ++i)
759 if (!isa<UnknownLoc>(opLocs[i]))
760 operations[i].sourceLoc = opLocs[i];
761
762 llvm::DenseMap<uint32_t, uint32_t> initialRegisters;
763 if (outputType == AIEToConfigurationOutputType::ControlPacket && configured &&
764 configured.getOverlayAttr()) {
765 auto overlay = SymbolTable::lookupNearestSymbolFrom<DeviceOp>(
766 configured->getParentOp(), configured.getOverlayAttr());
767 if (!overlay)
768 return configured.emitOpError("references an unknown overlay device");
769 AIERTControl overlayCtl(overlay.getTargetModel());
770 if (failed(overlayCtl.setIOBackend(false, false)))
771 return failure();
772 overlayCtl.startTransaction();
773 if (failed(overlayCtl.configureSwitches(overlay)))
774 return failure();
775 auto overlayData = overlayCtl.exportSerializedTransaction();
776 std::vector<TransactionBinaryOperation> overlayOps;
777 if (!parseTransactionBinary(overlayData, overlayOps))
778 return failure();
779 // Masked writes must preserve fields installed by the overlay's PDI.
780 for (const auto &op : overlayOps) {
781 uint32_t &value = initialRegisters[op.cmd.RegOff];
782 if (op.cmd.Opcode == XAIE_IO_WRITE)
783 value = op.cmd.Value;
784 else if (op.cmd.Opcode == XAIE_IO_MASKWRITE)
785 value = (value & ~op.cmd.Mask) | (op.cmd.Value & op.cmd.Mask);
786 else
787 return overlay.emitOpError("has a non-register switch configuration");
788 }
789 }
790 return convertTransactionOpsToMLIR(builder, outputType, operations,
791 blockwriteData, initialRegisters);
792}
793
795 OpBuilder &builder, xilinx::AIE::DeviceOp device,
796 AIEX::BlockwriteData &blockwriteData, llvm::StringRef clElfDir,
797 AIE::AIEToConfigurationOutputType outputType, bool skipCtrlPktOverlay) {
798 const AIETargetModel &targetModel =
799 (const AIETargetModel &)device.getTargetModel();
800
801 if (!targetModel.hasProperty(AIETargetModel::IsNPU))
802 return failure();
803 if (failed(AIERTControl::isSupported(device, targetModel)))
804 return failure();
805
806 bool aieSim = false;
807 bool xaieDebug = false;
808
809 AIERTControl ctl(targetModel);
810 if (failed(ctl.setIOBackend(aieSim, xaieDebug)))
811 return failure();
812
813 // start collecting transactions
814 ctl.startTransaction();
815
816 DeviceOp configured = skipCtrlPktOverlay ? device : DeviceOp{};
817 bool controlPackets =
819 if (controlPackets) {
820 auto boundary =
821 AIEX::ControlPacketBarrierOp::create(builder, device.getLoc());
822 boundary.setIndependent(true);
823 }
824 if ((!device.getOps<CoreOp>().empty() &&
825 failed(ctl.addAieElfs(device, clElfDir, aieSim))) ||
826 failed(ctl.addInitConfig(device, skipCtrlPktOverlay)))
827 return failure();
828 if (controlPackets) {
829 if (failed(insertRecordedTransaction(ctl, builder, outputType,
830 blockwriteData, configured)))
831 return failure();
832 auto boundary =
833 AIEX::ControlPacketBarrierOp::create(builder, device.getLoc());
834 boundary.setIndependent(true);
835 ctl.clearTransaction();
836 ctl.startTransaction();
837 }
838 if (failed(ctl.addDmaActivation(device)) ||
839 (!device.getOps<CoreOp>().empty() && failed(ctl.addCoreEnable(device))))
840 return failure();
841 if (failed(insertRecordedTransaction(ctl, builder, outputType, blockwriteData,
842 configured)))
843 return failure();
844 if (controlPackets)
845 AIEX::ControlPacketBarrierOp::create(builder, device.getLoc());
846 return success();
847}
848
849namespace {
850
851using LockAddress = std::tuple<int32_t, int32_t, int32_t>;
852using LockAcquire = std::pair<LockAction, int32_t>;
853
854static std::optional<LockAddress> getLockAddress(UseLockOp use) {
855 auto lock = use.getLock().getDefiningOp<LockOp>();
856 if (!lock)
857 return std::nullopt;
858 auto lockId = lock.getLockID();
859 if (!lockId)
860 return std::nullopt;
861 auto tile = lock.getTileOp();
862 return LockAddress{tile.colIndex(), tile.rowIndex(), *lockId};
863}
864
865static std::optional<LockAcquire> getLockAcquire(UseLockOp use) {
866 APInt value;
867 if (!matchPattern(use.getValue(), m_ConstantInt(&value)))
868 return std::nullopt;
869 return LockAcquire{use.getAction(), value.getSExtValue()};
870}
871
872static CoreLockAcquiresAttr collectCoreLockAcquires(CoreOp core) {
873 if (core.getElfFile())
874 return core.getLockAcquiresAttr();
875 llvm::SetVector<LockAcquireAttr> acquires;
876 llvm::DenseSet<Operation *> visited;
877 SmallVector<Operation *> pending{core};
878 bool unknown = false;
879 while (!pending.empty()) {
880 Operation *operation = pending.pop_back_val();
881 if (!visited.insert(operation).second)
882 continue;
883 operation->walk([&](UseLockOp use) {
884 if (use.release())
885 return;
886 auto address = getLockAddress(use);
887 auto acquire = getLockAcquire(use);
888 if (!address || !acquire) {
889 unknown = true;
890 return;
891 }
892 auto [column, row, lockId] = *address;
893 auto [action, value] = *acquire;
894 acquires.insert(LockAcquireAttr::get(core.getContext(), column, row,
895 lockId, action, value));
896 });
897 operation->walk([&](func::CallOp call) {
898 auto callee = SymbolTable::lookupNearestSymbolFrom<func::FuncOp>(
899 call, call.getCalleeAttr());
900 if (callee && !callee.isExternal())
901 pending.push_back(callee);
902 else if (!callee ||
903 !callee->getAttrOfType<UnitAttr>("aie.no_lock_acquires"))
904 unknown = true;
905 });
906 operation->walk([&](Operation *nested) {
907 if ((isa<CallOpInterface>(nested) && !isa<func::CallOp>(nested)) ||
908 isa<LLVM::CallIntrinsicOp, LLVM::InlineAsmOp>(nested))
909 unknown = true;
910 });
911 }
912 return CoreLockAcquiresAttr::get(core.getContext(), !unknown,
913 acquires.getArrayRef());
914}
915
916struct LockAcquireSummary {
917 std::set<LockAcquire> acquires;
918 SmallVector<CoreOp> cores;
919 bool unknown = false;
920
921 std::optional<int32_t> getSatisfyingValue(uint32_t maximum) const {
922 if (unknown || acquires.empty())
923 return std::nullopt;
924 int32_t lowerBound = 0;
925 std::optional<int32_t> equality;
926 for (auto [action, value] : acquires) {
927 if (value < 0 || static_cast<uint32_t>(value) > maximum)
928 return std::nullopt;
929 if (action == LockAction::AcquireGreaterEqual && value != 0) {
930 lowerBound = std::max(lowerBound, value);
931 } else {
932 if (equality && *equality != value)
933 return std::nullopt;
934 equality = value;
935 }
936 }
937 if (equality && *equality < lowerBound)
938 return std::nullopt;
939 return equality.value_or(lowerBound);
940 }
941};
942
943struct CoreLockAcquireAnalysis {
944 std::map<LockAddress, LockAcquireSummary> locks;
945 llvm::DenseMap<CoreOp, std::set<LockAddress>> coreLocks;
946 llvm::DenseSet<CoreOp> unsupported;
947
948 explicit CoreLockAcquireAnalysis(DeviceOp device) {
949 const auto &model = device.getTargetModel();
950 for (auto core : device.getOps<CoreOp>()) {
951 auto summary = collectCoreLockAcquires(core);
952 if (!summary) {
953 core.emitWarning("teardown cannot determine lock acquires for an ELF "
954 "without lock_acquires; skipping device "
955 "lock draining");
956 unsupported.insert(core);
957 continue;
958 }
959 if (!summary.getComplete()) {
960 core.emitWarning("teardown cannot determine every lock acquire: "
961 "unresolved locks, dynamic values, or opaque callees; "
962 "skipping device lock draining");
963 unsupported.insert(core);
964 continue;
965 }
966 for (LockAcquireAttr acquire : summary.getAcquires()) {
967 LockAddress address{acquire.getColumn(), acquire.getRow(),
968 acquire.getLockId()};
969 auto &lock = locks[address];
970 lock.acquires.emplace(acquire.getAction(), acquire.getValue());
971 if (coreLocks[core].insert(address).second)
972 lock.cores.push_back(core);
973 }
974 }
975 if (!unsupported.empty()) {
976 for (auto core : device.getOps<CoreOp>())
977 unsupported.insert(core);
978 return;
979 }
980 device.walkOutsideRuntimeSequences<UseLockOp>([&](UseLockOp use) {
981 if (use->getParentOfType<CoreOp>() || use.release() || !use.getAcqEn())
982 return;
983 auto address = getLockAddress(use);
984 if (!address)
985 return;
986 auto found = locks.find(*address);
987 if (found == locks.end())
988 return;
989 auto acquire = getLockAcquire(use);
990 if (!acquire)
991 found->second.unknown = true;
992 else
993 found->second.acquires.insert(*acquire);
994 });
995 for (auto &[address, lock] : locks) {
996 auto [column, row, lockId] = address;
997 bool competing = lock.cores.size() > 1;
998 bool incompatible = !lock.getSatisfyingValue(model.getMaxLockValue());
999 if (!competing && !incompatible)
1000 continue;
1001 for (auto core : lock.cores) {
1002 core.emitWarning()
1003 << "teardown cannot drain lock " << lockId << " on tile (" << column
1004 << ", " << row << "): "
1005 << (competing ? "multiple cores may consume the supplied count"
1006 : "no single writable value satisfies every acquire")
1007 << "; skipping core lock draining";
1008 unsupported.insert(core);
1009 }
1010 }
1011 }
1012};
1013
1014static LogicalResult
1015insertCoreLockDrain(OpBuilder &builder, DeviceOp device,
1016 AIEX::BlockwriteData &blockwriteData,
1017 AIEToConfigurationOutputType outputType) {
1018 const auto &model = device.getTargetModel();
1019 if (!model.hasProperty(AIETargetModel::UsesSemaphoreLocks))
1020 return success();
1021 CoreLockAcquireAnalysis analysis(device);
1022 std::set<LockAddress> candidates;
1023 SmallVector<CoreOp> cores;
1024 for (auto core : device.getOps<CoreOp>()) {
1025 auto found = analysis.coreLocks.find(core);
1026 if (analysis.unsupported.contains(core) ||
1027 found == analysis.coreLocks.end())
1028 continue;
1029 candidates.insert(found->second.begin(), found->second.end());
1030 cores.push_back(core);
1031 }
1032 auto tileAddress = [&](int32_t column, int32_t row) {
1033 return model.getTileAddress(column, row);
1034 };
1035 auto pollCoreStatus = [&](CoreOp core, uint32_t maskValue) {
1036 auto tile = core.getTileOp();
1037 auto constant = [&](uint32_t value) {
1038 return arith::ConstantOp::create(builder, core.getLoc(),
1039 builder.getI32IntegerAttr(value));
1040 };
1041 Value status =
1042 constant(tileAddress(tile.colIndex(), tile.rowIndex()) | 0x32004);
1043 Value zero = constant(0);
1044 Value mask = constant(maskValue);
1045 AIEX::NpuMaskPollOp::create(builder, core.getLoc(), status, zero, mask,
1046 nullptr, nullptr, nullptr);
1047 };
1048 std::vector<TransactionBinaryOperation> writes;
1049 for (auto address : candidates) {
1050 auto [column, row, lockId] = address;
1051 auto localAddress = model.getLocalLockAddress(lockId, TileID{column, row});
1052 auto value =
1053 analysis.locks.at(address).getSatisfyingValue(model.getMaxLockValue());
1054 if (!localAddress || !value)
1055 return device.emitOpError(
1056 "teardown lock drain requires a valid lock address and value");
1058 write.cmd.Opcode = XAie_TxnOpcode::XAIE_IO_WRITE;
1059 write.cmd.RegOff = tileAddress(column, row) | *localAddress;
1060 write.cmd.Value = *value;
1061 write.sourceLoc = device.getLoc();
1062 writes.push_back(write);
1063 }
1064 if (!writes.empty())
1065 for (auto core : device.getOps<CoreOp>())
1066 pollCoreStatus(core, 0x1);
1067 if (!writes.empty() &&
1069 auto boundary =
1070 AIEX::ControlPacketBarrierOp::create(builder, device.getLoc());
1071 boundary.setIndependent(true);
1072 }
1073 if (failed(convertTransactionOpsToMLIR(builder, outputType, writes,
1074 blockwriteData, {})))
1075 return failure();
1076 for (auto core : cores)
1077 pollCoreStatus(core, 0x3c0);
1078 return success();
1079}
1080
1081struct AIEAnnotateCoreLockAcquiresPass
1082 : xilinx::impl::AIEAnnotateCoreLockAcquiresBase<
1083 AIEAnnotateCoreLockAcquiresPass> {
1084 void runOnOperation() override {
1085 getOperation().walk([](CoreOp core) {
1086 if (auto summary = collectCoreLockAcquires(core))
1087 core.setLockAcquiresAttr(summary);
1088 });
1089 }
1090};
1091
1092} // namespace
1093
1094std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>>
1096 return std::make_unique<AIEAnnotateCoreLockAcquiresPass>();
1097}
1098
1100 OpBuilder &builder, xilinx::AIE::DeviceOp device,
1101 AIEX::BlockwriteData &blockwriteData,
1102 AIE::AIEToConfigurationOutputType outputType, bool skipCtrlPktOverlay) {
1103 const AIETargetModel &targetModel =
1104 (const AIETargetModel &)device.getTargetModel();
1105 if (!targetModel.hasProperty(AIETargetModel::IsNPU))
1106 return failure();
1107 if (failed(AIERTControl::isSupported(device, targetModel)))
1108 return failure();
1109
1110 AIERTControl ctl(targetModel);
1111 if (failed(ctl.setIOBackend(/*aieSim=*/false, /*xaieDebug=*/false)))
1112 return failure();
1113 ctl.startTransaction();
1114 if (failed(ctl.teardownSwitches(device, skipCtrlPktOverlay)) ||
1115 failed(ctl.disableCores(device)) || failed(ctl.resetDmaChannels(device)))
1116 return failure();
1118 auto boundary =
1119 AIEX::ControlPacketBarrierOp::create(builder, device.getLoc());
1120 boundary.setIndependent(true);
1121 }
1122 if (failed(
1123 insertRecordedTransaction(ctl, builder, outputType, blockwriteData,
1124 skipCtrlPktOverlay ? device : DeviceOp{})))
1125 return failure();
1126 return insertCoreLockDrain(builder, device, blockwriteData, outputType);
1127}
1128
1129LogicalResult
1130xilinx::AIE::insertConfigOps(ArrayRef<std::pair<Operation *, DeviceOp>> sites,
1132 bool ctrlPkt = outputType == AIE::AIEToConfigurationOutputType::ControlPacket;
1133 // Indexed by whether the site is a teardown.
1134 std::array<llvm::DenseMap<DeviceOp, AIEX::BlockwriteData>, 2> blockwriteData;
1135 std::array<llvm::DenseMap<std::pair<Operation *, Operation *>,
1136 std::unique_ptr<Block>>,
1137 2>
1138 configs;
1139 struct ConstantPool {
1140 Operation *last = nullptr;
1141 llvm::DenseMap<Attribute, Value> values;
1142 };
1143 llvm::DenseMap<Operation *, ConstantPool> pools;
1144 for (auto [at, configured] : sites) {
1145 auto device = at->getParentOfType<DeviceOp>();
1146 if (!device)
1147 return at->emitError("expected to be nested under an aie.device op");
1148 bool teardown = isa<AIEX::NpuWriteTeardownOp>(at);
1149 std::unique_ptr<Block> &config = configs[teardown][{configured, device}];
1150 if (!config) {
1151 AIEX::BlockwriteData &payloads =
1152 blockwriteData[teardown]
1153 .try_emplace(device, device, teardown ? "teardown_" : "loadpdi_")
1154 .first->second;
1155 auto generated = std::make_unique<Block>();
1156 OpBuilder configBuilder(at->getContext());
1157 configBuilder.setInsertionPointToEnd(generated.get());
1158 if (teardown ? failed(generateAndInsertTeardownOps(
1159 configBuilder, configured, payloads, outputType))
1161 configBuilder, configured, payloads,
1162 /*clElfDir=*/"", outputType,
1163 /*skipCtrlPktOverlay=*/ctrlPkt)))
1164 return at->emitError(teardown ? "Failed to generate teardown operations"
1165 : "Failed to generate configuration "
1166 "operations");
1167 config = std::move(generated);
1168 }
1169 auto seq = at->getParentOfType<RuntimeSequenceOp>();
1170 ConstantPool *pool = seq ? &pools[seq] : nullptr;
1171 OpBuilder builder(at);
1172 IRMapping mapping;
1173 for (Operation &op : *config) {
1174 Attribute key;
1175 if (auto constant = dyn_cast<arith::ConstantOp>(op))
1176 key = constant.getValue();
1177 else if (auto global = dyn_cast<memref::GetGlobalOp>(op))
1178 key = global.getNameAttr();
1179 if (!pool || !key) {
1180 builder.clone(op, mapping);
1181 continue;
1182 }
1183 Value &pooled = pool->values[key];
1184 if (!pooled) {
1185 OpBuilder::InsertionGuard guard(builder);
1186 if (pool->last)
1187 builder.setInsertionPointAfter(pool->last);
1188 else
1189 builder.setInsertionPointToStart(&seq.getBody().front());
1190 pool->last = builder.clone(op);
1191 pooled = pool->last->getResult(0);
1192 }
1193 mapping.map(op.getResult(0), pooled);
1194 }
1195 }
1196 return success();
1197}
1198
1199LogicalResult xilinx::AIE::inlineWriteConfigs(ModuleOp module) {
1200 SmallVector<std::pair<Operation *, DeviceOp>> sites;
1201 WalkResult walk = module.walk([&](Operation *write) {
1202 FlatSymbolRefAttr ref;
1203 if (auto config = dyn_cast<AIEX::NpuWriteConfigOp>(write))
1204 ref = config.getDeviceRefAttr();
1205 else if (auto teardown = dyn_cast<AIEX::NpuWriteTeardownOp>(write))
1206 ref = teardown.getDeviceRefAttr();
1207 else
1208 return WalkResult::advance();
1209 auto configured = module.lookupSymbol<DeviceOp>(ref);
1210 if (!configured) {
1211 write->emitOpError() << ref << " is not a device";
1212 return WalkResult::interrupt();
1213 }
1214 sites.emplace_back(write, configured);
1215 return WalkResult::advance();
1216 });
1217 if (walk.wasInterrupted() ||
1219 return failure();
1220 for (auto [write, configured] : sites)
1221 write->erase();
1222 return success();
1223}
1224
1225static LogicalResult
1226convertAIEToConfiguration(AIE::DeviceOp device, StringRef clElfDir,
1228
1229 OpBuilder builder(device.getBodyRegion());
1230 // search for aiex.configure ops in runtime sequences by walking the device
1231 // and collect them in a vector. If there are none, create a new runtime
1232 // sequence. Otherwise assume the insertion point is the first
1233 // aiex.configure op.
1234 auto loc = device.getLoc();
1235 SmallVector<AIEX::ConfigureOp> configureOps;
1236 device.walk([&](AIEX::ConfigureOp op) { configureOps.push_back(op); });
1237
1238 if (configureOps.empty()) {
1239 // create aiex.runtime_sequence
1240 int id = 0;
1241 std::string seq_name = "configure";
1242 while (device.lookupSymbol(seq_name))
1243 seq_name = "configure" + std::to_string(id++);
1244 StringAttr seq_sym_name = builder.getStringAttr(seq_name);
1245 auto seq = AIE::RuntimeSequenceOp::create(
1246 builder, loc, seq_sym_name, BoolAttr{}, AIE::TraceBufferAttr{},
1247 ArrayAttr{}, ArrayAttr{});
1248 // A user sequence may already own the name `configure`; consumers find
1249 // the configuration by this tag.
1250 AIE::AIEDialect::GeneratedConfigureAttrHelper(device.getContext())
1251 .setAttr(seq, builder.getUnitAttr());
1252 seq.getBody().push_back(new Block);
1253 builder.setInsertionPointToStart(&seq.getBody().front());
1254 } else {
1255 builder.setInsertionPoint(configureOps.front());
1256 }
1257
1258 // convert the parsed ops to MLIR
1259 AIEX::BlockwriteData blockwriteData(device, "config_blockwrite_data_");
1260 if (failed(generateAndInsertConfigOps(builder, device, blockwriteData,
1261 clElfDir, outputType)))
1262 return failure();
1263
1264 // If we chose the first aiex.configure as insertion point, erase it
1265 // and inline its child operations.
1266 if (!configureOps.empty()) {
1267 // splice the body into the current insertion point
1268 builder.getBlock()->getOperations().splice(
1269 builder.getInsertionPoint(),
1270 configureOps.front().getBody().front().getOperations());
1271 configureOps.front().erase();
1272 }
1273
1274 return success();
1275}
1276
1277namespace {
1278
1279template <typename BaseClass, AIE::AIEToConfigurationOutputType MyOutputType>
1280struct ConvertAIEToConfigurationPass : BaseClass {
1281 std::string &ref_clElfDir;
1282 std::string &ref_clDeviceName;
1283 ConvertAIEToConfigurationPass(std::string &clElfDir,
1284 std::string &clDeviceName)
1285 : ref_clElfDir(clElfDir), ref_clDeviceName(clDeviceName) {}
1286
1287 void getDependentDialects(DialectRegistry &registry) const override {
1288 registry.insert<memref::MemRefDialect, AIEX::AIEXDialect,
1289 arith::ArithDialect>();
1290 }
1291
1292 void runOnOperation() override {
1293 AIE::DeviceOp deviceOp = BaseClass::getOperation();
1294 if (!ref_clDeviceName.empty() &&
1295 deviceOp.getSymName() != ref_clDeviceName) {
1296 return;
1297 }
1298 if (failed(
1299 convertAIEToConfiguration(deviceOp, ref_clElfDir, MyOutputType))) {
1300 return BaseClass::signalPassFailure();
1301 }
1302 }
1303};
1304
1305struct ConvertAIEToTransactionPass
1306 : ConvertAIEToConfigurationPass<
1307 xilinx::impl::ConvertAIEToTransactionBase<
1308 ConvertAIEToTransactionPass>,
1309 AIE::AIEToConfigurationOutputType::Transaction> {
1310 ConvertAIEToTransactionPass()
1311 : ConvertAIEToConfigurationPass<
1312 xilinx::impl::ConvertAIEToTransactionBase<
1313 ConvertAIEToTransactionPass>,
1315 clDeviceName) {}
1316};
1317
1318struct ConvertAIEToControlPacketsPass
1319 : ConvertAIEToConfigurationPass<
1320 xilinx::impl::ConvertAIEToControlPacketsBase<
1321 ConvertAIEToControlPacketsPass>,
1322 AIE::AIEToConfigurationOutputType::ControlPacket> {
1323 ConvertAIEToControlPacketsPass()
1324 : ConvertAIEToConfigurationPass<
1325 xilinx::impl::ConvertAIEToControlPacketsBase<
1326 ConvertAIEToControlPacketsPass>,
1328 clDeviceName) {}
1329};
1330
1331} // end anonymous namespace
1332
1333std::unique_ptr<mlir::OperationPass<xilinx::AIE::DeviceOp>>
1335 return std::make_unique<ConvertAIEToTransactionPass>();
1336}
1337
1338std::unique_ptr<mlir::OperationPass<xilinx::AIE::DeviceOp>>
1340 return std::make_unique<ConvertAIEToControlPacketsPass>();
1341}
memref::GlobalOp getOrCreate(OpBuilder &builder, mlir::Location loc, ArrayRef< uint32_t > words)
Definition AIEUtils.cpp:187
AIE::DeviceOp getDevice() const
Definition AIEUtils.h:40
bool hasProperty(ModelProperty Prop) const
mlir::Value createConstantArgPlus(mlir::OpBuilder &builder, mlir::Location loc, uint64_t value)
mlir::Value createConstantI32(mlir::OpBuilder &builder, mlir::Location loc, uint32_t value)
mlir::LogicalResult insertConfigOps(llvm::ArrayRef< std::pair< mlir::Operation *, xilinx::AIE::DeviceOp > > sites, AIEToConfigurationOutputType outputType)
mlir::LogicalResult inlineWriteConfigs(mlir::ModuleOp module)
std::optional< int > parseTransactionBinary(const std::vector< uint8_t > &data, std::vector< TransactionBinaryOperation > &ops)
Parse an exported transaction.
std::unique_ptr< mlir::OperationPass< xilinx::AIE::DeviceOp > > createConvertAIEToTransactionPass()
mlir::LogicalResult generateAndInsertConfigOps(mlir::OpBuilder &builder, xilinx::AIE::DeviceOp device, xilinx::AIEX::BlockwriteData &blockwriteData, llvm::StringRef clElfDir="", AIEToConfigurationOutputType outputType=AIEToConfigurationOutputType::Transaction, bool skipCtrlPktOverlay=false)
std::unique_ptr< mlir::OperationPass< mlir::ModuleOp > > createAIEAnnotateCoreLockAcquiresPass()
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
mlir::LogicalResult generateAndInsertTeardownOps(mlir::OpBuilder &builder, xilinx::AIE::DeviceOp device, xilinx::AIEX::BlockwriteData &blockwriteData, AIEToConfigurationOutputType outputType=AIEToConfigurationOutputType::Transaction, bool skipCtrlPktOverlay=false)
std::optional< mlir::ModuleOp > convertTransactionBinaryToMLIR(mlir::MLIRContext *ctx, std::vector< uint8_t > &binary)
std::unique_ptr< mlir::OperationPass< xilinx::AIE::DeviceOp > > createConvertAIEToControlPacketsPass()
mlir::LogicalResult addDmaActivation(DeviceOp &targetOp)
Definition AIERT.cpp:1062
mlir::LogicalResult setIOBackend(bool aieSim, bool xaieDebug)
Definition AIERT.cpp:341
std::vector< uint8_t > exportSerializedTransaction()
Definition AIERT.cpp:1390
static mlir::LogicalResult isSupported(mlir::Operation *op, const AIETargetModel &tm)
Diagnose, on op, a target this aie-rt lowering cannot configure.
Definition AIERT.cpp:269
mlir::LogicalResult disableCores(DeviceOp &targetOp)
Definition AIERT.cpp:953
mlir::LogicalResult addCoreEnable(DeviceOp &targetOp)
Definition AIERT.cpp:1103
const std::vector< mlir::Location > & getTxnOpLocs() const
Definition AIERT.cpp:1409
mlir::LogicalResult addInitConfig(DeviceOp &targetOp, bool skipCtrlPktOverlay=false)
Definition AIERT.cpp:1003
mlir::LogicalResult resetDmaChannels(DeviceOp &targetOp)
Definition AIERT.cpp:963
mlir::LogicalResult addAieElfs(DeviceOp &targetOp, const mlir::StringRef elfPath, bool aieSim)
Definition AIERT.cpp:1266
mlir::LogicalResult teardownSwitches(DeviceOp &targetOp, bool skipCtrlPktOverlay=false)
Definition AIERT.cpp:901
std::optional< LoadPdiPayload > loadPdi
std::optional< mlir::Location > sourceLoc
std::optional< AddressPatchPayload > addressPatch