Search code examples
hdlchisel

How to get size of UInt() in chisel?


Maybe it's easy but I can't simply found how to get the bitsize of an UInt() value in Chisel ?

I know how to set a size by declaration :

val a = UInt(INPUT, 16)

But to get the 'a' size, is there a property like :

val size = a.?

Or :

val size = width(a)

Solution

  • A couple of things. First, looks like you are using Chisel 2 semantics. You should probably be using Chisel 3 semantics which means you should be writing

    val a = Input(UInt(16.W))
    

    The quick answer is you can get the width like:

    val theWidth = if(io.in0.widthKnown) io.in0.getWidth else -1
    

    or using match

    val theWidth = io.in0.widthOption match {
      case Some(w) => w
      case None => -1 // you decide what you want the unknown case to be.
    }
    

    You now have the value of the width in the Scala variable theWidth which is an Int, the if or the match must be used because the width may, in principle, be undefined.

    The longer answer is that you should be careful with wanting to do this. theWidth is evaluated at circuit generation time, if width inference is being used (which is usually the case if you are interrogating a chisel type for its width) you won't be able to see it because width inference is done after the circuit is elaborated and it is processed by the Firrtl compiler.

    It's possible you should make the width you want to know a parameter to the circuit and use that instead of widthOption. Something like.

    class X(ioWidth: Int) extends Module {
      val io = IO( new Bundle {
        val in0 = Input(UInt(ioWidth.W))
        ...
      })
    
      val reg = Reg(UInt((ioWidth * 2).W)) // using width parameter here.
      ...
    }