Search code examples
chisel

How to initialize a Reg of Bundle in Chisel?


I declared a Bundle for my specific data :

class RValue (val cSize: Int = 16) extends Bundle {
  val rvalue = Output(UInt(cSize.W))
  val er     = Output(UInt((cSize/2).W))
  val part   = Output(Bool()) /* set if value is partial */
}

And I want to use it as a register in my module :

  val valueReg = Reg(new RValue(cSize))
//...
  valueReg.rvalue := 0.U
  valueReg.er := 0.U

That works well. But I want to initialize it at Register declaration with RegInit(). Is it Possible ?

  val valueReg = RegInit(new RValue(cSize), ?? ) ??

Solution

  • Chick's answer of using Bundle Literals is the cool new way and is nice because you can give a Bundle arbitrary values in a single expression.

    If you just want to zero-out the register at reset type, you could always cast from a literal zero to the Bundle:

    val valueReg = RegInit(0.U.asTypeOf(new RValue(cSize))
    

    You can do similar things with any literal if you want, but I wouldn't recommend it unless you're zeroing out or setting everything to 1s.

    For setting each field to some other value, I think Chick's way is better, but the normal style you'll see in older code is something like:

    val valueReg = RegInit({
      val bundle = Wire(new RValue(cSize))
      bundle.rvalue := 1.U
      bundle.er := 2.U
      bundle.part := 3.U
      bundle
    })
    

    In Scala, you can put { } anywhere an expression is needed and the last expression in the Block will be the return value. Thus we can create a Wire with the values we want to reset the register to and then pass that Bundle as the initialization value. It would be equivalent to write:

    val valueRegInit = Wire(new RValue(cSize))
    valueRegInit.rvalue := 1.U
    valueRegInit.er := 2.U
    valueRegInit.part := 3.U
    val valueReg = RegInit(valueRegInit)
    

    I hope this helps!