Why isn't parameter being passed properly in Verilog? - parameter-passing

I have two verlog modules as seen below. The parameter statement is supposed too allow me to pass the bus width i'd like to instantiate another module at.
I keep getting an error when trying to compile saying "Port expression 64 does not match expected width 1 or 2."
module LabL3;
parameter SIZE = 64;
reg [SIZE-1:0]a;
reg [SIZE-1:0]b;
reg c;
wire [SIZE-1:0]z;
integer i,j,k;
yMux #(SIZE) mux(z,a,b,c);
initial
begin
for(i=0;i<4;i=i+1)begin
for(j=0;j<4;j=j+1)begin
for(k=0;k<2;k=k+1)begin
a=i;b=j;c=k;
#1$display("a=%d b=%d c=%d z=%d",a,b,c,z);
end
end
end
end
endmodule
and the other file is:
module yMux(z,a,b,c);
parameter SIZE= 0;
output [SIZE-1:0]z;
input [SIZE-1:0]a,b;
input c;
yMux1 mux[SIZE-1:0](z,a,b,c);
endmodule
and lastly
module yMux1(z,a,b,c);
output z;
input a,b,c;
wire not_C, upper, lower;
not my_not(notC,c);
and upperAnd(upper,a,notC);
and lowerAnd(lower,c,b);
or my_or(z,upper,lower);
endmodule
and the command I am using is: iverilog LabL3.v yMux1.v yMux.v
I have tried the different syntax's for parameter passing. All give the same result.
Any hints would greatly be appreciated.
- Chris

You are using vectored instances:
yMux1 mux[SIZE-1:0](z,a,b,c);
Where you end up with SIZE number of yMux1 instances. This should connect z,a,b bitwise correctly and connect the single bit c to all yMux1 c ports via replication.
If you really want to drive all c ports to the same value I would try manually replicating the port with:
yMux1 mux[SIZE-1:0](z,a,b,{SIZE{c}});
Example on EDAPlayground looks fine to me. Could be an issue with the specific tool not supporting vectored instances correctly.
When possible I would recommend using named port connections (ANSI header style) from section 23.2.1 of the SystemVerilog IEEE 1800-2012 Standard.
This style is very clear as to your design intent, I find it much easier to read which relates to less bugs. It also allows easier refactoring of the code due to the named connections and not being order dependent.
module LabL3;
parameter SIZE = 64;
reg [SIZE-1:0] a;
reg [SIZE-1:0] b;
reg c;
wire [SIZE-1:0] z;
yMux #(
.SIZE(SIZE)
) mux (
.z(z),
.a(a),
.b(b),
.c(c)
);
yMux definiton:
module yMux #(
parameter SIZE= 0
) (
output [SIZE-1:0] z,
input [SIZE-1:0] a,
input [SIZE-1:0] b,
input c
);
// ...
endmodule
An example of the above code on EDAPlayground.

Related

Passing parameters between Verilog modules

I fairly new to Verilog and learning the ropes. I have some code which generates an 8 bit up-counter (module counter.v), which is then called by a top module (top_module.v). There is a simulation test fixture (test_fixture.v) which calls the top module for testing.
I was trying to define the width of the counter using a parameter (parameter COUNTER_WIDTH) and was having difficulty doing so. A colleague fixed the code for me and it does now indeed work, but I want to understand a few things so I can understand what is actually going on.
Here is the code for the counter module:
module counter
#(parameter COUNTER_WIDTH = 8)
(
input wire CLK,
input wire RST,
input wire CE,
output reg[COUNTER_WIDTH-1:0] out = {COUNTER_WIDTH{1'b0}}
);
always #(posedge CLK) begin
if (RST == 1) begin
out <= {COUNTER_WIDTH{1'b0}};
end else begin
if (CE == 1) begin
out <= out + 1'b1;
end
end
end
endmodule
The top module:
module top_module
#(parameter COUNTER_WIDTH = 8)
(
input wire CLK,
input wire CE,
input wire RST,
output wire[COUNTER_WIDTH-1:0] out
);
counter #(
.COUNTER_WIDTH(COUNTER_WIDTH)
)
counter_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(out)
);
endmodule
And the test fixture:
module test_fixture();
parameter COUNTER_WIDTH = 8;
// inputs
reg CLK = 0;
reg RST = 0;
reg CE = 0;
// outputs
wire [COUNTER_WIDTH-1:0] Q;
// instance of top module to be tested
top_module #(
.COUNTER_WIDTH(COUNTER_WIDTH)
)
test_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(Q)
);
endmodule
I think I'm fine with the counter module, but have a question about what is going on in top module/test fixture:
It looks like the parameter COUNTER_WIDTH is declared in each module (#(parameter COUNTER_WIDTH = 8)), and then "connected to" (if that is the correct expression) the parameter declaration in the other module (e.g. #(.COUNTER_WIDTH(COUNTER_WIDTH) )
Is that understanding correct? If so, why do we have to declare the parameter within a module and connect it to a parameter within another module?
Thanks in advance for your help!
Think of a parameter as a special kind of constant input whose value is fixed at compile time. Originally, in Verilog, parameters were constants that could be overridden from outside a module (using the now deprecated defparam statement). So, a Verilog parameter had two roles:
a local constant
a way of customising a module from outside
Then, in the 2001 version of the standard (IEEE 1364-2001), the syntax you're using below was introduced (the so-called "ANSI style"). Also IEEE 1364-2001 introduced localparams (which fulfill the first of these two roles because they cannot be overridden from outside), so leaving parameters to handle the second of these two roles (the customisation). With the ANSI-style syntax, you override a parameter when you instantiate a module. You can associate the parameter with any static value, for example a parameter of the parent module, a localparam, a genvar or a literal (a hard-coded value in your code).
Because of this historical dual-role, in Verilog you must give a parameter a default value, even if it makes no sense. (And this restriction is lifted in SystemVerilog.)
Does giving the parameters different names and default values help your understanding?
// the default value
// |
module counter // V
#(parameter COUNTER_WIDTH = 1)
(
input wire CLK,
input wire RST,
input wire CE,
output reg[COUNTER_WIDTH-1:0] out = {COUNTER_WIDTH{1'b0}}
);
always #(posedge CLK) begin
if (RST == 1) begin
out <= {COUNTER_WIDTH{1'b0}};
end else begin
if (CE == 1) begin
out <= out + 1'b1;
end
end
end
endmodule
Then, in top module, let's give the parameter a different name:
// the default value
// |
module top_module // V
#(parameter COUNTER_NUM_BITS = 2)
(
input wire CLK,
input wire CE,
input wire RST,
output wire[COUNTER_NUM_BITS-1:0] out
);
counter #(
.COUNTER_WIDTH(COUNTER_NUM_BITS)
)
counter_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(out)
);
endmodule
And again in the test fixture:
module test_fixture();
localparam COUNTER_SIZE = 8; // This is not overridden from outside, so using
// a localparam would be better here.
// (A localparam being a kind of parameter that
// cannot be overridden from outside. Normal
// languages would call it a constant.)
// inputs
reg CLK = 0;
reg RST = 0;
reg CE = 0;
// outputs
wire [COUNTER_SIZE-1:0] Q;
// instance of top module to be tested
top_module #(
.COUNTER_NUM_BITS(COUNTER_SIZE)
)
test_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(Q)
);
endmodule
why do we have to declare the parameter within a module and connect it to a parameter within another module?
Because, you don't HAVE to give a parameter a value when you instance the module.
In which case the tools need to have at least some value to work with.
So where you do:
counter #(
.COUNTER_WIDTH(COUNTER_WIDTH)
)
counter_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(out)
);
You may also use:
counter
counter_inst(
.CLK(CLK),
.RST(RST),
.CE(CE),
.out(out)
);
In which case the default value is used.

Verilog, How to pass different parameters when I use generate to instantiation module?

I have a question about parameters passing. I used generate for to do module instantiation. But how to pass different parameters to each module?
For example:
generate
for (i=0;i<N;i=i+1) begin:ModIns
Mod #(.p1(?),.p2(?)) M (
// Signal connection
);
end
endgenerate
For N modules, each with different p1 and p2. How to do that? By the way, the number of parameters is very large, can I pass parameters as a file?
Thanks!
Here are my 2 cents.
Declare a 2-D register and store all the parameters there.
reg [31:0] param_mem1 [N-1:0]; //Assuming parameter size to be 32 bit wide
reg [31:0] param_mem2 [N-1:0];
always#(posedge clk)
begin
for(i=0;i<N;i=i+1)
begin
param_mem1[i] <= i; //Here replace 'i' with your actual parameter value
param_mem2[i] <= i+1; //Dummy assignment, please use intended values
end
end
generate
for (i=0;i<N;i=i+1) begin:ModIns
Mod #(.p1(param_mem1[i]),.p2(param_mem2[i])) M (
// Signal connection
);
end
endgenerate
First: No you can't read it from a file. Parameters have to be known at compile time and a file is only readable in run time.
You can derive them from a genvar or pass them through a hierarchy, but then it more or less stops. Maybe what you are trying to do can be solved in a different way but the scope of the problem you have outlined for us here is rater limited.
As always: Tell us your problem, not your solution.
It would be easier to do this in SystemVerilog because a parameter can be an array, and your generate loop could select an element for each iteration of the loop.
In Verilog, you can pack your elements into a bit-vector, and your generate loop could select a slice for each iteration of the loop.
parameter A1={8'd1, 8'd2, 8'd3, 8'd4, ...};
parameter A2={8'd9, 8'd8, 8'd7, 8'd6, ...};
generate
for (i=0;i<N;i=i+1) begin:ModIns
Mod #(.p1(A1[i*8+:8),.p2(A2[i*8+:8])) M (
// Signal connection
);
end
endgenerate
If you want to define the parameters from a file, you can put the parameter declarations in a separate file and `include the file.
This compiles with VCS:
genvar port_idx;
generate
for (port_idx = 0; port_idx < 5; port_idx++) begin : intf
xactor_t xactor (core_clk, core_rst);
defparam xactor.intf_id = 18 + port_idx;
end

Calling std::vector constructor when containing class manually allocated

I'm afraid to ask questions in case it turns out to be stupid... But I tried to search and don't see the same situation.
I'm retrofitting a std::vector into some existing legacy code that is mostly C style. Our next major release which isn't due for a year or two will jettison a lot of the legacy code. But for now, the way we work is, every project gets recompiled for the customer, depending on specs. Some projects are on Visual Studio 2008, some 2010, etc. My added std::vector code I'm working on has no visible problems when compiled with 2013, but, I get crashes within the STL code when running VS 2008 SP1.
The existing code has a struct, and a fixed size array in it:
#define MAX_REMOTE_CONN 75
typedef struct {
int rno;
int adrs;
bool integ_pending;
} RTUref;
typedef struct {
char device[64];
int port;
RTUref RTU[MAX_REMOTE_CONN];
// more stuff...
} Connect_Info;
So, my basic goal is to get rid of the hard coded size limit to the RTU array. So, I have revised it like this:
class{
public:
int rno;
int adrs;
bool integ_pending;
} RTUref;
typedef std::vector <RTUref> RTUlist;
typedef struct {
char device[64];
int port;
RTUlist RTU;
// more stuff...
} Connect_Info;
The Connect_Info structs are allocated using our own memory manager. Don't know much about it other than it is supposed to be more efficient than use malloc() and free(). I'm guessing that the constructor for RTU doesn't get called since the struct it is contained in data allocated by our own memory manager?
Nevertheless, the code where I size the array, put values into the array all at least seem to work okay. But, when I call .clear() I get a crash from within the STL. And as I said, only if I use 2008. If I use 2013, I don't get that crash.
Assuming pct is a pointer to an allocated Connect_Info structure, the the line:
pct->RTU.clear();
Generates a crash on VS 2008. I am able to resize and add elements to the array. And I even tried to add a check that I don't clear unless the size is greater than zero like so:
if (pct->RTU.size() > 0)
pct->RTU.clear();
And I still get the crash on the clear.
So, I made the educated guess that I need to call a constructor. But, I wasn't quite sure of how to do it. But, in the code where the Connect_Info struct is allocated, I tried to add contructor code like this:
pct->RTU = RTUlist();
It compiles. But, I then get a crash in the STL on that line.
I haven't yet tried to build a small contained test program, as I'm not even sure that I will be able to reproduce the problem without our memory manager. But, I will try if that is what I need to do. I thought maybe someone might see obviously what I'm doing wrong. I'm fairly novice to the STL.
A little background: there is a term in C++ called "POD Type" (or "Plain Old Data Type").
There are verbose rules, but basically things that may do special things on allocations, deallocations, or copies are not POD types. The original Connect_Info was a POD type since it didn't do special things at those times and didn't have any non-POD members.
However, since you added a std::vector (which is not a POD type because it has to do special things at allocation, deallocation, copy, etc (because it allocates memory)), Connect_Info is not a POD type.
POD types can be allocated safely with malloc and deallocated with free since they don't do special things. However, non-POD types cannot (except in exceedingly rare cases which you'll first see after several years of programming C++) be allocated like that.
C only has POD types, so malloc is perfectly acceptable. There are a few options you can do:
int main ( ... )
{
Connect_Info * info = new Connect_Info() ;
std::cout << info->port << std::endl ;
delete info ;
}
Or
Connect_Info * makeOne ()
{
void * ptr = malloc ( sizeof(Connect_Info) ) ;
if ( ! ptr ) return 0 ;
return new (ptr) Connect_Info () ; // "In-Place constructor"
}
void deleteOne ( Connect_Info * info )
{
if ( ! ptr ) return ;
info = info->~Connect_Info() ; // manually call its destructor with the weirdest syntax ever
// Note: I'm not 100% sure this call to 'free' is right because the in-place new can return a different pointer, but I don't know how to the get the original back
free ( static_cast<void*>(info) ) ;
}
int main ( ... )
{
Connect_Info * info = makeOne ()
std::cout << info->port << std::endl ;
deleteOne ( info ) ;
}
If you have boost available (or C++11, which you probably don't), this is a MUCH better option (and only uses header components of boost):
boost::shared_ptr<Connect_Info> makeOne ()
{
return boost::make_shared<Connect_Info> () ;
}
int main ( ... )
{
boost::shared_ptr<Connect_Info> info = makeOne ()
std::cout << info->port << std::endl ;
// nothing else: shared_ptr takes care of that for you
}
(If you have C++11, use std::shared_ptr and std::make_shared)

Calling size in Matlab user function causes error

This should be a simple question for Matlab users out there.
The parameter y is 1 x 81 matrix (an array).
My function looks like this:
function [ ] = test( y )
length(y)
end
Yet when call test I get the following error:
"??? Attempt to reference field of non-structure array."
What did I do wrong?
You need to specify a return parameter!
function [size] = test (y ) etc...
test is a built in function, already.
>> help test
--- help for classregtree/test ---
test Compute error rate for tree.
COST = test(T,'resubstitution') computes the cost of the tree T
where T is a decision tree.

Is there a programming language that allows variable declaration at call site?

Update 2: examples removed, because they were misleading. The ones below are more relevant.
My question:
Is there a programming language with such a construct?
Update:
Now when I think about it, Prolog has something similar.
I even allows defining operations at definition line.
(forget about backtracking and relations - think about syntax)
I asked this question because I believe, it's a nice thing to have symmetry in a language.
Symmetry between "in" parameters and "out" parameters.
If returning values like that would be easy, we could drop explicit returning in designed language.
retruning pairs ... I think this is a hack. we do not need a data structure to pass multiple parameters to a function.
Update 2:
To give an example of syntax I'm looking for:
f (s, d&) = // & indicates 'out' variable
d = s+s.
main =
f("say twice", &twice) // & indicates 'out' variable declaration
print(twice)
main2 =
print (f("say twice", _))
Or in functional + prolog style
f $s (s+s). // use $ to mark that s will get it's value in other part of the code
main =
f "say twice" $twice // on call site the second parameter will get it's value from
print twice
main2 =
print (f "Say twice" $_) // anonymous variable
In a proposed language, there are no expressions, because all returns are through parameters. This would be cumbersome in situations where deep hierarchical function calls are natural. Lisp'ish example:
(let x (* (+ 1 2) (+ 3 4))) // equivalent to C x = ((1 + 2) * (3 + 4))
would need in the language names for all temporary variables:
+ 1 2 res1
+ 3 4 res2
* res1 res2 x
So I propose anonymous variables that turn a whole function call into value of this variable:
* (+ 1 2 _) (+ 3 4 _)
This is not very natural, because all the cultural baggage we have, but I want to throw away all preconceptions about syntax we currently have.
<?php
function f($param, &$ret) {
$ret = $param . $param;
}
f("say twice", $twice);
echo $twice;
?>
$twice is seen after the call to f(), and it has the expected value. If you remove the ampersand, there are errors. So it looks like PHP will declare the variable at the point of calling. I'm not convinced that buys you much, though, especially in PHP.
"Is there a programming language with such a construct?"
Your question is in fact a little unclear.
In a sense, any language that supports assignment to [the variable state associated with] a function argument, supports "such a construct".
C supports it because "void f (type *address)" allows modification of anything address points to. Java supports it because "void f (Object x)" allows any (state-modifying) invocation of some method of x. COBOL supports it because "PROCEDURE DIVISION USING X" can involve an X that holds a pointer/memory address, ultimately allowing to go change the state of the thing pointed to by that address.
From that perspective, I'd say almost every language known to mankind supports "such a construct", with the exception perhaps of languages such as Tutorial D, which claim to be "absolutely pointer-free".
I'm having a hard time understanding what you want. You want to put the return type on call signature? I'm sure someone could hack that together but is it really useful?
// fakelang example - use a ; to separate ins and outs
function f(int in1, int in2; int out1, int out2, int out3) {...}
// C++0x-ish
auto f(int in1, int in2) -> int o1, int o2, int o3 {...}
int a, b, c;
a, b, c = f(1, 2);
I get the feeling this would be implemented internally this way:
LEA EAX, c // push output parameter pointers first, in reverse order
PUSH EAX
LEA EAX, b
PUSH EAX
LEA EAX, a
PUSH EAX
PUSH 1 // push input parameters
PUSH 2
CALL f // Caller treat the outputs as references
ADD ESP,20 // clean the stack
For your first code snippet, I'm not aware of any such languages, and frankly I'm glad it is the case. Declaring a variable in the middle of expression like that, and then using it outside said expression, looks very wrong to me. If anything, I'd expect the scope of such variable to be restricted to the function call, but then of course it's quite pointless in the first place.
For the second one - multiple return values - pretty much any language with first-class tuple support has something close to that. E.g. Python:
def foo(x, y):
return (x + 1), (y + 1)
x, y = foo(1, 2)
Lua doesn't have first-class tuples (i.e. you can't bind a tuple value to a single variable - you always have to expand it, possibly discarding part of it), but it does have multiple return values, with essentially the same syntax:
function foo(x, y)
return (x + 1), (y + 1)
end
local x, y = foo(x, y)
F# has first-class tuples, and so everything said earlier about Python applies to it as well. But it can also simulate tuple returns for methods that were declared in C# or VB with out or ref arguments, which is probably the closest to what you describe - though it is still implicit (i.e. you don't specify the out-argument at all, even as _). Example:
// C# definition
int Foo(int x, int y, out int z)
{
z = y + 1;
return x + 1;
}
// explicit F# call
let mutable y = 0
let x = Foo(1, 2, byref y);
// tupled F# call
let x, y = Foo(1, 2)
Here is how you would do it in Perl:
sub f { $_[1] = $_[0] . $_[0] } #in perl all variables are passed by reference
f("say twice", my $twice);
# or f("...", our $twice) or f("...", $twice)
# the last case is only possible if you are not running with "use strict;"
print $twice;
[edit] Also, since you seem interested in minimal syntax:
sub f { $_[1] = $_[0] x 2 } # x is the repetition operator
f "say twice" => $twice; # => is a quoting comma, used here just for clarity
print $twice;
is perfectly valid perl. Here's an example of normal quoting comma usage:
("abc", 1, "d e f", 2) # is the same as
(abc => 1, "d e f" => 2) # the => only quotes perl /\w+/ strings
Also, on return values, unless exited with a "return" early, all perl subroutines automatically return the last line they execute, be it a single value, or a list. Lastly, take a look at perl6's feed operators, which you might find interesting.
[/edit]
I am not sure exactly what you are trying to achieve with the second example, but the concept of implicit variables exists in a few languages, in Perl, it is $_.
an example would be some of perl's builtins which look at $_ when they dont have an argument.
$string = "my string\n";
for ($string) { # loads "my string" into $_
chomp; # strips the last newline from $_
s/my/our/; # substitutes my for our in $_
print; # prints $_
}
without using $_, the above code would be:
chomp $string;
$string =~ s/my/our/;
print $string;
$_ is used in many cases in perl to avoid repeatedly passing temporary variables to functions
Not programming languages, but various process calculi have syntax for binding names at the receiver call sites in the scope of process expressions dependent on them. While Pict has such syntax, it doesn't actually make sense in the derived functional syntax that you're asking about.
You might have a look at Oz. In Oz you only have procedures and you assign values to variables instead of returning them.
It looks like this:
proc {Max X Y Z}
if X >= Y then Z = X else Z = Y end
end
There are functions (that return values) but this is only syntactic sugar.
Also, Concepts, Techniques, and Models of Computer Programming is a great SICP-like book that teaches programming by using Oz and the Mozart Programming System.
I don't think so. Most languages that do something like that use Tuples so that there can be multiple return values. Come to think of it, the C-style reference and output parameters are mostly hacks around not being about to return Tuples...
Somewhat confusing, but C++ is quite happy with declaring variables and passing them as out parameters in the same statement:
void foo ( int &x, int &y, int &z ) ;
int a,b,c = (foo(a,b,c),c);
But don't do that outside of obfuscation contests.
You might also want to look at pass by name semantics in Algol, which your fuller description smells vaguely similar to.