nyuuzyou/wikis huggingface dataset:
Always nolatches

Suppose you're building a circuit to process scancodes from a PS/2 keyboard for a game. Given the last two bytes of scancodes received, you need to indicate whether one of the arrow keys on the keyboard have been pressed. This involves a fairly simple mapping, which can be implemented as a case statement (or if-elseif) with four cases.
Scancode [15:0]	Arrow key
16'he06b 	left arrow
16'he072 	down arrow
16'he074 	right arrow
16'he075 	up arrow
Anything else 	none
Your circuit has one 16-bit input, and four outputs. Build this circuit that recognizes these four scancodes and asserts the correct output.
To avoid creating latches, all outputs must be assigned a value in all possible conditions (See also <vlgstat tc=always_if2/>). Simply having a default case is not enough. You must assign a value to all four outputs in all four cases and the default case. This can involve a lot of unnecessary typing. One easy way around this is to assign a "default value" to the outputs before the case statement:
always @(*) begin
 up = 1'b0; down = 1'b0; left = 1'b0; right = 1'b0;
 case (scancode)
 ... // Set to 1 as necessary.
 endcase
end
This style of code ensures the outputs are assigned a value (of 0) in all possible cases unless the case statement overrides the assignment. This also means that a default: case item becomes unnecessary.
Reminder: The logic synthesizer generates a combinational circuit that behaves equivalently to what the code describes. Hardware does not "execute" the lines of code in sequence.
Alwaysblock1

Since digital circuits are composed of logic gates connected with wires, any circuit can be expressed as some combination of modules and assign statements. However, sometimes this is not the most convenient way to describe the circuit. Procedures (of which always blocks are one example) provide an alternative syntax for describing circuits.
For synthesizing hardware, two types of always blocks are relevant:
* Combinational: always @(*)
* Clocked: always @(posedge clk)
Combinational always blocks are equivalent to assign statements, thus there is always a way to express a combinational circuit both ways. The choice between which to use is mainly an issue of which syntax is more convenient. The syntax for code inside a procedural block is different from code that is outside. Procedural blocks have a richer set of statements (e.g., if-then, case), cannot contain continuous assignments*, but also introduces many new non-intuitive ways of making errors.
(*Procedural continuous assignments do exist, but are somewhat different from continuous assignments, and are not synthesizable.)
For example, the assign and combinational always block describe the same circuit. Both create the same blob of combinational logic. Both will recompute the output whenever any of the inputs (right side) changes value.
assign out1 = a & b | c ^ d;
always @(*) out2 = a & b | c ^ d;
For combinational always blocks, always use a sensitivity list of (*). Explicitly listing out the signals is error-prone (if you miss one), and is ignored for hardware synthesis. If you explicitly specify the sensitivity list and miss a signal, the synthesized hardware will still behave as though (*) was specified, but the simulation will not and not match the hardware's behaviour. (In SystemVerilog, use always_comb.)
A note on wire vs. reg: The left-hand-side of an assign statement must be a net type (e.g., wire), while the left-hand-side of a procedural assignment (in an always block) must be a variable type (e.g., reg). These types (wire vs. reg) have nothing to do with what hardware is synthesized, and is just syntax left over from Verilog's use as a hardware simulation language. 
=== A bit of practice ===
Build an AND gate using both an assign statement and a combinational always block. (Since assign statements and combinational always blocks function identically, there is no way to enforce that you're using both methods. But you're here for practice, right?...)
Alwaysblock2

For hardware synthesis, there are two types of always blocks that are relevant:
* Combinational: always @(*)
* Clocked: always @(posedge clk)
Clocked always blocks create a blob of combinational logic just like combinational always blocks, but also creates a set of flip-flops (or "registers") at the output of the blob of combinational logic. Instead of the outputs of the blob of logic being visible immediately, the outputs are visible only immediately after the next (posedge clk).
==== Blocking vs. Non-Blocking Assignment ====
There are three types of assignments in Verilog:
* Continuous assignments (assign x = y;). Can only be used when not inside a procedure ("always block").
* Procedural blocking assignment: (x = y;). Can only be used inside a procedure.
* Procedural non-blocking assignment: (x <= y;). Can only be used inside a procedure.
In a combinational always block, use blocking assignments. In a clocked always block, use non-blocking assignments. A full understanding of why is not particularly useful for hardware design and requires a good understanding of how Verilog simulators keep track of events. Not following this rule results in extremely hard to find errors that are both non-deterministic and differ between simulation and synthesized hardware.
=== A bit of practice ===
Build an XOR gate three ways, using an assign statement, a combinational always block, and a clocked always block. Note that the clocked always block produces a different circuit from the other two: There is a flip-flop so the output is delayed.
Andgate

Create a module that implements an AND gate.
This circuit now has three wires (a, b, and out). Wires a and b already have values driven onto them by the input ports. But wire out currently is not driven by anything. Write an assign statement that drives out with the AND of signals a and b.
Note that this circuit is very similar to the <vlgstat tc=notgate>NOT gate</vlgstat>, just with one more input. If it sounds different, it's because I've started describing signals as being driven (has a known value determined by something attached to it) or not driven by something. Input wires are driven by something outside the module. assign statements will drive a logic level onto a wire. As you might expect, a wire cannot have more than one driver (what is its logic level if there is?), and a wire that has no drivers will have an undefined value (often treated as 0 when synthesizing hardware).
Bcdadd100

You are provided with a BCD one-digit adder named bcd_fadd that adds two BCD digits and carry-in, and produces a sum and carry-out.
module bcd_fadd (
 input [3:0] a,
 input [3:0] b,
 input cin,
 output cout,
 output [3:0] sum );
Instantiate 100 copies of bcd_fadd to create a 100-digit BCD ripple-carry adder. Your adder should add two 100-digit BCD numbers (packed into 400-bit vectors) and a carry-in to produce a 100-digit sum and carry out.
Bcdadd4

You are provided with a BCD (binary-coded decimal) one-digit adder named bcd_fadd that adds two BCD digits and carry-in, and produces a sum and carry-out.
module bcd_fadd (
 input [3:0] a,
 input [3:0] b,
 input cin,
 output cout,
 output [3:0] sum );
Instantiate 4 copies of bcd_fadd to create a 4-digit BCD ripple-carry adder. Your adder should add two 4-digit BCD numbers (packed into 16-bit vectors) and a carry-in to produce a 4-digit sum and carry out.
Conditional

Verilog has a ternary conditional operator ( ? : ) much like C:
(condition ? if_true : if_false)
This can be used to choose one of two values based on condition (a mux!) on one line, without using an if-then inside a combinational always block.
Examples:
(0 ? 3 : 5) // This is 5 because the condition is false.
(sel ? b : a) // A 2-to-1 multiplexer between a and b selected by sel.
always @(posedge clk) // A T-flip-flop.
 q <= toggle ? ~q : q;
always @(*) // State transition logic for a one-input FSM
 case (state)
 A: next = w ? B : A;
 B: next = w ? A : B;
 endcase
assign out = ena ? q : 1'bz; // A tri-state buffer
((sel[1:0] == 2'h0) ? a : // A 3-to-1 mux
 (sel[1:0] == 2'h1) ? b :
 c )
== A Bit of Practice ==
Given four unsigned numbers, find the minimum. Unsigned numbers can be compared with standard comparison operators (a < b). Use the conditional operator to make two-way min circuits, then compose a few of them to create a 4-way min circuit. You'll probably want some wire vectors for the intermediate results.
Conwaylife

Conway's Game of Life is a two-dimensional cellular automaton.
The "game" is played on a two-dimensional grid of cells, where each cell is either 1 (alive) or 0 (dead). At each time step, each cell changes state depending on how many neighbours it has:
* 0-1 neighbour: Cell becomes 0.
* 2 neighbours: Cell state does not change.
* 3 neighbours: Cell becomes 1.
* 4+ neighbours: Cell becomes 0.
The game is formulated for an infinite grid. In this circuit, we will use a 16x16 grid. To make things more interesting, we will use a 16x16 toroid, where the sides wrap around to the other side of the grid. For example, the corner cell (0,0) has 8 neighbours: (15,1), (15,0), (15,15), (0,1), (0,15), (1,1), (1,0), and (1,15). The 16x16 grid is represented by a length 256 vector, where each row of 16 cells is represented by a sub-vector: q[15:0] is row 0, q[31:16] is row 1, etc. (This tool accepts SystemVerilog, so you may use 2D vectors if you wish.)
* load: Loads data into q at the next clock edge, for loading initial state.
* q: The 16x16 current state of the game, updated every clock cycle.
The game state should advance by one timestep every clock cycle.
John Conway, mathematician and creator of the Game of Life cellular automaton, passed away from COVID-19 on April 11, 2020.
Count10

Build a decade counter that counts from 0 through 9, inclusive, with a period of 10. The reset input is synchronous, and should reset the counter to 0.
<wavedrom skin="narrow">
{ signal: [{ name: "clk", wave: "p..............." },
 { name: "reset", wave: "10...........10." },
 { name: "q", wave: "x===============", data: ['0','1','2','3','4','5','6','7','8','9','0','1','2', "0", "1"] }
] }
</wavedrom>
Count15

Build a 4-bit binary counter that counts from 0 through 15, inclusive, with a period of 16. The reset input is synchronous, and should reset the counter to 0.
<wavedrom skin="narrow">
{ signal: [{ name: "clk", wave: "p..............." },
 { name: "reset", wave: "0............10." },
 { name: "q", wave: "================", data: ['5', '6','7','8','9','a','b','c','d','e','f','0','1','2', "0", "1"] }
] }
</wavedrom>
Count1to10

Make a decade counter that counts 1 through 10, inclusive. The reset input is synchronous, and should reset the counter to 1.
<wavedrom>
{ signal: [{ name: "clk", wave: "p......." },
 { name: "reset", wave: "10...10." },
 { name: "q", wave: "x=======", data: ["1", "2", "3", "4", "5", "1", "2"] }
] }
</wavedrom>
Count clock

Create a set of counters suitable for use as a 12-hour clock (with am/pm indicator). Your counters are clocked by a fast-running clk, with a pulse on ena whenever your clock should increment (i.e., once per second).
reset resets the clock to 12:00 AM. pm is 0 for AM and 1 for PM. hh, mm, and ss are two BCD (Binary-Coded Decimal) digits each for hours (01-12), minutes (00-59), and seconds (00-59). Reset has higher priority than enable, and can occur even when not enabled.
The following timing diagram shows the rollover behaviour from 11:59:59 AM to 12:00:00 PM and the synchronous reset and enable behaviour.
<wavedrom>
{ signal: [{ name: "clk", wave: "p........" },
 { name: "reset", wave: "0...10..." },
 { name: "ena", wave: "1...x1.0." },
 { name: "pm", wave: "0..1.0...", data: ["57", "58", "59", "00", "01", "00", "01", "02" ] },
 { name: "hh[7:0]", wave: "=..=.....", data: ["8'h11", "8'h12"] },
 { name: "mm[7:0]", wave: "=..=.....", data: ["8'h59", "8'h00"] },
 { name: "ss[7:0]", wave: "========.", data: ["8'h57", "8'h58", "8'h59", "8'h00", "8'h01", "8'h00", "8'h01", "8'h02" ] }
] }
</wavedrom>
Countbcd

Build a 4-digit BCD (binary-coded decimal) counter. Each decimal digit is encoded using 4 bits: q[3:0] is the ones digit, q[7:4] is the tens digit, etc. For digits [3:1], also output an enable signal indicating when each of the upper three digits should be incremented.
You may want to instantiate or modify some one-digit decade counters.
<wavedrom>
{ signal: [{ name: "clk", wave: "p......." },
 { name: "reset", wave: "0...10.." },
 { name: "q[3:0]", wave: "========", data: ["7", "8", "9", "0", "1", "0", "1", "2", ] },
 { name: "ena[1]", wave: "0.10...." },
 { name: "q[7:4]", wave: "=..=.=..", data: [ "5", "6", "0" ] }
] }
</wavedrom>
Countslow

Build a decade counter that counts from 0 through 9, inclusive, with a period of 10. The reset input is synchronous, and should reset the counter to 0. We want to be able to pause the counter rather than always incrementing every clock cycle, so the slowena input indicates when the counter should increment.
<wavedrom skin="narrow">
{ signal: [{ name: "clk", wave: "p................" },
 { name: "reset", wave: "10...........10.." },
 { name: "slowena", wave: "10.10.10.10.10.10" },
 { name: "q", wave: "x=..=..=..=..==.=", data: ['0','1','2','3','4','0', '1'] }
] }
</wavedrom>
Cs450/counter 2bc

Branch direction predictors are often structured as tables of counters indexed by the program counter and branch history. Each table entry usually uses two-bits of state because one-bit of state (remember last outcome) does not have enough hysteresis and flips states too easily.
A two-bit state machine that works fairly well is a saturating counterR. Nair, "Optimal 2-bit branch predictors", IEEE Trans. Computers, vol. 44 no. 5, May, 1995, which counts up to 3 (or 2'b11) or down to 0 (or 2'b00) but does not wrap around. A "taken" result increments the counter, while a "not-taken" result decrements the counter. A branch is predicted to be taken when the count is 2 or 3 (or 2'b1x). Adding some hysteresis prevents a flipping of the prediction when a strongly-biased branch occasionally takes a different direction, requiring two increments in the opposite direction before the prediction is flipped.
==== References ====
=== Description ===
Build a two-bit saturating counter. 
The counter increments (up to a maximum of 3) when train_valid = 1 and train_taken = 1. 
It decrements (down to a minimum of 0) when train_valid = 1 and train_taken = 0. When not training (train_valid = 0), the counter keeps its value unchanged.
areset is an asynchronous reset that resets the counter to weakly not-taken (2'b01). Output state[1:0] is the two-bit counter value.
Cs450/history shift

Branch direction predictors are often structured as tables of counters indexed by the program counter and branch history. The branch history is a sequence of "taken" or "not taken" results from recent branches. 
In hardware, the branch history register can be implemented as a N-bit shift register. After each conditional branch direction is predicted, its predicted direction is shifted into the shift register. The shift register thus holds the most recent N branch results.
Additional complexity arises due to pipeline flushes because branch predictions are done speculatively. When a branch misprediction occurs, the processor state needs to be rolled back to the state immediately after the mispredicted branch. This includes rolling back the global history register, which may contain predicted branch results that were shifted-in by branches younger than the mispredicted branch, but now need to be discarded.
We assume here that there is hardware outside of the branch predictor that remembers the state of the branch history register that was used to predict each branch, which is saved for later use for branch predictor training and pipeline flushes. When a branch misprediction occurs, this hardware informs the branch predictor that a branch has mispredicted, the direction the branch should have taken, and the state of the branch history register corresponding to the point in the program immediately before the mispredicted branch.
Of course, since the processor restarts to the point after the mispredicted branch, the branch history register after the pipeline flush needs to have the actual direction of the mispredicted branch appended.
=== Description ===
Build a 32-bit global history shift register, including support for rolling back state in response to a pipeline flush caused by a branch misprediction.
When a branch prediction is made (predict_valid = 1), shift in predict_taken from the LSB side to update the branch history for the predicted branch. (predict_history[0] is the direction of the youngest branch.)
When a branch misprediction occurs (train_mispredicted = 1), load the branch history register with the history after the completion of the mispredicted branch. This is the history before the mispredicted branch (train_history) concatenated with the actual result of the branch (train_taken).
If both a prediction and misprediction occur at the same time, the misprediction takes precedence, because the pipeline flush will also flush out the branch that is currently making a prediction.
predict_history is the value of the branch history register.
areset is an asynchronous reset that resets the history counter to zero.
Cs450/timer

Implement a timer that counts down for a given number of clock cycles, then asserts a signal to indicate that the given duration has elapsed. A good way to implement this is with a down-counter that asserts an output signal when the count becomes 0.
At each clock cycle:
* If load = 1, load the internal counter with the 10-bit data, the number of clock cycles the timer should count before timing out. The counter can be loaded at any time, including when it is still counting and has not yet reached 0.
* If load = 0, the internal counter should decrement by 1.
The output signal tc ("terminal count") indicates whether the internal counter has reached 0. Once the internal counter has reached 0, it should stay 0 (stop counting) until the counter is loaded again.
Below is an example of what happens when asking the timer to count for 3 cycles:
<wavedrom>
{"signal":[["Inputs",{"name":"clk","wave":"ppppppppp"},
 {"name":"load","wave":"010......"},
 {"name":"data","wave":"x=x......","data":["3"]}
 ],
{"name":""},
["Internal",{"name":"counter","wave":"x.====...", "data":['3','2','1','0']}],
{"name":""},
["Outputs",{"name":"tc","wave":"0....1..."}],
{"name":""}]}
</wavedrom>
Dff

A D flip-flop is a circuit that stores a bit and is updated periodically, at the (usually) positive edge of a clock signal. 
D flip-flops are created by the logic synthesizer when a clocked always block is used (See <vlgstat tc=alwaysblock2/>). A D flip-flop is the simplest form of "blob of combinational logic followed by a flip-flop" where the combinational logic portion is just a wire.
Create a single D flip-flop.
Dff16e

Create 16 D flip-flops. It's sometimes useful to only modify parts of a group of flip-flops. The byte-enable inputs control whether each byte of the 16 registers should be written to on that cycle. byteena[1] controls the upper byte d[15:8], while byteena[0] controls the lower byte d[7:0].
resetn is a synchronous, active-low reset.
All DFFs should be triggered by the positive edge of clk.
Dualedge

You're familiar with flip-flops that are triggered on the positive edge of the clock, or negative edge of the clock. A dual-edge triggered flip-flop is triggered on both edges of the clock. However, FPGAs don't have dual-edge triggered flip-flops, and always @(posedge clk or negedge clk) is not accepted as a legal sensitivity list.
Build a circuit that functionally behaves like a dual-edge triggered flip-flop:
<wavedrom>
{ signal: [{ name: "clk", wave: "p......", period: 1 },
 { name: "d", wave: "010.1.010.1..0", period: 0.5 },
 { name: "q", wave: "x010.1.010.1..", period: 0.5 }
] }
</wavedrom>
(Note: It's not necessarily perfectly equivalent: The output of flip-flops have no glitches, but a larger combinational circuit that emulates this behaviour might. But we'll ignore this detail here.)
Edgecapture

For each bit in a 32-bit vector, capture when the input signal changes from 1 in one clock cycle to 0 the next. "Capture" means that the output will remain 1 until the register is reset (synchronous reset). 
Each output bit behaves like a SR flip-flop: The output bit should be set (to 1) the cycle after a 1 to 0 transition occurs. The output bit should be reset (to 0) at the positive clock edge when reset is high. If both of the above events occur at the same time, reset has precedence. In the last 4 cycles of the example waveform below, the 'reset' event occurs one cycle earlier than the 'set' event, so there is no conflict here.
In the example waveform below, reset, in[1] and out[1] are shown again separately for clarity.
<wavedrom>
{ signal: [{ name: "clk", wave: "p.............." },
 { name: "in[31:0]", wave: "=.=...=.==..=..", data: ['0', '2', 'e', '0', '2', '0' ] },
 { name: "reset", wave: "10.........10.."},
 { name: "out[31:0]", wave: "=........=..==.", data: ['0', 'e', '0', '2'] },
 { },
 { name: "in[1]", wave: "0.1.....01..0..", node: '...........c...' },
 { name: "out[1]", wave: "0........1..01.", node: '............bd..' },
 { name: "reset", wave: "10.........10..", node: '...........a...'},
 ],
 edge: [ 'a~->b reset', 'c-~>d set' ]
 }
</wavedrom>
Edgedetect

For each bit in an 8-bit vector, detect when the input signal changes from 0 in one clock cycle to 1 the next (similar to positive edge detection). The output bit should be set the cycle after a 0 to 1 transition occurs. 
Here are some examples. For clarity, in[1] and pedge[1] are shown separately.
<wavedrom>
{ signal: [{ name: "clk", wave: "p............" },
 { name: "in[7:0]", wave: "=.=...=.==...", data: ['0', '2', 'e', '0', '2' ] },
 { name: "pedge[7:0]", wave: "=..==..==.==.", data: ['0', '2', '0', 'c', '0', '2', '0'] },
 { name: "in[1]", wave: "0.1.....01..." },
 { name: "pedge[1]", wave: "0..10.....10." }
 ] }
</wavedrom>
Edgedetect2

For each bit in an 8-bit vector, detect when the input signal changes from one clock cycle to the next (detect any edge). The output bit should be set the cycle after a 0 to 1 transition occurs. 
Here are some examples. For clarity, in[1] and anyedge[1] are shown separately
<wavedrom>
{ signal: [{ name: "clk", wave: "p............" },
 { name: "in[7:0]", wave: "=.=...=.==...", data: ['0', '2', 'e', '0', '2' ] },
 { name: "anyedge[7:0]", wave: "=..==..=====.", data: ['0', '2', '0', 'c', '0', 'e', '2', '0'] },
 { name: "in[1]", wave: "0.1.....01..." },
 { name: "anyedge[1]", wave: "0..10....1.0." }
 ] }
</wavedrom>
Exams/2012 q2b

The state diagram for this question is shown again below.
Assume that a one-hot code is used with the state assignment
y[5:0] = 000001(A), 000010(B), 000100(C), 001000(D), 010000(E), 100000(F)
Write a logic expression for the signal Y1, which is the input of state flip-flop y[1].
Write a logic expression for the signal Y3, which is the input of state flip-flop y[3].
(Derive the logic equations by inspection assuming a one-hot encoding. The testbench will test with non-one hot inputs to make sure you're not trying to do something more complicated).