Using Parameters to declare variable-sized Vec - chisel

I'm trying to have a variable-sized array based on a Module Paramete (example below). When the size PARAM is non-zero, the code works as intended.
class HWModule (PARAM : Int) extends Module{
val my_Vec = RegInit(Vec(Seq.fill(PARAM)(0.U(32.W))))
if (PARAM > 0){
for (i <- 0 until PARAM -1){
my_Vec(i) := i.U //Example Code
}
}
}
However, when I try to have PARAM = 0, it stops working. I've tried using Patter Matching (How do I write to a conditional output) to solve the problem, but I get the following error messages (and similar ones):
Equals does not take parameters
Expression does not convert to assignment because receiver is not assignable.
My goal is to be able to remove certain portions of code when PARAM = 0, while also allowing to variable-sized instantiation of Vecs, Regs, Wires, etc.
If anyone could point me to a good solution or information about it, I would appreciate it.
Thank you,
Miguel Silva

Maybe you can use Option like this :
val my_Vec_or_none = if(PARAM > 0) Some(RegInit(Vec(Seq.fill(PARAM))(0.U(32.W)))) else None
Then get register with get method :
if (PARAM > 0){
val my_Vec = my_Vec_or_none.get
for (i <- 0 until PARAM -1){
my_Vec(i) := i.U //Example Code
}
}
Also you can use indexed value directly (without intermediate val) :
val my_Vec = if(PARAM > 0) Some(RegInit(Vec(Seq.fill(PARAM))(0.U(32.W)))) else None
if (PARAM > 0){
for (i <- 0 until PARAM -1){
my_Vec.get(i) := i.U //Example Code
}
}
And use this variable in another part of the code.

Related

Is there an accepted way to get a Gray Code counter in Chisel?

I'm looking to write counters in Chisel3 that will be used to address subunits. If the counter matches some register in a subunit then the subunit fires, otherwise it doesn't.
I would much rather have the addresses cycle in Gray code than in binary. It's easy enough to write a binary counter in Chisel, but I see no provision for a Gray code counter.
I can write a new type akin to Uint and Sint, but I'm reluctant to reinvent it if it's already out there. Yet I don't see anything in the cookbook or other docs about Gray code. Github just turns up a Minecraft-oriented repo (because it matches "chisel") There is existing stuff for VHDL but I want to express this in Chisel.
So have I missed a resource that would provide a Gray counter in Chisel? Failing that, is building a new type akin to Uint a reasonable way to proceed?
I did a quick look around and didn't find anything quite like what you're looking for. The closest thing I could find was a simple Gray counter in rocket-chip (https://github.com/chipsalliance/rocket-chip/blob/29ce00180f2a69947546d6385a1da86cbc584376/src/main/scala/util/AsyncQueue.scala#L49) but it uses regular binary counting and then just returns a UInt in Gray code. It also doesn't take advantage of any Scala type safety.
I think this would be a reasonable thing to build, and if you want you could contribute it to https://github.com/freechipsproject/ip-contributions for increased visibility.
I think if you wanted a proper GrayCode type, it would be reasonable to create a custom type. Unfortunately, there is no way to extend Data for a Bits-like type (all of the types in that hierarchy are sealed), but you could create a custom Bundle that wraps a UInt and then implement your own set of operations, eg.
class GrayCode(private val w: Int) extends Bundle {
val value = UInt(w.W)
def +(that: GrayCode): GrayCode = ???
}
object GrayCode {
// Lets you write GrayCode(4.W)
// Width is defined in chisel3.internal.firrtl though which is awkward...
def apply(width: Width): GrayCode = ???
}
This is just a quick sketch. The DSP Tools library has examples of custom types for DSP: https://github.com/ucb-bar/dsptools
They tend to use Scala Typeclasses a lot which is a more advanced Scala feature. Just mentioning in case some of the syntax in their looks alien.
You might take a look at this link programmersought gray code fifo it seems like it may be relevant but I am not familiar with it otherwise.
As with Jack I'm not familiar with the math needed to actually increment values in Gray code, but something like the following code would convert Gray code to binary, add, then convert it back to Gray code. I'm not sure if the Vec() code below would work correctly but should make the idea clear.
import chisel3._
import chisel3.util._
class GrayCode(private val w: Int) extends Bundle {
val value = UInt(w.W)
def bin2grey(x : UInt) : UInt = {
x ^ (x >> 1.U)
}
def grey2bin(x : UInt, n : Int) : UInt = {
val tmp = Wire(Vec(n, Bool()))
tmp(n-1) := x(n-1)
for (i <- 0 to (n-2)) {
tmp(i) := x(i) ^ tmp(i+1)
}
Cat(tmp.reverse)
}
def +(that: GrayCode): GrayCode = {
val sum = new GrayCode(w)
sum.value := grey2bin(bin2grey(this.value) + bin2grey(that.value), w)
sum
}
}
It seems like all implementations here use binary-to-Gray conversion. For asynchronous FIFOs, this only works if the Gray code is latched just before crossing clock domains. What if you want a counter that actually counts Gray codes instead of converting binary values to Gray codes?
One option is to convert Gray to binary, add, then convert back to Gray and store the result. The other is to use custom arithmetic to calculate the next Gray value in the sequence. The typical sequence is a reflected-binary Gray code, but others exist.
The code below implements a Gray code counter using a reflected-binary Gray code. It was adapted from this blog post. It only counts up. It works like the Chisel Counter object, except it adds support for a synchronous reset and custom register name. It returns the counter and wrap status.
import chisel3._
import chisel3.util._
// a Gray counter counts in Gray code
object GrayCounter {
// Gray unit cell
// b is the current state of this bit
// returns (t, z_o) where t is the next state of this bit
def grayCell(b: Bool, q_i: Bool, z_i: Bool, enable: Bool, parity: Bool): (Bool, Bool) = {
(b ^ (enable && q_i && z_i && parity), (!q_i) && z_i)
}
// cond = counts when true
// n = count value, must be a power of 2
// synchronousReset = resets counter to 0
// name = name for this counter
def apply(cond: Bool, n: Int, synchronousReset: Bool = false.B, name: String = null) = {
require(isPow2(n), s"Gray counter must have power-of-2 length (you asked for $n)")
require(n > 2, s"Gray counter minimum count is 4 (you asked for $n)")
val counter = RegInit(0.U(log2Ceil(n).W))
if (name != null) {
counter.suggestName(name)
}
val counterNext = Wire(Vec(log2Ceil(n), Bool()))
counter := counterNext.asUInt
val z_wires = Wire(Vec(log2Ceil(n), Bool()))
val parity = counter.xorR
for (i <- 0 until log2Ceil(n)) {
if (i == 0) {
val grayCellOut = grayCell(counter(i), true.B, true.B, cond, !parity)
counterNext(i) := grayCellOut._1
z_wires(i) := grayCellOut._2
} else {
val grayCellOut = grayCell(counter(i), counter(i-1) || (i == log2Ceil(n)-1).B,
z_wires(i-1) || (i == 1).B, cond, parity)
counterNext(i) := grayCellOut._1
z_wires(i) := grayCellOut._2
}
}
when (synchronousReset) {
counter := 0.U
}
val wrap = counter === (n/2).U && cond
(counter, wrap)
}
}

"for-loop" to reduce coding on Chisel3.2

I want to code with for-loop for redundant part.
Coding.
//Priority Encoder
class P_Encoder(NumInputs: UInt) extends Module {
val io = new Bundle {
val Req[NumInputs] = Bool(INPUT) //Requests
val Rls[NumInputs] = Bool(INPUT) //Releases
val Grant[NumInputs] = UInt(OUTPUT(log(NumInputs))) //Grants
}
val cnt = 0
for (i<-0 to NumInputs-1) {
when (io.Req[i] & !io.Rls[i]) {
cnt := cnt + 1.W
io.Grant[i] = cnt
}
else {
io.Grant[i] = 0.W
}
}
}
I want to code using "for-loop" to code redundant part.
There are a few minor issues with this code:
Generally we name variables starting with a lower-case letter in Scala, this is primarily style, but it does have semantic meaning it certain circumstances (like pattern matching)
Square brackets are only used for type parameters (like Java generics), indexing uses normal parentheses in Scala
An input Vec of Bools is normally defined as: val req = Input(Vec(numInputs, Bool())) (assuming import chisel3._, but this should also work in Chisel._ for Chisel 3.2)
if and else are used for static parameterization (ie. at hardware elaboration time) while when and .otherwise are used for dynamic logic (eg. actual muxes)
UInt is for hardware types, if you have a static parameter (like numInputs), use a Scala Int
Other than the minor syntactical stuff, the trickiest part of getting this code right is understanding the difference between Scala constructs that are only run at elaboration time (ie. when the Scala program generates the hardware), vs. what actually shows up in the hardware. I would suggest reading this thread from the chisel-users mailing list for some more context about some of this stuff: https://groups.google.com/d/msg/chisel-users/gRoNnH-Y5hE/ynDCtmNPCAAJ
I'm a little confused as to what value io.grant is supposed to get, but I'm assuming it should be the index of the highest priority io.req.
Here's an untested version of your code that I think should work and do what you want:
//Priority Encoder
class P_Encoder(numInputs: Int) extends Module {
// We wrap ports in IO
val io = IO(new Bundle {
val req = Input(Vec(numInputs, Bool()))
val rls = Input(Vec(numInputs, Bool()))
val grant = Output(UInt(log2Up(numInputs).W))
})
io.grant := 0.U // default grant value
// Due to Chisel last connect semantics, the last connection wins
// Thus the highest index will have priority
for (i <- 0 to numInputs - 1) {
when (io.req(i) && !io.rls(i)) {
io.grant := i.U
}
}
}
This code is tricky because it's mixing an elaboration time for loop with hardware whens and connections, I'm going to manually unroll this loop to illustrate what it's doing:
io.grant := 0.U
when (io.req(0) && !io.rls(0)) {
io.grant := 0.U
}
when (io.req(1) && !io.rls(1)) {
io.grant := 1.U
}
when (io.req(2) && !io.rls(2)) {
io.grant := 2.U
}
...
Alternatively, we can just reuse the built-in PriorityEncoder utility if we want
import chisel3.util.PriorityEncoder
val enables = io.req.zip(io.rls).map { case (x, y) => x && !y }
// PriorityEncoder gives priority to *lowest* order bit
io.grant := PriorityEncoder(enables)
I agree with everything #jkoenig says.
In an another example assuming Jack's IO structure, there are times I like
using foldLeft combined with when/elsewhen
io.rel.zip(io.req).zipWithIndex.foldLeft(when(false.B){}) { case (lastWhen,((req, rel), index)) =>
lastWhen.elsewhen(req && !rel) {
io.grant := index.U
}
} otherwise {
io.grant := 0.U
}
when and elsewhen both return a WhenClause which can be used with foldLeft to keep adding clauses.

Chisel : When-otherwise clause not working in function definition

I am trying to develop a simple circuit using Chisel 3 to generate the factorial for a number n. Here's my implementation :
class Factorial extends Module{
val io = IO(new Bundle{
val input = Input(UInt(8.W))
val output = Output(UInt(16.W))
})
def factorial(n: UInt): UInt = {
when (n === 0.U) {1.U}
.otherwise {n*factorial(n-1.U)}
}
io.out := factorial(io.in)
}
However, when I try to run it, I get the following error :
cmd26.sc:9: type mismatch;
found : Unit
required: chisel3.UInt
.otherwise {n*factorial(n-1.U)}
^Compilation Failed
Is there any particular reason for this? How do I solve this issue?
Also, I realize that an easy solution is to just have the number n to be of type Int, and have an if-else clause instead. Is there any way to type cast the parameter being passed during function call (i.e. from chisel3.UInt to Int)?
The Chisel when,elsewhen, and otherwise statement do not return a value.
Your design seems to be an attempt to compute the factorial value for an input in a single cycle. This is only going be practical for small input values and would probably be easier to implement via a lookup table.
I think what you are looking for (which would be a good learning exercise) is to build a circuit that given an input will return the factorial value after some number of cycles. This is very very similar to the way the GCD example works, GCD is included as an example in the chisel-template repo as an example. To do this you will need registers and ready and valid ports.
I suggest you figure out how that works and you should have a much easier time making your factorial. Good luck. And as suggested by #FabienM you will need a very large output port to contain the answer for even modest input values.
I thinks you can't do that. when(){}.otherwise{} is an hardware construction that don't return any value (Unit) as we can see in code.
With this construct you want to generate hardware «on the fly», which is impossible.
I think you have generate all solutions directly like it:
class Factorial extends Module{
val io = IO(new Bundle{
val input = Input(UInt(8.W))
val output = Output(UInt(1676.W))
})
def factorial(n: BigInt): BigInt = {
if(n == 0){
1
}else{
n*factorial(n-1)
}
}
io.output := 0.U
for(i <- 0 to 0xFF) {
when(io.input === i.U){
io.output := factorial(i).U
}
}
}
You can keep your recursive scala fonction but just for hardware generation step.
Note that 255! is a really big number you will need more than 16 bits UInt to output the value ;)

How to specify a return of an array of unknown size in Chapel

I tried to rely on type inference for a function with signature:
proc mode(data: [?]int)
but the compiler said it could not resolve the return type (which is a warning in in itself I guess given there are only two return statements). I tried:
proc mode(data: [?]int): [?]int
but the compiler then said there was an internal error:
internal error: CAL0057 chpl Version 1.13.1.518d486
What is the correct way of specifying that the length of an array returned by a function can only be known at run time?
If the domain/size of the array being returned cannot be described directly in the function prototype, I believe your best bet at present is to omit any description of the return type and lean on Chapel's type inference machinery to determine that you're returning an array (as you attempted). For instance, here is a procedure that reads in an array of previously unknown size and returns it:
proc readArrFromConsole() {
var len = stdin.read(int);
var X: [1..len] real;
for x in X do
x = stdin.read(real);
return X;
}
var A = readArrFromConsole();
writeln(A);
Running it and typing this at the console:
3 1.2 3.4 5.6
Generates:
1.2 3.4 5.6
Your question mentions multiple return statements, which opens up the question about how aggressively Chapel unifies types across distinct arrays. A simple example with multiple arrays of the same type (each with a unique domain, size, and bounds) seems to work:
proc createArr() {
var len = stdin.read(int);
if (len > 0) {
var X: [1..len] real;
return X;
} else {
var Y: [-1..1] real;
return Y;
}
}
var A = createArr();
writeln(A);
To understand why the compiler couldn't resolve the return type in your example may require more information about what your procedure body / return statements contained.
I've come across this from time to time in recursive functions, in situations where omitting the return type fails; in this case I create a record which is an array with its domain, e.g.:
record stringarray {
var D: domain(1);
var strs : [D] string;
}
and then define the recursive array to return one of those records:
proc repeats() : stringarray {
var reps: stringarray;
//...
for child in children do {
childreps = child.repeats();
for childrep in childreps do
reps.push_back(childrep);
}
//...
return reps;
}

Why is my Scala function returning type Unit and not whatever is the last line?

I am trying to figure out the issue, and tried different styles that I have read on Scala, but none of them work. My code is:
....
val str = "(and x y)";
def stringParse ( exp: String, pos: Int, expreshHolder: ArrayBuffer[String], follow: Int )
var b = pos; //position of where in the expression String I am currently in
val temp = expreshHolder; //holder of expressions without parens
var arrayCounter = follow; //just counts to make sure an empty spot in the array is there to put in the strings
if(exp(b) == '(') {
b = b + 1;
while(exp(b) == ' '){b = b + 1} //point of this is to just skip any spaces between paren and start of expression type
if(exp(b) == 'a') {
temp(arrayCounter) = exp(b).toString;
b = b+1;
temp(arrayCounter)+exp(b).toString; b = b+1;
temp(arrayCounter) + exp(b).toString; arrayCounter+=1}
temp;
}
}
val hold: ArrayBuffer[String] = stringParse(str, 0, new ArrayBuffer[String], 0);
for(test <- hold) println(test);
My error is:
Driver.scala:35: error: type mismatch;
found : Unit
required: scala.collection.mutable.ArrayBuffer[String]
ho = stringParse(str, 0, ho, 0);
^one error found
When I add an equals sign after the arguments in the method declaration, like so:
def stringParse ( exp: String, pos: Int, expreshHolder: ArrayBuffer[String], follow: Int ) ={....}
It changes it to "Any". I am confused on how this works. Any ideas? Much appreciated.
Here's a more general answer on how one may approach such problems:
It happens sometimes that you write a function and in your head assume it returns type X, but somewhere down the road the compiler disagrees. This almost always happens when the function has just been written, so while the compiler doesn't give you the actual source (it points to the line where your function is called instead) you normally know that your function's return type is the problem.
If you do not see the type problem straight away, there is the simple trick to explicitly type your function. For example, if you thought your function should have returned Int, but somehow the compiler says it found a Unit, it helps to add : Int to your function. This way, you help the compiler to help you, as it will spot the exact place, where a path in your function returns a non-Int value, which is the actual problem you were looking for in the first place.
You have to add the equals sign if you want to return a value. Now, the reason that your function's return value is Any is that you have 2 control paths, each returning a value of a different type - 1 is when the if's condition is met (and the return value will be temp) and the other is when if's condition isn't (and the return value will be b=b+1, or b after it's incremented).
class Test(condition: Boolean) {
def mixed = condition match {
case true => "Hi"
case false => 100
}
def same = condition match {
case true => List(1,2,3)
case false => List(4,5,6)
}
case class Foo(x: Int)
case class Bar(x: Int)
def parent = condition match {
case true => Foo(1)
case false => Bar(1)
}
}
val test = new Test(true)
test.mixed // type: Any
test.same // type List[Int]
test.parent // type is Product, the case class super type
The compiler will do its best to apply the most specific type it can based on the possible set of result types returned from the conditional (match, if/else, fold, etc.).