CIRCT 24.0.0git
Loading...
Searching...
No Matches
FIREmitter.cpp
Go to the documentation of this file.
1//===- FIREmitter.cpp - FIRRTL dialect to .fir emitter --------------------===//
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//
9// This implements a .fir file emitter.
10//
11//===----------------------------------------------------------------------===//
12
19#include "circt/Support/LLVM.h"
21#include "mlir/IR/BuiltinOps.h"
22#include "mlir/Tools/mlir-translate/Translation.h"
23#include "llvm/ADT/APSInt.h"
24#include "llvm/ADT/StringSet.h"
25#include "llvm/ADT/TypeSwitch.h"
26#include "llvm/Support/Debug.h"
27
28#define DEBUG_TYPE "export-firrtl"
29
30using namespace circt;
31using namespace firrtl;
32using namespace chirrtl;
33using namespace pretty;
34
35//===----------------------------------------------------------------------===//
36// Emitter
37//===----------------------------------------------------------------------===//
38
39// NOLINTBEGIN(misc-no-recursion)
40namespace {
41
42constexpr size_t defaultTargetLineLength = 80;
43
44/// An emitter for FIRRTL dialect operations to .fir output.
45struct Emitter {
46 Emitter(llvm::raw_ostream &os, FIRVersion version,
47 size_t targetLineLength = defaultTargetLineLength)
48 : pp(os, targetLineLength), ps(pp, saver), version(version) {
49 pp.setListener(&saver);
50 }
51 LogicalResult finalize();
52
53 // Circuit/module/class emission
54 void emitCircuit(CircuitOp op);
55 void emitModule(FModuleOp op);
56 void emitModule(FExtModuleOp op);
57 void emitModule(FIntModuleOp op);
58 void emitClass(ClassOp op);
59 void emitClass(ExtClassOp op);
60 void emitPortsAndBody(ArrayRef<PortInfo> ports, Block &body);
61 void emitPorts(ArrayRef<PortInfo> ports,
62 Block::BlockArgListType arguments = {});
63 void emitModuleParameters(Operation *op, ArrayAttr parameters);
64 void emitDeclaration(DomainOp op);
65 void emitDeclaration(LayerOp op);
66 void emitDeclaration(OptionOp op);
67 void emitDeclaration(FormalOp op);
68 void emitDeclaration(SimulationOp op);
69 void emitFormalLike(Operation *op, StringRef keyword, StringAttr symName,
70 StringAttr moduleName, DictionaryAttr params);
71 void emitEnabledLayers(ArrayRef<Attribute> layers, Operation *op);
72 void emitKnownLayers(ArrayRef<Attribute> layers, Operation *op);
73 void emitRequirements(ArrayRef<Attribute> requirements);
74 void emitParamAssign(ParamDeclAttr param, Operation *op,
75 std::optional<PPExtString> wordBeforeLHS = std::nullopt);
76 void emitParamValue(Attribute value, Operation *op);
77
78 void emitGenericIntrinsic(GenericIntrinsicOp op);
79
80 // Statement emission
81 void emitStatementsInBlock(Block &block);
82 void emitStatement(WhenOp op);
83 void emitStatement(WireOp op);
84 void emitStatement(RegOp op);
85 void emitStatement(RegResetOp op);
86 void emitStatement(NodeOp op);
87 void emitStatement(StopOp op);
88 void emitStatement(SkipOp op);
89 void emitFormatString(Operation *op, StringRef formatString, OperandRange ops,
90 llvm::SmallVectorImpl<Value> &substitutions);
91 template <class T>
92 void emitPrintfLike(T op, StringAttr fileName);
93 void emitStatement(PrintFOp op);
94 void emitStatement(FPrintFOp op);
95 void emitStatement(FFlushOp op);
96 void emitStatement(ConnectOp op);
97 void emitStatement(MatchingConnectOp op);
98 void emitStatement(PropertyAssertOp op);
99 void emitStatement(PropAssignOp op);
100 void emitStatement(InstanceOp op);
101 void emitStatement(InstanceChoiceOp op);
102 void emitStatement(AttachOp op);
103 void emitStatement(MemOp op);
104 void emitStatement(InvalidValueOp op);
105 void emitStatement(CombMemOp op);
106 void emitStatement(SeqMemOp op);
107 void emitStatement(MemoryPortOp op);
108 void emitStatement(MemoryDebugPortOp op);
109 void emitStatement(MemoryPortAccessOp op);
110 void emitStatement(DomainDefineOp op);
111 void emitStatement(RefDefineOp op);
112 void emitStatement(RefForceOp op);
113 void emitStatement(RefForceInitialOp op);
114 void emitStatement(RefReleaseOp op);
115 void emitStatement(RefReleaseInitialOp op);
116 void emitStatement(LayerBlockOp op);
117 void emitStatement(GenericIntrinsicOp op);
118 void emitStatement(DomainCreateAnonOp op);
119 void emitStatement(DomainCreateOp op);
120
121 template <class T>
122 void emitVerifStatement(T op, StringRef mnemonic);
123 void emitStatement(AssertOp op) { emitVerifStatement(op, "assert"); }
124 void emitStatement(AssumeOp op) { emitVerifStatement(op, "assume"); }
125 void emitStatement(CoverOp op) { emitVerifStatement(op, "cover"); }
126
127 // Exprsesion emission
128 void emitExpression(Value value);
129 void emitExpression(ConstantOp op);
130 void emitExpression(SpecialConstantOp op);
131 void emitExpression(SubfieldOp op);
132 void emitExpression(SubindexOp op);
133 void emitExpression(SubaccessOp op);
134 void emitExpression(OpenSubfieldOp op);
135 void emitExpression(DomainSubfieldOp op);
136 void emitExpression(OpenSubindexOp op);
137 void emitExpression(ObjectAnyRefCastOp op);
138 void emitExpression(DomainAnyRefCastOp op);
139 void emitExpression(RefResolveOp op);
140 void emitExpression(RefSendOp op);
141 void emitExpression(RefSubOp op);
142 void emitExpression(RWProbeOp op);
143 void emitExpression(RefCastOp op);
144 void emitExpression(UninferredResetCastOp op);
145 void emitExpression(ConstCastOp op);
146 void emitExpression(StringConstantOp op);
147 void emitExpression(FIntegerConstantOp op);
148 void emitExpression(BoolConstantOp op);
149 void emitExpression(DoubleConstantOp op);
150 void emitExpression(ListCreateOp op);
151 void emitExpression(OptionCreateOp op);
152 void emitExpression(UnresolvedPathOp op);
153 void emitExpression(GenericIntrinsicOp op);
154 void emitExpression(CatPrimOp op);
155 void emitExpression(UnsafeDomainCastOp op);
156 void emitExpression(UnknownValueOp op);
157
158 void emitPrimExpr(StringRef mnemonic, Operation *op,
159 ArrayRef<uint32_t> attrs = {});
160
161 void emitExpression(BitsPrimOp op) {
162 emitPrimExpr("bits", op, {op.getHi(), op.getLo()});
163 }
164 void emitExpression(HeadPrimOp op) {
165 emitPrimExpr("head", op, op.getAmount());
166 }
167 void emitExpression(TailPrimOp op) {
168 emitPrimExpr("tail", op, op.getAmount());
169 }
170 void emitExpression(PadPrimOp op) { emitPrimExpr("pad", op, op.getAmount()); }
171 void emitExpression(ShlPrimOp op) { emitPrimExpr("shl", op, op.getAmount()); }
172 void emitExpression(ShrPrimOp op) { emitPrimExpr("shr", op, op.getAmount()); }
173
174 void emitExpression(TimeOp op) {}
175
176 // Funnel all ops without attrs into `emitPrimExpr`.
177#define HANDLE(OPTYPE, MNEMONIC) \
178 void emitExpression(OPTYPE op) { emitPrimExpr(MNEMONIC, op); }
179 HANDLE(AddPrimOp, "add");
180 HANDLE(SubPrimOp, "sub");
181 HANDLE(MulPrimOp, "mul");
182 HANDLE(DivPrimOp, "div");
183 HANDLE(RemPrimOp, "rem");
184 HANDLE(AndPrimOp, "and");
185 HANDLE(OrPrimOp, "or");
186 HANDLE(XorPrimOp, "xor");
187 HANDLE(LEQPrimOp, "leq");
188 HANDLE(LTPrimOp, "lt");
189 HANDLE(GEQPrimOp, "geq");
190 HANDLE(GTPrimOp, "gt");
191 HANDLE(EQPrimOp, "eq");
192 HANDLE(NEQPrimOp, "neq");
193 HANDLE(DShlPrimOp, "dshl");
194 HANDLE(DShlwPrimOp, "dshlw");
195 HANDLE(DShrPrimOp, "dshr");
196 HANDLE(MuxPrimOp, "mux");
197 HANDLE(AsSIntPrimOp, "asSInt");
198 HANDLE(AsUIntPrimOp, "asUInt");
199 HANDLE(AsAsyncResetPrimOp, "asAsyncReset");
200 HANDLE(AsResetPrimOp, "asReset");
201 HANDLE(AsClockPrimOp, "asClock");
202 HANDLE(CvtPrimOp, "cvt");
203 HANDLE(NegPrimOp, "neg");
204 HANDLE(NotPrimOp, "not");
205 HANDLE(AndRPrimOp, "andr");
206 HANDLE(OrRPrimOp, "orr");
207 HANDLE(XorRPrimOp, "xorr");
208 HANDLE(StringConcatOp, "string_concat");
209#undef HANDLE
210
211 void emitExpression(PropEqOp op) {
212 if (failed(requireVersion({6, 0, 0}, op, "property equality")))
213 return;
214 if (type_isa<ClassType, AnyRefType>(op.getLhs().getType()) &&
215 failed(requireVersion(nextFIRVersion, op,
216 "property equality with AnyRef or Class types")))
217 return;
218 emitPrimExpr("prop_eq", op);
219 }
220
221 void emitExpression(ListLengthOp op) {
222 if (failed(requireVersion(nextFIRVersion, op, "list length")))
223 return;
224 emitPrimExpr("list_length", op);
225 }
226
227 void emitExpression(OptionGetOrElseOp op) {
228 if (failed(requireVersion(nextFIRVersion, op, "option get or else")))
229 return;
230 emitPrimExpr("option_get_or_else", op);
231 }
232
233 void emitExpression(ListContainsOp op) {
234 if (failed(requireVersion(missingSpecFIRVersion, op, "list contains")))
235 return;
236 emitPrimExpr("list_contains", op);
237 }
238
239 void emitExpression(BoolAndOp op) {
240 if (failed(requireVersion({6, 0, 0}, op, "boolean and")))
241 return;
242 emitPrimExpr("bool_and", op);
243 }
244
245 void emitExpression(BoolOrOp op) {
246 if (failed(requireVersion({6, 0, 0}, op, "boolean or")))
247 return;
248 emitPrimExpr("bool_or", op);
249 }
250
251 void emitExpression(BoolXorOp op) {
252 if (failed(requireVersion({6, 0, 0}, op, "boolean xor")))
253 return;
254 emitPrimExpr("bool_xor", op);
255 }
256
257 void emitExpression(IntegerAndOp op) {
258 if (failed(requireVersion(missingSpecFIRVersion, op, "integer and")))
259 return;
260 emitPrimExpr("integer_and", op);
261 }
262
263 void emitExpression(IntegerOrOp op) {
264 if (failed(requireVersion(missingSpecFIRVersion, op, "integer or")))
265 return;
266 emitPrimExpr("integer_or", op);
267 }
268
269 void emitExpression(IntegerNotOp op) {
270 if (failed(requireVersion(missingSpecFIRVersion, op, "integer not")))
271 return;
272 emitPrimExpr("integer_not", op);
273 }
274
275 // Attributes
276 void emitAttribute(MemDirAttr attr);
277 void emitAttribute(RUWBehaviorAttr attr);
278
279 // Types
280 void emitType(Type type, bool includeConst = true);
281 void emitTypeWithColon(Type type) {
282 ps << PP::space << ":" << PP::nbsp;
283 emitType(type);
284 }
285
286 // Domains
287 void emitDomains(Attribute attr, ArrayRef<PortInfo> ports);
288
289 // Locations
290 void emitLocation(Location loc);
291 void emitLocation(Operation *op) { emitLocation(op->getLoc()); }
292 template <typename... Args>
293 void emitLocationAndNewLine(Args... args) {
294 // Break so previous content is not impacted by following,
295 // but use a 'neverbreak' so it always fits.
296 ps << PP::neverbreak;
297 emitLocation(args...);
298 setPendingNewline();
299 }
300
301 void emitAssignLike(llvm::function_ref<void()> emitLHS,
302 llvm::function_ref<void()> emitRHS,
303 PPExtString syntax = PPExtString("="),
304 std::optional<PPExtString> wordBeforeLHS = std::nullopt) {
305 // If wraps, indent.
306 ps.scopedBox(PP::ibox2, [&]() {
307 if (wordBeforeLHS) {
308 ps << *wordBeforeLHS << PP::space;
309 }
310 emitLHS();
311 // Allow breaking before 'syntax' (e.g., '=') if long assignment.
312 ps << PP::space << syntax << PP::nbsp; /* PP::space; */
313 // RHS is boxed to right of the syntax.
314 ps.scopedBox(PP::ibox0, [&]() { emitRHS(); });
315 });
316 }
317
318 /// Emit the specified value as a subexpression, wrapping in an ibox2.
319 void emitSubExprIBox2(Value v) {
320 ps.scopedBox(PP::ibox2, [&]() { emitExpression(v); });
321 }
322
323 /// Emit a range of values separated by commas and a breakable space.
324 /// Each value is emitted by invoking `eachFn`.
325 template <typename Container, typename EachFn>
326 void interleaveComma(const Container &c, EachFn eachFn) {
327 llvm::interleave(c, eachFn, [&]() { ps << "," << PP::space; });
328 }
329
330 /// Emit a range of values separated by commas and a breakable space.
331 /// Each value is emitted in an ibox2.
332 void interleaveComma(ValueRange ops) {
333 return interleaveComma(ops, [&](Value v) { emitSubExprIBox2(v); });
334 }
335
336 void emitStatementFunctionOp(PPExtString name, Operation *op) {
337 startStatement();
338 ps << name << "(";
339 ps.scopedBox(PP::ibox0, [&]() {
340 interleaveComma(op->getOperands());
341 ps << ")";
342 });
343 emitLocationAndNewLine(op);
344 }
345
346 template <typename EachFn, typename Range>
347 void emitLiteralExpression(Type type, const Range &r, EachFn eachFn) {
348 emitType(type);
349 ps << "(";
350 ps.scopedBox(PP::ibox0, [&]() {
351 interleaveComma(r, eachFn);
352 ps << ")";
353 });
354 }
355
356 void emitLiteralExpression(Type type, ValueRange values) {
357 return emitLiteralExpression(type, values,
358 [&](Value v) { emitSubExprIBox2(v); });
359 }
360
361 /// Emit a (potentially nested) symbol reference as `A.B.C`.
362 void emitSymbol(SymbolRefAttr symbol) {
363 ps.ibox(2, IndentStyle::Block);
364 ps << symbol.getRootReference();
365 for (auto nested : symbol.getNestedReferences()) {
366 ps.zerobreak();
367 ps << ".";
368 ps << nested.getAttr();
369 }
370 ps.end();
371 }
372
373private:
374 /// Emit an error and remark that emission failed.
375 InFlightDiagnostic emitError(Operation *op, const Twine &message) {
376 encounteredError = true;
377 return op->emitError(message);
378 }
379
380 /// Emit an error and remark that emission failed.
381 InFlightDiagnostic emitOpError(Operation *op, const Twine &message) {
382 encounteredError = true;
383 return op->emitOpError(message);
384 }
385
386 /// Return false and emit an error if the target version is below minVersion.
387 LogicalResult requireVersion(FIRVersion minVersion, Operation *op,
388 Twine feature) {
389 if (version >= minVersion)
390 return success();
391
392 return emitOpError(op, feature + " requires FIRRTL ") << minVersion;
393 }
394
395 /// Return the name used during emission of a `Value`, or none if the value
396 /// has not yet been emitted or it was emitted inline.
397 std::optional<StringRef> lookupEmittedName(Value value) {
398 auto it = valueNames.find(value);
399 if (it != valueNames.end())
400 return {it->second};
401 return {};
402 }
403
404 /// If previous emission requires a newline, emit it now.
405 /// This gives us opportunity to open/close boxes before linebreak.
406 void emitPendingNewlineIfNeeded() {
407 if (pendingNewline) {
408 pendingNewline = false;
409 ps << PP::newline;
410 }
411 }
412 void setPendingNewline() {
413 assert(!pendingNewline);
414 pendingNewline = true;
415 }
416
417 void startStatement() { emitPendingNewlineIfNeeded(); }
418
419private:
420 /// String storage backing Tokens built from temporary strings.
421 /// PrettyPrinter will clear this as appropriate.
422 TokenStringSaver saver;
423
424 /// Pretty printer.
425 PrettyPrinter pp;
426
427 /// Stream helper (pp, saver).
428 TokenStream<> ps;
429
430 /// Whether a newline is expected, emitted late to provide opportunity to
431 /// open/close boxes we don't know we need at level of individual statement.
432 /// Every statement should set this instead of directly emitting (last)
433 /// newline. Most statements end with emitLocationInfoAndNewLine which handles
434 /// this.
435 bool pendingNewline = false;
436
437 /// Whether we have encountered any errors during emission.
438 bool encounteredError = false;
439
440 /// The names used to emit values already encountered. Anything that gets a
441 /// name in the output FIR is listed here, such that future expressions can
442 /// reference it.
443 DenseMap<Value, StringRef> valueNames;
444 StringSet<> valueNamesStorage;
445
446 /// Legalize names for emission. Convert names which begin with a number to
447 /// be escaped using backticks.
448 StringAttr legalize(StringAttr attr) {
449 StringRef str = attr.getValue();
450 if (str.empty() || !isdigit(str.front()))
451 return attr;
452 return StringAttr::get(attr.getContext(), "`" + Twine(attr) + "`");
453 }
454
455 void addValueName(Value value, StringAttr attr) {
456 valueNames.insert({value, attr.getValue()});
457 }
458 void addValueName(Value value, StringRef str) {
459 auto it = valueNamesStorage.insert(str);
460 valueNames.insert({value, it.first->getKey()});
461 }
462 void addForceable(Forceable op, StringAttr attr) {
463 addValueName(op.getDataRaw() /* may not be base type */, attr);
464 if (op.isForceable()) {
465 SmallString<32> rwName;
466 (Twine("rwprobe(") + attr.strref() + ")").toVector(rwName);
467 addValueName(op.getDataRef(), rwName);
468 }
469 }
470
471 /// The current circuit namespace valid within the call to `emitCircuit`.
472 CircuitNamespace circuitNamespace;
473
474 /// Symbol and Inner Symbol analyses, valid within the call to `emitCircuit`.
475 struct SymInfos {
476 SymbolTable symbolTable;
477 hw::InnerSymbolTableCollection istc;
478 hw::InnerRefNamespace irn{symbolTable, istc};
479 SymInfos(Operation *op) : symbolTable(op), istc(op) {}
480 };
481 std::optional<std::reference_wrapper<SymInfos>> symInfos;
482
483 /// The version of the FIRRTL spec that should be emitted.
484 FIRVersion version;
485};
486} // namespace
487
488LogicalResult Emitter::finalize() { return failure(encounteredError); }
489
490/// Emit an entire circuit.
491void Emitter::emitCircuit(CircuitOp op) {
492 circuitNamespace.add(op);
493 SymInfos circuitSymInfos(op);
494 symInfos = circuitSymInfos;
495 startStatement();
496 ps << "FIRRTL version ";
497 ps.addAsString(version.major);
498 ps << ".";
499 ps.addAsString(version.minor);
500 ps << ".";
501 ps.addAsString(version.patch);
502 ps << PP::newline;
503 ps << "circuit " << PPExtString(legalize(op.getNameAttr())) << " :";
504 setPendingNewline();
505 ps.scopedBox(PP::bbox2, [&]() {
506 for (auto &bodyOp : *op.getBodyBlock()) {
507 if (encounteredError)
508 break;
509 TypeSwitch<Operation *>(&bodyOp)
510 .Case<FModuleOp, FExtModuleOp, FIntModuleOp>([&](auto op) {
511 emitModule(op);
512 ps << PP::newline;
513 })
514 .Case<ClassOp, ExtClassOp>([&](auto op) {
515 emitClass(op);
516 ps << PP::newline;
517 })
518 .Case<DomainOp, LayerOp, OptionOp, FormalOp, SimulationOp>(
519 [&](auto op) { emitDeclaration(op); })
520 .Default([&](auto op) {
521 emitOpError(op, "not supported for emission inside circuit");
522 });
523 }
524 });
525 circuitNamespace.clear();
526 symInfos = std::nullopt;
527}
528
529void Emitter::emitEnabledLayers(ArrayRef<Attribute> layers, Operation *op) {
530 if (layers.empty())
531 return;
532 if (failed(requireVersion(FIRVersion(4, 0, 0), op, "enabled layers")))
533 return;
534 for (auto layer : layers) {
535 ps << PP::space;
536 ps.cbox(2, IndentStyle::Block);
537 ps << "enablelayer" << PP::space;
538 emitSymbol(cast<SymbolRefAttr>(layer));
539 ps << PP::end;
540 }
541}
542
543void Emitter::emitKnownLayers(ArrayRef<Attribute> layers, Operation *op) {
544 if (layers.empty())
545 return;
546 if (failed(requireVersion({6, 0, 0}, op, "known layers")))
547 return;
548 for (auto layer : layers) {
549 ps << PP::space;
550 ps.cbox(2, IndentStyle::Block);
551 ps << "knownlayer" << PP::space;
552 emitSymbol(cast<SymbolRefAttr>(layer));
553 ps << PP::end;
554 }
555}
556
557void Emitter::emitRequirements(ArrayRef<Attribute> requirements) {
558 if (requirements.empty())
559 return;
560 ps << PP::space;
561 ps.cbox(2, IndentStyle::Block);
562 ps << "requires" << PP::space;
563 llvm::interleaveComma(requirements, ps, [&](Attribute req) {
564 ps.writeQuotedEscaped(cast<StringAttr>(req).getValue());
565 });
566 ps << PP::end;
567}
568
569void Emitter::emitParamAssign(ParamDeclAttr param, Operation *op,
570 std::optional<PPExtString> wordBeforeLHS) {
571 if (wordBeforeLHS) {
572 ps << *wordBeforeLHS << PP::nbsp;
573 }
574 ps << PPExtString(param.getName().strref()) << PP::nbsp << "=" << PP::nbsp;
575 emitParamValue(param.getValue(), op);
576}
577
578void Emitter::emitParamValue(Attribute value, Operation *op) {
579 TypeSwitch<Attribute>(value)
580 .Case<IntegerAttr>([&](auto attr) { ps.addAsString(attr.getValue()); })
581 .Case<FloatAttr>([&](auto attr) {
582 SmallString<16> str;
583 attr.getValue().toString(str);
584 ps << str;
585 })
586 .Case<StringAttr>(
587 [&](auto attr) { ps.writeQuotedEscaped(attr.getValue()); })
588 .Case<ArrayAttr>([&](auto attr) {
589 ps.scopedBox(PP::bbox2, [&]() {
590 ps << "[";
591 interleaveComma(attr.getValue(),
592 [&](auto element) { emitParamValue(element, op); });
593 ps << "]";
594 });
595 })
596 .Case<DictionaryAttr>([&](auto attr) {
597 ps.scopedBox(PP::bbox2, [&]() {
598 ps << "{";
599 interleaveComma(attr.getValue(), [&](auto field) {
600 ps << PPExtString(field.getName()) << PP::nbsp << "=" << PP::nbsp;
601 emitParamValue(field.getValue(), op);
602 });
603 ps << "}";
604 });
605 })
606 .Default([&](auto attr) {
607 emitOpError(op, "with unsupported parameter attribute: ") << attr;
608 ps << "<unsupported-attr ";
609 ps.addAsString(attr);
610 ps << ">";
611 });
612}
613
614void Emitter::emitGenericIntrinsic(GenericIntrinsicOp op) {
615 ps << "intrinsic(";
616 ps.scopedBox(PP::cbox0, [&]() {
617 ps.scopedBox(PP::ibox2, [&]() {
618 ps << op.getIntrinsic();
619 ps.scopedBox(PP::ibox0, [&]() {
620 auto params = op.getParameters();
621 if (!params.empty()) {
622 ps << "<";
623 ps.scopedBox(PP::ibox0, [&]() {
624 interleaveComma(
625 params.getAsRange<ParamDeclAttr>(),
626 [&](ParamDeclAttr param) { emitParamAssign(param, op); });
627 });
628 ps << ">";
629 }
630 });
631 if (op.getNumResults() != 0)
632 emitTypeWithColon(op.getResult().getType());
633 });
634 if (op.getNumOperands() != 0) {
635 ps << "," << PP::space;
636 ps.scopedBox(PP::ibox0, [&]() { interleaveComma(op->getOperands()); });
637 }
638 ps << ")";
639 });
640}
641
642/// Emit an entire module.
643void Emitter::emitModule(FModuleOp op) {
644 startStatement();
645 ps.cbox(4, IndentStyle::Block);
646 if (op.isPublic() && FIRVersion(3, 3, 0) <= version)
647 ps << "public" << PP::nbsp;
648 ps << "module " << PPExtString(legalize(op.getNameAttr()));
649 emitEnabledLayers(op.getLayers(), op);
650 ps << PP::nbsp << ":" << PP::end;
651 emitLocation(op);
652
653 emitPortsAndBody(op.getPorts(), *op.getBodyBlock());
654}
655
656/// Emit an external module.
657void Emitter::emitModule(FExtModuleOp op) {
658 startStatement();
659 ps.cbox(4, IndentStyle::Block);
660 ps << "extmodule " << PPExtString(legalize(op.getNameAttr()));
661 emitKnownLayers(op.getKnownLayers(), op);
662 emitEnabledLayers(op.getLayers(), op);
663 if (auto reqs = op.getExternalRequirements())
664 emitRequirements(reqs.getValue());
665 ps << PP::nbsp << ":" << PP::end;
666 emitLocation(op);
667
668 ps.scopedBox(PP::bbox2, [&]() {
669 setPendingNewline();
670
671 // Emit the ports.
672 auto ports = op.getPorts();
673 emitPorts(ports);
674
675 // Emit the optional `defname`.
676 if (op.getDefname() && !op.getDefname()->empty()) {
677 startStatement();
678 ps << "defname = " << PPExtString(*op.getDefname());
679 setPendingNewline();
680 }
681
682 // Emit the parameters.
683 emitModuleParameters(op, op.getParameters());
684 });
685}
686
687/// Emit an intrinsic module
688void Emitter::emitModule(FIntModuleOp op) {
689 if (FIRVersion(4, 0, 0) <= version) {
690 emitOpError(op, "intrinsic modules were removed in FIRRTL 4.0.0");
691 return;
692 }
693 startStatement();
694 ps.cbox(4, IndentStyle::Block);
695 ps << "intmodule " << PPExtString(legalize(op.getNameAttr()));
696 emitEnabledLayers(op.getLayers(), op);
697 ps << PP::nbsp << ":" << PP::end;
698 emitLocation(op);
699
700 ps.scopedBox(PP::bbox2, [&]() {
701 setPendingNewline();
702
703 // Emit the ports.
704 auto ports = op.getPorts();
705 emitPorts(ports);
706
707 startStatement();
708 ps << "intrinsic = " << PPExtString(op.getIntrinsic());
709 setPendingNewline();
710
711 // Emit the parameters.
712 emitModuleParameters(op, op.getParameters());
713 });
714}
715
716/// Emit a class.
717void Emitter::emitClass(ClassOp op) {
718 if (failed(requireVersion({6, 0, 0}, op, "classes")))
719 return;
720 startStatement();
721 ps << "class " << PPExtString(legalize(op.getNameAttr())) << " :";
722 emitLocation(op);
723 emitPortsAndBody(op.getPorts(), *op.getBodyBlock());
724}
725
726/// Emit an external class.
727void Emitter::emitClass(ExtClassOp op) {
728 if (failed(requireVersion({6, 0, 0}, op, "external classes")))
729 return;
730 startStatement();
731 ps << "extclass " << PPExtString(legalize(op.getNameAttr())) << " :";
732 emitLocation(op);
733 ps.scopedBox(PP::bbox2, [&]() {
734 setPendingNewline();
735 emitPorts(op.getPorts());
736 });
737}
738
739/// Emit the ports and body of a module or class, then clear its value names.
740void Emitter::emitPortsAndBody(ArrayRef<PortInfo> ports, Block &body) {
741 ps.scopedBox(PP::bbox2, [&]() {
742 setPendingNewline();
743 emitPorts(ports, body.getArguments());
744 if (!ports.empty() && !body.empty())
745 ps << PP::newline;
746 emitStatementsInBlock(body);
747 });
748 valueNames.clear();
749 valueNamesStorage.clear();
750}
751
752/// Emit the ports of a module or class. If the `arguments` array is non-empty,
753/// it is used to populate `valueNames` with the port names for use during
754/// expression emission.
755void Emitter::emitPorts(ArrayRef<PortInfo> ports,
756 Block::BlockArgListType arguments) {
757 // Emit the ports.
758 for (unsigned i = 0, e = ports.size(); i < e; ++i) {
759 startStatement();
760 const auto &port = ports[i];
761 ps << (port.direction == Direction::In ? "input " : "output ");
762 auto legalName = legalize(port.name);
763 if (!arguments.empty())
764 addValueName(arguments[i], legalName);
765 ps << PPExtString(legalName) << " : ";
766 emitType(port.type);
767 emitDomains(port.domains, ports);
768 emitLocation(ports[i].loc);
769 setPendingNewline();
770 }
771}
772
773void Emitter::emitModuleParameters(Operation *op, ArrayAttr parameters) {
774 for (auto param : parameters.getAsRange<ParamDeclAttr>()) {
775 startStatement();
776 emitParamAssign(param, op, PPExtString("parameter"));
777 setPendingNewline();
778 }
779}
780
781void Emitter::emitDeclaration(DomainOp op) {
782 if (failed(requireVersion(missingSpecFIRVersion, op, "domains")))
783 return;
784 startStatement();
785 ps << "domain " << PPExtString(op.getSymName()) << " :";
786 emitLocationAndNewLine(op);
787 ps.scopedBox(PP::bbox2, [&]() {
788 for (auto attr : op.getFields()) {
789 auto fieldAttr = cast<DomainFieldAttr>(attr);
790 ps << PP::newline << PPExtString(fieldAttr.getName()) << " : ";
791 emitType(fieldAttr.getType());
792 }
793 });
794}
795
796/// Emit a layer definition.
797void Emitter::emitDeclaration(LayerOp op) {
798 if (failed(requireVersion(FIRVersion(3, 3, 0), op, "layers")))
799 return;
800 if (op.getConvention() == LayerConvention::Inline &&
801 failed(requireVersion(FIRVersion(4, 1, 0), op, "inline layers")))
802 return;
803 startStatement();
804 ps << "layer " << PPExtString(op.getSymName()) << ", "
805 << PPExtString(stringifyLayerConvention(op.getConvention()));
806
807 if (auto outputFile = op->getAttrOfType<hw::OutputFileAttr>("output_file")) {
808 ps << ", ";
809 ps.writeQuotedEscaped(outputFile.getFilename().getValue());
810 }
811
812 ps << " : ";
813 emitLocationAndNewLine(op);
814 ps.scopedBox(PP::bbox2, [&]() {
815 for (auto &bodyOp : op.getBody().getOps()) {
816 TypeSwitch<Operation *>(&bodyOp)
817 .Case<LayerOp>([&](auto op) { emitDeclaration(op); })
818 .Default([&](auto op) {
819 emitOpError(op,
820 "not supported for emission inside layer definition");
821 });
822 }
823 });
824}
825
826/// Emit an option declaration.
827void Emitter::emitDeclaration(OptionOp op) {
828 if (failed(requireVersion(missingSpecFIRVersion, op, "option groups")))
829 return;
830 startStatement();
831 ps << "option " << PPExtString(legalize(op.getSymNameAttr())) << " :";
832 emitLocation(op);
833 ps.scopedBox(PP::bbox2, [&] {
834 for (auto caseOp : op.getBody().getOps<OptionCaseOp>()) {
835 ps << PP::newline;
836 ps << PPExtString(legalize(caseOp.getSymNameAttr()));
837 emitLocation(caseOp);
838 }
839 });
840 ps << PP::newline << PP::newline;
841}
842
843/// Emit a formal test definition.
844void Emitter::emitDeclaration(FormalOp op) {
845 if (failed(requireVersion(FIRVersion(4, 0, 0), op, "formal tests")))
846 return;
847 emitFormalLike(op, "formal", op.getSymNameAttr(),
848 op.getModuleNameAttr().getAttr(), op.getParameters());
849}
850
851/// Emit a simulation test definition.
852void Emitter::emitDeclaration(SimulationOp op) {
853 if (failed(requireVersion(nextFIRVersion, op, "simulation tests")))
854 return;
855 emitFormalLike(op, "simulation", op.getSymNameAttr(),
856 op.getModuleNameAttr().getAttr(), op.getParameters());
857}
858
859/// Emit a formal or simulation test definition.
860void Emitter::emitFormalLike(Operation *op, StringRef keyword,
861 StringAttr symName, StringAttr moduleName,
862 DictionaryAttr params) {
863 startStatement();
864 ps.cbox(4, IndentStyle::Block);
865 ps << keyword << " " << PPExtString(legalize(symName));
866 ps << " of " << PPExtString(legalize(moduleName));
867 ps << PP::nbsp << ":" << PP::end;
868 emitLocation(op);
869
870 ps.scopedBox(PP::bbox2, [&]() {
871 setPendingNewline();
872 for (auto param : params) {
873 startStatement();
874 ps << PPExtString(param.getName()) << PP::nbsp << "=" << PP::nbsp;
875 emitParamValue(param.getValue(), op);
876 setPendingNewline();
877 }
878 });
879}
880
881/// Check if an operation is inlined into the emission of their users. For
882/// example, subfields are always inlined.
883static bool isEmittedInline(Operation *op) {
884 // FIRRTL expressions are statically classified as always inlineable.
885 // InvalidValueOp never is inlined, and is handled specially.
886 // GenericIntrinsicOp is inlined if has exactly one use (only emit once)
887 // that is not emitted inline. This is to ensure it is emitted inline
888 // in common cases, but only inspect one level deep.
889 return (isExpression(op) && !isa<InvalidValueOp>(op)) ||
890 (isa<GenericIntrinsicOp>(op) && op->hasOneUse() &&
891 !isEmittedInline(*op->getUsers().begin()));
892}
893
894void Emitter::emitStatementsInBlock(Block &block) {
895 for (auto &bodyOp : block) {
896 if (encounteredError)
897 return;
898 if (isEmittedInline(&bodyOp))
899 continue;
900 TypeSwitch<Operation *>(&bodyOp)
901 .Case<WhenOp, WireOp, RegOp, RegResetOp, NodeOp, StopOp, SkipOp,
902 PrintFOp, FPrintFOp, FFlushOp, AssertOp, AssumeOp, CoverOp,
903 ConnectOp, MatchingConnectOp, PropertyAssertOp, PropAssignOp,
904 InstanceOp, InstanceChoiceOp, AttachOp, MemOp, InvalidValueOp,
905 SeqMemOp, CombMemOp, MemoryPortOp, MemoryDebugPortOp,
906 MemoryPortAccessOp, DomainDefineOp, RefDefineOp, RefForceOp,
907 RefForceInitialOp, RefReleaseOp, RefReleaseInitialOp,
908 LayerBlockOp, GenericIntrinsicOp, DomainCreateAnonOp,
909 DomainCreateOp>([&](auto op) { emitStatement(op); })
910 .Default([&](auto op) {
911 startStatement();
912 ps << "// operation " << PPExtString(op->getName().getStringRef());
913 setPendingNewline();
914 emitOpError(op, "not supported as statement");
915 });
916 }
917}
918
919void Emitter::emitStatement(WhenOp op) {
920 startStatement();
921 ps << "when ";
922 emitExpression(op.getCondition());
923 ps << " :";
924 emitLocationAndNewLine(op);
925 ps.scopedBox(PP::bbox2, [&]() { emitStatementsInBlock(op.getThenBlock()); });
926 // emitStatementsInBlock(op.getThenBlock());
927 if (!op.hasElseRegion())
928 return;
929
930 startStatement();
931 ps << "else ";
932 // Sugar to `else when ...` if there's only a single when statement in the
933 // else block.
934 auto &elseBlock = op.getElseBlock();
935 if (!elseBlock.empty() && &elseBlock.front() == &elseBlock.back()) {
936 if (auto whenOp = dyn_cast<WhenOp>(&elseBlock.front())) {
937 emitStatement(whenOp);
938 return;
939 }
940 }
941 // Otherwise print the block as `else :`.
942 ps << ":";
943 setPendingNewline();
944 ps.scopedBox(PP::bbox2, [&]() { emitStatementsInBlock(elseBlock); });
945}
946
947void Emitter::emitStatement(WireOp op) {
948 auto legalName = legalize(op.getNameAttr());
949 addForceable(op, legalName);
950 startStatement();
951 ps.scopedBox(PP::ibox2, [&]() {
952 ps << "wire " << PPExtString(legalName);
953 emitTypeWithColon(op.getResult().getType());
954
955 // Emit domain associations if present
956 if (!op.getDomains().empty()) {
957 ps << PP::space << "domains" << PP::space << "[";
958 ps.scopedBox(PP::cbox0, [&]() {
959 llvm::interleaveComma(op.getDomains(), ps, [&](Value domain) {
960 auto name = lookupEmittedName(domain);
961 assert(name && "domain value must have a name");
962 ps << PPExtString(*name);
963 });
964 });
965 ps << "]";
966 }
967 });
968 emitLocationAndNewLine(op);
969}
970
971void Emitter::emitStatement(RegOp op) {
972 auto legalName = legalize(op.getNameAttr());
973 addForceable(op, legalName);
974 startStatement();
975 ps.scopedBox(PP::ibox2, [&]() {
976 ps << "reg " << PPExtString(legalName);
977 emitTypeWithColon(op.getResult().getType());
978 ps << "," << PP::space;
979 emitExpression(op.getClockVal());
980 });
981 emitLocationAndNewLine(op);
982}
983
984void Emitter::emitStatement(RegResetOp op) {
985 auto legalName = legalize(op.getNameAttr());
986 addForceable(op, legalName);
987 startStatement();
988 if (FIRVersion(3, 0, 0) <= version) {
989 ps.scopedBox(PP::ibox2, [&]() {
990 ps << "regreset " << legalName;
991 emitTypeWithColon(op.getResult().getType());
992 ps << "," << PP::space;
993 emitExpression(op.getClockVal());
994 ps << "," << PP::space;
995 emitExpression(op.getResetSignal());
996 ps << "," << PP::space;
997 emitExpression(op.getResetValue());
998 });
999 } else {
1000 ps.scopedBox(PP::ibox2, [&]() {
1001 ps << "reg " << legalName;
1002 emitTypeWithColon(op.getResult().getType());
1003 ps << "," << PP::space;
1004 emitExpression(op.getClockVal());
1005 ps << PP::space << "with :";
1006 // Don't break this because of the newline.
1007 ps << PP::neverbreak;
1008 // No-paren version must be newline + indent.
1009 ps << PP::newline; // ibox2 will indent.
1010 ps << "reset => (" << PP::ibox0;
1011 emitExpression(op.getResetSignal());
1012 ps << "," << PP::space;
1013 emitExpression(op.getResetValue());
1014 ps << ")" << PP::end;
1015 });
1016 }
1017 emitLocationAndNewLine(op);
1018}
1019
1020void Emitter::emitStatement(NodeOp op) {
1021 auto legalName = legalize(op.getNameAttr());
1022 addForceable(op, legalName);
1023 startStatement();
1024 emitAssignLike([&]() { ps << "node " << PPExtString(legalName); },
1025 [&]() { emitExpression(op.getInput()); });
1026 emitLocationAndNewLine(op);
1027}
1028
1029void Emitter::emitStatement(StopOp op) {
1030 startStatement();
1031 ps.scopedBox(PP::ibox2, [&]() {
1032 ps << "stop(" << PP::ibox0;
1033 emitExpression(op.getClock());
1034 ps << "," << PP::space;
1035 emitExpression(op.getCond());
1036 ps << "," << PP::space;
1037 ps.addAsString(op.getExitCode());
1038 ps << ")" << PP::end;
1039 if (!op.getName().empty()) {
1040 ps << PP::space << ": " << PPExtString(legalize(op.getNameAttr()));
1041 }
1042 });
1043 emitLocationAndNewLine(op);
1044}
1045
1046void Emitter::emitStatement(SkipOp op) {
1047 startStatement();
1048 ps << "skip";
1049 emitLocationAndNewLine(op);
1050}
1051
1052void Emitter::emitFormatString(Operation *op, StringRef origFormatString,
1053 OperandRange substitutionOperands,
1054 llvm::SmallVectorImpl<Value> &substitutions) {
1055 // Replace the generic "{{}}" special substitutions with their attributes.
1056 // E.g.:
1057 //
1058 // "hello {{}} world"(%time)
1059 //
1060 // Becomes:
1061 //
1062 // "hello {{SimulationTime}} world"
1063 SmallString<64> formatString;
1064 for (size_t i = 0, e = origFormatString.size(), opIdx = 0; i != e; ++i) {
1065 auto c = origFormatString[i];
1066 switch (c) {
1067 case '%': {
1068 formatString.push_back(c);
1069
1070 // Parse the width specifier.
1071 SmallString<6> width;
1072 c = origFormatString[++i];
1073 while (isdigit(c)) {
1074 width.push_back(c);
1075 c = origFormatString[++i];
1076 }
1077
1078 // Parse the radix.
1079 switch (c) {
1080 case 'b':
1081 case 'd':
1082 case 'x':
1083 if (!width.empty())
1084 formatString.append(width);
1085 [[fallthrough]];
1086 case 'c':
1087 substitutions.push_back(substitutionOperands[opIdx++]);
1088 [[fallthrough]];
1089 default:
1090 formatString.push_back(c);
1091 }
1092 break;
1093 }
1094 case '{':
1095 if (origFormatString.slice(i, i + 4) == "{{}}") {
1096 formatString.append("{{");
1097 TypeSwitch<Operation *>(substitutionOperands[opIdx++].getDefiningOp())
1098 .Case<TimeOp>(
1099 [&](auto time) { formatString.append("SimulationTime"); })
1100 .Case<HierarchicalModuleNameOp>([&](auto time) {
1101 formatString.append("HierarchicalModuleName");
1102 })
1103 .Default([&](auto) {
1104 emitError(op, "unsupported fstring substitution type");
1105 });
1106 formatString.append("}}");
1107 }
1108 i += 3;
1109 break;
1110 default:
1111 formatString.push_back(c);
1112 }
1113 }
1114 ps.writeQuotedEscaped(formatString);
1115}
1116
1117void Emitter::emitStatement(PrintFOp op) {
1118 startStatement();
1119 ps.scopedBox(PP::ibox2, [&]() {
1120 ps << "printf(" << PP::ibox0;
1121 emitExpression(op.getClock());
1122 ps << "," << PP::space;
1123 emitExpression(op.getCond());
1124 ps << "," << PP::space;
1125
1126 SmallVector<Value, 4> substitutions;
1127 emitFormatString(op, op.getFormatString(), op.getSubstitutions(),
1128 substitutions);
1129 for (auto operand : substitutions) {
1130 ps << "," << PP::space;
1131 emitExpression(operand);
1132 }
1133 ps << ")" << PP::end;
1134 if (!op.getName().empty()) {
1135 ps << PP::space << ": " << PPExtString(legalize(op.getNameAttr()));
1136 }
1137 });
1138 emitLocationAndNewLine(op);
1139}
1140
1141void Emitter::emitStatement(FPrintFOp op) {
1142 if (failed(requireVersion({6, 0, 0}, op, "fprintf")))
1143 return;
1144 startStatement();
1145 ps.scopedBox(PP::ibox2, [&]() {
1146 ps << "fprintf(" << PP::ibox0;
1147 emitExpression(op.getClock());
1148 ps << "," << PP::space;
1149 emitExpression(op.getCond());
1150 ps << "," << PP::space;
1151
1152 SmallVector<Value, 4> outputFileSubstitutions;
1153 emitFormatString(op, op.getOutputFile(), op.getOutputFileSubstitutions(),
1154 outputFileSubstitutions);
1155 if (!outputFileSubstitutions.empty()) {
1156 ps << "," << PP::space;
1157 interleaveComma(outputFileSubstitutions);
1158 }
1159
1160 ps << "," << PP::space;
1161 SmallVector<Value, 4> substitutions;
1162 emitFormatString(op, op.getFormatString(), op.getSubstitutions(),
1163 substitutions);
1164 if (!substitutions.empty()) {
1165 ps << "," << PP::space;
1166 interleaveComma(substitutions);
1167 }
1168
1169 ps << ")" << PP::end;
1170 if (!op.getName().empty()) {
1171 ps << PP::space << ": " << PPExtString(legalize(op.getNameAttr()));
1172 }
1173 });
1174 emitLocationAndNewLine(op);
1175}
1176
1177void Emitter::emitStatement(FFlushOp op) {
1178 if (failed(requireVersion({6, 0, 0}, op, "fflush")))
1179 return;
1180 startStatement();
1181 ps.scopedBox(PP::ibox2, [&]() {
1182 ps << "fflush(" << PP::ibox0;
1183 emitExpression(op.getClock());
1184 ps << "," << PP::space;
1185 emitExpression(op.getCond());
1186 if (op.getOutputFileAttr()) {
1187 ps << "," << PP::space;
1188 SmallVector<Value, 4> substitutions;
1189 emitFormatString(op, op.getOutputFileAttr(),
1190 op.getOutputFileSubstitutions(), substitutions);
1191 if (!substitutions.empty()) {
1192 ps << "," << PP::space;
1193 interleaveComma(substitutions);
1194 }
1195 }
1196 ps << ")" << PP::end;
1197 });
1198 emitLocationAndNewLine(op);
1199}
1200
1201template <class T>
1202void Emitter::emitVerifStatement(T op, StringRef mnemonic) {
1203 startStatement();
1204 ps.scopedBox(PP::ibox2, [&]() {
1205 ps << mnemonic << "(" << PP::ibox0;
1206 emitExpression(op.getClock());
1207 ps << "," << PP::space;
1208 emitExpression(op.getPredicate());
1209 ps << "," << PP::space;
1210 emitExpression(op.getEnable());
1211 ps << "," << PP::space;
1212 ps.writeQuotedEscaped(op.getMessage());
1213 ps << ")" << PP::end;
1214 if (!op.getName().empty()) {
1215 ps << PP::space << ": " << PPExtString(legalize(op.getNameAttr()));
1216 }
1217 });
1218 emitLocationAndNewLine(op);
1219}
1220
1221void Emitter::emitStatement(ConnectOp op) {
1222 startStatement();
1223 if (FIRVersion(3, 0, 0) <= version) {
1224 ps.scopedBox(PP::ibox2, [&]() {
1225 if (op.getSrc().getDefiningOp<InvalidValueOp>()) {
1226 ps << "invalidate" << PP::space;
1227 emitExpression(op.getDest());
1228 } else {
1229 ps << "connect" << PP::space;
1230 emitExpression(op.getDest());
1231 ps << "," << PP::space;
1232 emitExpression(op.getSrc());
1233 }
1234 });
1235 } else {
1236 auto emitLHS = [&]() { emitExpression(op.getDest()); };
1237 if (op.getSrc().getDefiningOp<InvalidValueOp>()) {
1238 emitAssignLike(
1239 emitLHS, [&]() { ps << "invalid"; }, PPExtString("is"));
1240 } else {
1241 emitAssignLike(
1242 emitLHS, [&]() { emitExpression(op.getSrc()); }, PPExtString("<="));
1243 }
1244 }
1245 emitLocationAndNewLine(op);
1246}
1247
1248void Emitter::emitStatement(MatchingConnectOp op) {
1249 startStatement();
1250 if (FIRVersion(3, 0, 0) <= version) {
1251 ps.scopedBox(PP::ibox2, [&]() {
1252 if (op.getSrc().getDefiningOp<InvalidValueOp>()) {
1253 ps << "invalidate" << PP::space;
1254 emitExpression(op.getDest());
1255 } else {
1256 ps << "connect" << PP::space;
1257 emitExpression(op.getDest());
1258 ps << "," << PP::space;
1259 emitExpression(op.getSrc());
1260 }
1261 });
1262 } else {
1263 auto emitLHS = [&]() { emitExpression(op.getDest()); };
1264 if (op.getSrc().getDefiningOp<InvalidValueOp>()) {
1265 emitAssignLike(
1266 emitLHS, [&]() { ps << "invalid"; }, PPExtString("is"));
1267 } else {
1268 emitAssignLike(
1269 emitLHS, [&]() { emitExpression(op.getSrc()); }, PPExtString("<="));
1270 }
1271 }
1272 emitLocationAndNewLine(op);
1273}
1274
1275void Emitter::emitStatement(PropertyAssertOp op) {
1276 if (failed(requireVersion(FIRVersion(6, 0, 0), op, "property assert")))
1277 return;
1278 startStatement();
1279 ps.scopedBox(PP::ibox2, [&]() {
1280 ps << "propassert" << PP::space;
1281 emitExpression(op.getCondition());
1282 ps << "," << PP::space;
1283 // For FIRRTL < 7.0.0, do a best effort emission that will inline a single
1284 // string expression. If we see anything more complicated than this, just
1285 // bail.
1286 if (version < FIRVersion(7, 0, 0)) {
1287 auto expr = dyn_cast<StringConstantOp>(op.getMessage().getDefiningOp());
1288 if (!expr) {
1289 auto diag =
1290 emitOpError(op, "unable to emit non-literal string expressions "
1291 "when targeting FIRRTL version <= 7.0.0");
1292 diag.attachNote(op.getMessage().getLoc())
1293 << "non-literal expression is here";
1294 }
1295 } else {
1296 emitExpression(op.getMessage());
1297 }
1298 });
1299 emitLocationAndNewLine(op);
1300}
1301
1302void Emitter::emitStatement(PropAssignOp op) {
1303 if (failed(requireVersion(FIRVersion(3, 1, 0), op, "properties")))
1304 return;
1305 startStatement();
1306 ps.scopedBox(PP::ibox2, [&]() {
1307 ps << "propassign" << PP::space;
1308 interleaveComma(op.getOperands());
1309 });
1310 emitLocationAndNewLine(op);
1311}
1312
1313void Emitter::emitStatement(InstanceOp op) {
1314 startStatement();
1315 auto legalName = legalize(op.getNameAttr());
1316 ps << "inst " << PPExtString(legalName) << " of "
1317 << PPExtString(legalize(op.getModuleNameAttr().getAttr()));
1318 emitLocationAndNewLine(op);
1319
1320 // Make sure we have a name like `<inst>.<port>` for each of the instance
1321 // result values.
1322 SmallString<16> portName(legalName);
1323 portName.push_back('.');
1324 unsigned baseLen = portName.size();
1325 for (unsigned i = 0, e = op.getNumResults(); i < e; ++i) {
1326 portName.append(legalize(op.getPortNameAttr(i)));
1327 addValueName(op.getResult(i), portName);
1328 portName.resize(baseLen);
1329 }
1330}
1331
1332void Emitter::emitStatement(InstanceChoiceOp op) {
1333 if (failed(requireVersion(missingSpecFIRVersion, op,
1334 "option groups/instance choices")))
1335 return;
1336 startStatement();
1337 auto legalName = legalize(op.getNameAttr());
1338 ps << "instchoice " << PPExtString(legalName) << " of "
1339 << PPExtString(legalize(op.getDefaultTargetAttr().getAttr())) << ", "
1340 << PPExtString(legalize(op.getOptionNameAttr())) << " :";
1341 emitLocation(op);
1342 ps.scopedBox(PP::bbox2, [&] {
1343 for (const auto &[optSym, targetSym] : op.getTargetChoices()) {
1344 ps << PP::newline;
1345 ps << PPExtString(legalize(optSym.getLeafReference()));
1346 ps << " => ";
1347 ps << PPExtString(legalize(targetSym.getAttr()));
1348 }
1349 });
1350 setPendingNewline();
1351
1352 SmallString<16> portName(legalName);
1353 portName.push_back('.');
1354 unsigned baseLen = portName.size();
1355 for (unsigned i = 0, e = op.getNumResults(); i < e; ++i) {
1356 portName.append(legalize(op.getPortNameAttr(i)));
1357 addValueName(op.getResult(i), portName);
1358 portName.resize(baseLen);
1359 }
1360}
1361
1362void Emitter::emitStatement(AttachOp op) {
1363 emitStatementFunctionOp(PPExtString("attach"), op);
1364}
1365
1366void Emitter::emitStatement(MemOp op) {
1367 auto legalName = legalize(op.getNameAttr());
1368 SmallString<16> portName(legalName);
1369 portName.push_back('.');
1370 auto portNameBaseLen = portName.size();
1371 for (auto result : llvm::zip(op.getResults(), op.getPortNames())) {
1372 portName.resize(portNameBaseLen);
1373 portName.append(legalize(cast<StringAttr>(std::get<1>(result))));
1374 addValueName(std::get<0>(result), portName);
1375 }
1376
1377 startStatement();
1378 ps << "mem " << PPExtString(legalName) << " :";
1379 emitLocationAndNewLine(op);
1380 ps.scopedBox(PP::bbox2, [&]() {
1381 startStatement();
1382 ps << "data-type => ";
1383 emitType(op.getDataType());
1384 ps << PP::newline;
1385 ps << "depth => ";
1386 ps.addAsString(op.getDepth());
1387 ps << PP::newline;
1388 ps << "read-latency => ";
1389 ps.addAsString(op.getReadLatency());
1390 ps << PP::newline;
1391 ps << "write-latency => ";
1392 ps.addAsString(op.getWriteLatency());
1393 ps << PP::newline;
1394
1395 SmallString<16> reader, writer, readwriter;
1396 for (std::pair<StringAttr, MemOp::PortKind> port : op.getPorts()) {
1397 auto add = [&](SmallString<16> &to, StringAttr name) {
1398 if (!to.empty())
1399 to.push_back(' ');
1400 to.append(name.getValue());
1401 };
1402 switch (port.second) {
1403 case MemOp::PortKind::Read:
1404 add(reader, legalize(port.first));
1405 break;
1406 case MemOp::PortKind::Write:
1407 add(writer, legalize(port.first));
1408 break;
1409 case MemOp::PortKind::ReadWrite:
1410 add(readwriter, legalize(port.first));
1411 break;
1412 case MemOp::PortKind::Debug:
1413 emitOpError(op, "has unsupported 'debug' port");
1414 return;
1415 }
1416 }
1417 if (!reader.empty())
1418 ps << "reader => " << reader << PP::newline;
1419 if (!writer.empty())
1420 ps << "writer => " << writer << PP::newline;
1421 if (!readwriter.empty())
1422 ps << "readwriter => " << readwriter << PP::newline;
1423
1424 ps << "read-under-write => ";
1425 emitAttribute(op.getRuwAttr());
1426 setPendingNewline();
1427 });
1428}
1429
1430void Emitter::emitStatement(SeqMemOp op) {
1431 startStatement();
1432 ps.scopedBox(PP::ibox2, [&]() {
1433 ps << "smem " << PPExtString(legalize(op.getNameAttr()));
1434 emitTypeWithColon(op.getType());
1435 ps << "," << PP::space;
1436 emitAttribute(op.getRuwAttr());
1437 });
1438 emitLocationAndNewLine(op);
1439}
1440
1441void Emitter::emitStatement(CombMemOp op) {
1442 startStatement();
1443 ps.scopedBox(PP::ibox2, [&]() {
1444 ps << "cmem " << PPExtString(legalize(op.getNameAttr()));
1445 emitTypeWithColon(op.getType());
1446 });
1447 emitLocationAndNewLine(op);
1448}
1449
1450void Emitter::emitStatement(MemoryPortOp op) {
1451 // Nothing to output for this operation.
1452 addValueName(op.getData(), legalize(op.getNameAttr()));
1453}
1454
1455void Emitter::emitStatement(MemoryDebugPortOp op) {
1456 // Nothing to output for this operation.
1457 addValueName(op.getData(), legalize(op.getNameAttr()));
1458}
1459
1460void Emitter::emitStatement(MemoryPortAccessOp op) {
1461 startStatement();
1462
1463 // Print the port direction and name.
1464 auto port = cast<MemoryPortOp>(op.getPort().getDefiningOp());
1465 emitAttribute(port.getDirection());
1466 // TODO: emitAssignLike
1467 ps << " mport " << PPExtString(legalize(port.getNameAttr())) << " = ";
1468
1469 // Print the memory name.
1470 auto *mem = port.getMemory().getDefiningOp();
1471 if (auto seqMem = dyn_cast<SeqMemOp>(mem))
1472 ps << legalize(seqMem.getNameAttr());
1473 else
1474 ps << legalize(cast<CombMemOp>(mem).getNameAttr());
1475
1476 // Print the address.
1477 ps << "[";
1478 emitExpression(op.getIndex());
1479 ps << "], ";
1480
1481 // Print the clock.
1482 emitExpression(op.getClock());
1483
1484 emitLocationAndNewLine(op);
1485}
1486
1487void Emitter::emitStatement(DomainDefineOp op) {
1488 if (failed(requireVersion(missingSpecFIRVersion, op, "domains")))
1489 return;
1490 // If the source is an anonymous domain, then we can skip emitting this op.
1491 if (isa_and_nonnull<DomainCreateAnonOp>(op.getSrc().getDefiningOp()))
1492 return;
1493
1494 startStatement();
1495 emitAssignLike([&]() { emitExpression(op.getDest()); },
1496 [&]() { emitExpression(op.getSrc()); }, PPExtString("="),
1497 PPExtString("domain_define"));
1498 emitLocationAndNewLine(op);
1499}
1500
1501void Emitter::emitStatement(RefDefineOp op) {
1502 startStatement();
1503 emitAssignLike([&]() { emitExpression(op.getDest()); },
1504 [&]() { emitExpression(op.getSrc()); }, PPExtString("="),
1505 PPExtString("define"));
1506 emitLocationAndNewLine(op);
1507}
1508
1509void Emitter::emitStatement(RefForceOp op) {
1510 emitStatementFunctionOp(PPExtString("force"), op);
1511}
1512
1513void Emitter::emitStatement(RefForceInitialOp op) {
1514 startStatement();
1515 auto constantPredicate =
1516 dyn_cast_or_null<ConstantOp>(op.getPredicate().getDefiningOp());
1517 bool hasEnable = !constantPredicate || constantPredicate.getValue() == 0;
1518 if (hasEnable) {
1519 ps << "when ";
1520 emitExpression(op.getPredicate());
1521 ps << ":" << PP::bbox2 << PP::neverbreak << PP::newline;
1522 }
1523 ps << "force_initial(";
1524 ps.scopedBox(PP::ibox0, [&]() {
1525 interleaveComma({op.getDest(), op.getSrc()});
1526 ps << ")";
1527 });
1528 if (hasEnable)
1529 ps << PP::end;
1530 emitLocationAndNewLine(op);
1531}
1532
1533void Emitter::emitStatement(RefReleaseOp op) {
1534 emitStatementFunctionOp(PPExtString("release"), op);
1535}
1536
1537void Emitter::emitStatement(RefReleaseInitialOp op) {
1538 startStatement();
1539 auto constantPredicate =
1540 dyn_cast_or_null<ConstantOp>(op.getPredicate().getDefiningOp());
1541 bool hasEnable = !constantPredicate || constantPredicate.getValue() == 0;
1542 if (hasEnable) {
1543 ps << "when ";
1544 emitExpression(op.getPredicate());
1545 ps << ":" << PP::bbox2 << PP::neverbreak << PP::newline;
1546 }
1547 ps << "release_initial(";
1548 emitExpression(op.getDest());
1549 ps << ")";
1550 if (hasEnable)
1551 ps << PP::end;
1552 emitLocationAndNewLine(op);
1553}
1554
1555void Emitter::emitStatement(LayerBlockOp op) {
1556 if (failed(requireVersion(FIRVersion(3, 3, 0), op, "layers")))
1557 return;
1558 startStatement();
1559 ps << "layerblock " << op.getLayerName().getLeafReference() << " :";
1560 emitLocationAndNewLine(op);
1561 auto *body = op.getBody();
1562 ps.scopedBox(PP::bbox2, [&]() { emitStatementsInBlock(*body); });
1563}
1564
1565void Emitter::emitStatement(InvalidValueOp op) {
1566 // Only emit this invalid value if it is used somewhere else than the RHS of
1567 // a connect.
1568 if (llvm::all_of(op->getUses(), [&](OpOperand &use) {
1569 return use.getOperandNumber() == 1 &&
1570 isa<ConnectOp, MatchingConnectOp>(use.getOwner());
1571 }))
1572 return;
1573
1574 // TODO: emitAssignLike ?
1575 startStatement();
1576 auto name = circuitNamespace.newName("_invalid");
1577 addValueName(op, name);
1578 ps << "wire " << PPExtString(name) << " : ";
1579 emitType(op.getType());
1580 emitLocationAndNewLine(op);
1581 startStatement();
1582 if (FIRVersion(3, 0, 0) <= version)
1583 ps << "invalidate " << PPExtString(name);
1584 else
1585 ps << PPExtString(name) << " is invalid";
1586 emitLocationAndNewLine(op);
1587}
1588
1589void Emitter::emitStatement(GenericIntrinsicOp op) {
1590 if (failed(requireVersion(FIRVersion(4, 0, 0), op, "generic intrinsics")))
1591 return;
1592 startStatement();
1593 if (op.use_empty())
1594 emitGenericIntrinsic(op);
1595 else {
1596 assert(!isEmittedInline(op));
1597 auto name = circuitNamespace.newName("_gen_int");
1598 addValueName(op.getResult(), name);
1599 emitAssignLike([&]() { ps << "node " << PPExtString(name); },
1600 [&]() { emitGenericIntrinsic(op); });
1601 }
1602 emitLocationAndNewLine(op);
1603}
1604
1605void Emitter::emitStatement(DomainCreateAnonOp op) {
1606 // These ops are not emitted.
1607}
1608
1609void Emitter::emitStatement(DomainCreateOp op) {
1610 if (failed(requireVersion(missingSpecFIRVersion, op, "domains")))
1611 return;
1612 startStatement();
1613 auto name = legalize(op.getNameAttr());
1614 addValueName(op.getResult(), name);
1615 ps.scopedBox(PP::ibox2, [&]() {
1616 ps << "domain " << PPExtString(name) << " of "
1617 << PPExtString(op.getDomainAttr().getValue());
1618
1619 auto fieldValues = op.getFieldValues();
1620 if (fieldValues.empty())
1621 return;
1622
1623 ps << "(" << PP::ibox0;
1624 interleaveComma(fieldValues, [&](auto value) { emitExpression(value); });
1625 ps << ")" << PP::end;
1626 });
1627
1628 emitLocationAndNewLine(op);
1629}
1630
1631void Emitter::emitExpression(Value value) {
1632 // Handle the trivial case where we already have a name for this value which
1633 // we can use.
1634 if (auto name = lookupEmittedName(value)) {
1635 // Don't use PPExtString here, can't trust valueNames storage, cleared.
1636 ps << *name;
1637 return;
1638 }
1639
1640 auto *op = value.getDefiningOp();
1641 assert(op && "value must either be a block arg or the result of an op");
1642 TypeSwitch<Operation *>(op)
1643 .Case<
1644 // Basic expressions
1645 ConstantOp, SpecialConstantOp, SubfieldOp, SubindexOp, SubaccessOp,
1646 OpenSubfieldOp, OpenSubindexOp, DomainSubfieldOp,
1647 // Binary
1648 AddPrimOp, SubPrimOp, MulPrimOp, DivPrimOp, RemPrimOp, AndPrimOp,
1649 OrPrimOp, XorPrimOp, LEQPrimOp, LTPrimOp, GEQPrimOp, GTPrimOp,
1650 EQPrimOp, NEQPrimOp, DShlPrimOp, DShlwPrimOp, DShrPrimOp,
1651 // Unary
1652 AsSIntPrimOp, AsUIntPrimOp, AsAsyncResetPrimOp, AsResetPrimOp,
1653 AsClockPrimOp, CvtPrimOp, NegPrimOp, NotPrimOp, AndRPrimOp, OrRPrimOp,
1654 XorRPrimOp,
1655 // Miscellaneous
1656 BitsPrimOp, HeadPrimOp, TailPrimOp, PadPrimOp, MuxPrimOp, ShlPrimOp,
1657 ShrPrimOp, UninferredResetCastOp, ConstCastOp, StringConstantOp,
1658 FIntegerConstantOp, BoolConstantOp, DoubleConstantOp, ListCreateOp,
1659 UnresolvedPathOp, GenericIntrinsicOp, CatPrimOp, UnsafeDomainCastOp,
1660 ObjectAnyRefCastOp, DomainAnyRefCastOp, UnknownValueOp, IntegerAndOp,
1661 IntegerOrOp, IntegerNotOp, StringConcatOp, PropEqOp, ListLengthOp,
1662 ListContainsOp, OptionCreateOp, OptionGetOrElseOp, BoolAndOp,
1663 BoolOrOp, BoolXorOp,
1664 // Reference expressions
1665 RefSendOp, RefResolveOp, RefSubOp, RWProbeOp, RefCastOp,
1666 // Format String expressions
1667 TimeOp>([&](auto op) {
1668 ps.scopedBox(PP::ibox0, [&]() { emitExpression(op); });
1669 })
1670 .Default([&](auto op) {
1671 emitOpError(op, "not supported as expression");
1672 ps << "<unsupported-expr-" << PPExtString(op->getName().stripDialect())
1673 << ">";
1674 });
1675}
1676
1677void Emitter::emitExpression(ConstantOp op) {
1678 // Don't include 'const' on the type in a literal expression
1679 emitType(op.getType(), false);
1680 // TODO: Add option to control base-2/8/10/16 output here.
1681 ps << "(";
1682 ps.addAsString(op.getValue());
1683 ps << ")";
1684}
1685
1686void Emitter::emitExpression(SpecialConstantOp op) {
1687 auto emitInner = [&]() {
1688 ps << "UInt<1>(";
1689 ps.addAsString(op.getValue());
1690 ps << ")";
1691 };
1692 // TODO: Emit type decl for type alias.
1693 FIRRTLTypeSwitch<FIRRTLType>(type_cast<FIRRTLType>(op.getType()))
1694 .Case<ClockType>([&](auto type) {
1695 ps << "asClock(";
1696 emitInner();
1697 ps << ")";
1698 })
1699 .Case<ResetType>([&](auto type) { emitInner(); })
1700 .Case<AsyncResetType>([&](auto type) {
1701 ps << "asAsyncReset(";
1702 emitInner();
1703 ps << ")";
1704 });
1705}
1706
1707// NOLINTNEXTLINE(misc-no-recursion)
1708void Emitter::emitExpression(SubfieldOp op) {
1709 BundleType type = op.getInput().getType();
1710 emitExpression(op.getInput());
1711 ps << "." << legalize(type.getElementNameAttr(op.getFieldIndex()));
1712}
1713
1714// NOLINTNEXTLINE(misc-no-recursion)
1715void Emitter::emitExpression(SubindexOp op) {
1716 emitExpression(op.getInput());
1717 ps << "[";
1718 ps.addAsString(op.getIndex());
1719 ps << "]";
1720}
1721
1722// NOLINTNEXTLINE(misc-no-recursion)
1723void Emitter::emitExpression(SubaccessOp op) {
1724 emitExpression(op.getInput());
1725 ps << "[";
1726 emitExpression(op.getIndex());
1727 ps << "]";
1728}
1729
1730void Emitter::emitExpression(OpenSubfieldOp op) {
1731 auto type = op.getInput().getType();
1732 emitExpression(op.getInput());
1733 ps << "." << legalize(type.getElementNameAttr(op.getFieldIndex()));
1734}
1735
1736// NOLINTNEXTLINE(misc-no-recursion)
1737void Emitter::emitExpression(DomainSubfieldOp op) {
1738 emitExpression(op.getInput());
1739 ps << "." << legalize(op.getFieldName());
1740}
1741
1742void Emitter::emitExpression(OpenSubindexOp op) {
1743 emitExpression(op.getInput());
1744 ps << "[";
1745 ps.addAsString(op.getIndex());
1746 ps << "]";
1747}
1748
1749void Emitter::emitExpression(ObjectAnyRefCastOp op) {
1750 emitExpression(op.getInput());
1751}
1752
1753void Emitter::emitExpression(DomainAnyRefCastOp op) {
1754 emitExpression(op.getInput());
1755}
1756
1757void Emitter::emitExpression(RefSendOp op) {
1758 ps << "probe(";
1759 emitExpression(op.getBase());
1760 ps << ")";
1761}
1762
1763void Emitter::emitExpression(RefResolveOp op) {
1764 ps << "read(";
1765 emitExpression(op.getRef());
1766 ps << ")";
1767}
1768
1769void Emitter::emitExpression(RefSubOp op) {
1770 emitExpression(op.getInput());
1771 FIRRTLTypeSwitch<FIRRTLBaseType, void>(op.getInput().getType().getType())
1772 .Case<FVectorType>([&](auto type) {
1773 ps << "[";
1774 ps.addAsString(op.getIndex());
1775 ps << "]";
1776 })
1777 .Case<BundleType>(
1778 [&](auto type) { ps << "." << type.getElementName(op.getIndex()); });
1779}
1780
1781void Emitter::emitExpression(RWProbeOp op) {
1782 ps << "rwprobe(";
1783
1784 // Find the probe target.
1785 auto target = symInfos->get().irn.lookup(op.getTarget());
1786 Value base;
1787 if (target.isPort()) {
1788 auto mod = cast<FModuleOp>(target.getOp());
1789 auto port = target.getPort();
1790 base = mod.getArgument(port);
1791 } else
1792 base = cast<hw::InnerSymbolOpInterface>(target.getOp()).getTargetResult();
1793
1794 // Print target. Needs this to have a name already.
1795 emitExpression(base);
1796
1797 // Print indexing for the target field.
1798 auto fieldID = target.getField();
1799 auto type = base.getType();
1800 while (fieldID) {
1801 FIRRTLTypeSwitch<Type, void>(type)
1802 .Case<FVectorType, OpenVectorType>([&](auto vecTy) {
1803 auto index = vecTy.getIndexForFieldID(fieldID);
1804 ps << "[";
1805 ps.addAsString(index);
1806 ps << "]";
1807 auto [subtype, subfieldID] = vecTy.getSubTypeByFieldID(fieldID);
1808 type = subtype;
1809 fieldID = subfieldID;
1810 })
1811 .Case<BundleType, OpenBundleType>([&](auto bundleTy) {
1812 auto index = bundleTy.getIndexForFieldID(fieldID);
1813 ps << "." << bundleTy.getElementName(index);
1814 auto [subtype, subfieldID] = bundleTy.getSubTypeByFieldID(fieldID);
1815 type = subtype;
1816 fieldID = subfieldID;
1817 });
1818 }
1819 ps << ")";
1820}
1821
1822void Emitter::emitExpression(RefCastOp op) { emitExpression(op.getInput()); }
1823
1824void Emitter::emitExpression(UninferredResetCastOp op) {
1825 emitExpression(op.getInput());
1826}
1827
1828void Emitter::emitExpression(FIntegerConstantOp op) {
1829 if (failed(requireVersion(FIRVersion(3, 1, 0), op, "Integers")))
1830 return;
1831 ps << "Integer(";
1832 ps.addAsString(op.getValue());
1833 ps << ")";
1834}
1835
1836void Emitter::emitExpression(BoolConstantOp op) {
1837 if (failed(requireVersion({6, 0, 0}, op, "Bools")))
1838 return;
1839 ps << "Bool(" << (op.getValue() ? "true" : "false") << ")";
1840}
1841
1842void Emitter::emitExpression(DoubleConstantOp op) {
1843 if (failed(requireVersion({6, 0, 0}, op, "Doubles")))
1844 return;
1845 ps << "Double(";
1846 // Use APFloat::toString.
1847 // Printing as double is not what we want,
1848 // and this at least handles the basic cases in a way
1849 // that will round-trip.
1850 SmallString<16> str;
1851 op.getValueAttr().getValue().toString(str);
1852 ps << str;
1853 ps << ")";
1854}
1855
1856void Emitter::emitExpression(StringConstantOp op) {
1857 if (failed(requireVersion(FIRVersion(3, 1, 0), op, "Strings")))
1858 return;
1859 ps << "String(";
1860 ps.writeQuotedEscaped(op.getValue());
1861 ps << ")";
1862}
1863
1864void Emitter::emitExpression(ListCreateOp op) {
1865 if (failed(requireVersion(FIRVersion(4, 0, 0), op, "Lists")))
1866 return;
1867 return emitLiteralExpression(op.getType(), op.getElements());
1868}
1869
1870void Emitter::emitExpression(OptionCreateOp op) {
1871 if (failed(requireVersion(nextFIRVersion, op, "Options")))
1872 return;
1873 emitLiteralExpression(op.getType(), op->getOperands());
1874}
1875
1876void Emitter::emitExpression(UnresolvedPathOp op) {
1877 if (failed(requireVersion({6, 0, 0}, op, "Paths")))
1878 return;
1879 ps << "path(";
1880 ps.writeQuotedEscaped(op.getTarget());
1881 ps << ")";
1882}
1883
1884void Emitter::emitExpression(GenericIntrinsicOp op) {
1885 if (failed(requireVersion(FIRVersion(4, 0, 0), op, "generic intrinsics")))
1886 return;
1887 emitGenericIntrinsic(op);
1888}
1889
1890void Emitter::emitExpression(ConstCastOp op) { emitExpression(op.getInput()); }
1891
1892void Emitter::emitPrimExpr(StringRef mnemonic, Operation *op,
1893 ArrayRef<uint32_t> attrs) {
1894 ps << mnemonic << "(" << PP::ibox0;
1895 interleaveComma(op->getOperands());
1896 if (!op->getOperands().empty() && !attrs.empty())
1897 ps << "," << PP::space;
1898 interleaveComma(attrs, [&](auto attr) { ps.addAsString(attr); });
1899 ps << ")" << PP::end;
1900}
1901
1902void Emitter::emitExpression(CatPrimOp op) {
1903 size_t numOperands = op.getNumOperands();
1904 switch (numOperands) {
1905 case 0:
1906 // Emit "UInt<0>(0)"
1907 emitType(op.getType(), false);
1908 ps << "(0)";
1909 return;
1910 case 1: {
1911 auto operand = op->getOperand(0);
1912 // If there is no sign conversion, just emit the operand.
1913 if (isa<UIntType>(operand.getType()))
1914 return emitExpression(operand);
1915
1916 // Emit cat to convert sign.
1917 ps << "cat(" << PP::ibox0;
1918 emitExpression(op->getOperand(0));
1919 ps << "," << PP::space << "SInt<0>(0))" << PP::end;
1920 return;
1921 }
1922
1923 default:
1924 // Construct a linear tree of cats.
1925 for (size_t i = 0; i < numOperands - 1; ++i) {
1926 ps << "cat(" << PP::ibox0;
1927 emitExpression(op->getOperand(i));
1928 ps << "," << PP::space;
1929 }
1930
1931 emitExpression(op->getOperand(numOperands - 1));
1932 for (size_t i = 0; i < numOperands - 1; ++i)
1933 ps << ")" << PP::end;
1934 return;
1935 }
1936}
1937
1938void Emitter::emitExpression(UnsafeDomainCastOp op) {
1939 if (failed(requireVersion(nextFIRVersion, op, "unsafe_domain_cast")))
1940 return;
1941 ps << "unsafe_domain_cast(" << PP::ibox0;
1942 interleaveComma(op.getOperands(),
1943 [&](Value operand) { emitExpression(operand); });
1944 ps << ")" << PP::end;
1945}
1946
1947void Emitter::emitExpression(UnknownValueOp op) {
1948 if (failed(
1949 requireVersion(nextFIRVersion, op, "unknown property expressions")))
1950 return;
1951 ps << "Unknown(";
1952 emitType(op.getType());
1953 ps << ")";
1954}
1955
1956void Emitter::emitAttribute(MemDirAttr attr) {
1957 switch (attr) {
1958 case MemDirAttr::Infer:
1959 ps << "infer";
1960 break;
1961 case MemDirAttr::Read:
1962 ps << "read";
1963 break;
1964 case MemDirAttr::Write:
1965 ps << "write";
1966 break;
1967 case MemDirAttr::ReadWrite:
1968 ps << "rdwr";
1969 break;
1970 }
1971}
1972
1973void Emitter::emitAttribute(RUWBehaviorAttr attr) {
1974 switch (attr.getValue()) {
1975 case RUWBehavior::Undefined:
1976 ps << "undefined";
1977 break;
1978 case RUWBehavior::Old:
1979 ps << "old";
1980 break;
1981 case RUWBehavior::New:
1982 ps << "new";
1983 break;
1984 }
1985}
1986
1987/// Emit a FIRRTL type into the output.
1988void Emitter::emitType(Type type, bool includeConst) {
1989 if (includeConst && isConst(type))
1990 ps << "const ";
1991 auto emitWidth = [&](std::optional<int32_t> width) {
1992 if (width) {
1993 ps << "<";
1994 ps.addAsString(*width);
1995 ps << ">";
1996 }
1997 };
1998 // TODO: Emit type decl for type alias.
1999 FIRRTLTypeSwitch<Type>(type)
2000 .Case<ClockType>([&](auto) { ps << "Clock"; })
2001 .Case<ResetType>([&](auto) { ps << "Reset"; })
2002 .Case<AsyncResetType>([&](auto) { ps << "AsyncReset"; })
2003 .Case<UIntType>([&](auto type) {
2004 ps << "UInt";
2005 emitWidth(type.getWidth());
2006 })
2007 .Case<SIntType>([&](auto type) {
2008 ps << "SInt";
2009 emitWidth(type.getWidth());
2010 })
2011 .Case<AnalogType>([&](auto type) {
2012 ps << "Analog";
2013 emitWidth(type.getWidth());
2014 })
2015 .Case<OpenBundleType, BundleType>([&](auto type) {
2016 ps << "{";
2017 if (!type.getElements().empty())
2018 ps << PP::nbsp;
2019 bool anyEmitted = false;
2020 ps.scopedBox(PP::cbox0, [&]() {
2021 for (auto &element : type.getElements()) {
2022 if (anyEmitted)
2023 ps << "," << PP::space;
2024 ps.scopedBox(PP::ibox2, [&]() {
2025 if (element.isFlip)
2026 ps << "flip ";
2027 ps << legalize(element.name);
2028 emitTypeWithColon(element.type);
2029 anyEmitted = true;
2030 });
2031 }
2032 if (anyEmitted)
2033 ps << PP::nbsp;
2034 ps << "}";
2035 });
2036 })
2037 .Case<OpenVectorType, FVectorType, CMemoryType>([&](auto type) {
2038 emitType(type.getElementType());
2039 ps << "[";
2040 ps.addAsString(type.getNumElements());
2041 ps << "]";
2042 })
2043 .Case<RefType>([&](RefType type) {
2044 if (type.getForceable())
2045 ps << "RW";
2046 ps << "Probe<";
2047 ps.cbox(2, IndentStyle::Block);
2048 ps.zerobreak();
2049 emitType(type.getType());
2050 if (auto layer = type.getLayer()) {
2051 ps << ",";
2052 ps.space();
2053 emitSymbol(type.getLayer());
2054 }
2055 ps << BreakToken(0, -2) << ">";
2056 ps.end();
2057 })
2058 .Case<ClassType>([&](ClassType type) {
2059 ps << "Inst<" << PPExtString(legalize(type.getNameAttr().getAttr()))
2060 << ">";
2061 })
2062 .Case<AnyRefType>([&](AnyRefType type) { ps << "AnyRef"; })
2063 .Case<StringType>([&](StringType type) { ps << "String"; })
2064 .Case<FIntegerType>([&](FIntegerType type) { ps << "Integer"; })
2065 .Case<BoolType>([&](BoolType type) { ps << "Bool"; })
2066 .Case<DoubleType>([&](DoubleType type) { ps << "Double"; })
2067 .Case<PathType>([&](PathType type) { ps << "Path"; })
2068 .Case<ListType>([&](ListType type) {
2069 ps << "List<";
2070 emitType(type.getElementType());
2071 ps << ">";
2072 })
2073 .Case<OptionType>([&](OptionType type) {
2074 ps << "Option<";
2075 emitType(type.getElementType());
2076 ps << ">";
2077 })
2078 .Case<RegistryType>([&](RegistryType type) {
2079 ps << "Registry<";
2080 emitType(type.getElementType());
2081 ps << ">";
2082 })
2083 .Case<DomainType>([&](DomainType type) {
2084 ps << "Domain of " << PPExtString(type.getName().getValue());
2085 })
2086 .Default([&](auto type) {
2087 llvm_unreachable("all types should be implemented");
2088 });
2089}
2090
2091void Emitter::emitDomains(Attribute attr, ArrayRef<PortInfo> ports) {
2092 if (!attr)
2093 return;
2094 auto domains = cast<ArrayAttr>(attr);
2095 if (domains.empty())
2096 return;
2097 ps << " domains [";
2098 ps.scopedBox(PP::ibox0, [&]() {
2099 interleaveComma(domains, [&](Attribute attr) {
2100 ps.addAsString(ports[cast<IntegerAttr>(attr).getUInt()].name.getValue());
2101 });
2102 ps << "]";
2103 });
2104}
2105
2106/// Emit a location as `@[<filename> <line>:<column>]` annotation, including a
2107/// leading space.
2108void Emitter::emitLocation(Location loc) {
2109 // TODO: Handle FusedLoc and uniquify locations, avoid repeated file names.
2110 ps << PP::neverbreak;
2111 if (auto fileLoc =
2112 dyn_cast_or_null<FileLineColLoc, LocationAttr>(LocationAttr(loc))) {
2113 ps << " @[" << fileLoc.getFilename().getValue();
2114 if (auto line = fileLoc.getLine()) {
2115 ps << " ";
2116 ps.addAsString(line);
2117 if (auto col = fileLoc.getColumn()) {
2118 ps << ":";
2119 ps.addAsString(col);
2120 }
2121 }
2122 ps << "]";
2123 }
2124}
2125// NOLINTEND(misc-no-recursion)
2126
2127//===----------------------------------------------------------------------===//
2128// Driver
2129//===----------------------------------------------------------------------===//
2130
2131// Emit the specified FIRRTL circuit into the given output stream.
2132mlir::LogicalResult
2133circt::firrtl::exportFIRFile(mlir::ModuleOp module, llvm::raw_ostream &os,
2134 std::optional<size_t> targetLineLength,
2135 FIRVersion version) {
2136 if (version < minimumFIRVersion)
2137 return module.emitError("--firrtl-version ")
2138 << version << " is below the minimum supported "
2139 << "version " << minimumFIRVersion;
2140 Emitter emitter(os, version,
2141 targetLineLength.value_or(defaultTargetLineLength));
2142 for (auto &op : *module.getBody()) {
2143 if (auto circuitOp = dyn_cast<CircuitOp>(op))
2144 emitter.emitCircuit(circuitOp);
2145 }
2146 return emitter.finalize();
2147}
2148
2150 static llvm::cl::opt<size_t> targetLineLength(
2151 "target-line-length",
2152 llvm::cl::desc("Target line length for emitted .fir; 0 disables line "
2153 "wrapping"),
2154 llvm::cl::value_desc("number of chars"),
2155 llvm::cl::init(defaultTargetLineLength));
2156 static llvm::cl::opt<std::string> firrtlVersionStr(
2157 "firrtl-version",
2158 llvm::cl::desc("FIRRTL version to target (e.g. \"3.0.0\"). "
2159 "Defaults to the latest supported version."),
2160 llvm::cl::value_desc("major.minor.patch"), llvm::cl::init(""));
2161 static mlir::TranslateFromMLIRRegistration toFIR(
2162 "export-firrtl", "emit FIRRTL dialect operations to .fir output",
2163 [](ModuleOp module, llvm::raw_ostream &os) -> mlir::LogicalResult {
2164 FIRVersion version = exportFIRVersion;
2165 if (!firrtlVersionStr.empty()) {
2166 auto ver = FIRVersion::fromString(firrtlVersionStr);
2167 if (!ver)
2168 return module.emitError("invalid --firrtl-version: '")
2169 << firrtlVersionStr
2170 << "', expected format 'major.minor.patch'";
2171 version = *ver;
2172 }
2173 return exportFIRFile(module, os, targetLineLength, version);
2174 },
2175 [](mlir::DialectRegistry &registry) {
2176 registry.insert<chirrtl::CHIRRTLDialect>();
2177 registry.insert<firrtl::FIRRTLDialect>();
2178 });
2179}
assert(baseType &&"element must be base type")
#define HANDLE(OPTYPE, OPKIND)
static bool isEmittedInline(Operation *op)
Check if an operation is inlined into the emission of their users.
#define isdigit(x)
Definition FIRLexer.cpp:26
static std::vector< mlir::Value > toVector(mlir::ValueRange range)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
return success()
NamedAttrList attrs
void space()
Add a breakable space.
void cbox(int32_t offset=0, IndentStyle style=IndentStyle::Visual)
Start a consistent group with specified offset.
void zerobreak()
Add a break that is zero-wide if not broken.
auto scopedBox(T &&t, Callable &&c, Token close=EndToken())
Open a box, invoke the lambda, and close it after.
TokenStream & addAsString(T &&t)
General-purpose "format this" helper, for types not supported by operator<< yet.
TokenStream & writeQuotedEscaped(StringRef str, bool useHexEscapes=false, StringRef left="\"", StringRef right="\"")
BaseTy type_cast(Type type)
mlir::LogicalResult exportFIRFile(mlir::ModuleOp module, llvm::raw_ostream &os, std::optional< size_t > targetLineLength, FIRVersion version)
constexpr FIRVersion nextFIRVersion(7, 0, 0)
The next version of FIRRTL that is not yet released.
constexpr FIRVersion exportFIRVersion
The version of FIRRTL that the exporter produces.
Definition FIRParser.h:151
void registerToFIRFileTranslation()
bool isConst(Type type)
Returns true if this is a 'const' type whose value is guaranteed to be unchanging at circuit executio...
constexpr FIRVersion missingSpecFIRVersion
A marker for parser features that are currently missing from the spec.
Definition FIRParser.h:147
bool isExpression(Operation *op)
Return true if the specified operation is a firrtl expression.
constexpr FIRVersion minimumFIRVersion(2, 0, 0)
The current minimum version of FIRRTL that the parser supports.
bool type_isa(Type type)
Definition HWTypes.h:201
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
The FIRRTL specification version.
Definition FIRParser.h:89
static std::optional< FIRVersion > fromString(StringRef str)
Parse a version string of the form "major.minor.patch".
Definition FIRParser.h:115