Exception connecting Vec of IO - chisel

Can anyone explain what the problem with this construction is? I have a child module with a Vec of IO that I'm trying to attach to the equivilent IO in the parent module.
This works out fine with just a Seq but I get an exception during elaboration when wrapped up in Vec. The Vec is needed since in my real case that gets indexed with a hardware signal in the child module.
The error:
[error] chisel3.internal.ChiselException: Connection between left (MyBundle[3](Wire in Lower)) and source (MyBundle[3](Wire in Upper)) failed #(0).out: Left or Right unavailable to current module.
The code:
package Testcase
import chisel3._
import chisel3.util._
import chisel3.stage.ChiselStage
import amba._
class MyBundle extends Bundle {
val out = Output(UInt(32.W))
}
class Upper (n : Int) extends RawModule {
val io = VecInit(Seq.fill(n)(IO(new MyBundle)))
val lower = Module(new Lower(n))
// This should word in the Vec case but gets the same error
// lower.io <> io
// This works for non Vec case
(lower.io, io).zipped map (_ <> _)
}
class Lower (n : Int) extends RawModule {
val io = VecInit(Seq.fill(n)(IO(new MyBundle)))
for (i <- 0 to n - 1) {
io(i).out := 0.U
}
}
object VerilogMain extends App {
(new ChiselStage).emitVerilog(new Upper(3), Array("--target-dir", "generated"))
}

The issue here is that VecInit creates a Wire of type Vec and connects everything in the Seq to the elements of that Wire. What you're basically doing is creating a Seq of IOs and then connecting them to a Wire.
This is mentioned in the error message (eg. (MyBundle[3](Wire in Lower))) but I totally see the confusion--it's not all that clear and VecInit is probably misnamed. This particular ambiguity in the API comes from historical design decisions in Chisel that are slowly getting fixed but it is a wart that sometimes bites users, sorry about that.
Here's the right way to accomplish what you want, just using IO(Vec(<n>, <type>)). Vec(<n>, <type>) is the way to create something of type Vec, in this case an IO of type Vec, as opposed to creating a Wire and connecting all of the fields:
class Upper (n : Int) extends RawModule {
//val io = VecInit(Seq.fill(n)(IO(new MyBundle)))
val io = IO(Vec(n, new MyBundle))
val lower = Module(new Lower(n))
// This should word in the Vec case but gets the same error
lower.io <> io
}
class Lower (n : Int) extends RawModule {
//val io = VecInit(Seq.fill(n)(IO(new MyBundle)))
val io = IO(Vec(n, new MyBundle))
for (i <- 0 to n - 1) {
io(i).out := 0.U
}
}
(Scastie link: https://scastie.scala-lang.org/COb88oXGRmKQb7BZ3id9gg)

Related

Implementing a diplomatic AXI Stream interface in Chisel - BundleMap.cloneType error

I am trying to build a minimal example, of how to generate an AXI4Stream interface using Chisel and diplomacy. I am using the diplomatic interface already available in rocket-chip (freechips.rocketchip.amba.axis). I have some experience with Chisel, but I am still trying to learn diplomacy.
Anyway, I've managed to create a small APB example using the answer provided here: IP block generation/testing when using diplomacy. Possible to give dummy node?
Following that, I tried to create a similar, simple AXI Stream example, but I keep getting errors. Concretely, I get the following error:
[error] (Compile / run) java.lang.Exception: Unable to use BundleMap.cloneType on class freechips.rocketchip.amba.axis.AXISBundleBits, probably because class freechips.rocketchip.amba.axis.AXISBundleBits does not have a constructor accepting BundleFields. Consider overriding cloneType() on class freechips.rocketchip.amba.axis.AXISBundleBits
The code:
package chipyard.example
import chisel3._
import chisel3.internal.sourceinfo.SourceInfo
import chisel3.stage.ChiselStage
import freechips.rocketchip.config.{Config, Parameters}
import freechips.rocketchip.amba.axis._
import freechips.rocketchip.diplomacy.{SimpleNodeImp, ValName, SourceNode, NexusNode,
SinkNode, LazyModule, LazyModuleImp, TransferSizes,
SimpleDevice, AddressSet}
class MyAxisController(implicit p: Parameters) extends LazyModule {
val device = new SimpleDevice("my-device", Seq("tutorial,my-device0"))
val axisParams = AXISSlaveParameters.v1(name = "axisSlave", supportsSizes = TransferSizes(8,8))
val axisPortParams = AXISSlavePortParameters.v1(slaves = Seq(axisParams))
val node = AXISSlaveNode(portParams = Seq(axisPortParams))
lazy val module = new LazyModuleImp(this) {
val ins = node.in.unzip._1
val register = RegInit(UInt(8.W), 0.U)
register := register + ins(0).bits.data
}
}
class AXISMaster()(implicit p: Parameters) extends LazyModule {
val axisMasterParams = AXISMasterParameters.v1(
name = "axisMaster", emitsSizes = TransferSizes(8, 8)
)
val axisMasterPortParams = AXISMasterPortParameters.v1(
masters = Seq(axisMasterParams),
beatBytes = Option(8)
)
val node = AXISMasterNode(
portParams = Seq(axisMasterPortParams)
)
lazy val module = new LazyModuleImp(this) {
//The dontTouch here preserves the interface so logic is generated
dontTouch(node.out.head._1)
}
}
class MyAxisWrapper()(implicit p: Parameters) extends LazyModule {
val master = LazyModule(new AXISMaster)
val slave = LazyModule(new MyAxisController()(Parameters.empty))
slave.node := master.node
lazy val module = new LazyModuleImp(this) {
//nothing???
}
}
and Main.scala:
package chipyard.example
import chisel3._
import freechips.rocketchip.config.Parameters
import freechips.rocketchip.diplomacy._
import java.io.File
import java.io.FileWriter
/**
* An object extending App to generate the Verilog code.
*/
object Main {
def main(args: Array[String]): Unit = {
//(new chisel3.stage.ChiselStage).execute(args, Seq(ChiselGeneratorAnnotation(() => LazyModule(new MyWrapper()(Parameters.empty)).module)))
val verilog = (new chisel3.stage.ChiselStage).emitVerilog(
LazyModule(new MyAxisWrapper()(Parameters.empty)).module
)
//println(s"```verilog\n$verilog```")
val fileWriter = new FileWriter(new File("./gen/gen.v"))
fileWriter.write(verilog)
fileWriter.close()
}
}
The code is also available at https://github.com/jurevreca12/temp_dspblock_example/tree/axistream2/scala/main.
My question is. Why do I get this error? Or am I doing something wrong in the first place, and is there an easier way to create an AXIStream module?
I appreciate any feedback.
This looks to be an issue with Rocket-Chip's changes to bump to Chisel 3.5. During those changes, AXISBundleBits had its cloneType removed even though it extends off BundleMap (and therefore requires cloneType due to extending off Record).
I don't have all the details of cloneType at this time, but essentially:
Records require cloneType
Bundles used to require cloneType, but since the compiler plugin was implemented, as of 3.5 they no longer require cloneType.
BundleMap is a confusing case because it is a custom Bundle type extending directly off Record and isn't of type Bundle. Therefore, it shouldn't have had its cloneType method removed during the 3.5 Chisel bump and that will need to be added back for AXIS in RC's main branch to start working again.
Edit: the cloneType exception issue is now fixed for 3.5 on the main branch :)

How to exchange certain bits of the register

I want to exchange certain bits of a register variable, just like the following example.
val data = Reg(UInt(100.W))
val re_order1 = Wire(UInt(log2Ceil(100).W))
val re_order2 = Wire(UInt(log2Ceil(100).W))
//Exchange the bits of the data register in re_order1 and re_order2
data(re_order1) := data(re_order2)
data(re_order2) := data(re_order1)
I tried to use shift and mask to achieve, but found it will be very complicated, is there a simple way
The following chisel Module does what I think you are aiming for here, that is: flip two arbitrary dynamically indexed bits in a register. This is going to require a lot of Muxes to accomplish this but I think this example shows that chisel can generate those pretty cleanly. The basic strategy is to treat the register as a Vec of bools then create a Mux every one of those bools to any other bit, based on whether the bit is referenced as one of the two bit addresses.
Then convert the sequences of generated as a new Vec using VecInit and then convert that vec to a UInt and wire it back into reg.
This module has a little bit of additional code to load the register. You may want to do that some other way.
import chisel3._
import chisel3.util.log2Ceil
import chiseltest._
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
class FlipBits(bitWidth: Int) extends Module {
val io = IO(new Bundle {
val load = Input(Bool())
val loadValue = Input(UInt(bitWidth.W))
val bitAddress1 = Input(UInt(log2Ceil(bitWidth).W))
val bitAddress2 = Input(UInt(log2Ceil(bitWidth).W))
val out = Output(UInt(bitWidth.W))
})
val reg = RegInit(0.U(bitWidth.W))
val bits = VecInit(reg.asBools())
when(io.load) {
reg := io.loadValue
}.otherwise {
reg := VecInit(bits.indices.map { index =>
val index1 = Mux(index.U === io.bitAddress1, io.bitAddress2, index.U)
val index2 = Mux(index.U === io.bitAddress2, io.bitAddress1, index1)
bits(index2)
}).asUInt
}
io.out := reg
}

Chisel Bundle connection and type Safety

Just noticed you can do something like:
class MyBundle1 extends Bundle {
val a = Bool()
val x = UInt(2.W)
val y = Bool()
}
class MyBundle2 extends Bundle {
val x = Bool()
val y = Bool()
}
class Foo extends Module {
val io = IO(new Bundle {
val in = Input(new MyBundle1)
val out = Output(new MyBundle2)
})
io.out := io.in
}
not get an error and actually get the correct or, at least, expected verilog. One would think that Chisel was type-safe wrt to Bundles in this sort of bulk connection. Is this intentional? If so, is there any particular reasons for it?
The semantics of := on Bundle allow the RHS to have fields that are not present on the LHS, but not vice-versa. The high-level description of x := y is "drive all fields of x with corresponding fields of y."
The bi-directional <> operator is stricter.
I can't speak precisely to the reasoning, but connection operators are often a matter of taste with respect to "do what I mean." The idea of including alternate forms of connection operators for future releases is an ongoing discussion, with the threat of "operator glut" being weighed against the ability of users to specify exactly what they'd like to do.

chisel-firrtl combinational loop handling

I have met some troubles while simulating design that contains comb-loop. Firrtl throws exception like
"No valid linearization for cyclic graph"
while verilator backend goes normal with warnings.
Is it possible to simulate such design with firrtl backend?
And can we apply --no-check-comb-loops not for all design but for some part of it while elaborating?
Example code here:
import chisel3._
import chisel3.iotesters.PeekPokeTester
import org.scalatest.{FlatSpec, Matchers}
class Xor extends core.ImplicitModule {
val io = IO(new Bundle {
val a = Input(UInt(4.W))
val b = Input(UInt(4.W))
val out = Output(UInt(4.W))
})
io.out <> (io.a ^ io.b)
}
class Reverse extends core.ImplicitModule {
val io = IO(new Bundle {
val in = Input(UInt(4.W))
val out = Output(UInt(4.W))
})
io.out <> util.Reverse(io.in)
}
class Loop extends core.ImplicitModule {
val io = IO(new Bundle {
val a = Input(UInt(4.W))
val b = Input(UInt(4.W))
val mux = Input(Bool())
val out = Output(UInt(4.W))
})
val x = Module(new Xor)
val r = Module(new Reverse)
r.io.in <> Mux(io.mux, io.a, x.io.out)
x.io.a <> Mux(io.mux, r.io.out, io.a)
x.io.b <> io.b
io.out <> Mux(io.mux, x.io.out, r.io.out)
}
class LoopBackExampleTester(cc: Loop) extends PeekPokeTester(cc) {
poke(cc.io.mux, false)
poke(cc.io.a, 0)
poke(cc.io.b, 1)
step(1)
expect(cc.io.out, 8)
}
class LoopBackExample extends FlatSpec with Matchers {
behavior of "Loop"
it should "work" in {
chisel3.iotesters.Driver.execute(Array("--no-check-comb-loops", "--fr-allow-cycles"), () => new Loop) { cc =>
new LoopBackExampleTester(cc)
} should be(true)
}
}
I will start by noting that Chisel is intended to make synchronous, flop-based, digital design easier and more flexible. It is not intended to represent all possible digital circuits. Fundamentally, Chisel exists to make the majority of stuff easier while leaving things that tend to be more closely coupled to implementation technology (like Analog) to Verilog or other languages.
Chisel (well FIRRTL) does not support such apparent combinational loops even if it possible to show that the loop can't occur due to the actual values on the mux selects. Such loops break timing analysis in synthesis and can make it difficult to create a sensible circuit. Furthermore, it isn't really true that the loop "can't occur". Unless there is careful physical design done here, there will likely be brief moments (a tiny fraction of a clock cycle) where there will be shorts which can cause substantial problems in your ASIC. Unless you are building something like a ring oscillator, most physical design teams will ask you not to do this anyway. For the cases where it is necessary, these designs typically are closely tied to the implementation technology (hand designed with standard cells) and as such are not really within the domain of Chisel.
If you need such a loop, you can express it in Verilog and instantiate the design as a BlackBox in your Chisel.

Vector of RegEnable

Looking for an example/advice on how to use RegEnable as vector.
Also I want to control the inputs & enable signals to be a function of the register index in the Vector.
So first, how do I declare Vector of RegEnable(), and second how to iterate over it and connect the input & enable. In the RegEnable() case the declaration and the connection are made in the same statement. Something like:
for (j <- 0 until len) {
val pipe(j) = RegEnable(in(j),en(j))
}
The above code doesn't compile. Also in & en are vectors or bit selection
For this type of thing, it's likely much easier to use RegEnable to construct a Seq[T <: Data] and then construct a Vec out of that. The Vec object has two main apply methods: a varargs one and a seq. For your own reference, take a look at the Chisel Vec object API documentation.
The following full example builds, but the relevant part is the val pipe and val pipe2 lines. You can do this with either a map or a for/yield.
import chisel3._
import chisel3.util.RegEnable
import chisel3.iotesters
import chisel3.experimental.MultiIOModule
class Example(len: Int) extends MultiIOModule {
val in = Seq.fill(len)(IO(Input(UInt(1.W))))
val en = Seq.fill(len)(IO(Input(Bool())))
val mySeq: Seq[Data] = (0 until len).map( j => RegEnable(in(j), en(j)) )
val pipe = Vec(mySeq)
val mySeq2: Seq[Data] = for (j <- 0 until len) yield ( RegEnable(in(j), en(j)) )
val pipe2 = Vec(mySeq2)
}