Difference of SystemVerilog data types (reg, logic, bit) - system-verilog

There are different data types in SystemVerilog that can be used like the following:
reg [31:0] data;
logic [31:0] data;
bit [31:0] data;
How do the three of them differ?

reg and wire were the original types. Wires are constantly assigned and regs are evaluated at particular points, the advantage here is for the simulator to make optimisations.
wire w_data;
assign w_data = y;
// Same function as above using reg
reg r_data;
always #*
r_data = y ;
A common mistake when learning Verilog is to assume the a reg type implies a register in hardware. The earlier optimisation for the simulator can be done through the context of its usage.
This introduces logic which can be used in place of wire and reg.
logic w_data;
assign w_data = y;
// Same function as above using reg
logic r_data;
always #*
r_data = y ;
The type bit and byte have also been created that can only hold 2 states 0 or 1 no x or z. byte implies bit [7:0]. Using these types offers a small speed improvement but I would recommend not using them in RTL as your verification may miss uninitialized values or critical resets.
The usage of bit and byte would be more common in testbench components, but can lead to issues in case of having to drive x's to stimulate data corruption and recovery.
Update
At the time of writing I was under the impression that logic could not be used for tristate, I am unable to find the original paper that I based this on. Until further updates, comments or edits, I revoke my assertion that logic can not be used to create tri-state lines.
The tri type has been added, for explicitly defining a tri-state line. It is based on the properties of a wire, logic is based on the properties of a reg.
tri t_data;
assign t_data = (drive) ? y : 1'bz ;
If you no longer have to support backwards compatibility Verilog then I would recommend switching to using logic and tri. Using logic aids re-factoring and and tri reflects the design intent of a tristate line.

The choice of the name reg turned out to be a mistake, because the existence of registers is instead inferred based on how assignments are performed. Due to this, use of reg is essentially deprecated in favor of logic, which is actually the same type.
logic is a 1-bit, 4-state data type
bit is a 1-bit, 2-state data type which may simulate faster than logic
If a logic is also declared as a wire, it has the additional capability of supporting multiple drivers. Note that by default wire is equivalent to wire logic.
In general, the "nets" (such as wire and tri) are most suitable for designing communication buses.
Practically speaking, for RTL it usually doesn't matter whether you declare with reg, or logic, or wire. However, if you have to make an explicit declaration of a 4-state type (as opposed to when you don't), you should typically choose logic since that is what is intended by the language.
Related articles:
What’s the deal with those wire’s and reg’s in Verilog
An analysis of the "logic" data type by Cliff Cummings - 20021209

As I'm unable to add a comment I've to write what looks like a new answer but isn't. Sigh!
#e19293001, #Morgan, logic defines a 4-state variable unlike bit, and hence a logic variable can be used to store 1'bz so the following code is valid and compiles:
logic t_data;
assign t_data = (drive) ? y : 1'bz ;
But I agree that to reflect the design intent tri should be used instead of logic in these cases (although I must say I don't see people using tri instead of logic/wire too often).

reg and logic are exactly the same. These data types appear inside the always or initial blocks and store values i.e. always #(a) b <= a;, the reg b gets evaluated only when 'a' changes but otherwise it simply stores the value it has been assigned last.
wire are just simply connections and need to continuously driven. I agree that they can behave identical as #Morgan mentioned, but they can be imagined as a piece of hard wire, the value of which changes only the value at the other end or the source changes.

How do the three of them differ?
There is no difference between logic and reg.
The difference between bit and the other two is that bit is 2-state, whereas logic/reg are 4-state.
Refer to IEEE Std 1800-2017, section 6.11.2, 2-state (two-value) and 4-state (four-value) data types:
logic and reg denote the same type.
Also, section 6.3.1 Logic values:
The SystemVerilog value set consists of the following four basic values:
0 —represents a logic zero or a false condition
1 —represents a logic one or a true condition
x —represents an unknown logic value
z —represents a high-impedance state
Several SystemVerilog data types are 4-state types, which can store
all four logic values. All bits of 4-state vectors can be
independently set to one of the four basic values. Some SystemVerilog
data types are 2-state, and only store 0 or 1 values in each bit of a
vector.

Logic data type doesn't permit multiple driver. The last assignment wins in case of multiple assignment .Reg/Wire data type give X if multiple driver try to drive them with different value. Logic data type simply assign the last assignment value.

The "Reg" data type is used in procedural assignment, whereas the "Logic" data type can be used anywhere.

Related

-svinputport option in modelsim

I am using modlesim for my design and in this we are passing an option -svinputport=var, what is the use of this option? we are passing `default_nettype none before compiling each design files. Does these both are dependent? Could anyone help me with an example.
The description is as below for the option
svinputport=net|var|compat|relaxed
Select the default kind for an input port that is
declared with a type, but without the var keyword.
Select 'net' for strict LRM compliance, where the
kind always defaults to wire. Select 'var' for
non-compliant behavior, where the kind always defaults
to var. Select 'compat', where only types compatible with
net declarations default to wire. The default is 'relaxed',
where only a type that is a 4-state scalar or 4-state single
dimension vector type defaults to wire.
Question (2)
Thank you very much for the detailed explanation. I have one more doubt related to this. I am getting a warning when I run the following code:
`default_nettype none
module test(
input reg sig1,
output logic sig2);
reg [1:0] ab;
endmodule
xmvlog: *W,NODNTW (test.sv,4|14): Implicit net port (sig1) is not allowed since `default_nettype is declared as 'none'; 'wire' used instead [19.2(IEEE 2001)]. why it is referring input reg sig1 as an implicit net port, I already explicitly declared it as reg? As per the message it is changing to wire so will the statement be like "input wire reg sig1" ?
Can we declare input reg a; in systemverilog(input port with reg type) ? Is this implicitly equivalent to input wire reg a; (if I dont use `default_nettype none)
Verilog is littered with implicit defaults all over the place. When you write
module m(a);
initial $disaply(a);
endmodule
this is implicitly the same as
// direction kind type range signal
module m(inout wire logic [0:0] a);
initial $disaply(a);
endmodule
For inout and input directions, if you omit the kind the default is wire or taken from the `default_nettype setting. The none setting generates an error. However, the default kind for an output is different. As soon as you add a datatype to an output, the default kind goes to var, which is similar to non-port declarations. See this post for more details and examples.
However, very early versions of SystemVerilog/Superlog had input and inout with the same kind default as output. The -svinputport=var switch was added for a very large microprocessor developer customer whose name I cannot mention who did not want to change their code. The =net options is the behavior I mentioned above and is the way current LRM is defined.
The other two options are hybrids between the var/net options, mainly for lazy people using the default_nettype none options and don't want to see errors in their port declarations.

What is a difference between following two logic implementation from Hardware perspective?

Implementation 1:
logic [2:0][3:0] reg0; // Packed
always_ff#(clk_a)
reg0[1:0] <= in0[1:0];
always_ff#clk_b)
reg0[3:2] <= in1[1:0];
Implementation 2:
logic [2:0] reg0 [3:0]; // unpacked
always_ff#(clk_a)
reg0[1:0] <= in0[1:0];
always_ff#clk_b)
reg0[3:2] <= in1[1:0];
Why tool gives me multi-driver error for implementation 1?
The difference is what the LRM considers a variable. You are not allowed to have multiple assignments to the same variable from different processes. A packed array is considered a variable as well as each element if an unpacked array. The reason for this restriction has more do do with efficient simulation implementation and not really with hardware implementation and the distinction about what constitutes a variable is used in other places in the LRM (i.e. pass by reference).

how single and double type variables work in the same copy of code in Matlab like template in C++

I am writing a signal processing program using matlab. I know there are two types of float-pointing variables, single and double. Considering the memory usage, I want my code to work with only single type variable when the system's memory is not large, while it can also be adapted to work with double type variables when necessary, without significant modification (simple and light modification before running is OK, i.e., I don't need runtime-check technique). I know this can be done by macro in C and by template in C++. I don't find practical techniques which can do this in matlab. Do you have any experience with this?
I have a simple idea that I define a global string containing "single" or "double", then I pass this string to any memory allocation method called in my code to indicate what type I need. I think this can work, I just want to know which technique you guys use and is widely accepted.
I cannot see how a template would help here. The type of c++ templates are still determined in compile time (std::vector vec ...). Also note that Matlab defines all variables as double by default unless something else is stated. You basically want runtime checks for your code. I can think of one solution as using a function with a persistent variable. The variable is set once per run. When you generate variables you would then have to generate all variables you want to have as float through this function. This will slow down assignment though, since you have to call a function to assign variables.
This example is somehow an implementation of the singleton pattern (but not exactly). The persistent variable type is set at the first use and cannot change later in the program (assuming that you do not do anything stupid as clearing the variable explicitly). I would recommend to go for hardcoding single in case performance is an issue, instead of having runtime checks or assignment functions or classes or what you can come up with.
function c = assignFloat(a,b)
persistent type;
if (isempty(type) & nargin==2)
type = b;
elseif (isempty(type))
type = 'single';
% elseif(nargin==2), error('Do not set twice!') % Optional code, imo unnecessary.
end
if (strcmp(type,'single'))
c = single(a);
return;
end
c = double(a);
end

What should '{default:'1} do in system verilog?

I have an array that I would like to initialize to all 1. To do this, I used the following code snippet:
logic [15:0] memory [8];
always_ff #(posedge clk or posedge reset) begin
if(reset) begin
memory <= '{default:'1};
end
else begin
...
end
end
My simulator does what I think is the correct thing and sets the registers to 16'hFFFF on reset. However, my lint tool gives me a warning that bit 0 has an async set while bits 1 through 15 have async resets. This implies that the linter thinks that this code assigns 16'h0001 to the registers.
Since both tools come from the same vendor I file a bug report since they can't both be right.
The question is: Which behavior is correct according to the spec? There is no example that shows this exact situation. Section 5.7.1 mentions that:
An unsized single-bit value can be specified by preceding the single-bit value with an apostrophe ( ' ), but
without the base specifier. All bits of the unsized value shall be set to the value of the specified bit. In a
self-determined context, an unsized single-bit value shall have a width of 1 bit, and the value shall be treated
as unsigned.
'0, '1, 'X, 'x, 'Z, 'z // sets all bits to specified value
I f this is a "self-determined context" then the answer is 1 bit sign extended to 16'h0001, but if it is not, then I guess the example which says it "sets all bits to the specified value" applies. I am not sure if this is a self -determined context.
The simulator is correct: memory <= '{default:'1}; will assign all each bit in memory to 1. The linting tool does have a bug. See IEEE Std 1800-2012 § 10.9.1 Array assignment patterns:
The **default:***value* applies to elements or subarrays that are not matched by either index or type key. If the type of the element or subarray is a simple bit vector type, matches the self-determined type of the value, or is not an array or structure type, then the value is evaluated in the context of each assignment to an element or subarray by the default and shall be castable to the type of the element or subarray; otherwise, an error is generated. ...
The LRM goes beyond what is synthesizable when it comes to assignment patterns. And most of the tools are sill playing catchup with supporting all the SystemVerilog features. Experiment to make sure your tools (simulator,synthesizer, lint tool, logic-equivalency-checker, etc.) all have the necessary support for the features you want.

What is the correct way to select real solutions?

Suppose one needs to select the real solutions after solving some equation.
Is this the correct and optimal way to do it, or is there a better one?
restart;
mu := 3.986*10^5; T:= 8*60*60:
eq := T = 2*Pi*sqrt(a^3/mu):
sol := solve(eq,a);
select(x->type(x,'realcons'),[sol]);
I could not find real as type. So I used realcons. At first I did this:
select(x->not(type(x,'complex')),[sol]);
which did not work, since in Maple 5 is considered complex! So ended up with no solutions.
type(5,'complex');
(* true *)
Also I could not find an isreal() type of function. (unless I missed one)
Is there a better way to do this that one should use?
update:
To answer the comment below about 5 not supposed to be complex in maple.
restart;
type(5,complex);
true
type(5,'complex');
true
interface(version);
Standard Worksheet Interface, Maple 18.00, Windows 7, February
From help
The type(x, complex) function returns true if x is an expression of the form
a + I b, where a (if present) and b (if present) are finite and of type realcons.
Your solutions sol are all of type complex(numeric). You can select only the real ones with type,numeric, ie.
restart;
mu := 3.986*10^5: T:= 8*60*60:
eq := T = 2*Pi*sqrt(a^3/mu):
sol := solve(eq,a);
20307.39319, -10153.69659 + 17586.71839 I, -10153.69659 - 17586.71839 I
select( type, [sol], numeric );
[20307.39319]
By using the multiple argument calling form of the select command we here can avoid using a custom operator as the first argument. You won't notice it for your small example, but it should be more efficient to do so. Other commands such as map perform similarly, to avoid having to make an additional function call for each individual test.
The types numeric and complex(numeric) cover real and complex integers, rationals, and floats.
The types realcons and complex(realcons) includes the previous, but also allow for an application of evalf done during the test. So Int(sin(x),x=1..3) and Pi and sqrt(2) are all of type realcons since following an application of evalf they become floats of type numeric.
The above is about types. There are also properties to consider. Types are properties, but not necessarily vice versa. There is a real property, but no real type. The is command can test for a property, and while it is often used for mixed numeric-symbolic tests under assumptions (on the symbols) it can also be used in tests like yours.
select( is, [sol], real );
[20307.39319]
It is less efficient to use is for your example. If you know that you have a collection of (possibly non-real) floats then type,numeric should be an efficient test.
And, just to muddy the waters... there is a type nonreal.
remove( type, [sol], nonreal );
[20307.39319]
The one possibility is to restrict the domain before the calculation takes place.
Here is an explanation on the Maplesoft website regarding restricting the domain:
4 Basic Computation
UPD: Basically, according to this and that, 5 is NOT considered complex in Maple, so there might be some bug/error/mistake (try checking what may be wrong there).
For instance, try putting complex without quotes.
Your way seems very logical according to this.
UPD2: According to the Maplesoft Website, all the type checks are done with type() function, so there is rather no isreal() function.