diff --git a/core/src/main/scala/chisel3/internal/firrtl/IR.scala b/core/src/main/scala/chisel3/internal/firrtl/IR.scala index 5551a5944b2..88810159412 100644 --- a/core/src/main/scala/chisel3/internal/firrtl/IR.scala +++ b/core/src/main/scala/chisel3/internal/firrtl/IR.scala @@ -170,7 +170,9 @@ private[chisel3] object ir { val unsigned = if (n < 0) (BigInt(1) << width.get) + n else n s"asSInt(${ULit(unsigned, width).name})" } - def minWidth: Int = (if (w.known) 0 else 1) + n.bitLength + + // Special case for 0 which can be specified to zero-width (but defaults to 1 bit). + def minWidth: Int = if (n == 0 && w.known) 0 else 1 + n.bitLength def cloneWithWidth(newWidth: Width): this.type = { SLit(n, newWidth).asInstanceOf[this.type] diff --git a/src/test/scala/chiselTests/SIntOps.scala b/src/test/scala/chiselTests/SIntOps.scala index c5450c76cb3..452ef793773 100644 --- a/src/test/scala/chiselTests/SIntOps.scala +++ b/src/test/scala/chiselTests/SIntOps.scala @@ -248,4 +248,44 @@ class SIntOpsSpec extends ChiselPropSpec with Utils { -5.S(8.W).pad(16).litValue should be(-5) -5.S(8.W).pad(16).getWidth should be(16) } +<<<<<<< HEAD:src/test/scala/chiselTests/SIntOps.scala +||||||| parent of db931617 (Fix SInt literals to reject too small of widths (#4786)):src/test/scala-2/chiselTests/SIntOps.scala + + property("Casting a SInt literal to a Bundle should maintain the literal value") { + class SimpleBundle extends Bundle { + val x = UInt(4.W) + val y = UInt(4.W) + } + val blit = -23.S.asTypeOf(new SimpleBundle) + blit.litOption should be(Some(0x29)) + blit.x.litOption should be(Some(2)) + blit.y.litOption should be(Some(9)) + } +======= + + property("Casting a SInt literal to a Bundle should maintain the literal value") { + class SimpleBundle extends Bundle { + val x = UInt(4.W) + val y = UInt(4.W) + } + val blit = -23.S.asTypeOf(new SimpleBundle) + blit.litOption should be(Some(0x29)) + blit.x.litOption should be(Some(2)) + blit.y.litOption should be(Some(9)) + } + + property("SInt literals with too small of a width should be rejected") { + // Sanity checks. + 0.S.getWidth should be(1) + 0.S(0.W).getWidth should be(0) + -1.S.getWidth should be(1) + 1.S.getWidth should be(2) + // The real check. + -2.S.getWidth should be(2) + an[IllegalArgumentException] shouldBe thrownBy(-2.S(1.W)) + 0xde.S.getWidth should be(9) + an[IllegalArgumentException] shouldBe thrownBy(0xde.S(8.W)) + an[IllegalArgumentException] shouldBe thrownBy(0xde.S(4.W)) + } +>>>>>>> db931617 (Fix SInt literals to reject too small of widths (#4786)):src/test/scala-2/chiselTests/SIntOps.scala }