<<

ELEX 7660 : Digital System Design 2018 Winter Term System Verilog

Verilog expressions are similar to those in with additional properties so they can better describe hardware. Verilog has both parallel and sequential statements that allow it to better describe the behaviour of hardware. is lecture describes Verilog types, operators and the evaluation of expressions as well as the most common Verilog statements. More details are available in the System Verilog standard, IEEE Std 1800-2012. Aer this lecture you should be able to: predict the size and value of a Verilog expression that uses the signals, constants and operators described below; and predict the flow of control between the statements described below. e result of an expression is unsigned unless all Types and Logic Values the operands are signed. 1 Verilog 4-state types, such as logic, can have four Figure 1 shows how the size of an expression de- values: 0 (false), 1 (true), x (unknown) and z (high pends on its operands. impedance). ese are used for modeling logic. Values are le-padded or le-truncated as neces- 2-state types such as bit and integer can have sary. Padding replicates the sign bit only for signed values 0 and 1. ese are primarily used as counters values. and array indices. Arrays Numeric Constants Variables may have multiple “packed” and “un- packed” dimensions. In addition to declaring the size and base as described Packed dimensions are those given before the previously, constants (“literals”) can also be declared signal name. ese bits are stored contiguously as signed by prefixing the base with ’s’ (e.g. 4'shf for (“packed”) and the packed item can be treated as a a 4-bit -1). Decimal constants are treated as signed by scalar – a single number – in expressions. Packed di- default. mensions typically model a word or bit fields within A numeric constant can also include x (unknown) a word (e.g. a 32-bit word composed of 4 bytes of 8 or z (high-impedance) values. ese have useful bits). interpretations for synthesis (don’t-care and high- impedance respectively) but when used in simula- Unpacked dimensions appear aer the signal tions the result, in most cases, will be unknown (x). name. ese bits may not necessarily be stored con- tiguously. Unpacked dimensions model memories e notations '0 and '1 are convenient abbrevia- where only one element can be accessed at a time. tions for a constant that is all-zeros or all-ones. In array references, the unpacked dimension(s) are specified first, followed by the packed dimensions (if and Size any).

Variables and expressions can have a size (measured Array Literals in bits) and can be signed or unsigned. e behaviour of some operators depends on the signedness of the Array literals (constants) can be defined by grouping operands. the individual elements within '{...}. e quote Signedness does not affect the values of the bits distinguishes array literal syntax from the syntacti- (0 or 1) only how operators act on them. Negative cally similar concatenation operator. values of signed values are assumed to be in twos- complement form. Decimal literals are signed and based literals are 1Tables are from the IEEE System Verilog Standard, IEEE Std unsigned unless s is used with the base. 1800-2012. lec3.tex 1 2018-01-23 00:00 Figure 1: Size of Expressions.

Exercise 1: What are the packed and unpacked dimensions Examples of each declaration? e examples below illustrate the rules described Exercise 2: What are the signedness, size and value of each above. constant and each expression above? module ex12 ; initial begin Operators

logic [3:0] x ; Figure 2 below lists the Verilog operators and Figure logic signed [15:0] y ; 3 their precedence. Operators that differ from those logic [3:0] [7:0] z [15:0] ; in C and that are widely supported for synthesis are x = 4'b01xz ; // described below. x = -1 + 0 ; // x=15 Arithmetic vs Logical Shi Le shi always zero- y = -1 + 4'shf ; // y=-2 fills on the right. Arithmetic right shis (>>>) x = y ; // x=14 replicate the sign bit if the result is signed. Log- ical right shis (>>) always zero-fill. z[0] = '1 ; // z[0]=4294967295 z[0] = {4{4'b1}} ; // z[0]=4369 Logical Reduction Operators ese unary (one z[0][0][7] = 1 ; // z[0]=4497 z[15:0] = '{16{z[0]}} ; // z[*]=4497 operand) operators apply a logical operation to the bits of the operand. For example, to test end if any bit is set we can apply the or-reduction endmodule operator.

2 Figure 2: Verilog operators.

Conditional Operator e result when the condi- x or z. tional expression contains x or z is not what you might expect (the rules are complex). e wildcard equality comparison (==?) ex- cludes bits that are x or z in the right operand Equality e regular equality comparison opera- from the comparison. e result is always 0 or tors (e.g. ==) return x if either operand contains 1.

3 Figure 3: Operator Precedence.

e 4-state comparison (===) compares the two Examples operands for an exact match, including x and z. Concatenation Bits can be concatenated by sepa- module ex13 ; rating expressions with commas and surround- initial begin ing them with braces ({}). logic [15:0] x ; Concatenations of variables can be used on the logic signed [15:0] y ; le hand side of an assignment. x = 16'hfff0 ; // x=65520 Replication e syntax is similar to concatenation y = x >>> 1 ; // y=0x7ff8 but uses two pairs of nested braces and repeti- y = signed'(x) >>> 1 ; // y=0xfff8 tion value. y = |y ; // y=1

Array Slices e array subscript operator can be x = 8'h4x ; // x=X used to extract contiguous portions (slices) of an y = x == 8'h4x ; // y=X array. e bit order cannot be reversed. y = x[6:3] === 7'b100x ; // y=1 y = x ==? 8'h4x ; // y=1 Cast Although not an operator, a cast (') can be y = {x[7:4],x[6]} ; // y=0x0009 used to change the type, size or signedness of an end expression. endmodule

4 struct structures allow grouping variables (or sig- Modules nals) of different data types. Each is accessed using a dot followed by the member name. In Modules represent the top-level blocks of a hardware System Verilog structs can be declared packed, description. A module includes declarations and allowing them to also be treated as scalars, sim- parallel (concurrently executing) statements between ilar to packed arrays. module and endmodule. e module’s header de- fines the module’s name, parameters and ports. Ports typedef typedefs define user-defined types. can be in, out or inout (to model bidirectional sig- nals). enum defines enumerated types that can take on one When a module is instantiated, a signal can be of a set of values. connected to module port by port order (sig); by port name together with an explicit signal name Functions (.port(sig)), by port name with the signal name implicit (.port) and using a wildcard (.*) that Functions can be declared in modules and can be matches all remaining matching port and signal used to model combinational logic (only). Functions names. Expressions can be used instead of a signal allow the same logic to be re-used in multiple places. name. Specialized combinational logic functions (e.g. 7- segment LED decoder) are oen coded as functions.

Parameters Packages Parameters are named constants. ey are oen included in the module’s declaration to allow cus- Packages serve a purpose similar to header (.h) files tomization of each instantiation of a module. Param- in C. Since function and declarations are lo- eters such as bus width or clock frequency are com- cal to the module in which they are declared, to re- mon. use them across modules they should be declared be- Default values can be specified for parameters. As tween package/endpackage keywords. ese func- with signals, the values of parameters can be specified tions and data types can then be made available by by position or by name. using an import statement in a module: e following example shows how parameters with default values can be specified, how they can be used package ex15pkg ; to specify the dimensions of an array port and how typedef enum { INIT=1, ITER=2, $size() $right() system functions such as , and DONE=4 } state_t ; ⌈ ⌉ $clog2(x) ( log(x) ) can be used to compute pa- rameter values in module instantiations: typedef logic [3:0] nybble ; module setbits #(M=7,L=0) (output [M:L] x); typedef struct { assign x = '1 ; logic [7:0] r, theta ; } polar_t ; endmodule // (slow) 32-bit priority encoder module ex18 ; function automatic logic [5:0] logic [31:16] x ; pri(logic [31:0] x) ; setbits #(.L($right(x,1)),.M(31)) s0(x); for ( pri=32 ; pri>0 ; pri-- ) endmodule if ( x[pri-1] ) return pri ; endfunction

endpackage struct, typedef and enum module ex15 ( input logic [15:0] irqs, System Verilog includes several data modeling fea- output logic [4:0] irq, tures derived from C that can be used in declarations. output logic active ) ;

5 A common mistake is to omit signals from the sen- import ex15pkg::* ; sitivity list or not assign to a variable. is results in unintended latched logic. nybble [7:0] word32 ; To avoid this, System Verilog has three vari- always always_ff polar_t pos ; ants of the procedural block: , always_comb and always_latch that document assign pos = '{ 8'd255, 8'h7f } ; the designer’s intent. A warning or error is generated if the sensitivity list or assignments within the block assign irq = pri(irqs) ; would not result in the intended type of logic. assign active = irq ? '1 : '0 ; An always_comb does not need a sensitivity list – the implied sensitivity list includes all signals that are endmodule ‘read’ within the block. e import statement (and declarations) can be An always_ff block requires a sensitivity list that placed outside and before the module declaration. In includes posedge or negedge qualifiers on each sig- this case they apply to subsequent modules that are nal. compiled with the same command. is is not rec- ommended because it’s not possible to tell from the initial Procedural Blocks source which files should be compiled at the same time or in which order. An initial block is executed once at the start of the simulation. ese are only synthesizable when used to initialize FPGA memory and registers. Parallel Statements

A module can contain any number of the following Continuous assignment parallel statements, all of which execute concurrently. An assign statement continuously assigns (con- nects) the result of an expression to a net. It is a more always Procedural Blocks concise way to define combinational logic than using always_comb always blocks execute the following statement in an but is limited to a single expression. infinite loop. Execution of the next statement is oen controlled by one of the following: Sequential Statements #number delays number before each execution. is e following statements appear within always or is not synthesizable but is useful for simulation. initial procedural blocks and execute sequentially @(expression) waits until the value of the expres- (one aer the other). sion (the “sensitivity list”) changes. is can be used to model combinational, latched or flip- begin/end flop logic. ese keywords group statements that should be exe- e type of logic generated by the always block de- cuted together. ey are similar to braces in C. ey pends on the the sensitivity list and which variables also begin a new scope for declarations. ey can are assigned to within the block. be labelled so that any variables declared within the If for some conditions variables are not assigned block can be referenced (e.g. by simulators). to within the block then the language semantics re- quire that memory be generated so that the previous for/while/do/repeat/forever loops value is retained. is memory can be edge-triggered (when the sensitivity list uses posedge or negedge) e for, while and do loops are the same as in C. e or a latch (otherwise). On the other hand, if all vari- repeat and forever statements execute a statement ables in the sensitivity list are updated each time the a given number of times or forever. e break and block executes then combinational logic is generated. continue statements from C can also be used.

6 As shown in the first lecture, loops generate com- case/casez binational logic and are only synthesizable when the is is the equivalent of C’s switch statement. Be- number of iterations is known at compile time. How- tween case and endcase are a sequence of expres- ever, they are very useful when writing testbenches sions, each followed by a colon and a statement. for simulation. A default value indicates the statement that should be executed if none of the vales match. Blocking and Non-Blocking Assignments By default a case statement synthesizes a multi- A blocking assignment (=) evaluates the RHS (right plexer tree with each condition tested in sequence. hand side) and immediately sets the value of the vari- us the case semantics are the same as a sequence able on the LHS (le HS). of nested if-else statements. A non-blocking assignment (<=) evaluates the Placing unique before case implies that exactly RHS but does not set the value of the LHS until the one case expression will match. is allows the ex- next time step (typically, aer all sequential state- pressions to be tested in parallel resulting in faster ments have executed). logic. For example, Placing priority before case implies that at least one case expression will match and that the first match a = b ; b = a ; should be used. Since both unique and priority imply that one would set both a and b to the value of b while of the expressions will match, when these are used a <= b ; there should be no default expression. b <= a ; e casez variant of the case statement allows the case expressions to include ? (or z) values which are a b would swap the values of and . treated as “don’t care” bits. ere is also a casex vari- Recommended practice is to use non-blocking ant where x (undefined) also matches anything which always_ff assignments for sequential logic (in is usually not desired. blocks). is models the behaviour of flip-flops whose outputs don’t change until the next rising clock edge. Interfaces Blocking assignments are more convenient for de- signing combinational logic (inside always_comb An interface groups signals. Interfaces are de- blocks) as this matches programming language se- fined by declaring signals between interface and mantics and allows use of intermediate results. endinterface. A module can then declare an in- Assignments can synthesize combinational or se- stance of an interface and use it to connect other quential logic depending on the sensitivity list and modules. Individual signals from an interface are se- type of the enclosing always block as described lected using the same ‘dot’ syntax as structure mem- above. ber names. For example, an SPI bus could be mod- Do not assign to the same signal from more than elled as: one always block – the order in which always blocks execute is undefined. interface spibus ( input logic clk ) ; You can sometimes break these rules but your code logic sclk, mosi, miso, ssn ; is more likely to have logical errors and the results endinterface may not be repeatable (between simulators or from module master ( spibus io ) ; simulation to synthesis). logic x ; assign io.mosi = 1 ; if/else assign x = io.miso ; endmodule e if/else statement syntax is similar to C and syn- thesizes multiplexers trees whose hierarchy defined module slave ( spibus io ) ; by the order of the conditions. logic x ;

7 assign x = io.mosi ; values in different ways. Bidirectional (inout) mod- assign io.miso = 2 ; ule ports must also be declared with net types. endmodule module ex17 ( input logic clk ) ; Initialization spibus io ( clk ) ; e ability to initialize registers modeled as ordinary master m0 ( io ) ; (“static”) variables depends on the target technology. slave s0 ( io ) ; endmodule ASIC registers power up in undefined states and must be explicitly reset. However, most FPGA technolo- gies allow the power-on values of registers to be be in- Interfaces can also include type and function dec- cluded in the FPGA configuration data that is loaded larations, and ports that allow connections to all con- when the FPGA is powered on. In this case initializa- nections to that interface (e.g. for clock and reset sig- tion of static variables is synthesizable. nals). Variables and functions can also be declared automatic to define semantics similar to those for Interfaces can also define variants (e.g. master dynamically allocated variables in conventional pro- and slave) defined as modports, that include different gramming languages. ese variables can be initial- combinations of signals, each of which is declared as ized each time the block is executed. For example, an input or an output. cnt below will be reset on each rising clock edge:

always_ff@(posedge clk) begin Other Language Topics automatic logic [7:0] cnt = '0 ; // ... end Variables and Nets, reg and wire

A variable can store a value. It models a register. A $readmemh/$readmemb variable can only be assigned within an always block. ese system tasks allow large blocks of con- A net does not store a value. It models a connection. stant data, in hex and binary bases respec- It must be driven by a continuous assignment state- tively, to be read from files. For example: ment. $readmemh("data.hex",memory); would read Earlier versions of Verilog used reg and wire dec- hex values into the variable (array) memory from the larations instead of logic. Assignments in proce- file “data.hex.” dural statements (within always blocks) must be to reg “variables” declared . Other signals are “nets” and System Tasks are declared wire. However, reg variables need not represent regis- Functions beginning with $ are system tasks. Some ters and wire signals oen originate in register out- examples: $display(), similar to C’s printf(), puts. us wire and reg convey little informa- can be used to print messages during simulation; tion. Use System Verilog’s logic declarations instead $finish and $stop can terminate a simulation. whenever possible. Exercise 3: Should each of the following nets (or variables) be Identifiers and Reserved Words declared wire or reg? module test (a,b,c,d,q) ; System Verilog has about 250 reserved words that dff d0 (clk,d,q) ; // assume only q is an output cannot be used as identifiers. Unfortunately, this in- assign d = a & b ; cludes many words that you might be tempted to use always@* clk = a & c ; as signal names (buf, time, wait, disable,...). e endmodule language specification has a complete list. Only nets may have multiple drivers (e.g. to model buses with tri-state drivers). ere are vari- ous flavours (wire, tri, wand, ..) each with different “resolution functions” that combine multiple driving

8