Skip to content

Commit db93161

Browse files
Fix SInt literals to reject too small of widths (#4786)
Co-authored-by: Schuyler Eldridge <[email protected]>
1 parent a7effb7 commit db93161

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

core/src/main/scala/chisel3/internal/firrtl/IR.scala

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,9 @@ private[chisel3] object ir {
171171
val unsigned = if (n < 0) (BigInt(1) << width.get) + n else n
172172
s"asSInt(${ULit(unsigned, width).name})"
173173
}
174-
def minWidth: Int = (if (w.known) 0 else 1) + n.bitLength
174+
175+
// Special case for 0 which can be specified to zero-width (but defaults to 1 bit).
176+
def minWidth: Int = if (n == 0 && w.known) 0 else 1 + n.bitLength
175177

176178
def cloneWithWidth(newWidth: Width): this.type = {
177179
SLit(n, newWidth).asInstanceOf[this.type]

src/test/scala-2/chiselTests/SIntOps.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,4 +284,18 @@ class SIntOpsSpec extends AnyPropSpec with Matchers with ShiftRightWidthBehavior
284284
blit.x.litOption should be(Some(2))
285285
blit.y.litOption should be(Some(9))
286286
}
287+
288+
property("SInt literals with too small of a width should be rejected") {
289+
// Sanity checks.
290+
0.S.getWidth should be(1)
291+
0.S(0.W).getWidth should be(0)
292+
-1.S.getWidth should be(1)
293+
1.S.getWidth should be(2)
294+
// The real check.
295+
-2.S.getWidth should be(2)
296+
an[IllegalArgumentException] shouldBe thrownBy(-2.S(1.W))
297+
0xde.S.getWidth should be(9)
298+
an[IllegalArgumentException] shouldBe thrownBy(0xde.S(8.W))
299+
an[IllegalArgumentException] shouldBe thrownBy(0xde.S(4.W))
300+
}
287301
}

0 commit comments

Comments
 (0)