Counting instances of modules in SystemVerilog - module

I am attempting to design a simple CPU and I ma using SystemVerilog to design and ModelSim to simulate the design. I am trying to set up some code to count the number of instances of a specific module. I am currently using static variables to try to achieve this however it is not working. My code is as follows.
module testbench;
logic a0, b0, y0;
logic a1, b1, y1;
logic a2, b2, y2;
AND and0(.a(a0), .b(b0), .y(y0));
AND and1(.a(a1), .b(b1), .y(y1));
AND or0(.a(a2), .b(b2), .y(y2));
initial
begin
$display("AND Gates : ", and0.instance_count);
$display("OR Gates : ", or0.instance_count);
end
endmodule
module AND(input logic a, b, output logic y);
static int instance_count = 0;
initial
instance_count++;
and(y, a, b);
endmodule
module OR(input logic a, b, output logic y);
static int instance_count = 0;
initial
instance_count++;
or(y, a, b);
endmodule
The output this gives is 1 instance for both the AND gates and OR gates, which is incorrect. How could I change my code to fix this issue? In addition to this, a solution to this problem which can be determined through modelsim and not require me to add any code to my model would be an ideal solution, if that is possible.

All declarations at the module level are already static, and each module instance has a separate allocation of variable instances.
You could create a global package with an associative array.
package inst;
int count[string] = '{default:0};
endpackage
module AND(input logic a, b, output logic y);
initial inst::count["AND"]++;
and(y, a, b);
endmodule
SystemVerilog has no built-in introspection, but there are ways of building it in to your flow if you really want to dive into the VPI details.
But many tools including ModelSim have Tcl commands like
find instances -r /testbench/* -file instances.txt
that would be easy to write a counting script of individual instances.

Related

Verilog: Use of register: When are the values actually updated?

When exactly are the variables inside an always-block in Verilog updated?
E.g. if the reg C is changed multiple times in an always-block: does the value of it always change? Or is the value only "physically written" to the reg at the end of the always-block?
Would it be better to use an extra intermediate register which is only actualized at the end of the always-block? Would it make any difference?
reg C;
always #(*)
C = 0;
C = A;
C = 1;
C = B;
end
Other example:
If I have a module with an always block as follows, could the multiple assignments of the output exhibit sort of a glitch, where the output quickly goes to 0 before getting the value of B? Does it make a difference if I use blocking (=) or non-blocking (<=) assignments?
module example1 (output C, input A, input B);
always #(*)
begin
C = 1’b0;
if (A==1)
C = B ;
end
endmodule
Example with intermediate register to avoid unwanted change of the output.
module example1 (output C, input A, input B);
reg intermediateReg;
always #(*)
begin
intermediateReg = 1’b0;
if (A==1)
intermediateReg = B ;
end
C <= intermediateReg;
endmodule
In the examples you provided the code behaves identically to the 'c' code. The variable gets re-assigned new values and the last one wins. In verilog this is true for blocking (=) or non-blocking (<=) assignments, but not for the mix of them.
As in 'c' it is up to the compiler optimization technique. It can eliminate unneeded assignments, so only the last one is relevant.
In your first example the value of 'C' will be 'B' at the end of the block. The value of 'C' in the second example will either be 0 or B, depending on A.
Now, for the purpose of a simplicity of explanation, mixing of blocking and non-blocking assignments will cause the last 'non-blocking' assignment win. The reason is that all nba's are executed after the block is finished.
always #(*) begin
C <= A;
C = B;
end
The value of C will be A at the end of the simulation cycle.
As for the question about using intermediate values, there is no difference. You use them as needed. The simulation compiler or synthesis will optimize your code in any case. The last example is absolutely normal, except that it does not change anything at all. It behaves the same way as this, which is more explicit and more readable in my opinion. The only problem is that you incorrectly use nba assignments int combinational logic (which i fixed).
always #(*)
begin
if (A==1)
C = B ;
else
C = 1'b0;
I guess there is another silent question in your post, will the intermediate value cause events on 'C', the answer in this case is no. There will be no events produced by the always block till it finishes its execution (or till it hits a delay or starts waiting on an event). So, only the last value is relevant.
In a testbench code you can see a situation like that:
always #* begin
C = A;
C = B;
#5 C = D;
end
In the above case The value of C will become B. The execution of the always block will stop for #5 delays. During that time other blocks will see the value B. In #5 ticks, the value will be changed to D.
If you want to know what blocking and non-blocking assignments do in standard Verilog (like you would have in simulation), you can easily look that up.
If you're talking about hardware, the type of hardware you get will depend on what's in the sensitivity list, not type type of assignments you use. The type of assignment will affect the combinational logic that is synthesized from your code. Assuming you aren't doing anything unsynthesizable, the logic you get should be equivalent to what the Verilog standard specifies but won't be a 1:1 direct mapping of your code.
So, no, adding intermediates won't necessarily help with glitches in the hardware. There will be other code and timing specifications, etc. for dealing with stuff like that.

verilog assigning to same variable not working

I am having a strange problem with Verilog HDL.
I found in my code that if I multiply a variable by two, but then
assign that value to the same variable, it gets all messed up.
Sometimes, the simv program even crashes. I originally needed to do this,
because I had a for loop for shifting or rotating a certain amount. But,
then I found that not only shifting the same variable did not work, but
also, addition, subtraction, multiplication, or division does not work either.
So in my code example, if you set a to 16'b0001_0000_1010_0101, and b to 3,
then you get an output of 16'b0000_0000_0000_0000. Just note that I am ignoring b for now... I should get 16'b0010_0001_0100_1010... but something is going wrong.
So, this is my code file test.v:
// ALU module.
module test(in1, in2, out1);
input [15:0] in1;
input [15:0] in2;
output reg [15:0] out1;
// Variables for shifting right and for rotating left or right.
reg [15:0] shiftedValue;
always#(in1, in2)
begin
assign shiftedValue = in1;
assign shiftedValue = shiftedValue * 2;
assign out1 = shiftedValue;
// This display value is correct!
// but it's still wrong in the test bench.
$display("out1 == %b", out1);
end
endmodule
module testStim;
reg [15:0] a;
reg [15:0] b;
wire [15:0] c;
// create ALU instance.
test myTest(a, b, c);
initial
begin
a = 16'b0001_0000_1010_0101;
b = 3;
#10
$display("op1In == %b, op1Out == %b", a, c);
$finish;
end
endmodule
This is the output after running simv (I stripped out the erroneous garbage...):
out1 == 0010000101001010
op1In == 0001000010100101, op1Out == 0000000000000000
Thanks,
Erik W.
You have done what is called as procedural continuous assignment.
The difference between regular continuous assignments and procedural continuous assignments is this:
Continuous assignment can only drive wire/net data type. Procedural assignment can drive only reg data type and not nets.
Continuous assignment should appear outside procedural blocks(always, initial etc), while latter must be inside procedural blocks.
Continuous assignment executes each time the right hand side expression changes. Procedural assignment depends on sensitivity list of always block.
As soon as the always block ends, the effect of assign statement is removed. You must add deassign statement to retain the values (which I think is not the real intent) or Just remove assign statement from the code. As shown below:
shiftedValue = in1;
shiftedValue = shiftedValue * 2;
out1 = shiftedValue;
More information about assign, deassign is available at this, this and this links.

What does "macro" mean in Objective-C?

I am new to iOS development and I just want to know the meaning of macro in Objective-C?
I have found that "macro" is used with #define but still do not get its meaning.
http://www.saturngod.net/ios-macro-define-value-with-condition
Yes, Larme is right. Macros can be used in many languages, it's not a specialty of objective-c language.
Macros are preprocessor definitions. What this means is that before your code is compiled, the preprocessor scans your code and, amongst other things, substitutes the definition of your macro wherever it sees the name of your macro. It doesn’t do anything more clever than that.
Almost literal code substitution. e.g.-
Suppose you want a method to return the maximum of two numbers. You write a macro to do this simple task:
#define MAX(x, y) x > y ? x : y
Simple, right? You then use the macro in your code like this:
int a = 1, b = 2;
int result = 3 + MAX(a, b);
EDIT:
The problem is that the preprocessor substitutes the macro definition into the code before compilation, so this is the code the compiler sees:
int a = 1, b = 2;
int result = 3 + a > b ? a : b;
C order of operations requires the sum 3 + a be calculated before the ternary operator is applied. You intended to save the value of 3 + 2 in result, but instead you add 3 + 1 first, and test if the sum is greater than 2, which it is. Thus result equals 2, rather than the 5 you expected.
So you fix the problem by adding some parentheses and try again:
#define MAX(x, y) ((x) > (y) ? (x) : (y))
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls.
An object-like macro is a simple identifier which will be replaced by a code fragment. It is called object-like because it looks like a data object in code that uses it. They are most commonly used to give symbolic names to numeric constants.
You create macros with the ‘#define’ directive. ‘#define’ is followed by the name of the macro and then the token sequence it should be an abbreviation for, which is variously referred to as the macro's body, expansion or replacement list. For example,
#define BUFFER_SIZE 1024
defines a macro named BUFFER_SIZE as an abbreviation for the token 1024. If somewhere after this ‘#define’ directive there comes a Objective C statement of the form
foo = (char *) malloc (BUFFER_SIZE);
The Objective C compiler will see the same tokens as it would if you had written
foo = (char *) malloc (1024);
You can also define macros whose use looks like a function call. These are called function-like macros. To define a function-like macro, you use the same ‘#define’ directive, but you put a pair of parentheses immediately after the macro name.
Like:
#define isIphone([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
#define GetImage(imageName) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:#"png"]]
Macros are compile time constants. That means they will replaced with actual values in the compile time.
#define MIN_VALUE 3 // Definition
if(x > MIN_VALUE) // Usage
{
}
While compiling it actually looks like
if(x > 3) // During compilation
{
}
Wikipedia has the answer, under Macro.
Definition:
The term originated with macro-assemblers, where the idea is to make available to the programmer a sequence of computing instructions as a single program statement, making the programming task less tedious and less error-prone.
Usage:
Keyboard and mouse macros that are created using an application's built-in macro features are sometimes called application macros. They are created by carrying out the sequence once and letting the application record the actions. An underlying macro programming language, most commonly a Scripting language, with direct access to the features of the application may also exist.

Input setting using Registers

I have a simple c program for printing n Fibonacci numbers and I would like to compile it to ELF object file. Instead of setting the number of fibonacci numbers (n) directly in my c code, I would like to set them in the registers since I am simulating it for an ARM processor.How can I do that?
Here is the code snippet
#include <stdio.h>
#include <stdlib.h>
#define ITERATIONS 3
static float fib(float i) {
return (i>1) ? fib(i-1) + fib(i-2) : i;
}
int main(int argc, char **argv) {
float i;
printf("starting...\n");
for(i=0; i<ITERATIONS; i++) {
printf("fib(%f) = %f\n", i, fib(i));
}
printf("finishing...\n");
return 0;
}
I would like to set the ITERATIONS counter in my Registers rather than in the code.
Thanks in advance
The register keyword can be used to suggest to the compiler that it uses a registers for the iterator and the number of iterations:
register float i;
register int numIterations = ITERATIONS;
but that will not help much. First of all, the compiler may or may not use your suggestion. Next, values will still need to be placed on the stack for the call to fib(), and, finally, depending on what functions you call within your loop, code in the procedure are calling could save your register contents in the stack frame at procedure entry, and restore them as part of the code implementing the procedure return.
If you really need to make every instruction count, then you will need to write machine code (using an assembly language). That way, you have direct control over your register usage. Assembly language programming is not for the faint of heart. Assembly language development is several times slower than using higher level languages, your risk of inserting bugs is greater, and they are much more difficult to track down. High level languages were developed for a reason, and the C language was developed to help write Unix. The minicomputers that ran the first Unix systems were extremely slow, but the reason C was used instead of assembly was that even then, it was more important to have code that took less time to code, had fewer bugs, and was easier to debug than assembler.
If you want to try this, here are the answers to a previous question on stackoverflow about resources for ARM programming that might be helpful.
One tactic you might take is to isolate your performance-critical code into a procedure, write the procedure in C, the capture the generated assembly language representation. Then rewrite the assembler to be more efficient. Test thoroughly, and get at least one other set of eyeballs to look the resulting code over.
Good Luck!
Make ITERATIONS a variable rather than a literal constant, then you can set its value directly in your debugger/simulator's watch or locals window just before the loop executes.
Alternatively as it appears you have stdio support, why not just accept the value via console input?

How to wire two modules in Verilog?

I have written two modules DLatch and RSLatch and i want to write verilog code to join those two.
Seriously, you should get yourself a Verilog handbook or search for some online resources.
Anyway, something like this should work:
module dff (
input Clk,
input D,
output Q,
output Qbar
);
wire q_to_s;
wire qbar_to_r;
wire clk_bar;
assign clk_bar = ~Clk;
D_latch dlatch (
.D(D),
.Clk(Clk),
.Q(q_to_s),
.Qbar(qbar_to_r)
);
RS_latch rslatch (
.S(q_to_s),
.R(qbar_to_r),
.Clk(clk_bar),
.Qa(Q),
.Qb(Qbar)
);
endmodule
You might want to look into Emacs AUTOWIRE
You will need to create an outer module, with the ports as shown in your schematic (D, Clk, Q, NQ). Inside this module you instantiate the two submodules DLatch and RSLatch, and wire the ports appropriately. (You will need to declare extra wires for the internal interconnects.)