CIRCT 23.0.0git
Loading...
Searching...
No Matches
InferWidths.cpp
Go to the documentation of this file.
1//===- InferWidths.cpp - Infer width of types -------------------*- 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//
9// This file defines the InferWidths pass.
10//
11//===----------------------------------------------------------------------===//
12
17#include "circt/Support/Debug.h"
19#include "mlir/IR/Threading.h"
20#include "mlir/Pass/Pass.h"
21#include "llvm/ADT/APSInt.h"
22#include "llvm/ADT/DenseSet.h"
23#include "llvm/ADT/Hashing.h"
24#include "llvm/ADT/SetVector.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ErrorHandling.h"
27
28#define DEBUG_TYPE "infer-widths"
29
30namespace circt {
31namespace firrtl {
32#define GEN_PASS_DEF_INFERWIDTHS
33#include "circt/Dialect/FIRRTL/Passes.h.inc"
34} // namespace firrtl
35} // namespace circt
36
37using mlir::InferTypeOpInterface;
38using mlir::WalkOrder;
39
40using namespace circt;
41using namespace firrtl;
42
43//===----------------------------------------------------------------------===//
44// Helpers
45//===----------------------------------------------------------------------===//
46
47static void diagnoseUninferredType(InFlightDiagnostic &diag, Type t,
48 Twine str) {
49 auto basetype = type_dyn_cast<FIRRTLBaseType>(t);
50 if (!basetype)
51 return;
52 if (!basetype.hasUninferredWidth())
53 return;
54
55 if (basetype.isGround())
56 diag.attachNote() << "Field: \"" << str << "\"";
57 else if (auto vecType = type_dyn_cast<FVectorType>(basetype))
58 diagnoseUninferredType(diag, vecType.getElementType(), str + "[]");
59 else if (auto bundleType = type_dyn_cast<BundleType>(basetype))
60 for (auto &elem : bundleType.getElements())
61 diagnoseUninferredType(diag, elem.type, str + "." + elem.name.getValue());
62}
63
64/// Calculate the "InferWidths-fieldID" equivalent for the given fieldID + type.
65static uint64_t convertFieldIDToOurVersion(uint64_t fieldID, FIRRTLType type) {
66 uint64_t convertedFieldID = 0;
67
68 auto curFID = fieldID;
69 Type curFType = type;
70 while (curFID != 0) {
71 auto [child, subID] =
73 if (isa<FVectorType>(curFType))
74 convertedFieldID++; // Vector fieldID is 1.
75 else
76 convertedFieldID += curFID - subID; // Add consumed portion.
77 curFID = subID;
78 curFType = child;
79 }
80
81 return convertedFieldID;
82}
83
84//===----------------------------------------------------------------------===//
85// Constraint Expressions
86//===----------------------------------------------------------------------===//
87
88namespace {
89struct Expr;
90} // namespace
91
92/// Allow rvalue refs to `Expr` and subclasses to be printed to streams.
93template <typename T, typename std::enable_if<std::is_base_of<Expr, T>::value,
94 int>::type = 0>
95inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const T &e) {
96 e.print(os);
97 return os;
98}
99
100// Allow expression subclasses to be hashed.
101namespace mlir {
102template <typename T, typename std::enable_if<std::is_base_of<Expr, T>::value,
103 int>::type = 0>
104inline llvm::hash_code hash_value(const T &e) {
105 return e.hash_value();
106}
107} // namespace mlir
108
109namespace {
110#define EXPR_NAMES(x) \
111 Var##x, Derived##x, Id##x, Known##x, Add##x, Pow##x, Max##x, Min##x
112#define EXPR_KINDS EXPR_NAMES()
113#define EXPR_CLASSES EXPR_NAMES(Expr)
114
115/// An expression on the right-hand side of a constraint.
116struct Expr {
117 enum class Kind : uint8_t { EXPR_KINDS };
118
119 /// Print a human-readable representation of this expr.
120 void print(llvm::raw_ostream &os) const;
121
122 std::optional<int32_t> getSolution() const {
123 if (hasSolution)
124 return solution;
125 return std::nullopt;
126 }
127
128 void setSolution(int32_t solution) {
129 hasSolution = true;
130 this->solution = solution;
131 }
132
133 Kind getKind() const { return kind; }
134
135protected:
136 Expr(Kind kind) : kind(kind) {}
137 llvm::hash_code hash_value() const { return llvm::hash_value(kind); }
138
139private:
140 int32_t solution;
141 Kind kind;
142 bool hasSolution = false;
143};
144
145/// Helper class to CRTP-derive common functions.
146template <class DerivedT, Expr::Kind DerivedKind>
147struct ExprBase : public Expr {
148 ExprBase() : Expr(DerivedKind) {}
149 static bool classof(const Expr *e) { return e->getKind() == DerivedKind; }
150 bool operator==(const Expr &other) const {
151 if (auto otherSame = dyn_cast<DerivedT>(other))
152 return *static_cast<DerivedT *>(this) == otherSame;
153 return false;
154 }
155};
156
157/// A free variable.
158struct VarExpr : public ExprBase<VarExpr, Expr::Kind::Var> {
159 void print(llvm::raw_ostream &os) const {
160 // Hash the `this` pointer into something somewhat human readable. Since
161 // this is just for debug dumping, we wrap around at 65536 variables.
162 os << "var" << ((size_t)this / llvm::PowerOf2Ceil(sizeof(*this)) & 0xFFFF);
163 }
164
165 /// The constraint expression this variable is supposed to be greater than or
166 /// equal to. This is not part of the variable's hash and equality property.
167 Expr *constraint = nullptr;
168
169 /// The upper bound this variable is supposed to be smaller than or equal to.
170 Expr *upperBound = nullptr;
171 std::optional<int32_t> upperBoundSolution;
172};
173
174/// A derived width.
175///
176/// These are generated for `InvalidValueOp`s which want to derived their width
177/// from connect operations that they are on the right hand side of.
178struct DerivedExpr : public ExprBase<DerivedExpr, Expr::Kind::Derived> {
179 void print(llvm::raw_ostream &os) const {
180 // Hash the `this` pointer into something somewhat human readable.
181 os << "derive"
182 << ((size_t)this / llvm::PowerOf2Ceil(sizeof(*this)) & 0xFFF);
183 }
184
185 /// The expression this derived width is equivalent to.
186 Expr *assigned = nullptr;
187};
188
189/// An identity expression.
190///
191/// This expression evaluates to its inner expression. It is used in a very
192/// specific case of constraints on variables, in order to be able to track
193/// where the constraint was imposed. Constraints on variables are represented
194/// as `var >= <expr>`. When the first constraint `a` is imposed, it is stored
195/// as the constraint expression (`var >= a`). When the second constraint `b` is
196/// imposed, a *new* max expression is allocated (`var >= max(a, b)`).
197/// Expressions are annotated with a location when they are created, which in
198/// this case are connect ops. Since imposing the first constraint does not
199/// create any new expression, the location information of that connect would be
200/// lost. With an identity expression, imposing the first constraint becomes
201/// `var >= identity(a)`, which is a *new* expression and properly tracks the
202/// location info.
203struct IdExpr : public ExprBase<IdExpr, Expr::Kind::Id> {
204 IdExpr(Expr *arg) : arg(arg) { assert(arg); }
205 void print(llvm::raw_ostream &os) const { os << "*" << *arg; }
206 bool operator==(const IdExpr &other) const {
207 return getKind() == other.getKind() && arg == other.arg;
208 }
209 llvm::hash_code hash_value() const {
210 return llvm::hash_combine(Expr::hash_value(), arg);
211 }
212
213 /// The inner expression.
214 Expr *const arg;
215};
216
217/// A known constant value.
218struct KnownExpr : public ExprBase<KnownExpr, Expr::Kind::Known> {
219 KnownExpr(int32_t value) : ExprBase() { setSolution(value); }
220 void print(llvm::raw_ostream &os) const { os << *getSolution(); }
221 bool operator==(const KnownExpr &other) const {
222 return *getSolution() == *other.getSolution();
223 }
224 llvm::hash_code hash_value() const {
225 return llvm::hash_combine(Expr::hash_value(), *getSolution());
226 }
227 int32_t getValue() const { return *getSolution(); }
228};
229
230/// A unary expression. Contains the actual data. Concrete subclasses are merely
231/// there for show and ease of use.
232struct UnaryExpr : public Expr {
233 bool operator==(const UnaryExpr &other) const {
234 return getKind() == other.getKind() && arg == other.arg;
235 }
236 llvm::hash_code hash_value() const {
237 return llvm::hash_combine(Expr::hash_value(), arg);
238 }
239
240 /// The child expression.
241 Expr *const arg;
242
243protected:
244 UnaryExpr(Kind kind, Expr *arg) : Expr(kind), arg(arg) { assert(arg); }
245};
246
247/// Helper class to CRTP-derive common functions.
248template <class DerivedT, Expr::Kind DerivedKind>
249struct UnaryExprBase : public UnaryExpr {
250 template <typename... Args>
251 UnaryExprBase(Args &&...args)
252 : UnaryExpr(DerivedKind, std::forward<Args>(args)...) {}
253 static bool classof(const Expr *e) { return e->getKind() == DerivedKind; }
254};
255
256/// A power of two.
257struct PowExpr : public UnaryExprBase<PowExpr, Expr::Kind::Pow> {
258 using UnaryExprBase::UnaryExprBase;
259 void print(llvm::raw_ostream &os) const { os << "2^" << arg; }
260};
261
262/// A binary expression. Contains the actual data. Concrete subclasses are
263/// merely there for show and ease of use.
264struct BinaryExpr : public Expr {
265 bool operator==(const BinaryExpr &other) const {
266 return getKind() == other.getKind() && lhs() == other.lhs() &&
267 rhs() == other.rhs();
268 }
269 llvm::hash_code hash_value() const {
270 return llvm::hash_combine(Expr::hash_value(), *args);
271 }
272 Expr *lhs() const { return args[0]; }
273 Expr *rhs() const { return args[1]; }
274
275 /// The child expressions.
276 Expr *const args[2];
277
278protected:
279 BinaryExpr(Kind kind, Expr *lhs, Expr *rhs) : Expr(kind), args{lhs, rhs} {
280 assert(lhs);
281 assert(rhs);
282 }
283};
284
285/// Helper class to CRTP-derive common functions.
286template <class DerivedT, Expr::Kind DerivedKind>
287struct BinaryExprBase : public BinaryExpr {
288 template <typename... Args>
289 BinaryExprBase(Args &&...args)
290 : BinaryExpr(DerivedKind, std::forward<Args>(args)...) {}
291 static bool classof(const Expr *e) { return e->getKind() == DerivedKind; }
292};
293
294/// An addition.
295struct AddExpr : public BinaryExprBase<AddExpr, Expr::Kind::Add> {
296 using BinaryExprBase::BinaryExprBase;
297 void print(llvm::raw_ostream &os) const {
298 os << "(" << *lhs() << " + " << *rhs() << ")";
299 }
300};
301
302/// The maximum of two expressions.
303struct MaxExpr : public BinaryExprBase<MaxExpr, Expr::Kind::Max> {
304 using BinaryExprBase::BinaryExprBase;
305 void print(llvm::raw_ostream &os) const {
306 os << "max(" << *lhs() << ", " << *rhs() << ")";
307 }
308};
309
310/// The minimum of two expressions.
311struct MinExpr : public BinaryExprBase<MinExpr, Expr::Kind::Min> {
312 using BinaryExprBase::BinaryExprBase;
313 void print(llvm::raw_ostream &os) const {
314 os << "min(" << *lhs() << ", " << *rhs() << ")";
315 }
316};
317
318void Expr::print(llvm::raw_ostream &os) const {
319 TypeSwitch<const Expr *>(this).Case<EXPR_CLASSES>(
320 [&](auto *e) { e->print(os); });
321}
322
323} // namespace
324
325//===----------------------------------------------------------------------===//
326// Fast bump allocator with optional interning
327//===----------------------------------------------------------------------===//
328
329namespace {
330
331// Hash slots in the interned allocator as if they were the pointed-to value
332// itself.
333template <typename T>
334struct InternedSlotInfo : DenseMapInfo<T *> {
335 static unsigned getHashValue(const T *val) { return mlir::hash_value(*val); }
336 static bool isEqual(const T *lhs, const T *rhs) {
337 if (!lhs || !rhs)
338 return lhs == rhs;
339 return *lhs == *rhs;
340 }
341};
342
343/// A simple bump allocator that ensures only ever one copy per object exists.
344/// The allocated objects must not have a destructor.
345template <typename T, typename std::enable_if_t<
346 std::is_trivially_destructible<T>::value, int> = 0>
347class InternedAllocator {
348 llvm::DenseSet<T *, InternedSlotInfo<T>> interned;
349 llvm::BumpPtrAllocator &allocator;
350
351public:
352 InternedAllocator(llvm::BumpPtrAllocator &allocator) : allocator(allocator) {}
353
354 /// Allocate a new object if it does not yet exist, or return a pointer to the
355 /// existing one. `R` is the type of the object to be allocated. `R` must be
356 /// derived from or be the type `T`.
357 template <typename R = T, typename... Args>
358 std::pair<R *, bool> alloc(Args &&...args) {
359 auto stackValue = R(std::forward<Args>(args)...);
360 auto *stackSlot = &stackValue;
361 auto it = interned.find(stackSlot);
362 if (it != interned.end())
363 return std::make_pair(static_cast<R *>(*it), false);
364 auto heapValue = new (allocator) R(std::move(stackValue));
365 interned.insert(heapValue);
366 return std::make_pair(heapValue, true);
367 }
368};
369
370/// A simple bump allocator. The allocated objects must not have a destructor.
371/// This allocator is mainly there for symmetry with the `InternedAllocator`.
372template <typename T, typename std::enable_if_t<
373 std::is_trivially_destructible<T>::value, int> = 0>
374class Allocator {
375 llvm::BumpPtrAllocator &allocator;
376
377public:
378 Allocator(llvm::BumpPtrAllocator &allocator) : allocator(allocator) {}
379
380 /// Allocate a new object. `R` is the type of the object to be allocated. `R`
381 /// must be derived from or be the type `T`.
382 template <typename R = T, typename... Args>
383 R *alloc(Args &&...args) {
384 return new (allocator) R(std::forward<Args>(args)...);
385 }
386};
387
388} // namespace
389
390//===----------------------------------------------------------------------===//
391// Constraint Solver
392//===----------------------------------------------------------------------===//
393
394namespace {
395/// A canonicalized linear inequality that maps a constraint on var `x` to the
396/// linear inequality `x >= max(a*x+b, c) + (failed ? ∞ : 0)`.
397///
398/// The inequality separately tracks recursive (a, b) and non-recursive (c)
399/// constraints on `x`. This allows it to properly identify the combination of
400/// the two constraints `x >= x-1` and `x >= 4` to be satisfiable as
401/// `x >= max(x-1, 4)`. If it only tracked inequality as `x >= a*x+b`, the
402/// combination of these two constraints would be `x >= x+4` (due to max(-1,4) =
403/// 4), which would be unsatisfiable.
404///
405/// The `failed` flag acts as an additional `∞` term that renders the inequality
406/// unsatisfiable. It is used as a tombstone value in case an operation renders
407/// the equality unsatisfiable (e.g. `x >= 2**x` would be represented as the
408/// inequality `x >= ∞`).
409///
410/// Inequalities represented in this form can easily be checked for
411/// unsatisfiability in the presence of recursion by inspecting the coefficients
412/// a and b. The `sat` function performs this action.
413struct LinIneq {
414 // x >= max(a*x+b, c) + (failed ? ∞ : 0)
415 int32_t recScale = 0; // a
416 int32_t recBias = 0; // b
417 int32_t nonrecBias = 0; // c
418 bool failed = false;
419
420 /// Create a new unsatisfiable inequality `x >= ∞`.
421 static LinIneq unsat() { return LinIneq(true); }
422
423 /// Create a new inequality `x >= (failed ? ∞ : 0)`.
424 explicit LinIneq(bool failed = false) : failed(failed) {}
425
426 /// Create a new inequality `x >= bias`.
427 explicit LinIneq(int32_t bias) : nonrecBias(bias) {}
428
429 /// Create a new inequality `x >= scale*x+bias`.
430 explicit LinIneq(int32_t scale, int32_t bias) {
431 if (scale != 0) {
432 recScale = scale;
433 recBias = bias;
434 } else {
435 nonrecBias = bias;
436 }
437 }
438
439 /// Create a new inequality `x >= max(recScale*x+recBias, nonrecBias) +
440 /// (failed ? ∞ : 0)`.
441 explicit LinIneq(int32_t recScale, int32_t recBias, int32_t nonrecBias,
442 bool failed = false)
443 : failed(failed) {
444 if (recScale != 0) {
445 this->recScale = recScale;
446 this->recBias = recBias;
447 this->nonrecBias = nonrecBias;
448 } else {
449 this->nonrecBias = std::max(recBias, nonrecBias);
450 }
451 }
452
453 /// Combine two inequalities by taking the maxima of corresponding
454 /// coefficients.
455 ///
456 /// This essentially combines `x >= max(a1*x+b1, c1)` and `x >= max(a2*x+b2,
457 /// c2)` into a new `x >= max(max(a1,a2)*x+max(b1,b2), max(c1,c2))`. This is
458 /// a pessimistic upper bound, since e.g. `x >= 2x-10` and `x >= x-5` may both
459 /// hold, but the resulting `x >= 2x-5` may pessimistically not hold.
460 static LinIneq max(const LinIneq &lhs, const LinIneq &rhs) {
461 return LinIneq(std::max(lhs.recScale, rhs.recScale),
462 std::max(lhs.recBias, rhs.recBias),
463 std::max(lhs.nonrecBias, rhs.nonrecBias),
464 lhs.failed || rhs.failed);
465 }
466
467 /// Combine two inequalities by summing up the two right hand sides.
468 ///
469 /// This is a tricky one, since the addition of the two max terms will lead to
470 /// a maximum over four possible terms (similar to a binomial expansion). In
471 /// order to shoehorn this back into a two-term maximum, we have to pick the
472 /// recursive term that will grow the fastest.
473 ///
474 /// As an example for this problem, consider the following addition:
475 ///
476 /// x >= max(a1*x+b1, c1) + max(a2*x+b2, c2)
477 ///
478 /// We would like to expand and rearrange this again into a maximum:
479 ///
480 /// x >= max(a1*x+b1 + max(a2*x+b2, c2), c1 + max(a2*x+b2, c2))
481 /// x >= max(max(a1*x+b1 + a2*x+b2, a1*x+b1 + c2),
482 /// max(c1 + a2*x+b2, c1 + c2))
483 /// x >= max((a1+a2)*x+(b1+b2), a1*x+(b1+c2), a2*x+(b2+c1), c1+c2)
484 ///
485 /// Since we are combining two two-term maxima, there are four possible ways
486 /// how the terms can combine, leading to the above four-term maximum. An easy
487 /// upper bound of the form we want would be the following:
488 ///
489 /// x >= max(max(a1+a2, a1, a2)*x + max(b1+b2, b1+c2, b2+c1), c1+c2)
490 ///
491 /// However, this is a very pessimistic upper-bound that will declare very
492 /// common patterns in the IR as unbreakable cycles, despite them being very
493 /// much breakable. For example:
494 ///
495 /// x >= max(x, 42) + max(0, -3) <-- breakable recursion
496 /// x >= max(max(1+0, 1, 0)*x + max(42+0, -3, 42), 42-2)
497 /// x >= max(x + 42, 39) <-- unbreakable recursion!
498 ///
499 /// A better approach is to take the expanded four-term maximum, retain the
500 /// non-recursive term (c1+c2), and estimate which one of the recursive terms
501 /// (first three) will become dominant as we choose greater values for x.
502 /// Since x never is inferred to be negative, the recursive term in the
503 /// maximum with the highest scaling factor for x will end up dominating as
504 /// x tends to ∞:
505 ///
506 /// x >= max({
507 /// (a1+a2)*x+(b1+b2) if a1+a2 >= max(a1+a2, a1, a2) and a1>0 and a2>0,
508 /// a1*x+(b1+c2) if a1 >= max(a1+a2, a1, a2) and a1>0,
509 /// a2*x+(b2+c1) if a2 >= max(a1+a2, a1, a2) and a2>0,
510 /// 0 otherwise
511 /// }, c1+c2)
512 ///
513 /// In case multiple cases apply, the highest bias of the recursive term is
514 /// picked. With this, the above problematic example triggers the second case
515 /// and becomes:
516 ///
517 /// x >= max(1*x+(0-3), 42-3) = max(x-3, 39)
518 ///
519 /// Of which the first case is chosen, as it has the lower bias value.
520 static LinIneq add(const LinIneq &lhs, const LinIneq &rhs) {
521 // Determine the maximum scaling factor among the three possible recursive
522 // terms.
523 auto enable1 = lhs.recScale > 0 && rhs.recScale > 0;
524 auto enable2 = lhs.recScale > 0;
525 auto enable3 = rhs.recScale > 0;
526 auto scale1 = lhs.recScale + rhs.recScale; // (a1+a2)
527 auto scale2 = lhs.recScale; // a1
528 auto scale3 = rhs.recScale; // a2
529 auto bias1 = lhs.recBias + rhs.recBias; // (b1+b2)
530 auto bias2 = lhs.recBias + rhs.nonrecBias; // (b1+c2)
531 auto bias3 = rhs.recBias + lhs.nonrecBias; // (b2+c1)
532 auto maxScale = std::max(scale1, std::max(scale2, scale3));
533
534 // Among those terms that have a maximum scaling factor, determine the
535 // largest bias value.
536 std::optional<int32_t> maxBias;
537 if (enable1 && scale1 == maxScale)
538 maxBias = bias1;
539 if (enable2 && scale2 == maxScale && (!maxBias || bias2 > *maxBias))
540 maxBias = bias2;
541 if (enable3 && scale3 == maxScale && (!maxBias || bias3 > *maxBias))
542 maxBias = bias3;
543
544 // Pick from the recursive terms the one with maximum scaling factor and
545 // minimum bias value.
546 auto nonrecBias = lhs.nonrecBias + rhs.nonrecBias; // c1+c2
547 auto failed = lhs.failed || rhs.failed;
548 if (enable1 && scale1 == maxScale && bias1 == *maxBias)
549 return LinIneq(scale1, bias1, nonrecBias, failed);
550 if (enable2 && scale2 == maxScale && bias2 == *maxBias)
551 return LinIneq(scale2, bias2, nonrecBias, failed);
552 if (enable3 && scale3 == maxScale && bias3 == *maxBias)
553 return LinIneq(scale3, bias3, nonrecBias, failed);
554 return LinIneq(0, 0, nonrecBias, failed);
555 }
556
557 /// Check if the inequality is satisfiable.
558 ///
559 /// The inequality becomes unsatisfiable if the RHS is ∞, or a>1, or a==1 and
560 /// b <= 0. Otherwise there exists as solution for `x` that satisfies the
561 /// inequality.
562 bool sat() const {
563 if (failed)
564 return false;
565 if (recScale > 1)
566 return false;
567 if (recScale == 1 && recBias > 0)
568 return false;
569 return true;
570 }
571
572 /// Dump the inequality in human-readable form.
573 void print(llvm::raw_ostream &os) const {
574 bool any = false;
575 bool both = (recScale != 0 || recBias != 0) && nonrecBias != 0;
576 os << "x >= ";
577 if (both)
578 os << "max(";
579 if (recScale != 0) {
580 any = true;
581 if (recScale != 1)
582 os << recScale << "*";
583 os << "x";
584 }
585 if (recBias != 0) {
586 if (any) {
587 if (recBias < 0)
588 os << " - " << -recBias;
589 else
590 os << " + " << recBias;
591 } else {
592 any = true;
593 os << recBias;
594 }
595 }
596 if (both)
597 os << ", ";
598 if (nonrecBias != 0) {
599 any = true;
600 os << nonrecBias;
601 }
602 if (both)
603 os << ")";
604 if (failed) {
605 if (any)
606 os << " + ";
607 os << "∞";
608 }
609 if (!any)
610 os << "0";
611 }
612};
613
614/// A simple solver for width constraints.
615class ConstraintSolver {
616public:
617 ConstraintSolver() = default;
618
619 VarExpr *var() {
620 auto *v = vars.alloc();
621 varExprs.push_back(v);
622 if (currentInfo)
623 info[v].insert(currentInfo);
624 if (currentLoc)
625 locs[v].insert(*currentLoc);
626 return v;
627 }
628 DerivedExpr *derived() {
629 auto *d = derivs.alloc();
630 derivedExprs.push_back(d);
631 return d;
632 }
633 KnownExpr *known(int32_t value) { return alloc<KnownExpr>(knowns, value); }
634 IdExpr *id(Expr *arg) { return alloc<IdExpr>(ids, arg); }
635 PowExpr *pow(Expr *arg) { return alloc<PowExpr>(uns, arg); }
636 AddExpr *add(Expr *lhs, Expr *rhs) { return alloc<AddExpr>(bins, lhs, rhs); }
637 MaxExpr *max(Expr *lhs, Expr *rhs) { return alloc<MaxExpr>(bins, lhs, rhs); }
638 MinExpr *min(Expr *lhs, Expr *rhs) { return alloc<MinExpr>(bins, lhs, rhs); }
639
640 /// Add a constraint `lhs >= rhs`. Multiple constraints on the same variable
641 /// are coalesced into a `max(a, b)` expr.
642 Expr *addGeqConstraint(VarExpr *lhs, Expr *rhs) {
643 if (lhs->constraint)
644 lhs->constraint = max(lhs->constraint, rhs);
645 else
646 lhs->constraint = id(rhs);
647 return lhs->constraint;
648 }
649
650 /// Add a constraint `lhs <= rhs`. Multiple constraints on the same variable
651 /// are coalesced into a `min(a, b)` expr.
652 Expr *addLeqConstraint(VarExpr *lhs, Expr *rhs) {
653 if (lhs->upperBound)
654 lhs->upperBound = min(lhs->upperBound, rhs);
655 else
656 lhs->upperBound = id(rhs);
657 return lhs->upperBound;
658 }
659
660 void dumpConstraints(llvm::raw_ostream &os);
661 LogicalResult solve();
662
663 using ContextInfo = DenseMap<Expr *, llvm::SmallSetVector<FieldRef, 1>>;
664 const ContextInfo &getContextInfo() const { return info; }
665 void setCurrentContextInfo(FieldRef fieldRef) { currentInfo = fieldRef; }
666 void setCurrentLocation(std::optional<Location> loc) { currentLoc = loc; }
667
668private:
669 // Allocator for constraint expressions.
670 llvm::BumpPtrAllocator allocator;
671 Allocator<VarExpr> vars = {allocator};
672 Allocator<DerivedExpr> derivs = {allocator};
673 InternedAllocator<KnownExpr> knowns = {allocator};
674 InternedAllocator<IdExpr> ids = {allocator};
675 InternedAllocator<UnaryExpr> uns = {allocator};
676 InternedAllocator<BinaryExpr> bins = {allocator};
677
678 /// A list of expressions in the order they were created.
679 std::vector<VarExpr *> varExprs;
680 std::vector<DerivedExpr *> derivedExprs;
681
682 /// Add an allocated expression to the list above.
683 template <typename R, typename T, typename... Args>
684 R *alloc(InternedAllocator<T> &allocator, Args &&...args) {
685 auto [expr, inserted] =
686 allocator.template alloc<R>(std::forward<Args>(args)...);
687 if (currentInfo)
688 info[expr].insert(currentInfo);
689 if (currentLoc)
690 locs[expr].insert(*currentLoc);
691 return expr;
692 }
693
694 /// Contextual information for each expression, indicating which values in the
695 /// IR lead to this expression.
696 ContextInfo info;
697 FieldRef currentInfo = {};
698 DenseMap<Expr *, llvm::SmallSetVector<Location, 1>> locs;
699 std::optional<Location> currentLoc;
700
701 // Forbid copyign or moving the solver, which would invalidate the refs to
702 // allocator held by the allocators.
703 ConstraintSolver(ConstraintSolver &&) = delete;
704 ConstraintSolver(const ConstraintSolver &) = delete;
705 ConstraintSolver &operator=(ConstraintSolver &&) = delete;
706 ConstraintSolver &operator=(const ConstraintSolver &) = delete;
707
708 void emitUninferredWidthError(VarExpr *var);
709
710 LinIneq checkCycles(VarExpr *var, Expr *expr,
711 SmallPtrSetImpl<Expr *> &seenVars,
712 InFlightDiagnostic *reportInto = nullptr,
713 unsigned indent = 1);
714};
715
716} // namespace
717
718/// Print all constraints in the solver to an output stream.
719void ConstraintSolver::dumpConstraints(llvm::raw_ostream &os) {
720 for (auto *v : varExprs) {
721 if (v->constraint)
722 os << "- " << *v << " >= " << *v->constraint << "\n";
723 else
724 os << "- " << *v << " unconstrained\n";
725 }
726}
727
728#ifndef NDEBUG
729inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const LinIneq &l) {
730 l.print(os);
731 return os;
732}
733#endif
734
735/// Compute the canonicalized linear inequality expression starting at `expr`,
736/// for the `var` as the left hand side `x` of the inequality. `seenVars` is
737/// used as a recursion breaker. Occurrences of `var` itself within the
738/// expression are mapped to the `a` coefficient in the inequality. Any other
739/// variables are substituted and, in the presence of a recursion in a variable
740/// other than `var`, treated as zero. `info` is a mapping from constraint
741/// expressions to values and operations that produced the expression, and is
742/// used during error reporting. If `reportInto` is present, the function will
743/// additionally attach unsatisfiable inequalities as notes to the diagnostic as
744/// it encounters them.
745LinIneq ConstraintSolver::checkCycles(VarExpr *var, Expr *expr,
746 SmallPtrSetImpl<Expr *> &seenVars,
747 InFlightDiagnostic *reportInto,
748 unsigned indent) {
749 auto ineq =
750 TypeSwitch<Expr *, LinIneq>(expr)
751 .Case<KnownExpr>(
752 [&](auto *expr) { return LinIneq(expr->getValue()); })
753 .Case<VarExpr>([&](auto *expr) {
754 if (expr == var)
755 return LinIneq(1, 0); // x >= 1*x + 0
756 if (!seenVars.insert(expr).second)
757 // Count recursions in other variables as 0. This is sane
758 // since the cycle is either breakable, in which case the
759 // recursion does not modify the resulting value of the
760 // variable, or it is not breakable and will be caught by
761 // this very function once it is called on that variable.
762 return LinIneq(0);
763 if (!expr->constraint)
764 // Count unconstrained variables as `x >= 0`.
765 return LinIneq(0);
766 auto l = checkCycles(var, expr->constraint, seenVars, reportInto,
767 indent + 1);
768 seenVars.erase(expr);
769 return l;
770 })
771 .Case<IdExpr>([&](auto *expr) {
772 return checkCycles(var, expr->arg, seenVars, reportInto,
773 indent + 1);
774 })
775 .Case<PowExpr>([&](auto *expr) {
776 // If we can evaluate `2**arg` to a sensible constant, do
777 // so. This is the case if a == 0 and c < 31 such that 2**c is
778 // representable.
779 auto arg =
780 checkCycles(var, expr->arg, seenVars, reportInto, indent + 1);
781 if (arg.recScale != 0 || arg.nonrecBias < 0 || arg.nonrecBias >= 31)
782 return LinIneq::unsat();
783 return LinIneq(1 << arg.nonrecBias); // x >= 2**arg
784 })
785 .Case<AddExpr>([&](auto *expr) {
786 return LinIneq::add(
787 checkCycles(var, expr->lhs(), seenVars, reportInto, indent + 1),
788 checkCycles(var, expr->rhs(), seenVars, reportInto,
789 indent + 1));
790 })
791 .Case<MaxExpr, MinExpr>([&](auto *expr) {
792 // Combine the inequalities of the LHS and RHS into a single overly
793 // pessimistic inequality. We treat `MinExpr` the same as `MaxExpr`,
794 // since `max(a,b)` is an upper bound to `min(a,b)`.
795 return LinIneq::max(
796 checkCycles(var, expr->lhs(), seenVars, reportInto, indent + 1),
797 checkCycles(var, expr->rhs(), seenVars, reportInto,
798 indent + 1));
799 })
800 .Default([](auto) { return LinIneq::unsat(); });
801
802 // If we were passed an in-flight diagnostic and the current inequality is
803 // unsatisfiable, attach notes to the diagnostic indicating the values or
804 // operations that contributed to this part of the constraint expression.
805 if (reportInto && !ineq.sat()) {
806 auto report = [&](Location loc) {
807 auto &note = reportInto->attachNote(loc);
808 note << "constrained width W >= ";
809 if (ineq.recScale == -1)
810 note << "-";
811 if (ineq.recScale != 1)
812 note << ineq.recScale;
813 note << "W";
814 if (ineq.recBias < 0)
815 note << "-" << -ineq.recBias;
816 if (ineq.recBias > 0)
817 note << "+" << ineq.recBias;
818 note << " here:";
819 };
820 auto it = locs.find(expr);
821 if (it != locs.end())
822 for (auto loc : it->second)
823 report(loc);
824 }
825 if (!reportInto)
826 LLVM_DEBUG(llvm::dbgs().indent(indent * 2)
827 << "- Visited " << *expr << ": " << ineq << "\n");
828
829 return ineq;
830}
831
832using ExprSolution = std::pair<std::optional<int32_t>, bool>;
833
834static ExprSolution
835computeUnary(ExprSolution arg, llvm::function_ref<int32_t(int32_t)> operation) {
836 if (arg.first)
837 arg.first = operation(*arg.first);
838 return arg;
839}
840
841static ExprSolution
843 llvm::function_ref<int32_t(int32_t, int32_t)> operation) {
844 auto result = ExprSolution{std::nullopt, lhs.second || rhs.second};
845 if (lhs.first && rhs.first)
846 result.first = operation(*lhs.first, *rhs.first);
847 else if (lhs.first)
848 result.first = lhs.first;
849 else if (rhs.first)
850 result.first = rhs.first;
851 return result;
852}
853
854namespace {
855struct Frame {
856 Frame(Expr *expr, unsigned indent) : expr(expr), indent(indent) {}
857 Expr *expr;
858 // Indent is only used for debug logs.
859 unsigned indent;
860};
861} // namespace
862
863/// Compute the value of a constraint `expr`. `seenVars` is used as a recursion
864/// breaker. Recursive variables are treated as zero. Returns the computed value
865/// and a boolean indicating whether a recursion was detected. This may be used
866/// to memoize the result of expressions in case they were not involved in a
867/// cycle (which may alter their value from the perspective of a variable).
868static ExprSolution solveExpr(Expr *expr, SmallPtrSetImpl<Expr *> &seenVars,
869 std::vector<Frame> &worklist) {
870 worklist.clear();
871 worklist.emplace_back(expr, 1);
872 llvm::DenseMap<Expr *, ExprSolution> solvedExprs;
873
874 while (!worklist.empty()) {
875 auto &frame = worklist.back();
876 auto indent = frame.indent;
877 auto setSolution = [&](ExprSolution solution) {
878 // Memoize the result.
879 if (solution.first && !solution.second)
880 frame.expr->setSolution(*solution.first);
881 solvedExprs[frame.expr] = solution;
882
883 // Produce some useful debug prints.
884 LLVM_DEBUG({
885 if (!isa<KnownExpr>(frame.expr)) {
886 if (solution.first)
887 llvm::dbgs().indent(indent * 2)
888 << "= Solved " << *frame.expr << " = " << *solution.first;
889 else
890 llvm::dbgs().indent(indent * 2) << "= Skipped " << *frame.expr;
891 llvm::dbgs() << " (" << (solution.second ? "cycle broken" : "unique")
892 << ")\n";
893 }
894 });
895
896 worklist.pop_back();
897 };
898
899 // See if we have a memoized result we can return.
900 if (frame.expr->getSolution()) {
901 LLVM_DEBUG({
902 if (!isa<KnownExpr>(frame.expr))
903 llvm::dbgs().indent(indent * 2) << "- Cached " << *frame.expr << " = "
904 << *frame.expr->getSolution() << "\n";
905 });
906 setSolution(ExprSolution{*frame.expr->getSolution(), false});
907 continue;
908 }
909
910 // Otherwise compute the value of the expression.
911 LLVM_DEBUG({
912 if (!isa<KnownExpr>(frame.expr))
913 llvm::dbgs().indent(indent * 2) << "- Solving " << *frame.expr << "\n";
914 });
915
916 TypeSwitch<Expr *>(frame.expr)
917 .Case<KnownExpr>([&](auto *expr) {
918 setSolution(ExprSolution{expr->getValue(), false});
919 })
920 .Case<VarExpr>([&](auto *expr) {
921 if (solvedExprs.contains(expr->constraint)) {
922 auto solution = solvedExprs[expr->constraint];
923 // If we've solved the upper bound already, store the solution.
924 // This will be explicitly solved for later if not computed as
925 // part of the solving that resolved this constraint.
926 // This should only happen if somehow the constraint is
927 // solved before visiting this expression, so that our upperBound
928 // was not added to the worklist such that it was handled first.
929 if (expr->upperBound && solvedExprs.contains(expr->upperBound))
930 expr->upperBoundSolution = solvedExprs[expr->upperBound].first;
931 seenVars.erase(expr);
932 // Constrain variables >= 0.
933 if (solution.first && *solution.first < 0)
934 solution.first = 0;
935 return setSolution(solution);
936 }
937
938 // Unconstrained variables produce no solution.
939 if (!expr->constraint)
940 return setSolution(ExprSolution{std::nullopt, false});
941 // Return no solution for recursions in the variables. This is sane
942 // and will cause the expression to be ignored when computing the
943 // parent, e.g. `a >= max(a, 1)` will become just `a >= 1`.
944 if (!seenVars.insert(expr).second)
945 return setSolution(ExprSolution{std::nullopt, true});
946
947 worklist.emplace_back(expr->constraint, indent + 1);
948 if (expr->upperBound)
949 worklist.emplace_back(expr->upperBound, indent + 1);
950 })
951 .Case<IdExpr>([&](auto *expr) {
952 if (solvedExprs.contains(expr->arg))
953 return setSolution(solvedExprs[expr->arg]);
954 worklist.emplace_back(expr->arg, indent + 1);
955 })
956 .Case<PowExpr>([&](auto *expr) {
957 if (solvedExprs.contains(expr->arg))
958 return setSolution(computeUnary(
959 solvedExprs[expr->arg], [](int32_t arg) { return 1 << arg; }));
960
961 worklist.emplace_back(expr->arg, indent + 1);
962 })
963 .Case<AddExpr>([&](auto *expr) {
964 if (solvedExprs.contains(expr->lhs()) &&
965 solvedExprs.contains(expr->rhs()))
966 return setSolution(computeBinary(
967 solvedExprs[expr->lhs()], solvedExprs[expr->rhs()],
968 [](int32_t lhs, int32_t rhs) { return lhs + rhs; }));
969
970 worklist.emplace_back(expr->lhs(), indent + 1);
971 worklist.emplace_back(expr->rhs(), indent + 1);
972 })
973 .Case<MaxExpr>([&](auto *expr) {
974 if (solvedExprs.contains(expr->lhs()) &&
975 solvedExprs.contains(expr->rhs()))
976 return setSolution(computeBinary(
977 solvedExprs[expr->lhs()], solvedExprs[expr->rhs()],
978 [](int32_t lhs, int32_t rhs) { return std::max(lhs, rhs); }));
979
980 worklist.emplace_back(expr->lhs(), indent + 1);
981 worklist.emplace_back(expr->rhs(), indent + 1);
982 })
983 .Case<MinExpr>([&](auto *expr) {
984 if (solvedExprs.contains(expr->lhs()) &&
985 solvedExprs.contains(expr->rhs()))
986 return setSolution(computeBinary(
987 solvedExprs[expr->lhs()], solvedExprs[expr->rhs()],
988 [](int32_t lhs, int32_t rhs) { return std::min(lhs, rhs); }));
989
990 worklist.emplace_back(expr->lhs(), indent + 1);
991 worklist.emplace_back(expr->rhs(), indent + 1);
992 })
993 .Default([&](auto) {
994 setSolution(ExprSolution{std::nullopt, false});
995 });
996 }
997
998 return solvedExprs[expr];
999}
1000
1001/// Solve the constraint problem. This is a very simple implementation that
1002/// does not fully solve the problem if there are weird dependency cycles
1003/// present.
1004LogicalResult ConstraintSolver::solve() {
1005 LLVM_DEBUG({
1006 llvm::dbgs() << "\n";
1007 debugHeader("Constraints") << "\n\n";
1008 dumpConstraints(llvm::dbgs());
1009 });
1010
1011 // Ensure that there are no adverse cycles around.
1012 LLVM_DEBUG({
1013 llvm::dbgs() << "\n";
1014 debugHeader("Checking for unbreakable loops") << "\n\n";
1015 });
1016 SmallPtrSet<Expr *, 16> seenVars;
1017 bool anyFailed = false;
1018
1019 for (auto *var : varExprs) {
1020 if (!var->constraint)
1021 continue;
1022 LLVM_DEBUG(llvm::dbgs()
1023 << "- Checking " << *var << " >= " << *var->constraint << "\n");
1024
1025 // Canonicalize the variable's constraint expression into a form that allows
1026 // us to easily determine if any recursion leads to an unsatisfiable
1027 // constraint. The `seenVars` set acts as a recursion breaker.
1028 seenVars.insert(var);
1029 auto ineq = checkCycles(var, var->constraint, seenVars);
1030 seenVars.clear();
1031
1032 // If the constraint is satisfiable, we're done.
1033 // TODO: It's possible that this result is already sufficient to arrive at a
1034 // solution for the constraint, and the second pass further down is not
1035 // necessary. This would require more proper handling of `MinExpr` in the
1036 // cycle checking code.
1037 if (ineq.sat()) {
1038 LLVM_DEBUG(llvm::dbgs()
1039 << " = Breakable since " << ineq << " satisfiable\n");
1040 continue;
1041 }
1042
1043 // If we arrive here, the constraint is not satisfiable at all. To provide
1044 // some guidance to the user, we call the cycle checking code again, but
1045 // this time with an in-flight diagnostic to attach notes indicating
1046 // unsatisfiable paths in the cycle.
1047 LLVM_DEBUG(llvm::dbgs()
1048 << " = UNBREAKABLE since " << ineq << " unsatisfiable\n");
1049 anyFailed = true;
1050 for (auto fieldRef : info.find(var)->second) {
1051 // Depending on whether this value stems from an operation or not, create
1052 // an appropriate diagnostic identifying the value.
1053 auto *op = fieldRef.getDefiningOp();
1054 auto diag = op ? op->emitOpError()
1055 : mlir::emitError(fieldRef.getValue().getLoc())
1056 << "value ";
1057 diag << "is constrained to be wider than itself";
1058
1059 // Re-run the cycle checking, but this time reporting into the diagnostic.
1060 seenVars.insert(var);
1061 checkCycles(var, var->constraint, seenVars, &diag);
1062 seenVars.clear();
1063 }
1064 }
1065
1066 // If there were cycles, return now to avoid complaining to the user about
1067 // dependent widths not being inferred.
1068 if (anyFailed)
1069 return failure();
1070
1071 // Iterate over the constraint variables and solve each.
1072 LLVM_DEBUG({
1073 llvm::dbgs() << "\n";
1074 debugHeader("Solving constraints") << "\n\n";
1075 });
1076 std::vector<Frame> worklist;
1077 for (auto *var : varExprs) {
1078 // Complain about unconstrained variables.
1079 if (!var->constraint) {
1080 LLVM_DEBUG(llvm::dbgs() << "- Unconstrained " << *var << "\n");
1081 emitUninferredWidthError(var);
1082 anyFailed = true;
1083 continue;
1084 }
1085
1086 // Compute the value for the variable.
1087 LLVM_DEBUG(llvm::dbgs()
1088 << "- Solving " << *var << " >= " << *var->constraint << "\n");
1089 seenVars.insert(var);
1090 auto solution = solveExpr(var->constraint, seenVars, worklist);
1091 // Compute the upperBound if there is one and haven't already.
1092 if (var->upperBound && !var->upperBoundSolution)
1093 var->upperBoundSolution =
1094 solveExpr(var->upperBound, seenVars, worklist).first;
1095 seenVars.clear();
1096
1097 // Constrain variables >= 0.
1098 if (solution.first) {
1099 if (*solution.first < 0)
1100 solution.first = 0;
1101 var->setSolution(*solution.first);
1102 }
1103
1104 // In case the width could not be inferred, complain to the user. This might
1105 // be the case if the width depends on an unconstrained variable.
1106 if (!solution.first) {
1107 LLVM_DEBUG(llvm::dbgs() << " - UNSOLVED " << *var << "\n");
1108 emitUninferredWidthError(var);
1109 anyFailed = true;
1110 continue;
1111 }
1112 LLVM_DEBUG(llvm::dbgs()
1113 << " = Solved " << *var << " = " << solution.first << " ("
1114 << (solution.second ? "cycle broken" : "unique") << ")\n");
1115
1116 // Check if the solution we have found violates an upper bound.
1117 if (var->upperBoundSolution && var->upperBoundSolution < *solution.first) {
1118 LLVM_DEBUG(llvm::dbgs() << " ! Unsatisfiable " << *var
1119 << " <= " << var->upperBoundSolution << "\n");
1120 emitUninferredWidthError(var);
1121 anyFailed = true;
1122 }
1123 }
1124
1125 // Copy over derived widths.
1126 for (auto *derived : derivedExprs) {
1127 auto *assigned = derived->assigned;
1128 if (!assigned || !assigned->getSolution()) {
1129 LLVM_DEBUG(llvm::dbgs() << "- Unused " << *derived << " set to 0\n");
1130 derived->setSolution(0);
1131 } else {
1132 LLVM_DEBUG(llvm::dbgs() << "- Deriving " << *derived << " = "
1133 << assigned->getSolution() << "\n");
1134 derived->setSolution(*assigned->getSolution());
1135 }
1136 }
1137
1138 return failure(anyFailed);
1139}
1140
1141// Emits the diagnostic to inform the user about an uninferred width in the
1142// design. Returns true if an error was reported, false otherwise.
1143void ConstraintSolver::emitUninferredWidthError(VarExpr *var) {
1144 FieldRef fieldRef = info.find(var)->second.back();
1145 Value value = fieldRef.getValue();
1146
1147 auto diag = mlir::emitError(value.getLoc(), "uninferred width:");
1148
1149 // Try to hint the user at what kind of node this is.
1150 if (isa<BlockArgument>(value)) {
1151 diag << " port";
1152 } else if (auto *op = value.getDefiningOp()) {
1153 TypeSwitch<Operation *>(op)
1154 .Case<WireOp>([&](auto) { diag << " wire"; })
1155 .Case<RegOp, RegResetOp>([&](auto) { diag << " reg"; })
1156 .Case<NodeOp>([&](auto) { diag << " node"; })
1157 .Default([&](auto) { diag << " value"; });
1158 } else {
1159 diag << " value";
1160 }
1161
1162 // Actually print what the user can refer to.
1163 auto [fieldName, rootKnown] = getFieldName(fieldRef);
1164 if (!fieldName.empty()) {
1165 if (!rootKnown)
1166 diag << " field";
1167 diag << " \"" << fieldName << "\"";
1168 }
1169
1170 if (!var->constraint) {
1171 diag << " is unconstrained";
1172 } else if (var->getSolution() && var->upperBoundSolution &&
1173 var->getSolution() > var->upperBoundSolution) {
1174 diag << " cannot satisfy all width requirements";
1175 LLVM_DEBUG(llvm::dbgs() << *var->constraint << "\n");
1176 LLVM_DEBUG(llvm::dbgs() << *var->upperBound << "\n");
1177 auto loc = locs.find(var->constraint)->second.back();
1178 diag.attachNote(loc) << "width is constrained to be at least "
1179 << *var->getSolution() << " here:";
1180 loc = locs.find(var->upperBound)->second.back();
1181 diag.attachNote(loc) << "width is constrained to be at most "
1182 << *var->upperBoundSolution << " here:";
1183 } else {
1184 diag << " width cannot be determined";
1185 LLVM_DEBUG(llvm::dbgs() << *var->constraint << "\n");
1186 auto loc = locs.find(var->constraint)->second.back();
1187 diag.attachNote(loc) << "width is constrained by an uninferred width here:";
1188 }
1189}
1190
1191//===----------------------------------------------------------------------===//
1192// Inference Constraint Problem Mapping
1193//===----------------------------------------------------------------------===//
1194
1195namespace {
1196
1197/// A helper class which maps the types and operations in a design to a set of
1198/// variables and constraints to be solved later.
1199class InferenceMapping {
1200public:
1201 InferenceMapping(ConstraintSolver &solver, SymbolTable &symtbl,
1203 : solver(solver), symtbl(symtbl), irn{symtbl, istc} {}
1204
1205 LogicalResult map(CircuitOp op);
1206 bool allWidthsKnown(Operation *op);
1207 LogicalResult mapOperation(Operation *op);
1208
1209 /// Declare all the variables in the value. If the value is a ground type,
1210 /// there is a single variable declared. If the value is an aggregate type,
1211 /// it sets up variables for each unknown width.
1212 void declareVars(Value value, bool isDerived = false);
1213
1214 /// Assign the constraint expressions of the fields in the `result` argument
1215 /// as the max of expressions in the `rhs` and `lhs` arguments. Both fields
1216 /// must be the same type.
1217 void maximumOfTypes(Value result, Value rhs, Value lhs);
1218
1219 /// Constrain the value "larger" to be greater than or equal to "smaller".
1220 /// These may be aggregate values. This is used for regular connects.
1221 void constrainTypes(Value larger, Value smaller, bool equal = false);
1222
1223 /// Constrain the expression "larger" to be greater than or equals to
1224 /// the expression "smaller".
1225 void constrainTypes(Expr *larger, Expr *smaller,
1226 bool imposeUpperBounds = false, bool equal = false);
1227
1228 /// Assign the constraint expressions of the fields in the `src` argument as
1229 /// the expressions for the `dst` argument. Both fields must be of the given
1230 /// `type`.
1231 void unifyTypes(FieldRef lhs, FieldRef rhs, FIRRTLType type);
1232
1233 /// Get the expr associated with the value. The value must be a non-aggregate
1234 /// type
1235 Expr *getExpr(Value value) const;
1236
1237 /// Get the expr associated with a specific field in a value.
1238 Expr *getExpr(FieldRef fieldRef) const;
1239
1240 /// Get the expr associated with a specific field in a value. If value is
1241 /// NULL, then this returns NULL.
1242 Expr *getExprOrNull(FieldRef fieldRef) const;
1243
1244 /// Set the expr associated with the value. The value must be a non-aggregate
1245 /// type.
1246 void setExpr(Value value, Expr *expr);
1247
1248 /// Set the expr associated with a specific field in a value.
1249 void setExpr(FieldRef fieldRef, Expr *expr);
1250
1251 /// Return whether a module was skipped due to being fully inferred already.
1252 bool isModuleSkipped(FModuleOp module) const {
1253 return skippedModules.count(module);
1254 }
1255
1256 /// Return whether all modules in the mapping were fully inferred.
1257 bool areAllModulesSkipped() const { return allModulesSkipped; }
1258
1259private:
1260 /// The constraint solver into which we emit variables and constraints.
1261 ConstraintSolver &solver;
1262
1263 /// The constraint exprs for each result type of an operation.
1264 DenseMap<FieldRef, Expr *> opExprs;
1265
1266 /// The fully inferred modules that were skipped entirely.
1267 SmallPtrSet<Operation *, 16> skippedModules;
1268 bool allModulesSkipped = true;
1269
1270 /// Cache of module symbols
1271 SymbolTable &symtbl;
1272
1273 /// Full design inner symbol information.
1275};
1276
1277} // namespace
1278
1279/// Check if a type contains any FIRRTL type with uninferred widths.
1280static bool hasUninferredWidth(Type type) {
1281 return TypeSwitch<Type, bool>(type)
1282 .Case<FIRRTLBaseType>([](auto base) { return base.hasUninferredWidth(); })
1283 .Case<RefType>(
1284 [](auto ref) { return ref.getType().hasUninferredWidth(); })
1285 .Default([](auto) { return false; });
1286}
1287
1288LogicalResult InferenceMapping::map(CircuitOp op) {
1289 LLVM_DEBUG(llvm::dbgs()
1290 << "\n===----- Mapping ops to constraint exprs -----===\n\n");
1291
1292 // Ensure we have constraint variables established for all module ports.
1293 for (auto module : op.getOps<FModuleOp>())
1294 for (auto arg : module.getArguments()) {
1295 solver.setCurrentContextInfo(FieldRef(arg, 0));
1296 declareVars(arg);
1297 }
1298
1299 for (auto module : op.getOps<FModuleOp>()) {
1300 // Check if the module contains *any* uninferred widths. This allows us to
1301 // do an early skip if the module is already fully inferred.
1302 bool anyUninferred = false;
1303 for (auto arg : module.getArguments()) {
1304 anyUninferred |= hasUninferredWidth(arg.getType());
1305 if (anyUninferred)
1306 break;
1307 }
1308 module.walk([&](Operation *op) {
1309 for (auto type : op->getResultTypes())
1310 anyUninferred |= hasUninferredWidth(type);
1311 if (anyUninferred)
1312 return WalkResult::interrupt();
1313 return WalkResult::advance();
1314 });
1315
1316 if (!anyUninferred) {
1317 LLVM_DEBUG(llvm::dbgs() << "Skipping fully-inferred module '"
1318 << module.getName() << "'\n");
1319 skippedModules.insert(module);
1320 continue;
1321 }
1322
1323 allModulesSkipped = false;
1324
1325 // Go through operations in the module, creating type variables for results,
1326 // and generating constraints.
1327 auto result = module.getBodyBlock()->walk(
1328 [&](Operation *op) { return WalkResult(mapOperation(op)); });
1329 if (result.wasInterrupted())
1330 return failure();
1331 }
1332
1333 return success();
1334}
1335
1336bool InferenceMapping::allWidthsKnown(Operation *op) {
1337 /// Ignore property assignments, no widths to infer.
1338 if (isa<PropAssignOp>(op))
1339 return true;
1340
1341 // If this is a mux, and the select signal is uninferred, we need to set an
1342 // upperbound limit on it.
1343 if (isa<MuxPrimOp, Mux4CellIntrinsicOp, Mux2CellIntrinsicOp>(op))
1344 if (hasUninferredWidth(op->getOperand(0).getType()))
1345 return false;
1346
1347 // We need to propagate through connects.
1348 if (isa<FConnectLike, AttachOp>(op))
1349 return false;
1350
1351 // Check if we know the width of every result of this operation.
1352 return llvm::all_of(op->getResults(), [&](auto result) {
1353 // Only consider FIRRTL types for width constraints. Ignore any foreign
1354 // types as they don't participate in the width inference process.
1355 if (auto type = type_dyn_cast<FIRRTLType>(result.getType()))
1356 if (hasUninferredWidth(type))
1357 return false;
1358 return true;
1359 });
1360}
1361
1362LogicalResult InferenceMapping::mapOperation(Operation *op) {
1363 if (allWidthsKnown(op))
1364 return success();
1365
1366 // Actually generate the necessary constraint expressions.
1367 bool mappingFailed = false;
1368 solver.setCurrentContextInfo(
1369 op->getNumResults() > 0 ? FieldRef(op->getResults()[0], 0) : FieldRef());
1370 solver.setCurrentLocation(op->getLoc());
1371 TypeSwitch<Operation *>(op)
1372 .Case<ConstantOp>([&](auto op) {
1373 // If the constant has a known width, use that. Otherwise pick the
1374 // smallest number of bits necessary to represent the constant.
1375 auto v = op.getValue();
1376 auto w = v.getBitWidth() - (v.isNegative() ? v.countLeadingOnes()
1377 : v.countLeadingZeros());
1378 if (v.isSigned())
1379 w += 1;
1380 setExpr(op.getResult(), solver.known(std::max(w, 1u)));
1381 })
1382 .Case<SpecialConstantOp>([&](auto op) {
1383 // Nothing required.
1384 })
1385 .Case<InvalidValueOp>([&](auto op) {
1386 // We must duplicate the invalid value for each use, since each use can
1387 // be inferred to a different width.
1388 declareVars(op.getResult(), /*isDerived=*/true);
1389 })
1390 .Case<WireOp, RegOp>([&](auto op) { declareVars(op.getResult()); })
1391 .Case<RegResetOp>([&](auto op) {
1392 // The original Scala code also constrains the reset signal to be at
1393 // least 1 bit wide. We don't do this here since the MLIR FIRRTL
1394 // dialect enforces the reset signal to be an async reset or a
1395 // `uint<1>`.
1396 declareVars(op.getResult());
1397 // Contrain the register to be greater than or equal to the reset
1398 // signal.
1399 constrainTypes(op.getResult(), op.getResetValue());
1400 })
1401 .Case<NodeOp>([&](auto op) {
1402 // Nodes have the same type as their input.
1403 unifyTypes(FieldRef(op.getResult(), 0), FieldRef(op.getInput(), 0),
1404 op.getResult().getType());
1405 })
1406
1407 // Aggregate Values
1408 .Case<SubfieldOp>([&](auto op) {
1409 BundleType bundleType = op.getInput().getType();
1410 auto fieldID = bundleType.getFieldID(op.getFieldIndex());
1411 unifyTypes(FieldRef(op.getResult(), 0),
1412 FieldRef(op.getInput(), fieldID), op.getType());
1413 })
1414 .Case<SubindexOp, SubaccessOp>([&](auto op) {
1415 // All vec fields unify to the same thing. Always use the first element
1416 // of the vector, which has a field ID of 1.
1417 unifyTypes(FieldRef(op.getResult(), 0), FieldRef(op.getInput(), 1),
1418 op.getType());
1419 })
1420 .Case<RefSubOp>([&](RefSubOp op) {
1421 uint64_t fieldID = TypeSwitch<FIRRTLBaseType, uint64_t>(
1422 op.getInput().getType().getType())
1423 .Case<FVectorType>([](auto _) { return 1; })
1424 .Case<BundleType>([&](auto type) {
1425 return type.getFieldID(op.getIndex());
1426 });
1427 unifyTypes(FieldRef(op.getResult(), 0),
1428 FieldRef(op.getInput(), fieldID), op.getType());
1429 })
1430
1431 // Arithmetic and Logical Binary Primitives
1432 .Case<AddPrimOp, SubPrimOp>([&](auto op) {
1433 auto lhs = getExpr(op.getLhs());
1434 auto rhs = getExpr(op.getRhs());
1435 auto e = solver.add(solver.max(lhs, rhs), solver.known(1));
1436 setExpr(op.getResult(), e);
1437 })
1438 .Case<MulPrimOp>([&](auto op) {
1439 auto lhs = getExpr(op.getLhs());
1440 auto rhs = getExpr(op.getRhs());
1441 auto e = solver.add(lhs, rhs);
1442 setExpr(op.getResult(), e);
1443 })
1444 .Case<DivPrimOp>([&](auto op) {
1445 auto lhs = getExpr(op.getLhs());
1446 Expr *e;
1447 if (op.getType().base().isSigned()) {
1448 e = solver.add(lhs, solver.known(1));
1449 } else {
1450 e = lhs;
1451 }
1452 setExpr(op.getResult(), e);
1453 })
1454 .Case<RemPrimOp>([&](auto op) {
1455 auto lhs = getExpr(op.getLhs());
1456 auto rhs = getExpr(op.getRhs());
1457 auto e = solver.min(lhs, rhs);
1458 setExpr(op.getResult(), e);
1459 })
1460 .Case<AndPrimOp, OrPrimOp, XorPrimOp>([&](auto op) {
1461 auto lhs = getExpr(op.getLhs());
1462 auto rhs = getExpr(op.getRhs());
1463 auto e = solver.max(lhs, rhs);
1464 setExpr(op.getResult(), e);
1465 })
1466
1467 .Case<CatPrimOp>([&](auto op) {
1468 if (op.getInputs().empty()) {
1469 setExpr(op.getResult(), solver.known(0));
1470 return;
1471 }
1472 auto result = getExpr(op.getInputs().front());
1473 for (auto operand : op.getInputs().drop_front()) {
1474 auto operandExpr = getExpr(operand);
1475 result = solver.add(result, operandExpr);
1476 }
1477 setExpr(op.getResult(), result);
1478 })
1479 // Misc Binary Primitives
1480 .Case<DShlPrimOp>([&](auto op) {
1481 auto lhs = getExpr(op.getLhs());
1482 auto rhs = getExpr(op.getRhs());
1483 auto e = solver.add(lhs, solver.add(solver.pow(rhs), solver.known(-1)));
1484 setExpr(op.getResult(), e);
1485 })
1486 .Case<DShlwPrimOp, DShrPrimOp>([&](auto op) {
1487 auto e = getExpr(op.getLhs());
1488 setExpr(op.getResult(), e);
1489 })
1490
1491 // Unary operators
1492 .Case<NegPrimOp>([&](auto op) {
1493 auto input = getExpr(op.getInput());
1494 auto e = solver.add(input, solver.known(1));
1495 setExpr(op.getResult(), e);
1496 })
1497 .Case<CvtPrimOp>([&](auto op) {
1498 auto input = getExpr(op.getInput());
1499 auto e = op.getInput().getType().base().isSigned()
1500 ? input
1501 : solver.add(input, solver.known(1));
1502 setExpr(op.getResult(), e);
1503 })
1504
1505 // Miscellaneous
1506 .Case<BitsPrimOp>([&](auto op) {
1507 setExpr(op.getResult(), solver.known(op.getHi() - op.getLo() + 1));
1508 })
1509 .Case<HeadPrimOp>([&](auto op) {
1510 setExpr(op.getResult(), solver.known(op.getAmount()));
1511 })
1512 .Case<TailPrimOp>([&](auto op) {
1513 auto input = getExpr(op.getInput());
1514 auto e = solver.add(input, solver.known(-op.getAmount()));
1515 setExpr(op.getResult(), e);
1516 })
1517 .Case<PadPrimOp>([&](auto op) {
1518 auto input = getExpr(op.getInput());
1519 auto e = solver.max(input, solver.known(op.getAmount()));
1520 setExpr(op.getResult(), e);
1521 })
1522 .Case<ShlPrimOp>([&](auto op) {
1523 auto input = getExpr(op.getInput());
1524 auto e = solver.add(input, solver.known(op.getAmount()));
1525 setExpr(op.getResult(), e);
1526 })
1527 .Case<ShrPrimOp>([&](auto op) {
1528 auto input = getExpr(op.getInput());
1529 // UInt saturates at 0 bits, SInt at 1 bit
1530 auto minWidth = op.getInput().getType().base().isUnsigned() ? 0 : 1;
1531 auto e = solver.max(solver.add(input, solver.known(-op.getAmount())),
1532 solver.known(minWidth));
1533 setExpr(op.getResult(), e);
1534 })
1535
1536 // Handle operations whose output width matches the input width.
1537 .Case<NotPrimOp, AsSIntPrimOp, AsUIntPrimOp, ConstCastOp>(
1538 [&](auto op) { setExpr(op.getResult(), getExpr(op.getInput())); })
1539 .Case<mlir::UnrealizedConversionCastOp>(
1540 [&](auto op) { setExpr(op.getResult(0), getExpr(op.getOperand(0))); })
1541
1542 // Handle operations with a single result type that always has a
1543 // well-known width.
1544 .Case<LEQPrimOp, LTPrimOp, GEQPrimOp, GTPrimOp, EQPrimOp, NEQPrimOp,
1545 AsClockPrimOp, AsAsyncResetPrimOp, AsResetPrimOp, AndRPrimOp,
1546 OrRPrimOp, XorRPrimOp>([&](auto op) {
1547 auto width = op.getType().getBitWidthOrSentinel();
1548 assert(width > 0 && "width should have been checked by verifier");
1549 setExpr(op.getResult(), solver.known(width));
1550 })
1551 .Case<MuxPrimOp, Mux2CellIntrinsicOp>([&](auto op) {
1552 auto *sel = getExpr(op.getSel());
1553 constrainTypes(solver.known(1), sel, /*imposeUpperBounds=*/true);
1554 maximumOfTypes(op.getResult(), op.getHigh(), op.getLow());
1555 })
1556 .Case<Mux4CellIntrinsicOp>([&](Mux4CellIntrinsicOp op) {
1557 auto *sel = getExpr(op.getSel());
1558 constrainTypes(solver.known(2), sel, /*imposeUpperBounds=*/true);
1559 maximumOfTypes(op.getResult(), op.getV3(), op.getV2());
1560 maximumOfTypes(op.getResult(), op.getResult(), op.getV1());
1561 maximumOfTypes(op.getResult(), op.getResult(), op.getV0());
1562 })
1563
1564 .Case<ConnectOp, MatchingConnectOp>(
1565 [&](auto op) { constrainTypes(op.getDest(), op.getSrc()); })
1566 .Case<RefDefineOp>([&](auto op) {
1567 // Dest >= Src, but also check Src <= Dest for correctness
1568 // (but don't solve to make this true, don't back-propagate)
1569 constrainTypes(op.getDest(), op.getSrc(), true);
1570 })
1571 .Case<AttachOp>([&](auto op) {
1572 // Attach connects multiple analog signals together. All signals must
1573 // have the same bit width. Signals without bit width inherit from the
1574 // other signals.
1575 if (op.getAttached().empty())
1576 return;
1577 auto prev = op.getAttached()[0];
1578 for (auto operand : op.getAttached().drop_front()) {
1579 auto e1 = getExpr(prev);
1580 auto e2 = getExpr(operand);
1581 constrainTypes(e1, e2, /*imposeUpperBounds=*/true);
1582 constrainTypes(e2, e1, /*imposeUpperBounds=*/true);
1583 prev = operand;
1584 }
1585 })
1586
1587 // Handle the no-ops that don't interact with width inference.
1588 .Case<AssertOp, AssumeOp, CoverOp, DomainDefineOp, FFlushOp, PrintFOp,
1589 SkipOp, StopOp, UnclockedAssumeIntrinsicOp, WhenOp>([&](auto) {})
1590
1591 // Handle instances of other modules.
1592 .Case<InstanceOp>([&](auto op) {
1593 auto refdModule = op.getReferencedOperation(symtbl);
1594 auto module = dyn_cast<FModuleOp>(&*refdModule);
1595 if (!module) {
1596 auto diag = mlir::emitError(op.getLoc());
1597 diag << "extern module `" << op.getModuleName()
1598 << "` has ports of uninferred width";
1599
1600 auto fml = cast<FModuleLike>(&*refdModule);
1601 auto ports = fml.getPorts();
1602 for (auto &port : ports) {
1603 auto baseType = getBaseType(port.type);
1604 if (baseType && baseType.hasUninferredWidth()) {
1605 diag.attachNote(op.getLoc()) << "Port: " << port.name;
1606 if (!baseType.isGround())
1607 diagnoseUninferredType(diag, baseType, port.name.getValue());
1608 }
1609 }
1610
1611 diag.attachNote(op.getLoc())
1612 << "Only non-extern FIRRTL modules may contain unspecified "
1613 "widths to be inferred automatically.";
1614 diag.attachNote(refdModule->getLoc())
1615 << "Module `" << op.getModuleName() << "` defined here:";
1616 mappingFailed = true;
1617 return;
1618 }
1619 // Simply look up the free variables created for the instantiated
1620 // module's ports, and use them for instance port wires. This way,
1621 // constraints imposed onto the ports of the instance will transparently
1622 // apply to the ports of the instantiated module.
1623 for (auto [result, arg] :
1624 llvm::zip(op->getResults(), module.getArguments()))
1625 unifyTypes({result, 0}, {arg, 0},
1626 type_cast<FIRRTLType>(result.getType()));
1627 })
1628
1629 // Handle memories.
1630 .Case<MemOp>([&](MemOp op) {
1631 // Create constraint variables for all ports.
1632 unsigned nonDebugPort = 0;
1633 for (const auto &result : llvm::enumerate(op.getResults())) {
1634 declareVars(result.value());
1635 if (!type_isa<RefType>(result.value().getType()))
1636 nonDebugPort = result.index();
1637 }
1638
1639 // A helper function that returns the indeces of the "data", "rdata",
1640 // and "wdata" fields in the bundle corresponding to a memory port.
1641 auto dataFieldIndices = [](MemOp::PortKind kind) -> ArrayRef<unsigned> {
1642 static const unsigned indices[] = {3, 5};
1643 static const unsigned debug[] = {0};
1644 switch (kind) {
1645 case MemOp::PortKind::Read:
1646 case MemOp::PortKind::Write:
1647 return ArrayRef<unsigned>(indices, 1); // {3}
1648 case MemOp::PortKind::ReadWrite:
1649 return ArrayRef<unsigned>(indices); // {3, 5}
1650 case MemOp::PortKind::Debug:
1651 return ArrayRef<unsigned>(debug);
1652 }
1653 llvm_unreachable("Imposible PortKind");
1654 };
1655
1656 // This creates independent variables for every data port. Yet, what we
1657 // actually want is for all data ports to share the same variable. To do
1658 // this, we find the first data port declared, and use that port's vars
1659 // for all the other ports.
1660 unsigned firstFieldIndex =
1661 dataFieldIndices(op.getPortKind(nonDebugPort))[0];
1662 FieldRef firstData(
1663 op.getResult(nonDebugPort),
1664 type_cast<BundleType>(op.getPortType(nonDebugPort).getPassiveType())
1665 .getFieldID(firstFieldIndex));
1666 LLVM_DEBUG(llvm::dbgs() << "Adjusting memory port variables:\n");
1667
1668 // Reuse data port variables.
1669 auto dataType = op.getDataType();
1670 for (unsigned i = 0, e = op.getResults().size(); i < e; ++i) {
1671 auto result = op.getResult(i);
1672 if (type_isa<RefType>(result.getType())) {
1673 // Debug ports are firrtl.ref<vector<data-type, depth>>
1674 // Use FieldRef of 1, to indicate the first vector element must be
1675 // of the dataType.
1676 unifyTypes(firstData, FieldRef(result, 1), dataType);
1677 continue;
1678 }
1679
1680 auto portType =
1681 type_cast<BundleType>(op.getPortType(i).getPassiveType());
1682 for (auto fieldIndex : dataFieldIndices(op.getPortKind(i)))
1683 unifyTypes(FieldRef(result, portType.getFieldID(fieldIndex)),
1684 firstData, dataType);
1685 }
1686 })
1687
1688 .Case<RefSendOp>([&](auto op) {
1689 declareVars(op.getResult());
1690 constrainTypes(op.getResult(), op.getBase(), true);
1691 })
1692 .Case<RefResolveOp>([&](auto op) {
1693 declareVars(op.getResult());
1694 constrainTypes(op.getResult(), op.getRef(), true);
1695 })
1696 .Case<RefCastOp>([&](auto op) {
1697 declareVars(op.getResult());
1698 constrainTypes(op.getResult(), op.getInput(), true);
1699 })
1700 .Case<RWProbeOp>([&](auto op) {
1701 auto ist = irn.lookup(op.getTarget());
1702 if (!ist) {
1703 op->emitError("target of rwprobe could not be resolved");
1704 mappingFailed = true;
1705 return;
1706 }
1707 auto ref = getFieldRefForTarget(ist);
1708 if (!ref) {
1709 op->emitError("target of rwprobe resolved to unsupported target");
1710 mappingFailed = true;
1711 return;
1712 }
1713 auto newFID = convertFieldIDToOurVersion(
1714 ref.getFieldID(), type_cast<FIRRTLType>(ref.getValue().getType()));
1715 unifyTypes(FieldRef(op.getResult(), 0),
1716 FieldRef(ref.getValue(), newFID), op.getType());
1717 })
1718 .Case<mlir::UnrealizedConversionCastOp>([&](auto op) {
1719 for (Value result : op.getResults()) {
1720 auto ty = result.getType();
1721 if (type_isa<FIRRTLType>(ty))
1722 declareVars(result);
1723 }
1724 })
1725 .Default([&](auto op) {
1726 op->emitOpError("not supported in width inference");
1727 mappingFailed = true;
1728 });
1729
1730 // Forceable declarations should have the ref constrained to data result.
1731 if (auto fop = dyn_cast<Forceable>(op); fop && fop.isForceable())
1732 unifyTypes(FieldRef(fop.getDataRef(), 0), FieldRef(fop.getDataRaw(), 0),
1733 fop.getDataType());
1734
1735 return failure(mappingFailed);
1736}
1737
1738/// Declare free variables for the type of a value, and associate the resulting
1739/// set of variables with that value.
1740void InferenceMapping::declareVars(Value value, bool isDerived) {
1741 // Declare a variable for every unknown width in the type. If this is a Bundle
1742 // type or a FVector type, we will have to potentially create many variables.
1743 unsigned fieldID = 0;
1744 std::function<void(FIRRTLBaseType)> declare = [&](FIRRTLBaseType type) {
1745 auto width = type.getBitWidthOrSentinel();
1746 if (width >= 0) {
1747 fieldID++;
1748 } else if (width == -1) {
1749 // Unknown width integers create a variable.
1750 FieldRef field(value, fieldID);
1751 solver.setCurrentContextInfo(field);
1752 if (isDerived)
1753 setExpr(field, solver.derived());
1754 else
1755 setExpr(field, solver.var());
1756 fieldID++;
1757 } else if (auto bundleType = type_dyn_cast<BundleType>(type)) {
1758 // Bundle types recursively declare all bundle elements.
1759 fieldID++;
1760 for (auto &element : bundleType)
1761 declare(element.type);
1762 } else if (auto vecType = type_dyn_cast<FVectorType>(type)) {
1763 fieldID++;
1764 auto save = fieldID;
1765 declare(vecType.getElementType());
1766 // Skip past the rest of the elements
1767 fieldID = save + vecType.getMaxFieldID();
1768 } else {
1769 llvm_unreachable("Unknown type inside a bundle!");
1770 }
1771 };
1772 if (auto type = getBaseType(value.getType()))
1773 declare(type);
1774}
1775
1776/// Assign the constraint expressions of the fields in the `result` argument as
1777/// the max of expressions in the `rhs` and `lhs` arguments. Both fields must be
1778/// the same type.
1779void InferenceMapping::maximumOfTypes(Value result, Value rhs, Value lhs) {
1780 // Recurse to every leaf element and set larger >= smaller.
1781 auto fieldID = 0;
1782 std::function<void(FIRRTLBaseType)> maximize = [&](FIRRTLBaseType type) {
1783 if (auto bundleType = type_dyn_cast<BundleType>(type)) {
1784 fieldID++;
1785 for (auto &element : bundleType.getElements())
1786 maximize(element.type);
1787 } else if (auto vecType = type_dyn_cast<FVectorType>(type)) {
1788 fieldID++;
1789 auto save = fieldID;
1790 // Skip 0 length vectors.
1791 if (vecType.getNumElements() > 0)
1792 maximize(vecType.getElementType());
1793 fieldID = save + vecType.getMaxFieldID();
1794 } else if (auto enumType = type_dyn_cast<FEnumType>(type)) {
1795 auto *e = solver.max(getExpr(FieldRef(rhs, fieldID)),
1796 getExpr(FieldRef(lhs, fieldID)));
1797 setExpr(FieldRef(result, fieldID), e);
1798 fieldID++;
1799 } else if (type.isGround()) {
1800 auto *e = solver.max(getExpr(FieldRef(rhs, fieldID)),
1801 getExpr(FieldRef(lhs, fieldID)));
1802 setExpr(FieldRef(result, fieldID), e);
1803 fieldID++;
1804 } else {
1805 llvm_unreachable("Unknown type inside a bundle!");
1806 }
1807 };
1808 if (auto type = getBaseType(result.getType()))
1809 maximize(type);
1810}
1811
1812/// Establishes constraints to ensure the sizes in the `larger` type are greater
1813/// than or equal to the sizes in the `smaller` type. Types have to be
1814/// compatible in the sense that they may only differ in the presence or absence
1815/// of bit widths.
1816///
1817/// This function is used to apply regular connects.
1818/// Set `equal` for constraining larger <= smaller for correctness but not
1819/// solving.
1820void InferenceMapping::constrainTypes(Value larger, Value smaller, bool equal) {
1821 // Recurse to every leaf element and set larger >= smaller. Ignore foreign
1822 // types as these do not participate in width inference.
1823
1824 auto fieldID = 0;
1825 std::function<void(FIRRTLBaseType, Value, Value)> constrain =
1826 [&](FIRRTLBaseType type, Value larger, Value smaller) {
1827 if (auto bundleType = type_dyn_cast<BundleType>(type)) {
1828 fieldID++;
1829 for (auto &element : bundleType.getElements()) {
1830 if (element.isFlip)
1831 constrain(element.type, smaller, larger);
1832 else
1833 constrain(element.type, larger, smaller);
1834 }
1835 } else if (auto vecType = type_dyn_cast<FVectorType>(type)) {
1836 fieldID++;
1837 auto save = fieldID;
1838 // Skip 0 length vectors.
1839 if (vecType.getNumElements() > 0) {
1840 constrain(vecType.getElementType(), larger, smaller);
1841 }
1842 fieldID = save + vecType.getMaxFieldID();
1843 } else if (auto enumType = type_dyn_cast<FEnumType>(type)) {
1844 constrainTypes(getExpr(FieldRef(larger, fieldID)),
1845 getExpr(FieldRef(smaller, fieldID)), false, equal);
1846 fieldID++;
1847 } else if (type.isGround()) {
1848 // Leaf element, look up their expressions, and create the constraint.
1849 constrainTypes(getExpr(FieldRef(larger, fieldID)),
1850 getExpr(FieldRef(smaller, fieldID)), false, equal);
1851 fieldID++;
1852 } else {
1853 llvm_unreachable("Unknown type inside a bundle!");
1854 }
1855 };
1856
1857 if (auto type = getBaseType(larger.getType()))
1858 constrain(type, larger, smaller);
1859}
1860
1861/// Establishes constraints to ensure the sizes in the `larger` type are greater
1862/// than or equal to the sizes in the `smaller` type.
1863void InferenceMapping::constrainTypes(Expr *larger, Expr *smaller,
1864 bool imposeUpperBounds, bool equal) {
1865 assert(larger && "Larger expression should be specified");
1866 assert(smaller && "Smaller expression should be specified");
1867
1868 // If one of the sides is `DerivedExpr`, simply assign the other side as the
1869 // derived width. This allows `InvalidValueOp`s to properly infer their width
1870 // from the connects they are used in, but also be inferred to something
1871 // useful on their own.
1872 if (auto *largerDerived = dyn_cast<DerivedExpr>(larger)) {
1873 largerDerived->assigned = smaller;
1874 LLVM_DEBUG(llvm::dbgs() << "Deriving " << *largerDerived << " from "
1875 << *smaller << "\n");
1876 return;
1877 }
1878 if (auto *smallerDerived = dyn_cast<DerivedExpr>(smaller)) {
1879 smallerDerived->assigned = larger;
1880 LLVM_DEBUG(llvm::dbgs() << "Deriving " << *smallerDerived << " from "
1881 << *larger << "\n");
1882 return;
1883 }
1884
1885 // If the larger expr is a free variable, create a `expr >= x` constraint for
1886 // it that we can try to satisfy with the smallest width.
1887 if (auto *largerVar = dyn_cast<VarExpr>(larger)) {
1888 [[maybe_unused]] auto *c = solver.addGeqConstraint(largerVar, smaller);
1889 LLVM_DEBUG(llvm::dbgs()
1890 << "Constrained " << *largerVar << " >= " << *c << "\n");
1891 // If we're constraining larger == smaller, add the LEQ contraint as well.
1892 // Solve for GEQ but check that LEQ is true.
1893 // Used for matchingconnect, some reference operations, and anywhere the
1894 // widths should be inferred strictly in one direction but are required to
1895 // also be equal for correctness.
1896 if (equal) {
1897 [[maybe_unused]] auto *leq = solver.addLeqConstraint(largerVar, smaller);
1898 LLVM_DEBUG(llvm::dbgs()
1899 << "Constrained " << *largerVar << " <= " << *leq << "\n");
1900 }
1901 return;
1902 }
1903
1904 // If the smaller expr is a free variable but the larger one is not, create a
1905 // `expr <= k` upper bound that we can verify once all lower bounds have been
1906 // satisfied. Since we are always picking the smallest width to satisfy all
1907 // `>=` constraints, any `<=` constraints have no effect on the solution
1908 // besides indicating that a width is unsatisfiable.
1909 if (auto *smallerVar = dyn_cast<VarExpr>(smaller)) {
1910 if (imposeUpperBounds || equal) {
1911 [[maybe_unused]] auto *c = solver.addLeqConstraint(smallerVar, larger);
1912 LLVM_DEBUG(llvm::dbgs()
1913 << "Constrained " << *smallerVar << " <= " << *c << "\n");
1914 }
1915 }
1916}
1917
1918/// Assign the constraint expressions of the fields in the `src` argument as the
1919/// expressions for the `dst` argument. Both fields must be of the given `type`.
1920void InferenceMapping::unifyTypes(FieldRef lhs, FieldRef rhs, FIRRTLType type) {
1921 // Fast path for `unifyTypes(x, x, _)`.
1922 if (lhs == rhs)
1923 return;
1924
1925 // Co-iterate the two field refs, recurring into every leaf element and set
1926 // them equal.
1927 auto fieldID = 0;
1928 std::function<void(FIRRTLBaseType)> unify = [&](FIRRTLBaseType type) {
1929 if (type.isGround()) {
1930 // Leaf element, unify the fields!
1931 FieldRef lhsFieldRef(lhs.getValue(), lhs.getFieldID() + fieldID);
1932 FieldRef rhsFieldRef(rhs.getValue(), rhs.getFieldID() + fieldID);
1933 LLVM_DEBUG(llvm::dbgs()
1934 << "Unify " << getFieldName(lhsFieldRef).first << " = "
1935 << getFieldName(rhsFieldRef).first << "\n");
1936 // Abandon variables becoming unconstrainable by the unification.
1937 if (auto *var = dyn_cast_or_null<VarExpr>(getExprOrNull(lhsFieldRef)))
1938 solver.addGeqConstraint(var, solver.known(0));
1939 setExpr(lhsFieldRef, getExpr(rhsFieldRef));
1940 fieldID++;
1941 } else if (auto bundleType = type_dyn_cast<BundleType>(type)) {
1942 fieldID++;
1943 for (auto &element : bundleType) {
1944 unify(element.type);
1945 }
1946 } else if (auto vecType = type_dyn_cast<FVectorType>(type)) {
1947 fieldID++;
1948 auto save = fieldID;
1949 // Skip 0 length vectors.
1950 if (vecType.getNumElements() > 0) {
1951 unify(vecType.getElementType());
1952 }
1953 fieldID = save + vecType.getMaxFieldID();
1954 } else if (auto enumType = type_dyn_cast<FEnumType>(type)) {
1955 FieldRef lhsFieldRef(lhs.getValue(), lhs.getFieldID() + fieldID);
1956 FieldRef rhsFieldRef(rhs.getValue(), rhs.getFieldID() + fieldID);
1957 LLVM_DEBUG(llvm::dbgs()
1958 << "Unify " << getFieldName(lhsFieldRef).first << " = "
1959 << getFieldName(rhsFieldRef).first << "\n");
1960 setExpr(lhsFieldRef, getExpr(rhsFieldRef));
1961 fieldID++;
1962 } else {
1963 llvm_unreachable("Unknown type inside a bundle!");
1964 }
1965 };
1966 if (auto ftype = getBaseType(type))
1967 unify(ftype);
1968}
1969
1970/// Get the constraint expression for a value.
1971Expr *InferenceMapping::getExpr(Value value) const {
1972 assert(type_cast<FIRRTLType>(getBaseType(value.getType())).isGround());
1973 // A field ID of 0 indicates the entire value.
1974 return getExpr(FieldRef(value, 0));
1975}
1976
1977/// Get the constraint expression for a value.
1978Expr *InferenceMapping::getExpr(FieldRef fieldRef) const {
1979 auto *expr = getExprOrNull(fieldRef);
1980 assert(expr && "constraint expr should have been constructed for value");
1981 return expr;
1982}
1983
1984Expr *InferenceMapping::getExprOrNull(FieldRef fieldRef) const {
1985 auto it = opExprs.find(fieldRef);
1986 if (it != opExprs.end())
1987 return it->second;
1988 // If we don't have an expression for this fieldRef, it should have a
1989 // constant width.
1990 auto baseType = getBaseType(fieldRef.getValue().getType());
1991 auto type =
1993 auto width = cast<FIRRTLBaseType>(type).getBitWidthOrSentinel();
1994 if (width < 0)
1995 return nullptr;
1996 return solver.known(width);
1997}
1998
1999/// Associate a constraint expression with a value.
2000void InferenceMapping::setExpr(Value value, Expr *expr) {
2001 assert(type_cast<FIRRTLType>(getBaseType(value.getType())).isGround());
2002 // A field ID of 0 indicates the entire value.
2003 setExpr(FieldRef(value, 0), expr);
2004}
2005
2006/// Associate a constraint expression with a value.
2007void InferenceMapping::setExpr(FieldRef fieldRef, Expr *expr) {
2008 LLVM_DEBUG({
2009 llvm::dbgs() << "Expr " << *expr << " for " << fieldRef.getValue();
2010 if (fieldRef.getFieldID())
2011 llvm::dbgs() << " '" << getFieldName(fieldRef).first << "'";
2012 auto fieldName = getFieldName(fieldRef);
2013 if (fieldName.second)
2014 llvm::dbgs() << " (\"" << fieldName.first << "\")";
2015 llvm::dbgs() << "\n";
2016 });
2017 opExprs[fieldRef] = expr;
2018}
2019
2020//===----------------------------------------------------------------------===//
2021// Inference Result Application
2022//===----------------------------------------------------------------------===//
2023
2024namespace {
2025/// A helper class which maps the types and operations in a design to a set
2026/// of variables and constraints to be solved later.
2027class InferenceTypeUpdate {
2028public:
2029 InferenceTypeUpdate(InferenceMapping &mapping) : mapping(mapping) {}
2030
2031 LogicalResult update(CircuitOp op);
2032 FailureOr<bool> updateOperation(Operation *op);
2033 FailureOr<bool> updateValue(Value value);
2035
2036private:
2037 const InferenceMapping &mapping;
2038};
2039
2040} // namespace
2041
2042/// Update the types throughout a circuit.
2043LogicalResult InferenceTypeUpdate::update(CircuitOp op) {
2044 LLVM_DEBUG({
2045 llvm::dbgs() << "\n";
2046 debugHeader("Update types") << "\n\n";
2047 });
2048 return mlir::failableParallelForEach(
2049 op.getContext(), op.getOps<FModuleOp>(), [&](FModuleOp op) {
2050 // Skip this module if it had no widths to be
2051 // inferred at all.
2052 if (mapping.isModuleSkipped(op))
2053 return success();
2054 auto isFailed = op.walk<WalkOrder::PreOrder>([&](Operation *op) {
2055 if (failed(updateOperation(op)))
2056 return WalkResult::interrupt();
2057 return WalkResult::advance();
2058 }).wasInterrupted();
2059 return failure(isFailed);
2060 });
2061}
2062
2063/// Update the result types of an operation.
2064FailureOr<bool> InferenceTypeUpdate::updateOperation(Operation *op) {
2065 bool anyChanged = false;
2066
2067 for (Value v : op->getResults()) {
2068 auto result = updateValue(v);
2069 if (failed(result))
2070 return result;
2071 anyChanged |= *result;
2072 }
2073
2074 // If this is a connect operation, width inference might have inferred a RHS
2075 // that is wider than the LHS, in which case an additional BitsPrimOp is
2076 // necessary to truncate the value.
2077 if (auto con = dyn_cast<ConnectOp>(op)) {
2078 auto lhs = con.getDest();
2079 auto rhs = con.getSrc();
2080 auto lhsType = type_dyn_cast<FIRRTLBaseType>(lhs.getType());
2081 auto rhsType = type_dyn_cast<FIRRTLBaseType>(rhs.getType());
2082
2083 // Nothing to do if not base types.
2084 if (!lhsType || !rhsType)
2085 return anyChanged;
2086
2087 auto lhsWidth = lhsType.getBitWidthOrSentinel();
2088 auto rhsWidth = rhsType.getBitWidthOrSentinel();
2089 if (lhsWidth >= 0 && rhsWidth >= 0 && lhsWidth < rhsWidth) {
2090 OpBuilder builder(op);
2091 auto trunc = builder.createOrFold<TailPrimOp>(con.getLoc(), con.getSrc(),
2092 rhsWidth - lhsWidth);
2093 if (type_isa<SIntType>(rhsType))
2094 trunc =
2095 builder.createOrFold<AsSIntPrimOp>(con.getLoc(), lhsType, trunc);
2096
2097 LLVM_DEBUG(llvm::dbgs()
2098 << "Truncating RHS to " << lhsType << " in " << con << "\n");
2099 con->replaceUsesOfWith(con.getSrc(), trunc);
2100 }
2101 return anyChanged;
2102 }
2103
2104 // If this is a module, update its ports.
2105 if (auto module = dyn_cast<FModuleOp>(op)) {
2106 // Update the block argument types.
2107 bool argsChanged = false;
2108 SmallVector<Attribute> argTypes;
2109 argTypes.reserve(module.getNumPorts());
2110 for (auto arg : module.getArguments()) {
2111 auto result = updateValue(arg);
2112 if (failed(result))
2113 return result;
2114 argsChanged |= *result;
2115 argTypes.push_back(TypeAttr::get(arg.getType()));
2116 }
2117
2118 // Update the module function type if needed.
2119 if (argsChanged) {
2120 module.setPortTypesAttr(ArrayAttr::get(module.getContext(), argTypes));
2121 anyChanged = true;
2122 }
2123 }
2124 return anyChanged;
2125}
2126
2127/// Resize a `uint`, `sint`, or `analog` type to a specific width.
2128static FIRRTLBaseType resizeType(FIRRTLBaseType type, uint32_t newWidth) {
2129 auto *context = type.getContext();
2131 .Case<UIntType>([&](auto type) {
2132 return UIntType::get(context, newWidth, type.isConst());
2133 })
2134 .Case<SIntType>([&](auto type) {
2135 return SIntType::get(context, newWidth, type.isConst());
2136 })
2137 .Case<AnalogType>([&](auto type) {
2138 return AnalogType::get(context, newWidth, type.isConst());
2139 })
2140 .Default([&](auto type) { return type; });
2141}
2142
2143/// Update the type of a value.
2144FailureOr<bool> InferenceTypeUpdate::updateValue(Value value) {
2145 // Check if the value has a type which we can update.
2146 auto type = type_dyn_cast<FIRRTLType>(value.getType());
2147 if (!type)
2148 return false;
2149
2150 // Fast path for types that have fully inferred widths.
2151 if (!hasUninferredWidth(type))
2152 return false;
2153
2154 // If this is an operation that does not generate any free variables that
2155 // are determined during width inference, simply update the value type based
2156 // on the operation arguments.
2157 if (auto op = dyn_cast_or_null<InferTypeOpInterface>(value.getDefiningOp())) {
2158 SmallVector<Type, 2> types;
2159 auto res =
2160 op.inferReturnTypes(op->getContext(), op->getLoc(), op->getOperands(),
2161 op->getAttrDictionary(), op->getPropertiesStorage(),
2162 op->getRegions(), types);
2163 if (failed(res))
2164 return failure();
2165
2166 assert(types.size() == op->getNumResults());
2167 for (auto [result, type] : llvm::zip(op->getResults(), types)) {
2168 LLVM_DEBUG(llvm::dbgs()
2169 << "Inferring " << result << " as " << type << "\n");
2170 result.setType(type);
2171 }
2172 return true;
2173 }
2174
2175 // Recreate the type, substituting the solved widths.
2176 auto *context = type.getContext();
2177 unsigned fieldID = 0;
2178 std::function<FIRRTLBaseType(FIRRTLBaseType)> updateBase =
2179 [&](FIRRTLBaseType type) -> FIRRTLBaseType {
2180 auto width = type.getBitWidthOrSentinel();
2181 if (width >= 0) {
2182 // Known width integers return themselves.
2183 fieldID++;
2184 return type;
2185 }
2186 if (width == -1) {
2187 // Unknown width integers return the solved type.
2188 auto newType = updateType(FieldRef(value, fieldID), type);
2189 fieldID++;
2190 return newType;
2191 }
2192 if (auto bundleType = type_dyn_cast<BundleType>(type)) {
2193 // Bundle types recursively update all bundle elements.
2194 fieldID++;
2195 llvm::SmallVector<BundleType::BundleElement, 3> elements;
2196 for (auto &element : bundleType) {
2197 auto updatedBase = updateBase(element.type);
2198 if (!updatedBase)
2199 return {};
2200 elements.emplace_back(element.name, element.isFlip, updatedBase);
2201 }
2202 return BundleType::get(context, elements, bundleType.isConst());
2203 }
2204 if (auto vecType = type_dyn_cast<FVectorType>(type)) {
2205 fieldID++;
2206 auto save = fieldID;
2207 // TODO: this should recurse into the element type of 0 length vectors and
2208 // set any unknown width to 0.
2209 if (vecType.getNumElements() > 0) {
2210 auto updatedBase = updateBase(vecType.getElementType());
2211 if (!updatedBase)
2212 return {};
2213 auto newType = FVectorType::get(updatedBase, vecType.getNumElements(),
2214 vecType.isConst());
2215 fieldID = save + vecType.getMaxFieldID();
2216 return newType;
2217 }
2218 // If this is a 0 length vector return the original type.
2219 return type;
2220 }
2221 llvm_unreachable("Unknown type inside a bundle!");
2222 };
2223
2224 // Update the type.
2225 auto newType = mapBaseTypeNullable(type, updateBase);
2226 if (!newType)
2227 return failure();
2228 LLVM_DEBUG(llvm::dbgs() << "Update " << value << " to " << newType << "\n");
2229 value.setType(newType);
2230
2231 // If this is a ConstantOp, adjust the width of the underlying APInt.
2232 // Unsized constants have APInts which are *at least* wide enough to hold
2233 // the value, but may be larger. This can trip up the verifier.
2234 if (auto op = value.getDefiningOp<ConstantOp>()) {
2235 auto k = op.getValue();
2236 auto bitwidth = op.getType().getBitWidthOrSentinel();
2237 if (k.getBitWidth() > unsigned(bitwidth))
2238 k = k.trunc(bitwidth);
2239 op->setAttr("value", IntegerAttr::get(op.getContext(), k));
2240 }
2241
2242 return newType != type;
2243}
2244
2245/// Update a type.
2246FIRRTLBaseType InferenceTypeUpdate::updateType(FieldRef fieldRef,
2247 FIRRTLBaseType type) {
2248 assert(type.isGround() && "Can only pass in ground types.");
2249 auto value = fieldRef.getValue();
2250 // Get the inferred width.
2251 Expr *expr = mapping.getExprOrNull(fieldRef);
2252 if (!expr || !expr->getSolution()) {
2253 // It should not be possible to arrive at an uninferred width at this point.
2254 // In case the constraints are not resolvable, checks before the calls to
2255 // `updateType` must have already caught the issues and aborted the pass
2256 // early. Might turn this into an assert later.
2257 mlir::emitError(value.getLoc(), "width should have been inferred");
2258 return {};
2259 }
2260 int32_t solution = *expr->getSolution();
2261 assert(solution >= 0); // The solver infers variables to be 0 or greater.
2262 return resizeType(type, solution);
2263}
2264
2265//===----------------------------------------------------------------------===//
2266// Pass Infrastructure
2267//===----------------------------------------------------------------------===//
2268
2269namespace {
2270class InferWidthsPass
2271 : public circt::firrtl::impl::InferWidthsBase<InferWidthsPass> {
2272 void runOnOperation() override;
2273};
2274} // namespace
2275
2276void InferWidthsPass::runOnOperation() {
2277 // Collect variables and constraints
2278 ConstraintSolver solver;
2279 InferenceMapping mapping(solver, getAnalysis<SymbolTable>(),
2280 getAnalysis<hw::InnerSymbolTableCollection>());
2281 if (failed(mapping.map(getOperation())))
2282 return signalPassFailure();
2283
2284 // fast path if no inferrable widths are around
2285 if (mapping.areAllModulesSkipped())
2286 return markAllAnalysesPreserved();
2287
2288 // Solve the constraints.
2289 if (failed(solver.solve()))
2290 return signalPassFailure();
2291
2292 // Update the types with the inferred widths.
2293 if (failed(InferenceTypeUpdate(mapping).update(getOperation())))
2294 return signalPassFailure();
2295}
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static void print(TypedAttr val, llvm::raw_ostream &os)
static unsigned getFieldID(BundleType type, unsigned index)
static FIRRTLBaseType updateType(FIRRTLBaseType oldType, unsigned fieldID, FIRRTLBaseType fieldType)
Update the type of a single field within a type.
std::pair< std::optional< int32_t >, bool > ExprSolution
static ExprSolution computeUnary(ExprSolution arg, llvm::function_ref< int32_t(int32_t)> operation)
static uint64_t convertFieldIDToOurVersion(uint64_t fieldID, FIRRTLType type)
Calculate the "InferWidths-fieldID" equivalent for the given fieldID + type.
static ExprSolution computeBinary(ExprSolution lhs, ExprSolution rhs, llvm::function_ref< int32_t(int32_t, int32_t)> operation)
#define EXPR_KINDS
#define EXPR_CLASSES
static FIRRTLBaseType resizeType(FIRRTLBaseType type, uint32_t newWidth)
Resize a uint, sint, or analog type to a specific width.
static void diagnoseUninferredType(InFlightDiagnostic &diag, Type t, Twine str)
static bool hasUninferredWidth(Type type)
Check if a type contains any FIRRTL type with uninferred widths.
static ExprSolution solveExpr(Expr *expr, SmallPtrSetImpl< Expr * > &seenVars, std::vector< Frame > &worklist)
Compute the value of a constraint expr.
This class represents a reference to a specific field or element of an aggregate value.
Definition FieldRef.h:28
unsigned getFieldID() const
Get the field ID of this FieldRef, which is a unique identifier mapped to a specific field in a bundl...
Definition FieldRef.h:61
Value getValue() const
Get the Value which created this location.
Definition FieldRef.h:39
bool isConst() const
Returns true if this is a 'const' type that can only hold compile-time constant values.
This class implements the same functionality as TypeSwitch except that it uses firrtl::type_dyn_cast ...
FIRRTLTypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
bool isGround()
Return true if this is a 'ground' type, aka a non-aggregate type.
This class represents a collection of InnerSymbolTable's.
FIRRTLType mapBaseTypeNullable(FIRRTLType type, function_ref< FIRRTLBaseType(FIRRTLBaseType)> fn)
Return a FIRRTLType with its base type component mutated by the given function.
FieldRef getFieldRefForTarget(const hw::InnerSymTarget &ist)
Get FieldRef pointing to the specified inner symbol target, which must be valid.
FIRRTLBaseType getBaseType(Type type)
If it is a base type, return it as is.
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const InstanceInfo::LatticeValue &value)
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
llvm::hash_code hash_value(const ClassElement &element)
std::pair<::mlir::Type, uint64_t > getSubTypeByFieldID(Type, uint64_t fieldID)
::mlir::Type getFinalTypeByFieldID(Type type, uint64_t fieldID)
static bool operator==(const ModulePort &a, const ModulePort &b)
Definition HWTypes.h:36
void info(Twine message)
Definition LSPUtils.cpp:20
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
llvm::raw_ostream & debugHeader(const llvm::Twine &str, unsigned width=80)
Write a "header"-like string to the debug stream with a certain width.
Definition Debug.cpp:17
Definition debug.py:1
llvm::hash_code hash_value(const DenseSet< T > &set)
llvm::hash_code hash_value(const T &e)
This class represents the namespace in which InnerRef's can be resolved.