MLIR-AIE 1.4.6.dev
AIERegisterDatabase.cpp
Go to the documentation of this file.
1//===- AIERegisterDatabase.cpp ----------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2025 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7// Register and event database implementation
8//===----------------------------------------------------------------------===//
9
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/Support/ErrorOr.h"
13#include "llvm/Support/FileSystem.h"
14#include "llvm/Support/MemoryBuffer.h"
15#include "llvm/Support/Path.h"
16#include "llvm/Support/Program.h"
17#include "llvm/Support/raw_ostream.h"
18#include <algorithm>
19#include <cstdlib>
20#include <limits>
21
22using namespace xilinx::AIE;
23using namespace llvm;
24
25const BitFieldInfo *RegisterInfo::getField(StringRef fieldName) const {
26 for (const auto &field : bit_fields) {
27 if (StringRef(field.name).equals_insensitive(fieldName)) {
28 return &field;
29 }
30 }
31 return nullptr;
32}
33
34namespace {
35/// Candidate register database directories, in lookup priority order.
36llvm::SmallVector<std::string> getRegDBDirs() {
37 llvm::SmallVector<std::string> dirs;
38 if (const char *installDir = std::getenv("MLIR_AIE_INSTALL_DIR")) {
39 llvm::SmallString<256> dir(installDir);
40 llvm::sys::path::append(dir, "lib", "regdb");
41 dirs.push_back(std::string(dir));
42 }
43
44 std::string mainExecutable = llvm::sys::fs::getMainExecutable(
45 nullptr, reinterpret_cast<void *>(&getRegDBDirs));
46 if (!mainExecutable.empty()) {
47 llvm::SmallString<256> dir(mainExecutable);
48 llvm::sys::path::remove_filename(dir);
49 llvm::sys::path::append(dir, "..", "lib", "regdb");
50 llvm::sys::path::remove_dots(dir, true);
51 dirs.push_back(std::string(dir));
52 }
53 return dirs;
54}
55} // namespace
56
57std::unique_ptr<RegisterDatabase> RegisterDatabase::load(StringRef registerFile,
58 StringRef archKey) {
59 // Take both files from the same directory so that two installs are never
60 // mixed, and fall through to the next directory if loading fails there.
61 // Diagnostics of a failed directory are only reported if all fail.
62 bool found = false;
63 std::string failures;
64 for (const std::string &dir : getRegDBDirs()) {
65 llvm::SmallString<256> registerPath(dir);
66 llvm::sys::path::append(registerPath, registerFile);
67 llvm::SmallString<256> eventPath(dir);
68 llvm::sys::path::append(eventPath, "events_database.json");
69 if (!llvm::sys::fs::exists(registerPath) ||
70 !llvm::sys::fs::exists(eventPath))
71 continue;
72 found = true;
73
74 std::string diagnostics;
75 llvm::raw_string_ostream diag(diagnostics);
76 auto db = std::unique_ptr<RegisterDatabase>(new RegisterDatabase());
77 if (db->loadFromJSON(registerPath, eventPath, archKey, diag)) {
78 llvm::errs() << diag.str();
79 db->buildOffsetIndex();
80 return db;
81 }
82 failures += diag.str();
83 }
84
85 if (!found)
86 llvm::errs() << "Failed to locate AIE register database resources. "
87 << "Set MLIR_AIE_INSTALL_DIR to the "
88 << "MLIR-AIE installation path.\n";
89 else
90 llvm::errs() << failures;
91 return nullptr;
92}
93
94std::unique_ptr<RegisterDatabase> RegisterDatabase::loadAIE2() {
95 return load("aie_registers_aie2.json", "aie2");
96}
97
98std::unique_ptr<RegisterDatabase> RegisterDatabase::loadAIE4() {
99 return load("aie_registers_aie4.json", "aie4");
100}
101
102bool RegisterDatabase::loadFromJSON(StringRef registerPath, StringRef eventPath,
103 StringRef archKey, raw_ostream &diag) {
104 // Load register database
105 auto registerBuf = MemoryBuffer::getFile(registerPath);
106 if (!registerBuf) {
107 diag << "Failed to load register database: " << registerPath << "\n";
108 return false;
109 }
110
111 auto registerJSON = json::parse(registerBuf.get()->getBuffer());
112 if (!registerJSON) {
113 diag << "Failed to parse register JSON\n";
114 return false;
115 }
116
117 // Parse register database
118 auto *root = registerJSON->getAsObject();
119 if (!root)
120 return false;
121
122 auto *modules = root->getObject("modules");
123 if (!modules)
124 return false;
125
126 // Iterate through modules (CORE_MODULE, MEMORY_MODULE, etc.)
127 for (const auto &modulePair : *modules) {
128 StringRef moduleName = modulePair.first;
129 auto *moduleObj = modulePair.second.getAsObject();
130 if (!moduleObj)
131 continue;
132
133 auto *registers = moduleObj->getArray("registers");
134 if (!registers)
135 continue;
136
137 // Parse each register
138 for (const auto &regVal : *registers) {
139 auto *regObj = regVal.getAsObject();
140 if (!regObj)
141 continue;
142
143 RegisterInfo regInfo;
144 regInfo.module = moduleName.str();
145 regInfo.offset = 0; // Initialize to 0
146
147 if (auto name = regObj->getString("name"))
148 regInfo.name = name->str();
149 if (auto offset = regObj->getString("offset")) {
150 // Parse hex offset (string like "0x00000340D0")
151 StringRef offsetStr = *offset;
152 // Remove "0x" prefix if present
153 if (offsetStr.starts_with("0x") || offsetStr.starts_with("0X"))
154 offsetStr = offsetStr.drop_front(2);
155
156 uint64_t offsetVal;
157 if (offsetStr.getAsInteger(16, offsetVal)) {
158 diag << "Warning: Failed to parse offset '" << *offset
159 << "' for register " << regInfo.name << "\n";
160 } else {
161 regInfo.offset = static_cast<uint32_t>(offsetVal);
162 }
163 }
164 if (auto width = regObj->getInteger("width"))
165 regInfo.width = static_cast<uint32_t>(*width);
166 if (auto type = regObj->getString("type"))
167 regInfo.type = type->str();
168 if (auto reset = regObj->getString("reset"))
169 regInfo.reset = reset->str();
170 if (auto desc = regObj->getString("description"))
171 regInfo.description = desc->str();
172
173 // Parse bit fields
174 if (auto *fields = regObj->getArray("bit_fields")) {
175 for (const auto &fieldVal : *fields) {
176 auto *fieldObj = fieldVal.getAsObject();
177 if (!fieldObj)
178 continue;
179
180 BitFieldInfo fieldInfo;
181 if (auto name = fieldObj->getString("name"))
182 fieldInfo.name = name->str();
183 if (auto *bitRange = fieldObj->getArray("bit_range")) {
184 if (bitRange->size() == 2) {
185 if (auto start = (*bitRange)[0].getAsInteger())
186 fieldInfo.bit_start = static_cast<uint32_t>(*start);
187 if (auto end = (*bitRange)[1].getAsInteger())
188 fieldInfo.bit_end = static_cast<uint32_t>(*end);
189 }
190 }
191 if (auto type = fieldObj->getString("type"))
192 fieldInfo.type = type->str();
193 if (auto reset = fieldObj->getString("reset"))
194 fieldInfo.reset = reset->str();
195 if (auto desc = fieldObj->getString("description"))
196 fieldInfo.description = desc->str();
197
198 regInfo.bit_fields.push_back(fieldInfo);
199 }
200 }
201
202 // Store with module::name as key for uniqueness (lowercase for
203 // case-insensitive lookup)
204 std::string key = moduleName.lower() + "::" + regInfo.name;
205 llvm::transform(key, key.begin(), ::tolower);
206 registers_[key] = regInfo;
207 }
208 }
209
210 // Load event database
211 auto eventBuf = MemoryBuffer::getFile(eventPath);
212 if (!eventBuf) {
213 diag << "Failed to load event database: " << eventPath << "\n";
214 return false;
215 }
216
217 auto eventJSON = json::parse(eventBuf.get()->getBuffer());
218 if (!eventJSON) {
219 diag << "Failed to parse event JSON\n";
220 return false;
221 }
222
223 // Parse the event database section for this architecture
224 auto *eventRoot = eventJSON->getAsObject();
225 if (!eventRoot)
226 return false;
227
228 auto *arch = eventRoot->getObject(archKey);
229 if (!arch) {
230 diag << "Failed to find '" << archKey
231 << "' architecture in event database\n";
232 return false;
233 }
234
235 auto *eventModules = arch->getObject("modules");
236 if (!eventModules)
237 return false;
238
239 // Iterate through modules (core, memory, pl, mem_tile)
240 for (const auto &modulePair : *eventModules) {
241 StringRef moduleName = modulePair.first;
242 auto *events = modulePair.second.getAsArray();
243 if (!events)
244 continue;
245
246 // Parse each event
247 for (const auto &eventVal : *events) {
248 auto *eventObj = eventVal.getAsObject();
249 if (!eventObj)
250 continue;
251
252 EventInfo eventInfo;
253 eventInfo.module = moduleName.str();
254
255 if (auto name = eventObj->getString("name"))
256 eventInfo.name = name->str();
257 if (auto number = eventObj->getInteger("number"))
258 eventInfo.number = static_cast<uint32_t>(*number);
259
260 // Store with module::name as key (lowercase for case-insensitive lookup)
261 std::string key = moduleName.str() + "::" + eventInfo.name;
262 llvm::transform(key, key.begin(), ::tolower);
263 events_[key] = eventInfo;
264 }
265 }
266
267 return true;
268}
269
271 StringRef module) const {
272 std::string key = module.str() + "::" + name.str();
273 llvm::transform(key, key.begin(), ::tolower);
274 auto it = registers_.find(key);
275 return it != registers_.end() ? &it->second : nullptr;
276}
277
278void RegisterDatabase::buildOffsetIndex() {
279 registersByOffset_.clear();
280 for (const auto &entry : registers_) {
281 const RegisterInfo &info = entry.second;
282 std::string moduleKey = info.module;
283 llvm::transform(moduleKey, moduleKey.begin(), ::tolower);
284 registersByOffset_[moduleKey][info.offset] = &info;
285 }
286}
287
288const RegisterInfo *
290 StringRef module) const {
291 std::string moduleKey = module.lower();
292 auto modIt = registersByOffset_.find(moduleKey);
293 if (modIt == registersByOffset_.end())
294 return nullptr;
295 auto offIt = modIt->second.find(offset);
296 if (offIt == modIt->second.end())
297 return nullptr;
298 return offIt->second;
299}
300
301std::optional<uint32_t> RegisterDatabase::lookupEvent(StringRef name,
302 StringRef module) const {
303 std::string key = module.str() + "::" + name.str();
304 llvm::transform(key, key.begin(), ::tolower);
305 auto it = events_.find(key);
306 if (it != events_.end()) {
307 return it->second.number;
308 }
309 return std::nullopt;
310}
311
312std::optional<uint32_t>
314 uint32_t value) const {
315 // Validate value fits in field width
316 uint32_t width = field.getWidth();
317 if (width == 0)
318 return std::nullopt;
319
320 uint64_t maxValue = width >= 32 ? std::numeric_limits<uint32_t>::max()
321 : ((1ULL << width) - 1ULL);
322
323 if (value > maxValue)
324 return std::nullopt;
325 if (width < 32)
326 value &= static_cast<uint32_t>(maxValue);
327
328 // Shift to correct bit position
329 uint64_t encoded = (static_cast<uint64_t>(value) << field.bit_start);
330 return static_cast<uint32_t>(encoded);
331}
std::optional< uint32_t > encodeFieldValue(const BitFieldInfo &field, uint32_t value) const
Encode a value for a specific bitfield.
static std::unique_ptr< RegisterDatabase > loadAIE2()
Load database for AIE2 architecture.
static std::unique_ptr< RegisterDatabase > loadAIE4()
Load database for AIE4 architecture.
const RegisterInfo * lookupRegister(llvm::StringRef name, llvm::StringRef module) const
Lookup register by name and module.
std::optional< uint32_t > lookupEvent(llvm::StringRef name, llvm::StringRef module) const
Lookup event by name and module.
const RegisterInfo * lookupRegisterByOffset(uint32_t offset, llvm::StringRef module) const
Lookup register by tile-relative offset and module name.
Bit field information for a register.
const BitFieldInfo * getField(llvm::StringRef fieldName) const
Lookup a bit field by name, case-insensitively.
std::vector< BitFieldInfo > bit_fields