CIRCT 24.0.0git
Loading...
Searching...
No Matches
EmitHGLDD.cpp
Go to the documentation of this file.
1//===- EmitHGLDD.cpp - HGLDD debug info emission --------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
18#include "mlir/IR/Threading.h"
19#include "mlir/Support/FileUtilities.h"
20#include "mlir/Support/IndentedOstream.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Support/FileSystem.h"
23#include "llvm/Support/JSON.h"
24#include "llvm/Support/Path.h"
25#include "llvm/Support/ToolOutputFile.h"
26
27#define DEBUG_TYPE "di"
28
29using namespace mlir;
30using namespace circt;
31using namespace debug;
32
34
35using JValue = llvm::json::Value;
36using JArray = llvm::json::Array;
37using JObject = llvm::json::Object;
38using JOStream = llvm::json::OStream;
39
40/// Walk the given `loc` and collect file-line-column locations that we want to
41/// report as source ("HGL") locations or as emitted Verilog ("HDL") locations.
42///
43/// This function treats locations inside a `NameLoc` called "emitted" or a
44/// `FusedLoc` with the metadata attribute string "verilogLocations" as emitted
45/// Verilog locations. All other locations are considered to be source
46/// locations.
47///
48/// The `level` parameter is used to track into how many "emitted" or
49/// "verilogLocations" we have already descended. For every one of those we look
50/// through the level gets decreased by one. File-line-column locations are only
51/// collected at level 0. We don't descend into "emitted" or "verilogLocations"
52/// once we've reached level 0. This effectively makes the `level` parameter
53/// decide behind how many layers of "emitted" or "verilogLocations" we want to
54/// collect file-line-column locations. Setting this to 0 effectively collects
55/// source locations, i.e., everything not marked as emitted. Setting this to 1
56/// effectively collects emitted locations, i.e., nothing that isn't behind
57/// exactly one layer of "emitted" or "verilogLocations".
58static void findLocations(Location loc, unsigned level,
59 SmallVectorImpl<FileLineColLoc> &locs) {
60 if (auto nameLoc = dyn_cast<NameLoc>(loc)) {
61 if (nameLoc.getName() == "emitted")
62 if (level-- == 0)
63 return;
64 findLocations(nameLoc.getChildLoc(), level, locs);
65 } else if (auto fusedLoc = dyn_cast<FusedLoc>(loc)) {
66 auto strAttr = dyn_cast_or_null<StringAttr>(fusedLoc.getMetadata());
67 if (strAttr && strAttr.getValue() == "verilogLocations")
68 if (level-- == 0)
69 return;
70 for (auto innerLoc : fusedLoc.getLocations())
71 findLocations(innerLoc, level, locs);
72 } else if (auto fileLoc = dyn_cast<FileLineColLoc>(loc)) {
73 if (level == 0)
74 locs.push_back(fileLoc);
75 }
76}
77
78/// Find the best location to report as source location ("HGL", emitted = false)
79/// or as emitted location ("HDL", emitted = true). Returns any non-FIR file it
80/// finds, and only falls back to FIR files if nothing else is found.
81static FileLineColLoc findBestLocation(Location loc, bool emitted,
82 bool fileMustExist) {
83 SmallVector<FileLineColLoc> locs;
84 findLocations(loc, emitted ? 1 : 0, locs);
85 if (fileMustExist) {
86 unsigned tail = 0;
87 for (unsigned head = 0, end = locs.size(); head != end; ++head)
88 if (llvm::sys::fs::exists(locs[head].getFilename().getValue()))
89 locs[tail++] = locs[head];
90 locs.resize(tail);
91 }
92 for (auto loc : locs)
93 if (!loc.getFilename().getValue().ends_with(".fir"))
94 return loc;
95 for (auto loc : locs)
96 if (loc.getFilename().getValue().ends_with(".fir"))
97 return loc;
98 return {};
99}
100
101// Allow `json::Value`s to be used as map keys for the purpose of struct
102// definition uniquification. This abuses the `null` and `[null]` JSON values as
103// markers, and uses a very inefficient hashing of the value's JSON string.
104namespace llvm {
105template <>
107 static unsigned getHashValue(const JValue &x) {
108 SmallString<128> buffer;
109 llvm::raw_svector_ostream(buffer) << x;
110 return hash_value(buffer);
111 }
112 static bool isEqual(const JValue &a, const JValue &b) { return a == b; }
113};
114} // namespace llvm
115
116/// Make the given `path` relative to the `relativeTo` path and store the result
117/// in `relativePath`. Returns whether the conversion was successful. Fails if
118/// the `relativeTo` path has a longer prefix of `../` than `path`, or if it
119/// contains any non-prefix `../` components. Does not clear `relativePath`
120/// before appending to it.
121static bool makePathRelative(StringRef path, StringRef relativeTo,
122 SmallVectorImpl<char> &relativePath) {
123 using namespace llvm::sys;
124 auto sourceIt = path::begin(path);
125 auto outputIt = path::begin(relativeTo);
126 auto sourceEnd = path::end(path);
127 auto outputEnd = path::end(relativeTo);
128
129 // Strip common prefix:
130 // - (), () -> (), ()
131 // - (a/b/c/d), (a/b/e/f) -> (c/d), (e/f)
132 // - (a/b), (a/b/c/d) -> (), (c/d)
133 // - (../a/b), (../a/c) -> (b), (c)
134 while (outputIt != outputEnd && sourceIt != sourceEnd &&
135 *outputIt == *sourceIt) {
136 ++outputIt;
137 ++sourceIt;
138 }
139
140 // For every component in the output path insert a `../` into the source
141 // path. Abort if the output path contains a `../`, because we don't
142 // know where that climbs out to. Consider the changes to the following
143 // output-source pairs as an example:
144 //
145 // - (a/b), (c/d) -> (), (../../c/d)
146 // - (), (a/b) -> (), (a/b)
147 // - (../a), (c/d) -> (../a), (c/d)
148 // - (a/../b), (c/d) -> (../b), (../c/d)
149 for (; outputIt != outputEnd && *outputIt != ".."; ++outputIt)
150 path::append(relativePath, "..");
151 for (; sourceIt != sourceEnd; ++sourceIt)
152 path::append(relativePath, *sourceIt);
153
154 // If there are no more remaining components in the output path, we were
155 // successfully able to translate them into `..` in the source path.
156 // Otherwise the `relativeTo` path contained `../` components that we could
157 // not handle.
158 return outputIt == outputEnd;
159}
160
161/// Legalize the given `name` such that it only consists of valid identifier
162/// characters in Verilog and does not collide with any Verilog keyword, and
163/// uniquify the resulting name such that it does not collide with any of the
164/// names stored in the `nextGeneratedNameIDs` map.
165///
166/// The HGLDD output is likely to be ingested by tools that have been developed
167/// to debug Verilog code. These have the limitation of only supporting valid
168/// Verilog identifiers for signals and other names. HGLDD therefore requires
169/// these names to be valid Verilog identifiers.
170static StringRef legalizeName(StringRef name,
171 llvm::StringMap<size_t> &nextGeneratedNameIDs) {
172 return sv::legalizeName(name, nextGeneratedNameIDs, true);
173}
174
175//===----------------------------------------------------------------------===//
176// HGLDD File Emission
177//===----------------------------------------------------------------------===//
178
179namespace {
180
181/// Contextual information for HGLDD emission shared across multiple HGLDD
182/// files. This struct keeps the DI analysis, symbol caches, and namespaces for
183/// name uniquification.
184struct GlobalState {
185 /// The root operation.
186 Operation *op;
187 /// The emission options.
188 const EmitHGLDDOptions &options;
189 /// The debug info analysis constructed for the root operation.
190 DebugInfo di;
191 /// A symbol cache with all top-level symbols in the root operation.
192 hw::HWSymbolCache symbolCache;
193 /// A uniquified name for each emitted DI module.
194 SmallDenseMap<DIModule *, StringRef> moduleNames;
195 /// A namespace used to deduplicate the names of HGLDD "objects" during
196 /// emission. This includes modules and struct type declarations.
197 llvm::StringMap<size_t> objectNamespace;
198
199 GlobalState(Operation *op, const EmitHGLDDOptions &options)
200 : op(op), options(options), di(op) {
201 symbolCache.addDefinitions(op);
202 symbolCache.freeze();
203 }
204};
205
206/// An emitted type.
207struct EmittedType {
208 StringRef name;
209 SmallVector<int64_t, 1> packedDims;
210 SmallVector<int64_t, 1> unpackedDims;
211
212 EmittedType() = default;
213 EmittedType(StringRef name) : name(name) {}
214 EmittedType(Type type) {
215 type = hw::getCanonicalType(type);
216 if (auto handleType = sv::getHandleElementType(type))
217 type = hw::getCanonicalType(handleType);
218 if (hw::isHWIntegerType(type)) {
219 name = "logic";
220 addPackedDim(hw::getBitWidth(type));
221 }
222 }
223
224 void addPackedDim(int64_t dim) { packedDims.push_back(dim); }
225 void addUnpackedDim(int64_t dim) { unpackedDims.push_back(dim); }
226
227 operator bool() const { return !name.empty(); }
228
229 bool operator==(const EmittedType &other) const {
230 return name == other.name && packedDims == other.packedDims &&
231 unpackedDims == other.unpackedDims;
232 }
233 bool operator!=(const EmittedType &other) const { return !(*this == other); }
234
235 static JArray emitDims(ArrayRef<int64_t> dims, bool skipFirstLen1Dim) {
236 JArray json;
237 if (skipFirstLen1Dim && !dims.empty() && dims[0] == 1)
238 dims = dims.drop_front();
239 for (auto dim : llvm::reverse(dims)) {
240 json.push_back(dim - 1);
241 json.push_back(0);
242 }
243 return json;
244 }
245 JArray emitPackedDims() const { return emitDims(packedDims, true); }
246 JArray emitUnpackedDims() const { return emitDims(unpackedDims, false); }
247};
248
249/// An emitted expression and its type.
250struct EmittedExpr {
251 JValue expr = nullptr;
252 EmittedType type;
253 operator bool() const { return expr != nullptr && type; }
254};
255
256[[maybe_unused]] static llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
257 const EmittedType &type) {
258 if (!type)
259 return os << "<null>";
260 os << type.name;
261 for (auto dim : type.packedDims)
262 os << '[' << dim << ']';
263 if (!type.unpackedDims.empty()) {
264 os << '$';
265 for (auto dim : type.unpackedDims)
266 os << '[' << dim << ']';
267 }
268 return os;
269}
270
271[[maybe_unused]] static llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
272 const EmittedExpr &expr) {
273 if (!expr)
274 return os << "<null>";
275 return os << expr.expr << " : " << expr.type;
276}
277
278/// Contextual information for a single HGLDD file to be emitted.
279struct FileEmitter {
280 GlobalState &state;
281 StringAttr hdlFile;
282 FileEmitter(GlobalState &state, StringAttr hdlFile)
283 : state(state), hdlFile(hdlFile) {}
284
285 /// The DI modules to be emitted into this HGLDD file.
286 SmallVector<DIModule *> modules;
287 /// The name of the output HGLDD file.
288 SmallString<64> outputFileName;
289
290 llvm::StringMap<size_t> moduleNamespace;
291 SmallMapVector<StringAttr, std::pair<StringAttr, unsigned>, 8> sourceFiles;
292 SmallMapVector<JValue, StringRef, 8> structDefs;
293 SmallString<128> structNameHint;
294
295 void emit(llvm::raw_ostream &os);
296 void emit(JOStream &json);
297 JValue emitLoc(FileLineColLoc loc, FileLineColLoc endLoc, bool emitted);
298 void emitModule(JOStream &json, DIModule *module);
299 void emitModuleBody(JOStream &json, DIModule *module);
300 void emitInstance(JOStream &json, DIInstance *instance);
301 void emitVariable(JOStream &json, DIVariable *variable);
302 EmittedExpr emitExpression(Value value);
303
304 unsigned getSourceFile(StringAttr sourceFile, bool emitted);
305
306 FileLineColLoc findBestLocation(Location loc, bool emitted) {
307 return ::findBestLocation(loc, emitted, state.options.onlyExistingFileLocs);
308 }
309
310 /// Find the best location and, if one is found, emit it under the given
311 /// `fieldName`.
312 void findAndEmitLoc(JOStream &json, StringRef fieldName, Location loc,
313 bool emitted) {
314 if (auto fileLoc = findBestLocation(loc, emitted))
315 json.attribute(fieldName, emitLoc(fileLoc, {}, emitted));
316 }
317
318 /// Find the best location and, if one is found, emit it under the given
319 /// `fieldName`. If none is found, guess a location by looking at nested
320 /// operations.
321 void findAndEmitLocOrGuess(JOStream &json, StringRef fieldName, Operation *op,
322 bool emitted) {
323 if (auto fileLoc = findBestLocation(op->getLoc(), emitted)) {
324 json.attribute(fieldName, emitLoc(fileLoc, {}, emitted));
325 return;
326 }
327
328 // Otherwise do a majority vote on the file name to report as location. Walk
329 // the operation, collect all locations, and group them by file name.
330 SmallMapVector<StringAttr, std::pair<SmallVector<FileLineColLoc>, unsigned>,
331 4>
332 locsByFile;
333 op->walk([&](Operation *subop) {
334 // Consider operations.
335 if (auto fileLoc = findBestLocation(subop->getLoc(), emitted))
336 locsByFile[fileLoc.getFilename()].first.push_back(fileLoc);
337
338 // Consider block arguments.
339 for (auto &region : subop->getRegions())
340 for (auto &block : region)
341 for (auto arg : block.getArguments())
342 if (auto fileLoc = findBestLocation(arg.getLoc(), emitted))
343 locsByFile[fileLoc.getFilename()].first.push_back(fileLoc);
344 });
345
346 // Give immediate block arguments a larger weight.
347 for (auto &region : op->getRegions())
348 for (auto &block : region)
349 for (auto arg : block.getArguments())
350 if (auto fileLoc = findBestLocation(arg.getLoc(), emitted))
351 locsByFile[fileLoc.getFilename()].second += 10;
352
353 if (locsByFile.empty())
354 return;
355
356 // Pick the highest-scoring file and create a location from it.
357 llvm::sort(locsByFile, [](auto &a, auto &b) {
358 return (a.second.first.size() + a.second.second) >
359 (b.second.first.size() + a.second.second);
360 });
361
362 auto &locs = locsByFile.front().second.first;
363 llvm::sort(locs, [](auto &a, auto &b) {
364 if (a.getLine() < b.getLine())
365 return true;
366 if (a.getLine() > b.getLine())
367 return false;
368 if (a.getColumn() < b.getColumn())
369 return true;
370 return false;
371 });
372
373 json.attribute(fieldName, emitLoc(locs.front(), locs.back(), emitted));
374 }
375
376 /// Find the best locations to report for HGL and HDL and set them as fields
377 /// on the `into` JSON object.
378 void findAndSetLocs(JObject &into, Location loc) {
379 if (auto fileLoc = findBestLocation(loc, false))
380 into["hgl_loc"] = emitLoc(fileLoc, {}, false);
381 if (auto fileLoc = findBestLocation(loc, true))
382 into["hdl_loc"] = emitLoc(fileLoc, {}, true);
383 }
384
385 /// Return the legalized and uniquified name of a DI module. Asserts that the
386 /// module has such a name.
387 StringRef getModuleName(DIModule *module) {
388 auto name = state.moduleNames.lookup(module);
389 assert(!name.empty() &&
390 "moduleNames should contain a name for every module");
391 return name;
392 }
393
394 StringRef legalizeInModuleNamespace(StringRef name) {
395 return legalizeName(name, moduleNamespace);
396 }
397};
398
399} // namespace
400
401/// Get a numeric index for the given `sourceFile`. Populates `sourceFiles`
402/// with a unique ID assignment for each source file.
403unsigned FileEmitter::getSourceFile(StringAttr sourceFile, bool emitted) {
404 using namespace llvm::sys;
405
406 // Check if we have already allocated an ID for this source file. If we
407 // have, return it. Otherwise, assign a new ID and normalize the path
408 // according to HGLDD requirements.
409 auto &slot = sourceFiles[sourceFile];
410 if (slot.first)
411 return slot.second;
412 slot.second = sourceFiles.size();
413
414 // If the source file is an absolute path, simply use that unchanged.
415 if (path::is_absolute(sourceFile.getValue())) {
416 slot.first = sourceFile;
417 return slot.second;
418 }
419
420 // If specified, apply the output file prefix if this is an output file
421 // (`emitted` is true), or the source file prefix if this is a source file
422 // (`emitted` is false).
423 StringRef filePrefix =
424 emitted ? state.options.outputFilePrefix : state.options.sourceFilePrefix;
425 if (!filePrefix.empty()) {
426 SmallString<64> buffer = filePrefix;
427 path::append(buffer, sourceFile.getValue());
428 slot.first = StringAttr::get(sourceFile.getContext(), buffer);
429 return slot.second;
430 }
431
432 // Otherwise make the path relative to the HGLDD output file.
433
434 // Remove any `./` and `../` inside the path. This has also been applied
435 // to the `outputFileName`. As a result, both paths start with zero or
436 // more `../`, followed by the rest of the path without any `./` or `../`.
437 SmallString<64> sourcePath = sourceFile.getValue();
438 path::remove_dots(sourcePath, true);
439
440 // If the output file is also relative, try to determine the relative path
441 // between them directly.
442 StringRef relativeToDir = path::parent_path(outputFileName);
443 if (!path::is_absolute(outputFileName)) {
444 SmallString<64> buffer;
445 if (makePathRelative(sourcePath, relativeToDir, buffer)) {
446 slot.first = StringAttr::get(sourceFile.getContext(), buffer);
447 return slot.second;
448 }
449 }
450
451 // If the above failed, try to make the output and source paths absolute and
452 // retry computing a relative path. Only do this if conversion to absolute
453 // paths is successful for both paths, and if the resulting paths have at
454 // least the first path component in common. This prevents computing a
455 // relative path between `/home/foo/bar` and `/tmp/baz/noob` as
456 // `../../../tmp/baz/noob`.
457 SmallString<64> outputPath = relativeToDir;
458 fs::make_absolute(sourcePath);
459 fs::make_absolute(outputPath);
460 if (path::is_absolute(sourcePath) && path::is_absolute(outputPath)) {
461 auto firstSourceComponent = *path::begin(path::relative_path(sourcePath));
462 auto firstOutputComponent = *path::begin(path::relative_path(outputPath));
463 if (firstSourceComponent == firstOutputComponent) {
464 SmallString<64> buffer;
465 if (makePathRelative(sourcePath, outputPath, buffer)) {
466 slot.first = StringAttr::get(sourceFile.getContext(), buffer);
467 return slot.second;
468 }
469 }
470 }
471
472 // Otherwise simply use the absolute source file path.
473 slot.first = StringAttr::get(sourceFile.getContext(), sourcePath);
474 return slot.second;
475}
476
477void FileEmitter::emit(llvm::raw_ostream &os) {
478 JOStream json(os, 2);
479 emit(json);
480 os << "\n";
481}
482
484 // The "HGLDD" header field needs to be the first in the JSON file (which
485 // violates the JSON spec, but what can you do). But we only know after module
486 // emission what the contents of the header will be.
487 SmallVector<std::string, 16> rawObjects;
488 for (auto *module : modules) {
489 llvm::raw_string_ostream objectOS(rawObjects.emplace_back());
490 JOStream objectJson(objectOS, 2);
491 objectJson.arrayBegin(); // dummy for indentation
492 objectJson.arrayBegin(); // dummy for indentation
493 emitModule(objectJson, module);
494 objectJson.arrayEnd(); // dummy for indentation
495 objectJson.arrayEnd(); // dummy for indentation
496 }
497
498 std::optional<unsigned> hdlFileIndex;
499 if (hdlFile)
500 hdlFileIndex = getSourceFile(hdlFile, true);
501
502 json.objectBegin();
503 json.attributeObject("HGLDD", [&] {
504 json.attribute("version", "1.0");
505 json.attributeArray("file_info", [&] {
506 for (auto [key, fileAndId] : sourceFiles)
507 json.value(fileAndId.first.getValue());
508 });
509 if (hdlFileIndex)
510 json.attribute("hdl_file_index", *hdlFileIndex);
511 });
512 json.attributeArray("objects", [&] {
513 for (auto &[structDef, name] : structDefs)
514 json.value(structDef);
515 for (auto &rawObject : rawObjects) {
516 // The "rawObject" is nested within two dummy arrays (`[[<stuff>]]`) to
517 // make the indentation of the actual object JSON inside line up with the
518 // current scope (`{"objects":[<stuff>]}`). This is a bit of a hack, but
519 // allows us to use the JSON `OStream` API when constructing the modules
520 // above, creating a simple string buffer, instead of building up a
521 // potentially huge in-memory hierarchy of JSON objects for every module
522 // first. To remove the two dummy arrays, we drop the `[` and `]` at the
523 // front and back twice, and trim the remaining whitespace after each
524 // (since the actual string looks a lot more like
525 // `[\n [\n <stuff>\n ]\n]`).
526 json.rawValue(StringRef(rawObject)
527 .drop_front()
528 .drop_back()
529 .trim()
530 .drop_front()
531 .drop_back()
532 .trim());
533 }
534 });
535 json.objectEnd();
536}
537
538JValue FileEmitter::emitLoc(FileLineColLoc loc, FileLineColLoc endLoc,
539 bool emitted) {
540 JObject obj;
541 obj["file"] = getSourceFile(loc.getFilename(), emitted);
542 if (loc.getLine()) {
543 obj["begin_line"] = loc.getLine();
544 obj["end_line"] = loc.getLine();
545 }
546 if (loc.getColumn()) {
547 obj["begin_column"] = loc.getColumn();
548 obj["end_column"] = loc.getColumn();
549 }
550 if (endLoc) {
551 if (endLoc.getLine())
552 obj["end_line"] = endLoc.getLine();
553 if (endLoc.getColumn())
554 obj["end_column"] = endLoc.getColumn();
555 }
556 return obj;
557}
558
559StringAttr getVerilogModuleName(DIModule &module) {
560 if (auto *op = module.op)
561 if (auto attr = op->getAttrOfType<StringAttr>("verilogName"))
562 return attr;
563 return module.name;
564}
565
567 if (auto *op = inst.op)
568 if (auto attr = op->getAttrOfType<StringAttr>("hw.verilogName"))
569 return attr;
570 return inst.name;
571}
572
573/// Emit the debug info for a `DIModule`.
574void FileEmitter::emitModule(JOStream &json, DIModule *module) {
575 moduleNamespace = state.objectNamespace;
576 structNameHint = module->name.getValue();
577 json.objectBegin();
578 json.attribute("kind", "module");
579 json.attribute("obj_name", getModuleName(module)); // HGL
580 json.attribute("module_name",
581 getVerilogModuleName(*module).getValue()); // HDL
582 if (module->isExtern)
583 json.attribute("isExtModule", 1);
584 if (auto *op = module->op) {
585 findAndEmitLocOrGuess(json, "hgl_loc", op, false);
586 findAndEmitLoc(json, "hdl_loc", op->getLoc(), true);
587 }
588 emitModuleBody(json, module);
589 json.objectEnd();
590}
591
592/// Emit the debug info for a `DIModule` body.
593void FileEmitter::emitModuleBody(JOStream &json, DIModule *module) {
594 json.attributeArray("port_vars", [&] {
595 for (auto *var : module->variables)
596 emitVariable(json, var);
597 });
598 json.attributeArray("children", [&] {
599 for (auto *instance : module->instances)
600 emitInstance(json, instance);
601 });
602}
603
604/// Emit the debug info for a `DIInstance`.
605void FileEmitter::emitInstance(JOStream &json, DIInstance *instance) {
606 json.objectBegin();
607
608 // Emit the instance and module name.
609 auto instanceName = legalizeInModuleNamespace(instance->name.getValue());
610 json.attribute("name", instanceName);
611 if (!instance->module->isInline) {
612 auto verilogName = getVerilogInstanceName(*instance);
613 if (verilogName != instanceName)
614 json.attribute("hdl_obj_name", verilogName.getValue());
615
616 json.attribute("obj_name",
617 getModuleName(instance->module)); // HGL
618 json.attribute("module_name",
619 getVerilogModuleName(*instance->module).getValue()); // HDL
620 }
621
622 if (auto *op = instance->op) {
623 findAndEmitLoc(json, "hgl_loc", op->getLoc(), false);
624 findAndEmitLoc(json, "hdl_loc", op->getLoc(), true);
625 }
626
627 // Emit the module body inline if this is an inline scope.
628 if (instance->module->isInline) {
629 auto structNameHintLen = structNameHint.size();
630 if (!instance->module->name.empty()) {
631 structNameHint += '_';
632 structNameHint += instance->module->name.getValue();
633 } else if (!instance->name.empty()) {
634 structNameHint += '_';
635 structNameHint += instanceName;
636 }
637 emitModuleBody(json, instance->module);
638 structNameHint.resize(structNameHintLen);
639 }
640
641 json.objectEnd();
642}
643
644/// Emit the debug info for a `DIVariable`.
645void FileEmitter::emitVariable(JOStream &json, DIVariable *variable) {
646 json.objectBegin();
647 auto variableName = legalizeInModuleNamespace(variable->name.getValue());
648 json.attribute("var_name", variableName);
649 findAndEmitLoc(json, "hgl_loc", variable->loc, false);
650 findAndEmitLoc(json, "hdl_loc", variable->loc, true);
651
652 EmittedExpr emitted;
653 if (auto value = variable->value) {
654 auto structNameHintLen = structNameHint.size();
655 structNameHint += '_';
656 structNameHint += variableName;
657 emitted = emitExpression(value);
658 structNameHint.resize(structNameHintLen);
659 }
660
661 LLVM_DEBUG(llvm::dbgs() << "- " << variable->name << ": " << emitted << "\n");
662 if (emitted) {
663 json.attributeBegin("value");
664 json.rawValue([&](auto &os) { os << emitted.expr; });
665 json.attributeEnd();
666 json.attribute("type_name", emitted.type.name);
667 if (auto dims = emitted.type.emitPackedDims(); !dims.empty())
668 json.attribute("packed_range", std::move(dims));
669 if (auto dims = emitted.type.emitUnpackedDims(); !dims.empty())
670 json.attribute("unpacked_range", std::move(dims));
671 }
672
673 json.objectEnd();
674}
675
676/// Emit the DI expression necessary to materialize a value.
677EmittedExpr FileEmitter::emitExpression(Value value) {
678 // A few helpers to simplify creating the various JSON operator and expression
679 // snippets.
680 auto hglddSigName = [](StringRef sigName) -> JObject {
681 return JObject{{"sig_name", sigName}};
682 };
683 auto hglddOperator = [](StringRef opcode, JValue args) -> JObject {
684 return JObject{
685 {"opcode", opcode},
686 {"operands", std::move(args)},
687 };
688 };
689 auto hglddInt32 = [](uint32_t value) -> JObject {
690 return JObject({{"integer_num", value}});
691 };
692
693 if (auto blockArg = dyn_cast<BlockArgument>(value)) {
694 auto module = dyn_cast<hw::HWModuleOp>(blockArg.getOwner()->getParentOp());
695 if (!module)
696 return {};
697 auto name = module.getInputNameAttr(blockArg.getArgNumber());
698 if (!name)
699 return {};
700 return {hglddSigName(name), value.getType()};
701 }
702
703 auto result = cast<OpResult>(value);
704 auto *op = result.getOwner();
705
706 // If the operation is a named signal in the output Verilog, use that name.
707 if (isa<hw::WireOp, sv::WireOp, sv::RegOp, sv::LogicOp, sv::VarOp>(op)) {
708 auto name = op->getAttrOfType<StringAttr>("hw.verilogName");
709 if (!name || name.empty())
710 name = op->getAttrOfType<StringAttr>("name");
711 if (name && !name.empty())
712 return {hglddSigName(name), result.getType()};
713 }
714
715 // Emit constants directly.
716 if (auto constOp = dyn_cast<hw::ConstantOp>(op)) {
717 // Determine the bit width of the constant.
718 auto type = constOp.getType();
719 auto width = hw::getBitWidth(type);
720
721 // Emit zero-width constants as a 1-bit zero value. This ensures we get a
722 // proper Verilog-compatible value as a result. Expressions like
723 // concatenation should instead skip zero-width values.
724 if (width < 1)
725 return {JObject({{"bit_vector", "0"}}),
726 IntegerType::get(op->getContext(), 1)};
727
728 // Serialize the constant as a base-2 binary string.
729 SmallString<64> buffer;
730 buffer.reserve(width);
731 constOp.getValue().toStringUnsigned(buffer, 2);
732
733 // Pad the string with leading zeros such that it is exactly of the required
734 // width. This is needed since tools will use the string length to determine
735 // the width of the constant.
736 std::reverse(buffer.begin(), buffer.end());
737 while (buffer.size() < (size_t)width)
738 buffer += '0';
739 std::reverse(buffer.begin(), buffer.end());
740 assert(buffer.size() == (size_t)width);
741
742 return {JObject({{"bit_vector", buffer}}), type};
743 }
744
745 // Emit structs as assignment patterns and generate corresponding struct
746 // definitions for inclusion in the main "objects" array.
747 if (auto structOp = dyn_cast<debug::StructOp>(op)) {
748 // Collect field names, expressions, and types.
749 auto structNameHintLen = structNameHint.size();
750 std::vector<JValue> values;
751 SmallVector<std::tuple<EmittedType, StringAttr, Location>> types;
752 for (auto [nameAttr, field] :
753 llvm::zip(structOp.getNamesAttr(), structOp.getFields())) {
754 auto name = cast<StringAttr>(nameAttr);
755 structNameHint += '_';
756 structNameHint += name.getValue();
757 if (auto value = emitExpression(field)) {
758 values.push_back(value.expr);
759 types.push_back({value.type, name, field.getLoc()});
760 }
761 structNameHint.resize(structNameHintLen);
762 }
763
764 // Emit empty structs as 0 `bit`.
765 if (values.empty())
766 return {hglddInt32(0), EmittedType("bit")};
767
768 // Assemble the struct type definition.
769 JArray fieldDefs;
770 llvm::StringMap<size_t> structNamespace;
771 for (auto [type, name, loc] : types) {
772 JObject fieldDef;
773 fieldDef["var_name"] =
774 std::string(legalizeName(name.getValue(), structNamespace));
775 fieldDef["type_name"] = type.name;
776 if (auto dims = type.emitPackedDims(); !dims.empty())
777 fieldDef["packed_range"] = std::move(dims);
778 if (auto dims = type.emitUnpackedDims(); !dims.empty())
779 fieldDef["unpacked_range"] = std::move(dims);
780 findAndSetLocs(fieldDef, loc);
781 fieldDefs.push_back(std::move(fieldDef));
782 }
783 auto structName = legalizeName(structNameHint, state.objectNamespace);
784 JObject structDef;
785 structDef["kind"] = "struct";
786 structDef["obj_name"] = structName;
787 structDef["port_vars"] = std::move(fieldDefs);
788 findAndSetLocs(structDef, structOp.getLoc());
789
790 StringRef structNameFinal =
791 structDefs.insert({std::move(structDef), structName}).first->second;
792
793 return {hglddOperator("'{", values), EmittedType(structNameFinal)};
794 }
795
796 // Emit arrays as assignment patterns.
797 if (auto arrayOp = dyn_cast<debug::ArrayOp>(op)) {
798 std::vector<JValue> values;
799 EmittedType type;
800 for (auto element : arrayOp.getElements()) {
801 if (auto value = emitExpression(element)) {
802 values.push_back(value.expr);
803 if (type && type != value.type)
804 return {};
805 type = value.type;
806 }
807 }
808
809 // Emit empty arrays as 0 `bit`.
810 if (!type)
811 return {hglddInt32(0), EmittedType("bit")};
812
813 type.addUnpackedDim(values.size());
814 return {hglddOperator("'{", values), type};
815 }
816
817 // Look through read inout ops.
818 if (auto readOp = dyn_cast<sv::ReadInOutOp>(op))
819 return emitExpression(readOp.getInput());
820
821 // Emit unary and binary combinational ops as their corresponding HGLDD
822 // operation.
823 StringRef unaryOpcode = TypeSwitch<Operation *, StringRef>(op)
824 .Case<comb::ParityOp>([](auto) { return "^"; })
825 .Default([](auto) { return ""; });
826 if (!unaryOpcode.empty() && op->getNumOperands() == 1) {
827 auto arg = emitExpression(op->getOperand(0));
828 if (!arg)
829 return {};
830 return {hglddOperator(unaryOpcode, JArray{arg.expr}), result.getType()};
831 }
832
833 StringRef binaryOpcode =
834 TypeSwitch<Operation *, StringRef>(op)
835 .Case<comb::AndOp>([](auto) { return "&"; })
836 .Case<comb::OrOp>([](auto) { return "|"; })
837 .Case<comb::XorOp>([](auto) { return "^"; })
838 .Case<comb::AddOp>([](auto) { return "+"; })
839 .Case<comb::SubOp>([](auto) { return "-"; })
840 .Case<comb::MulOp>([](auto) { return "*"; })
841 .Case<comb::DivUOp, comb::DivSOp>([](auto) { return "/"; })
842 .Case<comb::ModUOp, comb::ModSOp>([](auto) { return "%"; })
843 .Case<comb::ShlOp>([](auto) { return "<<"; })
844 .Case<comb::ShrUOp>([](auto) { return ">>"; })
845 .Case<comb::ShrSOp>([](auto) { return ">>>"; })
846 .Case<comb::ICmpOp>([](auto cmpOp) -> StringRef {
847 switch (cmpOp.getPredicate()) {
848 case comb::ICmpPredicate::eq:
849 return "==";
850 case comb::ICmpPredicate::ne:
851 return "!=";
852 case comb::ICmpPredicate::ceq:
853 return "===";
854 case comb::ICmpPredicate::cne:
855 return "!==";
856 case comb::ICmpPredicate::weq:
857 return "==?";
858 case comb::ICmpPredicate::wne:
859 return "!=?";
860 case comb::ICmpPredicate::ult:
861 case comb::ICmpPredicate::slt:
862 return "<";
863 case comb::ICmpPredicate::ugt:
864 case comb::ICmpPredicate::sgt:
865 return ">";
866 case comb::ICmpPredicate::ule:
867 case comb::ICmpPredicate::sle:
868 return "<=";
869 case comb::ICmpPredicate::uge:
870 case comb::ICmpPredicate::sge:
871 return ">=";
872 }
873 return {};
874 })
875 .Default([](auto) { return ""; });
876 if (!binaryOpcode.empty()) {
877 if (op->getNumOperands() != 2) {
878 op->emitOpError("must have two operands for HGLDD emission");
879 return {};
880 }
881 auto lhs = emitExpression(op->getOperand(0));
882 auto rhs = emitExpression(op->getOperand(1));
883 if (!lhs || !rhs)
884 return {};
885 return {hglddOperator(binaryOpcode, {lhs.expr, rhs.expr}),
886 result.getType()};
887 }
888
889 // Special handling for concatenation.
890 if (auto concatOp = dyn_cast<comb::ConcatOp>(op)) {
891 std::vector<JValue> args;
892 for (auto operand : concatOp.getOperands()) {
893 auto value = emitExpression(operand);
894 if (!value)
895 return {};
896 args.push_back(value.expr);
897 }
898 return {hglddOperator("{}", args), concatOp.getType()};
899 }
900
901 // Emit `ReplicateOp` as HGLDD `R{}` op.
902 if (auto replicateOp = dyn_cast<comb::ReplicateOp>(op)) {
903 auto arg = emitExpression(replicateOp.getInput());
904 if (!arg)
905 return {};
906 return {hglddOperator("R{}",
907 {
908 hglddInt32(replicateOp.getMultiple()),
909 arg.expr,
910 }),
911 replicateOp.getType()};
912 }
913
914 // Emit extracts as HGLDD `[]` ops.
915 if (auto extractOp = dyn_cast<comb::ExtractOp>(op)) {
916 auto arg = emitExpression(extractOp.getInput());
917 if (!arg)
918 return {};
919 auto lowBit = extractOp.getLowBit();
920 auto highBit = lowBit + extractOp.getType().getIntOrFloatBitWidth() - 1;
921 return {hglddOperator("[]",
922 {
923 arg.expr,
924 hglddInt32(highBit),
925 hglddInt32(lowBit),
926 }),
927 extractOp.getType()};
928 }
929
930 // Emit `MuxOp` as HGLDD `?:` ternary op.
931 if (auto muxOp = dyn_cast<comb::MuxOp>(op)) {
932 auto cond = emitExpression(muxOp.getCond());
933 auto lhs = emitExpression(muxOp.getTrueValue());
934 auto rhs = emitExpression(muxOp.getFalseValue());
935 if (!cond || !lhs || !rhs)
936 return {};
937 return {hglddOperator("?:", {cond.expr, lhs.expr, rhs.expr}),
938 muxOp.getType()};
939 }
940
941 // As a last resort, look for any named wire-like ops this value feeds into.
942 // This is useful for instance output ports for example since we cannot access
943 // instance ports as `<instName>.<portName>` in HGLDD. Instead, we look for a
944 // wire hooked up to the instance output, which is very likely to be present
945 // after Verilog emission.
946 for (auto &use : result.getUses()) {
947 auto *user = use.getOwner();
948 // Use name of `hw.wire` that carries this value.
949 if (auto wireOp = dyn_cast<hw::WireOp>(user))
950 if (wireOp.getInput() == result)
951 return emitExpression(wireOp);
952 // Use name of `sv.assign` destination that is assigned this value.
953 if (auto assignOp = dyn_cast<sv::AssignOp>(user))
954 if (assignOp.getSrc() == result)
955 return emitExpression(assignOp.getDest());
956 // Use name of `sv.var_assign` destination that is assigned this value.
957 if (auto varAssignOp = dyn_cast<sv::VarAssignOp>(user))
958 if (varAssignOp.getSrc() == result)
959 return emitExpression(varAssignOp.getDest());
960 // Use module output port name that carries this value.
961 if (isa<hw::OutputOp>(user)) {
962 auto mod = cast<hw::HWModuleLike>(user->getParentOp());
963 auto portName = mod.getPort(mod.getHWModuleType().getPortIdForOutputId(
964 use.getOperandNumber()))
965 .getVerilogName();
966 return {hglddSigName(portName), result.getType()};
967 }
968 }
969
970 return {};
971}
972
973//===----------------------------------------------------------------------===//
974// Output Splitting
975//===----------------------------------------------------------------------===//
976
977namespace {
978
979/// Contextual information for HGLDD emission shared across multiple HGLDD
980/// files. This struct is used to determine an initial split of debug info files
981/// and to distribute work.
982struct Emitter {
983 GlobalState state;
984 SmallVector<FileEmitter, 0> files;
985 Emitter(Operation *module, const EmitHGLDDOptions &options);
986};
987
988} // namespace
989
990Emitter::Emitter(Operation *module, const EmitHGLDDOptions &options)
991 : state(module, options) {
992 // Group the DI modules according to their emitted file path. Modules that
993 // don't have an emitted file path annotated are collected in a separate
994 // group. That group, with a null `StringAttr` key, is emitted into a separate
995 // "global.dd" file.
996 MapVector<StringAttr, FileEmitter> groups;
997 for (auto [moduleName, module] : state.di.moduleNodes) {
998 StringAttr hdlFile;
999 if (module->op)
1000 if (auto fileLoc = findBestLocation(module->op->getLoc(), true, false))
1001 hdlFile = fileLoc.getFilename();
1002 auto &fileEmitter =
1003 groups.try_emplace(hdlFile, state, hdlFile).first->second;
1004 fileEmitter.modules.push_back(module);
1005 state.moduleNames[module] =
1006 legalizeName(module->name.getValue(), state.objectNamespace);
1007 }
1008
1009 // Determine the output file names and move the emitters into the `files`
1010 // member.
1011 files.reserve(groups.size());
1012 for (auto &[hdlFile, emitter] : groups) {
1013 emitter.outputFileName = options.outputDirectory;
1014 StringRef fileName = hdlFile ? hdlFile.getValue() : "global";
1015 if (llvm::sys::path::is_absolute(fileName))
1016 emitter.outputFileName = fileName;
1017 else
1018 llvm::sys::path::append(emitter.outputFileName, fileName);
1019 llvm::sys::path::replace_extension(emitter.outputFileName, "dd");
1020 llvm::sys::path::remove_dots(emitter.outputFileName, true);
1021 files.push_back(std::move(emitter));
1022 }
1023
1024 // Dump some information about the files to be created.
1025 LLVM_DEBUG({
1026 llvm::dbgs() << "HGLDD files:\n";
1027 for (auto &emitter : files) {
1028 llvm::dbgs() << "- " << emitter.outputFileName << " (from "
1029 << emitter.hdlFile << ")\n";
1030 for (auto *module : emitter.modules)
1031 llvm::dbgs() << " - " << module->name << "\n";
1032 }
1033 });
1034}
1035
1036//===----------------------------------------------------------------------===//
1037// Emission Entry Points
1038//===----------------------------------------------------------------------===//
1039
1040LogicalResult debug::emitHGLDD(Operation *module, llvm::raw_ostream &os,
1041 const EmitHGLDDOptions &options) {
1042 Emitter emitter(module, options);
1043 for (auto &fileEmitter : emitter.files) {
1044 os << "\n// ----- 8< ----- FILE \"" + fileEmitter.outputFileName +
1045 "\" ----- 8< -----\n\n";
1046 fileEmitter.emit(os);
1047 }
1048 return success();
1049}
1050
1051LogicalResult debug::emitSplitHGLDD(Operation *module,
1052 const EmitHGLDDOptions &options) {
1053 Emitter emitter(module, options);
1054
1055 auto emit = [&](auto &fileEmitter) {
1056 // Open the output file for writing.
1057 std::string errorMessage;
1058 auto output =
1059 mlir::openOutputFile(fileEmitter.outputFileName, &errorMessage);
1060 if (!output) {
1061 module->emitError(errorMessage);
1062 return failure();
1063 }
1064
1065 // Emit the debug information and keep the file around.
1066 fileEmitter.emit(output->os());
1067 output->keep();
1068 return success();
1069 };
1070
1071 return mlir::failableParallelForEach(module->getContext(), emitter.files,
1072 emit);
1073}
assert(baseType &&"element must be base type")
static void emitDims(ArrayRef< Attribute > dims, raw_ostream &os, Location loc, ModuleEmitter &emitter)
Emit a list of packed dimensions.
StringAttr getVerilogInstanceName(DIInstance &inst)
llvm::json::OStream JOStream
Definition EmitHGLDD.cpp:38
static void findLocations(Location loc, unsigned level, SmallVectorImpl< FileLineColLoc > &locs)
Walk the given loc and collect file-line-column locations that we want to report as source ("HGL") lo...
Definition EmitHGLDD.cpp:58
llvm::json::Value JValue
Definition EmitHGLDD.cpp:35
static bool makePathRelative(StringRef path, StringRef relativeTo, SmallVectorImpl< char > &relativePath)
Make the given path relative to the relativeTo path and store the result in relativePath.
static FileLineColLoc findBestLocation(Location loc, bool emitted, bool fileMustExist)
Find the best location to report as source location ("HGL", emitted = false) or as emitted location (...
Definition EmitHGLDD.cpp:81
static StringRef legalizeName(StringRef name, llvm::StringMap< size_t > &nextGeneratedNameIDs)
Legalize the given name such that it only consists of valid identifier characters in Verilog and does...
llvm::json::Object JObject
Definition EmitHGLDD.cpp:37
llvm::json::Array JArray
Definition EmitHGLDD.cpp:36
false return failure()
Parse an optional keyword or string and set instance into 'result'.
return success()
nlohmann::json json
Get a JSON representation of a type.
Definition RpcClient.cpp:44
FileEmitter(VerilogEmitterState &state)
void emit(emit::FileOp op)
LogicalResult emitHGLDD(Operation *module, llvm::raw_ostream &os, const EmitHGLDDOptions &options={})
Serialize the debug information in the given module into the HGLDD format and writes it to output.
LogicalResult emitSplitHGLDD(Operation *module, const EmitHGLDDOptions &options={})
Serialize the debug information in the given module into the HGLDD format and emit one companion HGLD...
StringRef getVerilogModuleName(Operation *module)
Definition HWOps.h:56
OS & operator<<(OS &os, const InnerSymTarget &target)
Printing InnerSymTarget's.
static bool operator==(const ModulePort &a, const ModulePort &b)
Definition HWTypes.h:64
StringRef legalizeName(llvm::StringRef name, llvm::StringMap< size_t > &nextGeneratedNameIDs, bool caseInsensitiveKeywords)
Legalize the specified name for use in SV output.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
bool operator!=(uint64_t a, const FVInt &b)
Definition FVInt.h:685
Definition debug.py:1
Definition emit.py:1
llvm::hash_code hash_value(const DenseSet< T > &set)
Operation * op
The operation that generated this instance.
Definition DebugInfo.h:43
StringAttr name
The name of this instance.
Definition DebugInfo.h:45
DIModule * module
The instantiated module.
Definition DebugInfo.h:47
bool isInline
If this is an inline scope created by a dbg.scope operation.
Definition DebugInfo.h:38
Operation * op
The operation that generated this level of hierarchy.
Definition DebugInfo.h:28
SmallVector< DIInstance *, 0 > instances
Levels of hierarchy nested under this module.
Definition DebugInfo.h:32
SmallVector< DIVariable *, 0 > variables
Variables declared within this module.
Definition DebugInfo.h:34
bool isExtern
If this is an extern declaration.
Definition DebugInfo.h:36
StringAttr name
The name of this level of hierarchy.
Definition DebugInfo.h:30
Value value
The SSA value representing the value of this variable.
Definition DebugInfo.h:56
StringAttr name
The name of this variable.
Definition DebugInfo.h:52
LocationAttr loc
The location of the variable's declaration.
Definition DebugInfo.h:54
llvm::MapVector< StringAttr, DIModule * > moduleNodes
A mapping from module name to module debug info.
Definition DebugInfo.h:70
Options for HGLDD emission.
Definition DebugInfo.h:29
static unsigned getHashValue(const JValue &x)
static bool isEqual(const JValue &a, const JValue &b)