CIRCT 23.0.0git
Loading...
Searching...
No Matches
FIRRTLIntrinsics.cpp
Go to the documentation of this file.
1//===- FIRRTLIntrinsics.cpp - Lower Intrinsics ------------------*- C++ -*-===//
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
14#include "circt/Support/JSON.h"
15#include "mlir/Transforms/DialectConversion.h"
16#include "llvm/Support/JSON.h"
17
18using namespace circt;
19using namespace firrtl;
20
21// vtable anchor
23
24//===----------------------------------------------------------------------===//
25// GenericIntrinsic
26//===----------------------------------------------------------------------===//
27
28// Checks for a number of operands between n and n+c (allows for c optional
29// inputs)
30ParseResult GenericIntrinsic::hasNInputs(unsigned n, unsigned c) {
31 auto numOps = op.getNumOperands();
32 unsigned m = n + c;
33 if (numOps < n || numOps > m) {
34 auto err = emitError() << " has " << numOps << " inputs instead of ";
35 if (c == 0)
36 err << n;
37 else
38 err << " between " << n << " and " << m;
39 return failure();
40 }
41 return success();
42}
43
44// Accessor method for the number of inputs
45unsigned GenericIntrinsic::getNumInputs() { return op.getNumOperands(); }
46
47ParseResult GenericIntrinsic::hasNOutputElements(unsigned n) {
48 auto b = getOutputBundle();
49 if (!b)
50 return emitError() << " missing output bundle";
51 if (b.getType().getNumElements() != n)
52 return emitError() << " has " << b.getType().getNumElements()
53 << " output elements instead of " << n;
54 return success();
55}
56
57ParseResult GenericIntrinsic::hasNParam(unsigned n, unsigned c) {
58 unsigned num = 0;
59 if (op.getParameters())
60 num = op.getParameters().size();
61 if (num < n || num > n + c) {
62 auto d = emitError() << " has " << num << " parameters instead of ";
63 if (c == 0)
64 d << n;
65 else
66 d << " between " << n << " and " << (n + c);
67 return failure();
68 }
69 return success();
70}
71
72ParseResult GenericIntrinsic::namedParam(StringRef paramName, bool optional) {
73 for (auto a : op.getParameters()) {
74 auto param = cast<ParamDeclAttr>(a);
75 if (param.getName().getValue() == paramName) {
76 if (isa<StringAttr>(param.getValue()))
77 return success();
78
79 return emitError() << " has parameter '" << param.getName()
80 << "' which should be a string but is not";
81 }
82 }
83 if (optional)
84 return success();
85 return emitError() << " is missing parameter " << paramName;
86}
87
88ParseResult GenericIntrinsic::namedIntParam(StringRef paramName,
89 bool optional) {
90 for (auto a : op.getParameters()) {
91 auto param = cast<ParamDeclAttr>(a);
92 if (param.getName().getValue() == paramName) {
93 if (isa<IntegerAttr>(param.getValue()))
94 return success();
95
96 return emitError() << " has parameter '" << param.getName()
97 << "' which should be an integer but is not";
98 }
99 }
100 if (optional)
101 return success();
102 return emitError() << " is missing parameter " << paramName;
103}
104
105//===----------------------------------------------------------------------===//
106// IntrinsicOpConversion
107//===----------------------------------------------------------------------===//
108
109/// Conversion pattern adaptor dispatching via generic intrinsic name.
110namespace {
111class IntrinsicOpConversion final
112 : public OpConversionPattern<GenericIntrinsicOp> {
113public:
114 using ConversionMapTy = IntrinsicLowerings::ConversionMapTy;
115
116 IntrinsicOpConversion(TypeConverter &typeConverter, MLIRContext *context,
117 const ConversionMapTy &conversions,
118 size_t &numConversions,
119 bool allowUnknownIntrinsics = false)
120 : OpConversionPattern(typeConverter, context), conversions(conversions),
121 numConversions(numConversions),
122 allowUnknownIntrinsics(allowUnknownIntrinsics) {}
123
124 LogicalResult
125 matchAndRewrite(GenericIntrinsicOp op, OpAdaptor adaptor,
126 ConversionPatternRewriter &rewriter) const override {
127
128 auto it = conversions.find(op.getIntrinsicAttr());
129 if (it == conversions.end()) {
130 if (!allowUnknownIntrinsics)
131 return op.emitError("unknown intrinsic ") << op.getIntrinsicAttr();
132 return failure();
133 }
134
135 auto &conv = *it->second;
136 auto result = conv.checkAndConvert(GenericIntrinsic(op), adaptor, rewriter);
137 if (succeeded(result))
138 ++numConversions;
139 return result;
140 }
141
142private:
143 const ConversionMapTy &conversions;
144 size_t &numConversions;
145 const bool allowUnknownIntrinsics;
146};
147} // namespace
148
149//===----------------------------------------------------------------------===//
150// IntrinsicLowerings
151//===----------------------------------------------------------------------===//
152
153FailureOr<size_t> IntrinsicLowerings::lower(FModuleOp mod,
154 bool allowUnknownIntrinsics) {
155
156 ConversionTarget target(*context);
157
158 target.markUnknownOpDynamicallyLegal([](Operation *op) { return true; });
159 if (allowUnknownIntrinsics)
160 target.addDynamicallyLegalOp<GenericIntrinsicOp>(
161 [this](GenericIntrinsicOp op) {
162 return !conversions.contains(op.getIntrinsicAttr());
163 });
164 else
165 target.addIllegalOp<GenericIntrinsicOp>();
166
167 // Automatically insert wires + connect for compatible FIRRTL base types.
168 // For now, this is not customizable/extendable.
169 TypeConverter typeConverter;
170 typeConverter.addConversion([](Type type) { return type; });
171 auto firrtlBaseTypeMaterialization =
172 [](OpBuilder &builder, FIRRTLBaseType resultType, ValueRange inputs,
173 Location loc) -> Value {
174 if (inputs.size() != 1)
175 return {};
176 auto inputType = type_dyn_cast<FIRRTLBaseType>(inputs.front().getType());
177 if (!inputType)
178 return {};
179
180 if (!areTypesEquivalent(resultType, inputType) ||
181 !isTypeLarger(resultType, inputType))
182 return {};
183
184 auto w = WireOp::create(builder, loc, resultType).getResult();
185 emitConnect(builder, loc, w, inputs.front());
186 return w;
187 };
188 // New result doesn't match? Add wire + connect.
189 typeConverter.addSourceMaterialization(firrtlBaseTypeMaterialization);
190 // New operand doesn't match? Add wire + connect.
191 typeConverter.addTargetMaterialization(firrtlBaseTypeMaterialization);
192
193 RewritePatternSet patterns(context);
194 size_t count = 0;
195 patterns.add<IntrinsicOpConversion>(typeConverter, context, conversions,
196 count, allowUnknownIntrinsics);
197
198 if (failed(mlir::applyPartialConversion(mod, target, std::move(patterns))))
199 return failure();
200
201 return count;
202}
203
204//===----------------------------------------------------------------------===//
205// IntrinsicLoweringInterfaceCollection
206//===----------------------------------------------------------------------===//
207
209 IntrinsicLowerings &lowering) const {
210 for (const IntrinsicLoweringDialectInterface &interface : *this)
211 interface.populateIntrinsicLowerings(lowering);
212}
213
214//===----------------------------------------------------------------------===//
215// FIRRTL intrinsic lowering converters
216//===----------------------------------------------------------------------===//
217
218namespace {
219
220class CirctSizeofConverter : public IntrinsicOpConverter<SizeOfIntrinsicOp> {
221public:
222 using IntrinsicOpConverter::IntrinsicOpConverter;
223
224 bool check(GenericIntrinsic gi) override {
225 return gi.hasNInputs(1) || gi.sizedOutput<UIntType>(32) || gi.hasNParam(0);
226 }
227};
228
229class CirctIsXConverter : public IntrinsicOpConverter<IsXIntrinsicOp> {
230public:
231 using IntrinsicOpConverter::IntrinsicOpConverter;
232
233 bool check(GenericIntrinsic gi) override {
234 return gi.hasNInputs(1) || gi.sizedOutput<UIntType>(1) || gi.hasNParam(0);
235 }
236};
237
238class CirctPlusArgTestConverter : public IntrinsicConverter {
239public:
240 using IntrinsicConverter::IntrinsicConverter;
241
242 bool check(GenericIntrinsic gi) override {
243 return gi.hasNInputs(0) || gi.sizedOutput<UIntType>(1) ||
244 gi.namedParam("FORMAT") || gi.hasNParam(1);
245 }
246
247 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
248 PatternRewriter &rewriter) override {
249 rewriter.replaceOpWithNewOp<PlusArgsTestIntrinsicOp>(
250 gi.op, gi.getParamValue<StringAttr>("FORMAT"));
251 }
252};
253
254class CirctPlusArgValueConverter : public IntrinsicConverter {
255public:
256 using IntrinsicConverter::IntrinsicConverter;
257
258 bool check(GenericIntrinsic gi) override {
259 return gi.hasNOutputElements(2) ||
260 gi.sizedOutputElement<UIntType>(0, "found", 1) ||
261 gi.hasOutputElement(1, "result") || gi.namedParam("FORMAT") ||
262 gi.hasNParam(1);
263 }
264
265 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
266 PatternRewriter &rewriter) override {
267 auto bty = gi.getOutputBundle().getType();
268 auto newop = PlusArgsValueIntrinsicOp::create(
269 rewriter, gi.op.getLoc(), bty.getElementTypePreservingConst(0),
270 bty.getElementTypePreservingConst(1),
271 gi.getParamValue<StringAttr>("FORMAT"));
272 rewriter.replaceOpWithNewOp<BundleCreateOp>(
273 gi.op, bty, ValueRange({newop.getFound(), newop.getResult()}));
274 }
275};
276
277class CirctClockGateConverter
278 : public IntrinsicOpConverter<ClockGateIntrinsicOp> {
279public:
280 using IntrinsicOpConverter::IntrinsicOpConverter;
281
282 bool check(GenericIntrinsic gi) override {
283 if (gi.op.getNumOperands() == 3) {
284 return gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
285 gi.sizedInput<UIntType>(2, 1) || gi.typedOutput<ClockType>() ||
286 gi.hasNParam(0);
287 }
288 if (gi.op.getNumOperands() == 2) {
289 return gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
290 gi.typedOutput<ClockType>() || gi.hasNParam(0);
291 }
292 gi.emitError() << " has " << gi.op.getNumOperands()
293 << " ports instead of 3 or 4";
294 return true;
295 }
296};
297
298class CirctClockInverterConverter
299 : public IntrinsicOpConverter<ClockInverterIntrinsicOp> {
300public:
301 using IntrinsicOpConverter::IntrinsicOpConverter;
302
303 bool check(GenericIntrinsic gi) override {
304 return gi.hasNInputs(1) || gi.typedInput<ClockType>(0) ||
305 gi.typedOutput<ClockType>() || gi.hasNParam(0);
306 }
307};
308
309class CirctClockDividerConverter : public IntrinsicConverter {
310public:
311 using IntrinsicConverter::IntrinsicConverter;
312
313 bool check(GenericIntrinsic gi) override {
314 return gi.hasNInputs(1) || gi.typedInput<ClockType>(0) ||
315 gi.typedOutput<ClockType>() || gi.namedIntParam("POW_2") ||
316 gi.hasNParam(1);
317 }
318
319 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
320 PatternRewriter &rewriter) override {
321 auto pow2 =
322 gi.getParamValue<IntegerAttr>("POW_2").getValue().getZExtValue();
323
324 auto pow2Attr = rewriter.getI64IntegerAttr(pow2);
325
326 rewriter.replaceOpWithNewOp<ClockDividerIntrinsicOp>(
327 gi.op, adaptor.getOperands()[0], pow2Attr);
328 }
329};
330
331template <typename OpTy>
332class CirctLTLBinaryConverter : public IntrinsicOpConverter<OpTy> {
333public:
335
336 bool check(GenericIntrinsic gi) override {
337 return gi.hasNInputs(2) || gi.sizedInput<UIntType>(0, 1) ||
338 gi.sizedInput<UIntType>(1, 1) || gi.sizedOutput<UIntType>(1) ||
339 gi.hasNParam(0);
340 }
341};
342
343template <typename OpTy>
344class CirctLTLUnaryConverter : public IntrinsicOpConverter<OpTy> {
345public:
347
348 bool check(GenericIntrinsic gi) override {
349 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
350 gi.sizedOutput<UIntType>(1) || gi.hasNParam(0);
351 }
352};
353
354class CirctLTLDelayConverter : public IntrinsicConverter {
355public:
356 using IntrinsicConverter::IntrinsicConverter;
357
358 bool check(GenericIntrinsic gi) override {
359 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
360 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("delay") ||
361 gi.namedIntParam("length", true) || gi.hasNParam(1, 1);
362 }
363
364 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
365 PatternRewriter &rewriter) override {
366 auto getI64Attr = [&](IntegerAttr val) {
367 if (!val)
368 return IntegerAttr();
369 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
370 };
371 auto delay = getI64Attr(gi.getParamValue<IntegerAttr>("delay"));
372 auto length = getI64Attr(gi.getParamValue<IntegerAttr>("length"));
373 rewriter.replaceOpWithNewOp<LTLDelayIntrinsicOp>(
374 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], delay, length);
375 }
376};
377
378class CirctLTLPastConverter : public IntrinsicConverter {
379public:
380 using IntrinsicConverter::IntrinsicConverter;
381
382 bool check(GenericIntrinsic gi) override {
383 if (gi.hasNInputs(1, 1) || gi.sizedInput<UIntType>(0, 1) ||
384 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("delay") ||
385 gi.hasNParam(1))
386 return true;
387 if (gi.op.getNumOperands() > 1 && gi.typedInput<ClockType>(1))
388 return true;
389 return false;
390 }
391
392 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
393 PatternRewriter &rewriter) override {
394 auto delay = rewriter.getI64IntegerAttr(
395 gi.getParamValue<IntegerAttr>("delay").getValue().getZExtValue());
396 auto operands = adaptor.getOperands();
397 Value clock;
398 if (operands.size() > 1)
399 clock = operands[1];
400 rewriter.replaceOpWithNewOp<LTLPastIntrinsicOp>(
401 gi.op, gi.op.getResultTypes(), operands[0], delay, clock);
402 }
403};
404
405class CirctLTLClockConverter
406 : public IntrinsicOpConverter<LTLClockIntrinsicOp> {
407public:
408 using IntrinsicOpConverter::IntrinsicOpConverter;
409
410 bool check(GenericIntrinsic gi) override {
411 return gi.hasNInputs(2) || gi.sizedInput<UIntType>(0, 1) ||
412 gi.typedInput<ClockType>(1) || gi.sizedOutput<UIntType>(1) ||
413 gi.hasNParam(0);
414 }
415};
416
417class CirctLTLRepeatConverter : public IntrinsicConverter {
418public:
419 using IntrinsicConverter::IntrinsicConverter;
420
421 bool check(GenericIntrinsic gi) override {
422 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
423 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
424 gi.namedIntParam("more", true) || gi.hasNParam(1, 1);
425 }
426
427 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
428 PatternRewriter &rewriter) override {
429 auto getI64Attr = [&](IntegerAttr val) {
430 if (!val)
431 return IntegerAttr();
432 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
433 };
434 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
435 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
436 rewriter.replaceOpWithNewOp<LTLRepeatIntrinsicOp>(
437 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
438 }
439};
440
441class CirctLTLGoToRepeatConverter : public IntrinsicConverter {
442public:
443 using IntrinsicConverter::IntrinsicConverter;
444
445 bool check(GenericIntrinsic gi) override {
446 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
447 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
448 gi.namedIntParam("more") || gi.hasNParam(1, 1);
449 }
450
451 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
452 PatternRewriter &rewriter) override {
453 auto getI64Attr = [&](IntegerAttr val) {
454 if (!val)
455 return IntegerAttr();
456 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
457 };
458 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
459 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
460 rewriter.replaceOpWithNewOp<LTLGoToRepeatIntrinsicOp>(
461 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
462 }
463};
464
465class CirctLTLNonConsecutiveRepeatConverter : public IntrinsicConverter {
466public:
467 using IntrinsicConverter::IntrinsicConverter;
468
469 bool check(GenericIntrinsic gi) override {
470 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
471 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
472 gi.namedIntParam("more") || gi.hasNParam(1, 1);
473 }
474
475 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
476 PatternRewriter &rewriter) override {
477 auto getI64Attr = [&](IntegerAttr val) {
478 if (!val)
479 return IntegerAttr();
480 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
481 };
482 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
483 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
484 rewriter.replaceOpWithNewOp<LTLNonConsecutiveRepeatIntrinsicOp>(
485 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
486 }
487};
488
489template <class Op>
490class CirctVerifConverter : public IntrinsicConverter {
491public:
492 using IntrinsicConverter::IntrinsicConverter;
493
494 bool check(GenericIntrinsic gi) override {
495 return gi.hasNInputs(1, 2) || gi.sizedInput<UIntType>(0, 1) ||
496 gi.namedParam("label", true) || gi.hasNParam(0, 1) ||
497 gi.hasNoOutput();
498 }
499
500 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
501 PatternRewriter &rewriter) override {
502 auto label = gi.getParamValue<StringAttr>("label");
503 auto operands = adaptor.getOperands();
504
505 // Check if an enable was provided
506 Value enable;
507 if (gi.getNumInputs() == 2)
508 enable = operands[1];
509
510 rewriter.replaceOpWithNewOp<Op>(gi.op, operands[0], enable, label);
511 }
512};
513
514class CirctMux2CellConverter : public IntrinsicConverter {
515 using IntrinsicConverter::IntrinsicConverter;
516
517 bool check(GenericIntrinsic gi) override {
518 return gi.hasNInputs(3) || gi.typedInput<UIntType>(0) || gi.hasNParam(0) ||
519 gi.hasOutput();
520 }
521
522 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
523 PatternRewriter &rewriter) override {
524 auto operands = adaptor.getOperands();
525 rewriter.replaceOpWithNewOp<Mux2CellIntrinsicOp>(gi.op, operands[0],
526 operands[1], operands[2]);
527 }
528};
529
530class CirctMux4CellConverter : public IntrinsicConverter {
531 using IntrinsicConverter::IntrinsicConverter;
532
533 bool check(GenericIntrinsic gi) override {
534 return gi.hasNInputs(5) || gi.typedInput<UIntType>(0) || gi.hasNParam(0) ||
535 gi.hasOutput();
536 }
537
538 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
539 PatternRewriter &rewriter) override {
540 auto operands = adaptor.getOperands();
541 rewriter.replaceOpWithNewOp<Mux4CellIntrinsicOp>(
542 gi.op, operands[0], operands[1], operands[2], operands[3], operands[4]);
543 }
544};
545
546class CirctHasBeenResetConverter
547 : public IntrinsicOpConverter<HasBeenResetIntrinsicOp> {
548public:
549 using IntrinsicOpConverter::IntrinsicOpConverter;
550
551 bool check(GenericIntrinsic gi) override {
552 return gi.hasNInputs(2) || gi.typedInput<ClockType>(0) ||
553 gi.hasResetInput(1) || gi.sizedOutput<UIntType>(1) ||
554 gi.hasNParam(0);
555 }
556};
557
558class CirctProbeConverter : public IntrinsicOpConverter<FPGAProbeIntrinsicOp> {
559public:
560 using IntrinsicOpConverter::IntrinsicOpConverter;
561
562 bool check(GenericIntrinsic gi) override {
563 return gi.hasNInputs(2) || gi.typedInput<ClockType>(1) || gi.hasNParam(0) ||
564 gi.hasNoOutput();
565 }
566};
567
568template <class OpTy, bool ifElseFatal = false>
569class CirctAssertConverter : public IntrinsicConverter {
570public:
571 using IntrinsicConverter::IntrinsicConverter;
572
573 LogicalResult checkAndConvert(GenericIntrinsic gi,
574 GenericIntrinsicOpAdaptor adaptor,
575 PatternRewriter &rewriter) override {
576 // Check structure of the intrinsic.
577 if (gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
578 gi.sizedInput<UIntType>(2, 1) ||
579 gi.namedParam("format", /*optional=*/true) ||
580 gi.namedParam("label", /*optional=*/true) ||
581 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 3) ||
582 gi.hasNoOutput())
583 return failure();
584
585 auto format = gi.getParamValue<StringAttr>("format");
586 auto label = gi.getParamValue<StringAttr>("label");
587 auto guards = gi.getParamValue<StringAttr>("guards");
588
589 auto clock = adaptor.getOperands()[0];
590 auto predicate = adaptor.getOperands()[1];
591 auto enable = adaptor.getOperands()[2];
592
593 auto substitutions = adaptor.getOperands().drop_front(3);
594 auto name = label ? label.strref() : "";
595
596 // Parse the format string to handle special substitutions like
597 // {{SimulationTime}} and {{HierarchicalModuleName}}
598 StringAttr message;
599 SmallVector<Value> allOperands;
600 if (format) {
601 SmallVector<Value> substitutionVec(substitutions.begin(),
602 substitutions.end());
603 if (failed(parseFormatString(rewriter, gi.op->getLoc(), format.getValue(),
604 substitutionVec, message, allOperands)))
605 return failure();
606 } else {
607 // Message is not optional, so provide empty string if not present.
608 message = rewriter.getStringAttr("");
609 allOperands.append(substitutions.begin(), substitutions.end());
610 }
611
612 auto op = rewriter.template replaceOpWithNewOp<OpTy>(
613 gi.op, clock, predicate, enable, message, allOperands, name,
614 /*isConcurrent=*/true);
615 if (guards) {
616 SmallVector<StringRef> guardStrings;
617 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
618 /*KeepEmpty=*/false);
619 rewriter.startOpModification(op);
620 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
621 rewriter.finalizeOpModification(op);
622 }
623
624 if constexpr (ifElseFatal) {
625 rewriter.startOpModification(op);
626 op->setAttr("format", rewriter.getStringAttr("ifElseFatal"));
627 rewriter.finalizeOpModification(op);
628 }
629
630 return success();
631 }
632};
633
634class CirctCoverConverter : public IntrinsicConverter {
635public:
636 using IntrinsicConverter::IntrinsicConverter;
637
638 bool check(GenericIntrinsic gi) override {
639 return gi.hasNInputs(3) || gi.hasNoOutput() ||
640 gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
641 gi.sizedInput<UIntType>(2, 1) ||
642 gi.namedParam("label", /*optional=*/true) ||
643 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 2);
644 }
645
646 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
647 PatternRewriter &rewriter) override {
648 auto label = gi.getParamValue<StringAttr>("label");
649 auto guards = gi.getParamValue<StringAttr>("guards");
650
651 auto clock = adaptor.getOperands()[0];
652 auto predicate = adaptor.getOperands()[1];
653 auto enable = adaptor.getOperands()[2];
654
655 auto name = label ? label.strref() : "";
656 // Empty message string for cover, only 'name' / label.
657 auto message = rewriter.getStringAttr("");
658 auto op = rewriter.replaceOpWithNewOp<CoverOp>(
659 gi.op, clock, predicate, enable, message, ValueRange{}, name,
660 /*isConcurrent=*/true);
661 if (guards) {
662 SmallVector<StringRef> guardStrings;
663 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
664 /*KeepEmpty=*/false);
665 rewriter.startOpModification(op);
666 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
667 rewriter.finalizeOpModification(op);
668 }
669 }
670};
671
672class CirctUnclockedAssumeConverter : public IntrinsicConverter {
673public:
674 using IntrinsicConverter::IntrinsicConverter;
675
676 bool check(GenericIntrinsic gi) override {
677 return gi.sizedInput<UIntType>(0, 1) || gi.sizedInput<UIntType>(1, 1) ||
678 gi.namedParam("format", /*optional=*/true) ||
679 gi.namedParam("label", /*optional=*/true) ||
680 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 3) ||
681 gi.hasNoOutput();
682 }
683
684 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
685 PatternRewriter &rewriter) override {
686 auto format = gi.getParamValue<StringAttr>("format");
687 auto label = gi.getParamValue<StringAttr>("label");
688 auto guards = gi.getParamValue<StringAttr>("guards");
689
690 auto predicate = adaptor.getOperands()[0];
691 auto enable = adaptor.getOperands()[1];
692
693 auto substitutions = adaptor.getOperands().drop_front(2);
694 auto name = label ? label.strref() : "";
695 // Message is not optional, so provide empty string if not present.
696 auto message = format ? format : rewriter.getStringAttr("");
697 auto op = rewriter.template replaceOpWithNewOp<UnclockedAssumeIntrinsicOp>(
698 gi.op, predicate, enable, message, substitutions, name);
699 if (guards) {
700 SmallVector<StringRef> guardStrings;
701 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
702 /*KeepEmpty=*/false);
703 rewriter.startOpModification(op);
704 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
705 rewriter.finalizeOpModification(op);
706 }
707 }
708};
709
710class CirctDPICallConverter : public IntrinsicConverter {
711 static bool getIsClocked(GenericIntrinsic gi) {
712 return !gi.getParamValue<IntegerAttr>("isClocked").getValue().isZero();
713 }
714
715public:
716 using IntrinsicConverter::IntrinsicConverter;
717
718 bool check(GenericIntrinsic gi) override {
719 if (gi.hasNParam(2, 2) || gi.namedIntParam("isClocked") ||
720 gi.namedParam("functionName") ||
721 gi.namedParam("inputNames", /*optional=*/true) ||
722 gi.namedParam("outputName", /*optional=*/true))
723 return true;
724 auto isClocked = getIsClocked(gi);
725 // If clocked, the first operand must be a clock.
726 if (isClocked && gi.typedInput<ClockType>(0))
727 return true;
728 // Enable must be UInt<1>.
729 if (gi.sizedInput<UIntType>(isClocked, 1))
730 return true;
731
732 return false;
733 }
734
735 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
736 PatternRewriter &rewriter) override {
737 auto isClocked = getIsClocked(gi);
738 auto functionName = gi.getParamValue<StringAttr>("functionName");
739 ArrayAttr inputNamesStrArray;
740 StringAttr outputStr = gi.getParamValue<StringAttr>("outputName");
741 if (auto inputNames = gi.getParamValue<StringAttr>("inputNames")) {
742 SmallVector<StringRef> inputNamesTemporary;
743 inputNames.strref().split(inputNamesTemporary, ';', /*MaxSplit=*/-1,
744 /*KeepEmpty=*/false);
745 inputNamesStrArray = rewriter.getStrArrayAttr(inputNamesTemporary);
746 }
747 // Clock and enable are optional.
748 Value clock = isClocked ? adaptor.getOperands()[0] : Value();
749 Value enable = adaptor.getOperands()[static_cast<size_t>(isClocked)];
750
751 auto inputs =
752 adaptor.getOperands().drop_front(static_cast<size_t>(isClocked) + 1);
753
754 rewriter.replaceOpWithNewOp<DPICallIntrinsicOp>(
755 gi.op, gi.op.getResultTypes(), functionName, inputNamesStrArray,
756 outputStr, clock, enable, inputs);
757 }
758};
759
760//===----------------------------------------------------------------------===//
761// View intrinsic converter and helpers
762//===----------------------------------------------------------------------===//
763
764template <typename A>
765A tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc,
766 Twine path = Twine()) {
767 return tryGetAsBase<A>(dict, root, key, loc, "View 'info'",
768 "'info' attribute", path);
769}
770
771/// Recursively walk a sifive.enterprise.grandcentral.AugmentedType to extract
772/// and slightly restructure information needed for a view.
773std::optional<DictionaryAttr>
774parseAugmentedType(MLIRContext *context, Location loc,
775 DictionaryAttr augmentedType, DictionaryAttr root,
776 StringAttr name, StringAttr defName,
777 std::optional<StringAttr> description, Twine path = {}) {
778 auto classAttr =
779 tryGetAs<StringAttr>(augmentedType, root, "class", loc, path);
780 if (!classAttr)
781 return std::nullopt;
782 StringRef classBase = classAttr.getValue();
783 if (!classBase.consume_front("sifive.enterprise.grandcentral.Augmented")) {
784 mlir::emitError(loc,
785 "the 'class' was expected to start with "
786 "'sifive.enterprise.grandCentral.Augmented*', but was '" +
787 classAttr.getValue() + "' (Did you misspell it?)")
788 .attachNote()
789 << "see attribute: " << augmentedType;
790 return std::nullopt;
791 }
792
793 // An AugmentedBundleType looks like:
794 // "defName": String
795 // "elements": Seq[AugmentedField]
796 if (classBase == "BundleType") {
797 defName = tryGetAs<StringAttr>(augmentedType, root, "defName", loc, path);
798 if (!defName)
799 return std::nullopt;
800
801 // Each element is an AugmentedField with members:
802 // "name": String
803 // "description": Option[String]
804 // "tpe": AugmentedType
805 SmallVector<Attribute> elements;
806 auto elementsAttr =
807 tryGetAs<ArrayAttr>(augmentedType, root, "elements", loc, path);
808 if (!elementsAttr)
809 return std::nullopt;
810 for (size_t i = 0, e = elementsAttr.size(); i != e; ++i) {
811 auto field = dyn_cast_or_null<DictionaryAttr>(elementsAttr[i]);
812 if (!field) {
813 mlir::emitError(
814 loc,
815 "View 'info' attribute with path '.elements[" + Twine(i) +
816 "]' contained an unexpected type (expected a DictionaryAttr).")
817 .attachNote()
818 << "The received element was: " << elementsAttr[i];
819 return std::nullopt;
820 }
821 auto ePath = (path + ".elements[" + Twine(i) + "]").str();
822 auto name = tryGetAs<StringAttr>(field, root, "name", loc, ePath);
823 if (!name)
824 return std::nullopt;
825 auto tpe = tryGetAs<DictionaryAttr>(field, root, "tpe", loc, ePath);
826 if (!tpe)
827 return std::nullopt;
828 std::optional<StringAttr> description;
829 if (auto maybeDescription = field.get("description"))
830 description = cast<StringAttr>(maybeDescription);
831 auto eltAttr =
832 parseAugmentedType(context, loc, tpe, root, name, defName,
833 description, path + "_" + name.getValue());
834 if (!eltAttr)
835 return std::nullopt;
836
837 // Collect information necessary to build a module with this view later.
838 // This includes the optional description and name.
839 NamedAttrList attrs;
840 if (auto maybeDescription = field.get("description"))
841 attrs.append("description", cast<StringAttr>(maybeDescription));
842 attrs.append("name", name);
843 auto tpeClass = tpe.getAs<StringAttr>("class");
844 if (!tpeClass) {
845 mlir::emitError(loc, "missing 'class' key in") << tpe;
846 return std::nullopt;
847 }
848 attrs.append("tpe", tpeClass);
849 elements.push_back(*eltAttr);
850 }
851 // Add an attribute that stores information necessary to construct the
852 // interface for the view. This needs the name of the interface (defName)
853 // and the names of the components inside it.
854 NamedAttrList attrs;
855 attrs.append("class", classAttr);
856 attrs.append("defName", defName);
857 if (description)
858 attrs.append("description", *description);
859 attrs.append("elements", ArrayAttr::get(context, elements));
860 attrs.append("name", name);
861 return DictionaryAttr::getWithSorted(context, attrs);
862 }
863
864 // An AugmentedGroundType has no contents.
865 if (classBase == "GroundType") {
866 NamedAttrList elementIface;
867
868 // Populate the attribute for the interface element.
869 elementIface.append("class", classAttr);
870 if (description)
871 elementIface.append("description", *description);
872 elementIface.append("name", name);
873
874 return DictionaryAttr::getWithSorted(context, elementIface);
875 }
876
877 // An AugmentedVectorType looks like:
878 // "elements": Seq[AugmentedType]
879 if (classBase == "VectorType") {
880 auto elementsAttr =
881 tryGetAs<ArrayAttr>(augmentedType, root, "elements", loc, path);
882 if (!elementsAttr)
883 return std::nullopt;
884 SmallVector<Attribute> elements;
885 for (auto [i, elt] : llvm::enumerate(elementsAttr)) {
886 auto eltAttr = parseAugmentedType(
887 context, loc, cast<DictionaryAttr>(elt), root, name,
888 StringAttr::get(context, ""), std::nullopt, path + "_" + Twine(i));
889 if (!eltAttr)
890 return std::nullopt;
891 elements.push_back(*eltAttr);
892 }
893 NamedAttrList attrs;
894 attrs.append("class", classAttr);
895 if (description)
896 attrs.append("description", *description);
897 attrs.append("elements", ArrayAttr::get(context, elements));
898 attrs.append("name", name);
899 return DictionaryAttr::getWithSorted(context, attrs);
900 }
901
902 // Anything else is unexpected or a user error if they manually wrote
903 // the JSON/attribute. Print an error and error out.
904 mlir::emitError(loc, "found unknown AugmentedType '" + classAttr.getValue() +
905 "' (Did you misspell it?)")
906 .attachNote()
907 << "see attribute: " << augmentedType;
908 return std::nullopt;
909}
910
911class ViewConverter : public IntrinsicConverter {
912public:
913 LogicalResult checkAndConvert(GenericIntrinsic gi,
914 GenericIntrinsicOpAdaptor adaptor,
915 PatternRewriter &rewriter) override {
916 // Check structure of the intrinsic.
917 if (gi.hasNoOutput() || gi.namedParam("info") || gi.namedParam("name") ||
918 gi.namedParam("yaml", true))
919 return failure();
920
921 // Check operands.
922 for (auto idx : llvm::seq(gi.getNumInputs()))
923 if (gi.checkInputType(idx, "must be ground type", [](auto ty) {
924 auto base = type_dyn_cast<FIRRTLBaseType>(ty);
925 return base && base.isGround();
926 }))
927 return failure();
928
929 // Parse "info" string parameter as JSON.
930 auto view =
931 llvm::json::parse(gi.getParamValue<StringAttr>("info").getValue());
932 if (auto err = view.takeError()) {
933 handleAllErrors(std::move(err), [&](const llvm::json::ParseError &a) {
934 gi.emitError() << ": error parsing view JSON: " << a.message();
935 });
936 return failure();
937 }
938
939 // Convert JSON to MLIR attribute.
940 llvm::json::Path::Root root;
941 auto value = convertJSONToAttribute(gi.op.getContext(), view.get(), root);
942 assert(value && "JSON to attribute failed but should not ever fail");
943
944 // Check attribute is a dictionary, for AugmentedBundleTypeAttr
945 // construction.
946 auto dict = dyn_cast<DictionaryAttr>(value);
947 if (!dict)
948 return gi.emitError() << ": 'info' parameter must be a dictionary";
949
950 auto nameAttr = gi.getParamValue<StringAttr>("name");
951 auto result = parseAugmentedType(
952 gi.op.getContext(), gi.op.getLoc(), dict, dict, nameAttr,
953 /* defName= */ {}, /* description= */ std::nullopt);
954
955 if (!result)
956 return failure();
957
958 // Build AugmentedBundleTypeAttr, unchecked.
959 auto augmentedType =
960 AugmentedBundleTypeAttr::get(gi.op.getContext(), *result);
961 if (augmentedType.getClass() != augmentedBundleTypeAnnoClass)
962 return gi.emitError() << ": 'info' must be augmented bundle";
963
964 // Scan for ground-type (leaves) and count.
965 SmallVector<DictionaryAttr> worklist;
966 worklist.push_back(augmentedType.getUnderlying());
967 size_t numLeaves = 0;
968 auto augGroundAttr =
969 StringAttr::get(gi.op.getContext(), augmentedGroundTypeAnnoClass);
970 [[maybe_unused]] auto augBundleAttr =
971 StringAttr::get(gi.op.getContext(), augmentedBundleTypeAnnoClass);
972 [[maybe_unused]] auto augVectorAttr =
973 StringAttr::get(gi.op.getContext(), augmentedVectorTypeAnnoClass);
974 while (!worklist.empty()) {
975 auto dict = worklist.pop_back_val();
976 auto clazz = dict.getAs<StringAttr>("class");
977 if (clazz == augGroundAttr) {
978 ++numLeaves;
979 continue;
980 }
981 assert(clazz == augBundleAttr || clazz == augVectorAttr);
982 llvm::append_range(
983 worklist,
984 dict.getAs<ArrayAttr>("elements").getAsRange<DictionaryAttr>());
985 }
986
987 if (numLeaves != gi.getNumInputs())
988 return gi.emitError()
989 << " has " << gi.getNumInputs() << " operands but view 'info' has "
990 << numLeaves << " leaf elements";
991
992 // Check complete, convert!
993 auto yaml = gi.getParamValue<StringAttr>("yaml");
994 rewriter.replaceOpWithNewOp<ViewIntrinsicOp>(
995 gi.op, nameAttr.getValue(), yaml, augmentedType, adaptor.getOperands());
996 return success();
997 }
998};
999
1000} // namespace
1001
1002//===----------------------------------------------------------------------===//
1003// FIRRTL intrinsic lowering dialect interface
1004//===----------------------------------------------------------------------===//
1005
1006#include "FIRRTLIntrinsics.cpp.inc"
1007
1009 IntrinsicLowerings &lowering) const {
1010 populateLowerings(lowering);
1011}
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static std::optional< DictionaryAttr > parseAugmentedType(ApplyState &state, DictionaryAttr augmentedType, DictionaryAttr root, StringAttr name, StringAttr defName, std::optional< IntegerAttr > id, std::optional< StringAttr > description, Twine clazz, StringAttr companionAttr, Twine path={})
Recursively walk a sifive.enterprise.grandcentral.AugmentedType to extract any annotations it may con...
static LogicalResult convert(arc::ExecuteOp op, arc::ExecuteOp::Adaptor adaptor, ConversionPatternRewriter &rewriter, const TypeConverter &converter)
Base class for Intrinsic Converters.
Lowering helper which collects all intrinsic converters.
FailureOr< size_t > lower(FModuleOp mod, bool allowUnknownIntrinsics=false)
Lowers all intrinsics in a module. Returns number converted or failure.
llvm::DenseMap< StringAttr, std::unique_ptr< IntrinsicConverter > > ConversionMapTy
MLIRContext * context
Reference to the MLIR context.
ConversionMapTy conversions
Mapping from intrinsic names to converters.
A tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc, Twine clazz, Twine path=Twine())
Implements the same behavior as DictionaryAttr::getAs<A> to return the value of a specific type assoc...
bool areTypesEquivalent(FIRRTLType destType, FIRRTLType srcType, bool destOuterTypeIsConst=false, bool srcOuterTypeIsConst=false, bool requireSameWidths=false)
Returns whether the two types are equivalent.
bool isTypeLarger(FIRRTLBaseType dstType, FIRRTLBaseType srcType)
Returns true if the destination is at least as wide as a source.
mlir::ParseResult parseFormatString(mlir::OpBuilder &builder, mlir::Location loc, llvm::StringRef formatString, llvm::ArrayRef< mlir::Value > specOperands, mlir::StringAttr &formatStringResult, llvm::SmallVectorImpl< mlir::Value > &operands)
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs)
Emit a connect between two values.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Attribute convertJSONToAttribute(MLIRContext *context, llvm::json::Value &value, llvm::json::Path p)
Convert arbitrary JSON to an MLIR Attribute.
Definition seq.py:1
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const override
Helper class for checking and extracting information from the generic instrinsic op.
ParseResult sizedInput(unsigned n, int32_t size)
mlir::TypedValue< BundleType > getOutputBundle()
T getParamValue(StringRef name)
Get parameter value by name, if present, as requested type.
ParseResult hasResetInput(unsigned n)
ParseResult typedInput(unsigned n)
ParseResult hasNOutputElements(unsigned n)
ParseResult namedIntParam(StringRef paramName, bool optional=false)
ParseResult namedParam(StringRef paramName, bool optional=false)
ParseResult sizedOutput(int32_t size)
ParseResult sizedOutputElement(unsigned n, StringRef name, int32_t size)
ParseResult hasNParam(unsigned n, unsigned c=0)
ParseResult hasOutputElement(unsigned n, StringRef name)
ParseResult hasNInputs(unsigned n, unsigned c=0)
A dialect interface to provide lowering conversions.
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const