โšก 20 Premier Engineering Challenges

Interactive VLSI Challenges

Hands-on silicon design and verification drills. Analyze exact signal I/O specifications, conquer corner cases, inspect reference synthesizable RTL, and launch directly in live simulation.

0 / 20 Challenges Solved
0% Completion Rate
1 Day Active Streak
Combinational & Arithmetic Easy CH-01

4-Bit Priority Encoder with Valid Signal

Design a synthesizable 4-bit priority encoder where the highest-index active bit takes priority. Outputs a 2-bit encoded grant and an active-high valid flag.

Signal Interface Specification

PortDirectionEngineering Description
req[3:0]inputActive-high request lines from 4 clients
grant[1:0]output2-bit binary index of the highest priority active request
validoutputHigh when at least one request line is asserted

โฑ๏ธ Timing & Latency Constraint

Pure combinational logic. Maximum propagation delay should not exceed 2 gate delays.

โš ๏ธ Pitfalls & Edge Cases

Failing to prioritize req[3] over req[2:0]; asserting valid when all inputs are 0; incomplete case statements causing latch inference.

๐Ÿ’ก View Engineering Hint

Use a priority if-else ladder or synthesizable casez (with 4'b1??? -> 2'b11). Note that casez requires careful syntax to avoid simulation-synthesis mismatches.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module priority_encoder4 (
  input  wire [3:0] req,
  output reg  [1:0] grant,
  output wire       valid
);
  assign valid = |req; // Reduction OR across all requests

  always @(*) begin
    if (req[3])      grant = 2'b11;
    else if (req[2]) grant = 2'b10;
    else if (req[1]) grant = 2'b01;
    else             grant = 2'b00;
  end
endmodule

Hardware Trade-off: Priority if-else infers a cascaded mux structure with $O(N)$ delay. For large $N$ (e.g. 64 bits), a parallel tree lookahead encoder is preferred.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Combinational & Arithmetic Medium CH-02

Parameterized Gray-to-Binary & Binary-to-Gray Converter

Implement an N-bit bi-directional Gray code converter. Convert binary to reflected Gray code and convert Gray code back to binary with minimal logic levels.

Signal Interface Specification

PortDirectionEngineering Description
bin_in[WIDTH-1:0]inputN-bit binary input vector
gray_out[WIDTH-1:0]outputN-bit reflected Gray code equivalent
gray_in[WIDTH-1:0]inputN-bit Gray code input vector
bin_out[WIDTH-1:0]outputN-bit reconstructed binary value

โฑ๏ธ Timing & Latency Constraint

Binary-to-Gray is single-level XOR (bin ^ (bin >> 1)). Gray-to-Binary is a prefix XOR reduction with log2(N) delay.

โš ๏ธ Pitfalls & Edge Cases

Using a serial for-loop for Gray-to-Binary creates an N-level ripple XOR chain, violating setup time in high-speed CDC pointers.

๐Ÿ’ก View Engineering Hint

Binary to Gray is simply `bin ^ (bin >> 1)`. For Gray to Binary, bit i is the XOR sum of all Gray bits from i up to WIDTH-1.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module gray_converter #(
  parameter WIDTH = 4
)(
  input  wire [WIDTH-1:0] bin_in,
  output wire [WIDTH-1:0] gray_out,
  input  wire [WIDTH-1:0] gray_in,
  output reg  [WIDTH-1:0] bin_out
);
  // Binary to Gray conversion: Single gate delay
  assign gray_out = bin_in ^ (bin_in >> 1);

  // Gray to Binary conversion
  integer i;
  always @(*) begin
    for (i = 0; i < WIDTH; i = i + 1) begin
      bin_out[i] = ^(gray_in >> i); // XOR reduction of upper bits
    end
  end
endmodule

Hardware Trade-off: Prefix tree XOR reduction achieves $O(\log_2 N)$ latency compared to $O(N)$ for serial ripple XOR chains.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Combinational & Arithmetic Medium CH-03

8-Bit Multi-Mode Barrel Shifter & Rotator

Synthesize an 8-bit barrel shifter supporting logical left, logical right, arithmetic right (with sign extension), and cyclic rotate right operations in a single cycle.

Signal Interface Specification

PortDirectionEngineering Description
data_in[7:0]input8-bit input data word
shift_amt[2:0]inputShift amount from 0 to 7 positions
mode[1:0]input00: SLL, 01: SRL, 10: SRA (Arithmetic), 11: ROR (Rotate)
data_out[7:0]output8-bit shifted / rotated result

โฑ๏ธ Timing & Latency Constraint

Single-cycle execution. Implemented via 3 cascaded 2:1 multiplexer stages (stage 0: 1 bit, stage 1: 2 bits, stage 2: 4 bits).

โš ๏ธ Pitfalls & Edge Cases

Arithmetic right shift of unsigned variables in Verilog does not sign extend; the input must be explicitly cast to signed or filled using sign bit replication.

๐Ÿ’ก View Engineering Hint

Replicate data_in into a 16-bit virtual buffer `{data_in, data_in}` to simplify rotation, and use sign replication `{8{data_in[7]}}` for arithmetic shifting.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module barrel_shifter8 (
  input  wire [7:0] data_in,
  input  wire [2:0] shift_amt,
  input  wire [1:0] mode, // 00:SLL, 01:SRL, 10:SRA, 11:ROR
  output reg  [7:0] data_out
);
  always @(*) begin
    case (mode)
      2'b00: data_out = data_in << shift_amt;
      2'b01: data_out = data_in >> shift_amt;
      2'b10: data_out = $signed(data_in) >>> shift_amt; // SRA
      2'b11: data_out = (data_in >> shift_amt) | (data_in << (8 - shift_amt)); // ROR
      default: data_out = data_in;
    endcase
  end
endmodule

Hardware Trade-off: Logarithmic multi-stage multiplexers yield $O(\log_2 N)$ delay with minimal silicon area compared to a flat 8-input crossbar switch.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Combinational & Arithmetic Hard CH-04

16-Bit Carry-Skip Adder (CSA) with Block Bypass

Design a 16-bit Carry-Skip Adder divided into four 4-bit blocks. If all propagate signals in a block are true (P0 & P1 & P2 & P3 = 1), skip the carry around the block via bypass mux.

Signal Interface Specification

PortDirectionEngineering Description
a[15:0]input16-bit augend operand
b[15:0]input16-bit addend operand
cininputCarry-in bit
sum[15:0]output16-bit sum output
coutoutputCarry-out bit

โฑ๏ธ Timing & Latency Constraint

Reduces worst-case critical path delay from 16 ripple carry full-adder delays to 4 ripple stages + 3 bypass mux delays.

โš ๏ธ Pitfalls & Edge Cases

Incorrect skip condition generation (using XOR instead of OR for propagate, or missing cin in the block bypass select).

๐Ÿ’ก View Engineering Hint

For each 4-bit block, calculate generate G = a & b and propagate P = a ^ b. If &P[3:0] is 1, block carry-out is cin; otherwise, it is the ripple carry.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module carry_skip_adder16 (
  input  wire [15:0] a,
  input  wire [15:0] b,
  input  wire        cin,
  output wire [15:0] sum,
  output wire        cout
);
  wire [4:0] c;
  assign c[0] = cin;

  genvar i;
  generate
    for (i = 0; i < 4; i = i + 1) begin : gen_csa_blocks
      wire [3:0] blk_a = a[i*4 +: 4];
      wire [3:0] blk_b = b[i*4 +: 4];
      wire [3:0] blk_p = blk_a ^ blk_b;
      wire [4:0] blk_c;
      assign blk_c[0] = c[i];

      // 4-bit ripple carry inside block
      genvar j;
      for (j = 0; j < 4; j = j + 1) begin : gen_fa
        assign sum[i*4 + j] = blk_p[j] ^ blk_c[j];
        assign blk_c[j+1]   = (blk_a[j] & blk_b[j]) | (blk_p[j] & blk_c[j]);
      end

      // Skip bypass multiplexer
      wire skip = &blk_p;
      assign c[i+1] = skip ? c[i] : blk_c[4];
    end
  endgenerate

  assign cout = c[4];
endmodule

Hardware Trade-off: Offers near Carry-Lookahead speed with significantly less silicon area and routing congestion on standard cell ASICs.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Sequential Logic & FSMs Medium CH-05

Sequence Detector '1011' with Overlapping Streams

Design a synchronous sequence detector for pattern '1011' on serial input 'din'. Assert 'detected' high for 1 clock cycle upon pattern match, supporting overlapping sequences (e.g. 1011011 -> two detections).

Signal Interface Specification

PortDirectionEngineering Description
clkinputSystem clock
rst_ninputActive-low asynchronous reset
dininputSerial binary data input
detectedoutputHigh for 1 cycle when pattern 1011 is completed

โฑ๏ธ Timing & Latency Constraint

Moore machine outputs in the cycle following sequence completion; Mealy machine outputs in the cycle din completes the pattern.

โš ๏ธ Pitfalls & Edge Cases

Failing to transition from final state '1011' back to state '1' on next din=0, missing the overlapping detection.

๐Ÿ’ก View Engineering Hint

States: IDLE, S1 (saw 1), S10 (saw 10), S101 (saw 101). When in S101, if din=1, detect is asserted and next state is S1 (as the trailing 1 starts a new pattern).

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module seq_detector_1011 (
  input  wire clk,
  input  wire rst_n,
  input  wire din,
  output reg  detected
);
  localparam IDLE = 3'b000,
             S1   = 3'b001,
             S10  = 3'b010,
             S101 = 3'b011;

  reg [2:0] state, next_state;

  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) state <= IDLE;
    else        state <= next_state;
  end

  always @(*) begin
    next_state = state;
    detected   = 1'b0;
    case (state)
      IDLE: next_state = din ? S1 : IDLE;
      S1:   next_state = din ? S1 : S10;
      S10:  next_state = din ? S101 : IDLE;
      S101: begin
        if (din) begin
          detected   = 1'b1; // Pattern 1011 matched!
          next_state = S1;   // Overlap: trailing '1' can start next sequence
        end else begin
          next_state = S10;  // Trailing '0' matches prefix '10'
        end
      end
      default: next_state = IDLE;
    endcase
  end
endmodule

Hardware Trade-off: Mealy output has 0-cycle latency but can pass combinational glitches on din. A registered output adds 1 cycle latency but guarantees glitch-free timing.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Sequential Logic & FSMs Hard CH-06

Glitch-Free Dual-Clock Multiplexer Controller

Safely switch between two asynchronous clock sources (clk0 and clk1) using a select signal without producing runt pulses, narrow spikes, or metastability hazards.

Signal Interface Specification

PortDirectionEngineering Description
clk0inputAsynchronous clock source 0
clk1inputAsynchronous clock source 1
selinputSelect signal (0: clk0, 1: clk1)
rst_ninputActive-low system reset
clk_outoutputGlitch-free switched clock output

โฑ๏ธ Timing & Latency Constraint

A clock domain can only be enabled after the other clock domain has been cleanly disabled on its negative edge.

โš ๏ธ Pitfalls & Edge Cases

Using a simple combinational multiplexer `assign clk_out = sel ? clk1 : clk0;` produces deadly runt pulses when sel toggles while clocks are at different levels.

๐Ÿ’ก View Engineering Hint

Use cross-coupled negative-edge triggered flip-flops with dual-stage synchronizers. Negedge triggering ensures clock gating transitions occur when the clock is LOW.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module glitch_free_clock_mux (
  input  wire clk0,
  input  wire clk1,
  input  wire sel,
  input  wire rst_n,
  output wire clk_out
);
  reg q0_d1, q0_d2;
  reg q1_d1, q1_d2;

  // Cross-coupled negative-edge synchronizer for clk0
  always @(negedge clk0 or negedge rst_n) begin
    if (!rst_n) begin
      q0_d1 <= 1'b0;
      q0_d2 <= 1'b0;
    end else begin
      q0_d1 <= (~sel) & (~q1_d2); // Disable if clk1 active
      q0_d2 <= q0_d1;
    end
  end

  // Cross-coupled negative-edge synchronizer for clk1
  always @(negedge clk1 or negedge rst_n) begin
    if (!rst_n) begin
      q1_d1 <= 1'b0;
      q1_d2 <= 1'b0;
    end else begin
      q1_d1 <= sel & (~q0_d2); // Disable if clk0 active
      q1_d2 <= q1_d1;
    end
  end

  // Glitch-free clock combining
  assign clk_out = (clk0 & q0_d2) | (clk1 & q1_d2);
endmodule

Hardware Trade-off: Requires 2โ€“3 clock cycles of switchover latency between source clocks, but completely eliminates downstream flip-flop setup/hold violations.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Sequential Logic & FSMs Medium CH-07

Exact 50% Duty Cycle Clock Divider (Odd & Even)

Implement a configurable clock divider that achieves exact 50% duty cycle for both even (e.g. div 2, 4, 6) and odd (e.g. div 3, 5, 7) integer division factors.

Signal Interface Specification

PortDirectionEngineering Description
clk_ininputHigh-frequency source clock
rst_ninputActive-low asynchronous reset
clk_outoutputDivided clock output with exact 50% duty cycle

โฑ๏ธ Timing & Latency Constraint

For odd division (e.g. div by 3), 50% duty cycle requires combining positive-edge and negative-edge triggered counter snapshots.

โš ๏ธ Pitfalls & Edge Cases

Standard positive-edge counters can only achieve integer cycle pulse widths, resulting in 33% or 66% duty cycle on odd divisors.

๐Ÿ’ก View Engineering Hint

Generate two phase-shifted pulses: one on posedge clk_in and one on negedge clk_in, then bitwise OR them together.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module clock_div3_50pct (
  input  wire clk_in,
  input  wire rst_n,
  output wire clk_out
);
  reg [1:0] pos_cnt;
  reg [1:0] neg_cnt;

  // Posedge counter
  always @(posedge clk_in or negedge rst_n) begin
    if (!rst_n) pos_cnt <= 2'b00;
    else        pos_cnt <= (pos_cnt == 2'd2) ? 2'd0 : pos_cnt + 1'b1;
  end

  // Negedge counter
  always @(negedge clk_in or negedge rst_n) begin
    if (!rst_n) neg_cnt <= 2'b00;
    else        neg_cnt <= (neg_cnt == 2'd2) ? 2'd0 : neg_cnt + 1'b1;
  end

  // 50% duty cycle clock output: OR posedge pulse with negedge pulse
  assign clk_out = (pos_cnt != 2'd2) && (neg_cnt != 2'd2);
endmodule

Hardware Trade-off: Combines dual-edge flops, which requires tight clock duty-cycle integrity on clk_in to prevent output pulse width jitter.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Sequential Logic & FSMs Easy CH-08

4-Way Traffic Light Controller with Pedestrian Sensor

Design a synchronous traffic light controller managing Highway (HWY) and Farm Road (FARM). Includes Green, Yellow, Red states and a pedestrian push-button override.

Signal Interface Specification

PortDirectionEngineering Description
clkinput1 Hz timebase clock
rst_ninputActive-low reset
sensorinputFarm road / pedestrian presence sensor
hwy_lights[2:0]outputHighway [Red, Yellow, Green] lights
farm_lights[2:0]outputFarm road [Red, Yellow, Green] lights

โฑ๏ธ Timing & Latency Constraint

HWY Green stays on until sensor triggers. Minimum yellow light duration is 3 cycles.

โš ๏ธ Pitfalls & Edge Cases

Switching directly from Green to Red without Yellow transition; latch inference on missing light assignment.

๐Ÿ’ก View Engineering Hint

Use 4 states: HWY_G (H:Green, F:Red), HWY_Y (H:Yellow, F:Red), FARM_G (H:Red, F:Green), FARM_Y (H:Red, F:Yellow).

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module traffic_light_fsm (
  input  wire clk,
  input  wire rst_n,
  input  wire sensor,
  output reg  [2:0] hwy_lights,  // [Red, Yellow, Green]
  output reg  [2:0] farm_lights
);
  localparam S_HWY_G  = 2'd0,
             S_HWY_Y  = 2'd1,
             S_FARM_G = 2'd2,
             S_FARM_Y = 2'd3;

  reg [1:0] state, next_state;
  reg [3:0] timer;

  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      state <= S_HWY_G;
      timer <= 4'd0;
    end else begin
      state <= next_state;
      if (state != next_state) timer <= 4'd0;
      else                     timer <= timer + 1'b1;
    end
  end

  always @(*) begin
    next_state = state;
    case (state)
      S_HWY_G:  if (sensor && timer >= 4'd10) next_state = S_HWY_Y;
      S_HWY_Y:  if (timer >= 4'd3)           next_state = S_FARM_G;
      S_FARM_G: if (!sensor || timer >= 4'd8) next_state = S_FARM_Y;
      S_FARM_Y: if (timer >= 4'd3)           next_state = S_HWY_G;
    endcase
  end

  always @(*) begin
    hwy_lights  = 3'b100; // Red default
    farm_lights = 3'b100;
    case (state)
      S_HWY_G:  begin hwy_lights = 3'b001; farm_lights = 3'b100; end
      S_HWY_Y:  begin hwy_lights = 3'b010; farm_lights = 3'b100; end
      S_FARM_G: begin hwy_lights = 3'b100; farm_lights = 3'b001; end
      S_FARM_Y: begin hwy_lights = 3'b100; farm_lights = 3'b010; end
    endcase
  end
endmodule

Hardware Trade-off: Moore machine outputs ensure zero hazard glitches on physical driver outputs.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Microarchitecture & CDC Medium CH-09

Dual-Clock Fast-to-Slow Pulse Synchronizer

Transfer a 1-clock-cycle pulse from a fast clock domain (clk_src = 200 MHz) into an asynchronous slow clock domain (clk_dst = 50 MHz) without pulse loss.

Signal Interface Specification

PortDirectionEngineering Description
clk_srcinputFast source clock domain
rst_src_ninputSource reset
pulse_ininput1-cycle pulse in clk_src domain
clk_dstinputSlow destination clock domain
rst_dst_ninputDestination reset
pulse_outoutput1-cycle pulse in clk_dst domain

โฑ๏ธ Timing & Latency Constraint

A fast pulse is shorter than 1 destination clock cycle and will be completely missed by a standard 2-FF synchronizer without pulse stretching.

โš ๏ธ Pitfalls & Edge Cases

Feeding pulse_in directly into a 2-FF synchronizer; assuming pulse will meet setup/hold times of clk_dst registers.

๐Ÿ’ก View Engineering Hint

Toggle a state flip-flop in clk_src on each pulse_in. Synchronize the toggle signal into clk_dst using 2 flip-flops, then use an XOR edge detector to recreate the pulse.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module pulse_synchronizer (
  input  wire clk_src,
  input  wire rst_src_n,
  input  wire pulse_in,
  input  wire clk_dst,
  input  wire rst_dst_n,
  output wire pulse_out
);
  // Source domain: Toggle on pulse_in
  reg toggle_src;
  always @(posedge clk_src or negedge rst_src_n) begin
    if (!rst_src_n) toggle_src <= 1'b0;
    else if (pulse_in) toggle_src <= ~toggle_src;
  end

  // Destination domain: 2-FF synchronizer + delay reg
  reg sync_d1, sync_d2, sync_d3;
  always @(posedge clk_dst or negedge rst_dst_n) begin
    if (!rst_dst_n) begin
      sync_d1 <= 1'b0;
      sync_d2 <= 1'b0;
      sync_d3 <= 1'b0;
    end else begin
      sync_d1 <= toggle_src;
      sync_d2 <= sync_d1;
      sync_d3 <= sync_d2;
    end
  end

  // Edge detection: Output pulse on any transition of synchronized toggle
  assign pulse_out = sync_d2 ^ sync_d3;
endmodule

Hardware Trade-off: Minimum interval between consecutive pulses in clk_src must be at least 3 destination clock cycles to avoid pulse absorption.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Microarchitecture & CDC Easy CH-10

Asynchronous Reset Synchronizer (Async Assert, Sync Deassert)

Design a reset bridge that asserts reset immediately upon asynchronous event, but de-asserts synchronously to the clock to prevent recovery/removal timing violations.

Signal Interface Specification

PortDirectionEngineering Description
clkinputDestination clock domain
async_rst_ninputRaw asynchronous external reset
sync_rst_noutputSynchronized active-low reset

โฑ๏ธ Timing & Latency Constraint

Prevents flip-flop metastability on power-up reset release across digital chips.

โš ๏ธ Pitfalls & Edge Cases

Using pure asynchronous resets without de-assertion synchronizers causes registers to exit reset in different clock cycles.

๐Ÿ’ก View Engineering Hint

Tie the D-input of the first flip-flop to 1'b1. Both flip-flops have async reset connected to async_rst_n.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module reset_synchronizer (
  input  wire clk,
  input  wire async_rst_n,
  output wire sync_rst_n
);
  (* ASYNC_REG = "TRUE" *) reg rst_meta_n, rst_sync_n;

  always @(posedge clk or negedge async_rst_n) begin
    if (!async_rst_n) begin
      rst_meta_n <= 1'b0;
      rst_sync_n <= 1'b0;
    end else begin
      rst_meta_n <= 1'b1;
      rst_sync_n <= rst_meta_n;
    end
  end

  assign sync_rst_n = rst_sync_n;
endmodule

Hardware Trade-off: Requires 2 clock cycles after physical reset release before logic starts executing.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Microarchitecture & CDC Medium CH-11

Synchronous FIFO with Watermarks (Almost Full / Empty)

Build a parameterized synchronous circular FIFO with programmable watermarks: almost_full (ALMOST_FULL_THRESH) and almost_empty (ALMOST_EMPTY_THRESH).

Signal Interface Specification

PortDirectionEngineering Description
clkinputSystem clock
rst_ninputActive-low reset
wr_eninputWrite enable
din[DATA_W-1:0]inputWrite data word
rd_eninputRead enable
dout[DATA_W-1:0]outputRead data word
fulloutputFIFO full flag
emptyoutputFIFO empty flag
almost_fulloutputHigh when count >= ALMOST_FULL_THRESH
almost_emptyoutputHigh when count <= ALMOST_EMPTY_THRESH

โฑ๏ธ Timing & Latency Constraint

Simultaneous write and read when full or almost full must preserve data integrity and correct count.

โš ๏ธ Pitfalls & Edge Cases

Counter overflow when wr_en and rd_en are both active; dropping data when full without write protection.

๐Ÿ’ก View Engineering Hint

Maintain an explicit occupancy counter `count`. When wr_en & !rd_en, count++; when rd_en & !wr_en, count--; when both, count is unchanged.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module sync_fifo_watermarks #(
  parameter DATA_W = 8,
  parameter DEPTH  = 16,
  parameter AF_THRESH = 14,
  parameter AE_THRESH = 2
)(
  input  wire              clk,
  input  wire              rst_n,
  input  wire              wr_en,
  input  wire [DATA_W-1:0] din,
  input  wire              rd_en,
  output reg  [DATA_W-1:0] dout,
  output wire              full,
  output wire              empty,
  output wire              almost_full,
  output wire              almost_empty
);
  localparam ADDR_W = $clog2(DEPTH);

  reg [DATA_W-1:0] mem [0:DEPTH-1];
  reg [ADDR_W-1:0] wr_ptr, rd_ptr;
  reg [ADDR_W:0]   count;

  assign full         = (count == DEPTH);
  assign empty        = (count == 0);
  assign almost_full  = (count >= AF_THRESH);
  assign almost_empty = (count <= AE_THRESH);

  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      wr_ptr <= 0;
      rd_ptr <= 0;
      count  <= 0;
    end else begin
      // Write logic
      if (wr_en && !full) begin
        mem[wr_ptr] <= din;
        wr_ptr      <= (wr_ptr == DEPTH-1) ? 0 : wr_ptr + 1;
      end
      // Read logic
      if (rd_en && !empty) begin
        dout   <= mem[rd_ptr];
        rd_ptr <= (rd_ptr == DEPTH-1) ? 0 : rd_ptr + 1;
      end
      // Count update
      case ({wr_en && !full, rd_en && !empty})
        2'b10: count <= count + 1;
        2'b01: count <= count - 1;
        default: count <= count;
      endcase
    end
  end
endmodule

Hardware Trade-off: Occupancy counter uses an extra bit of logic but provides straightforward watermark flags compared to pointer distance subtraction.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Microarchitecture & CDC Hard CH-12

Ready-Valid Skid Buffer (Zero Bubble Register Slice)

Break timing paths on both data and backpressure ready signals in ready-valid handshake channels. Guarantee 100% throughput with zero bubble cycles upon backpressure release.

Signal Interface Specification

PortDirectionEngineering Description
clkinputClock
rst_ninputActive-low reset
s_validinputUpstream slave valid
s_readyoutputUpstream slave ready
s_data[31:0]inputUpstream data word
m_validoutputDownstream master valid
m_readyinputDownstream master ready
m_data[31:0]outputDownstream data word

โฑ๏ธ Timing & Latency Constraint

Both s_ready and m_valid must come directly from flip-flops to completely break combinational loops.

โš ๏ธ Pitfalls & Edge Cases

Forwarding m_ready combinatorially to s_ready creates a long timing path across chip partitions.

๐Ÿ’ก View Engineering Hint

Use two storage slots: primary register and skid buffer register. When downstream stalls (m_ready=0) and upstream provides data, capture the extra word in the skid buffer.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module skid_buffer #(
  parameter WIDTH = 32
)(
  input  wire             clk,
  input  wire             rst_n,
  input  wire             s_valid,
  output reg              s_ready,
  input  wire [WIDTH-1:0] s_data,
  output reg              m_valid,
  input  wire             m_ready,
  output reg  [WIDTH-1:0] m_data
);
  reg [WIDTH-1:0] buf_data;
  reg             buf_valid;

  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      s_ready   <= 1'b1;
      m_valid   <= 1'b0;
      m_data    <= {WIDTH{1'b0}};
      buf_valid <= 1'b0;
      buf_data  <= {WIDTH{1'b0}};
    end else begin
      // Drain skid buffer if master is ready
      if (m_ready) begin
        if (buf_valid) begin
          m_valid   <= 1'b1;
          m_data    <= buf_data;
          buf_valid <= 1'b0;
          s_ready   <= 1'b1;
        end else if (s_valid) begin
          m_valid <= 1'b1;
          m_data  <= s_data;
          s_ready <= 1'b1;
        end else begin
          m_valid <= 1'b0;
          s_ready <= 1'b1;
        end
      end else begin
        // Master stalled: fill skid buffer if incoming data
        if (s_valid && s_ready) begin
          buf_data  <= s_data;
          buf_valid <= 1'b1;
          s_ready   <= 1'b0; // Throttle upstream
        end
      end
    end
  end
endmodule

Hardware Trade-off: Consumes 2 data registers and small control logic, but allows maximum clock frequency scaling across wide bus architectures.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Timing & Bus Protocols Medium CH-13

Fixing Negative Setup Slack via Register Retiming

A critical 32-bit arithmetic datapath has a setup violation: Tperiod = 5.0ns, Arrival = 6.45ns (Slack = -1.45ns). Restructure into a 2-stage pipelined design to achieve positive slack (> 1.0ns).

Signal Interface Specification

PortDirectionEngineering Description
clkinput200 MHz system clock
rst_ninputActive-low reset
a[31:0]inputOperand A
b[31:0]inputOperand B
c[31:0]inputOperand C
result[31:0]outputPipelined (A * B + C) result (2 cycles latency)

โฑ๏ธ Timing & Latency Constraint

A 32-bit multiplier cannot complete in 5ns. Splitting multiplication and accumulation across two cycles resolves the violation.

โš ๏ธ Pitfalls & Edge Cases

Forgetting to pipeline operand C alongside the multiplication, leading to timing mismatches between product and addend.

๐Ÿ’ก View Engineering Hint

Stage 1 computes multiplier partial products or product `mult_reg <= a * b` and aligns `c_reg <= c`. Stage 2 computes `result <= mult_reg + c_reg`.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module retimed_mac32 (
  input  wire        clk,
  input  wire        rst_n,
  input  wire [31:0] a,
  input  wire [31:0] b,
  input  wire [31:0] c,
  output reg  [31:0] result
);
  // Pipeline Stage 1 registers
  reg [31:0] mult_stage1;
  reg [31:0] c_stage1;

  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      mult_stage1 <= 32'd0;
      c_stage1    <= 32'd0;
      result      <= 32'd0;
    end else begin
      // Stage 1: Multiplication (critical path ~2.8ns)
      mult_stage1 <= a * b;
      c_stage1    <= c; // Delay matching!

      // Stage 2: Accumulation (critical path ~1.8ns)
      result      <= mult_stage1 + c_stage1;
    end
  end
endmodule

Hardware Trade-off: Adds 1 cycle of pipeline latency, but increases achievable clock frequency from 155 MHz to over 350 MHz.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Timing & Bus Protocols Medium CH-14

AMBA APB3 Slave Register Bank with Wait States

Implement a synthesizable AMBA APB3 slave register interface supporting 4 memory-mapped 32-bit registers, address decoding, read/write handshakes, and 1 wait-state via PREADY.

Signal Interface Specification

PortDirectionEngineering Description
PCLKinputAPB clock
PRESETninputActive-low APB reset
PSELinputPeripheral select
PENABLEinputTransfer strobe
PWRITEinput1: Write, 0: Read
PADDR[3:0]inputByte address (word-aligned: 0x0, 0x4, 0x8, 0xC)
PWDATA[31:0]inputWrite data bus
PRDATA[31:0]outputRead data bus
PREADYoutputReady handshake flag

โฑ๏ธ Timing & Latency Constraint

APB transfers consist of SETUP phase (PSEL=1, PENABLE=0) and ACCESS phase (PSEL=1, PENABLE=1).

โš ๏ธ Pitfalls & Edge Cases

Asserting write data before PENABLE is high; failing to hold PRDATA stable until PREADY is acknowledged.

๐Ÿ’ก View Engineering Hint

Drive PREADY low during first cycle of ACCESS phase to introduce 1 wait state, then assert high on subsequent cycle.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module apb_slave_waitstate (
  input  wire        PCLK,
  input  wire        PRESETn,
  input  wire        PSEL,
  input  wire        PENABLE,
  input  wire        PWRITE,
  input  wire [3:0]  PADDR,
  input  wire [31:0] PWDATA,
  output reg  [31:0] PRDATA,
  output reg         PREADY
);
  reg [31:0] regs [0:3];
  reg wait_state_done;

  wire [1:0] reg_idx = PADDR[3:2];

  always @(posedge PCLK or negedge PRESETn) begin
    if (!PRESETn) begin
      PREADY          <= 1'b0;
      wait_state_done <= 1'b0;
      PRDATA          <= 32'd0;
      regs[0]         <= 32'hA0A0_0001;
      regs[1]         <= 32'hB0B0_0002;
      regs[2]         <= 32'hC0C0_0003;
      regs[3]         <= 32'hD0D0_0004;
    end else begin
      if (PSEL && PENABLE) begin
        if (!wait_state_done) begin
          PREADY          <= 1'b0; // Wait state cycle
          wait_state_done <= 1'b1;
        end else begin
          PREADY <= 1'b1; // Complete transfer
          if (PWRITE) begin
            regs[reg_idx] <= PWDATA;
          end else begin
            PRDATA <= regs[reg_idx];
          end
          wait_state_done <= 1'b0;
        end
      end else begin
        PREADY          <= 1'b1;
        wait_state_done <= 1'b0;
      end
    end
  end
endmodule

Hardware Trade-off: Wait states allow slow memory or multi-cycle peripherals to safely interface with high-speed APB system buses.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Timing & Bus Protocols Hard CH-15

Starvation-Free Fair Round-Robin Arbiter

Design a 4-request round-robin arbiter that guarantees fairness and zero starvation. Once client i is granted, next round priority starts at client (i+1)%4.

Signal Interface Specification

PortDirectionEngineering Description
clkinputSystem clock
rst_ninputActive-low reset
req[3:0]input4-bit request vector
grant[3:0]output1-hot grant vector

โฑ๏ธ Timing & Latency Constraint

Must grant in the same cycle requests appear (single-cycle arbitration).

โš ๏ธ Pitfalls & Edge Cases

Fixed priority arbiters starve lower-index clients when higher clients continuously request.

๐Ÿ’ก View Engineering Hint

Use two parallel priority encoders: one masked by priority pointer and one unmasked, then choose the masked result if active.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module round_robin_arbiter4 (
  input  wire       clk,
  input  wire       rst_n,
  input  wire [3:0] req,
  output reg  [3:0] grant
);
  reg [3:0] base_ptr;
  wire [3:0] masked_req;
  wire [3:0] raw_grant_masked;
  wire [3:0] raw_grant_unmasked;

  // Mask requests below current base pointer
  assign masked_req = req & ~((base_ptr - 1'b1) | base_ptr);

  // Priority encoder on masked requests
  assign raw_grant_masked[0] = masked_req[0];
  assign raw_grant_masked[1] = masked_req[1] & ~masked_req[0];
  assign raw_grant_masked[2] = masked_req[2] & ~|masked_req[1:0];
  assign raw_grant_masked[3] = masked_req[3] & ~|masked_req[2:0];

  // Priority encoder on unmasked requests
  assign raw_grant_unmasked[0] = req[0];
  assign raw_grant_unmasked[1] = req[1] & ~req[0];
  assign raw_grant_unmasked[2] = req[2] & ~|req[1:0];
  assign raw_grant_unmasked[3] = req[3] & ~|req[2:0];

  wire [3:0] next_grant = (|masked_req) ? raw_grant_masked : raw_grant_unmasked;

  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      grant    <= 4'b0000;
      base_ptr <= 4'b0001;
    end else begin
      grant <= next_grant;
      if (|next_grant) begin
        // Rotate base pointer to next slot
        base_ptr <= {next_grant[2:0], next_grant[3]};
      end
    end
  end
endmodule

Hardware Trade-off: Dual priority encoders require twice the logic area of fixed priority, but prevent bus monopolization.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
Timing & Bus Protocols Hard CH-16

AXI4-Stream Packet Frame Checker & Byte Counter

Monitor an AXI4-Stream packet flow. Calculate total payload length in bytes by parsing TVALID, TREADY, TLAST, and TKEEP[3:0]. Flag frame length violations against MTU.

Signal Interface Specification

PortDirectionEngineering Description
aclkinputAXI stream clock
aresetninputActive-low reset
tvalidinputMaster valid
treadyinputSlave ready
tlastinputEnd of packet indicator
tkeep[3:0]inputByte qualification strobe
pkt_bytes[15:0]outputTotal accumulated byte count on TLAST
frame_erroutputHigh if packet exceeds MTU (1500 bytes)

โฑ๏ธ Timing & Latency Constraint

A transfer beat occurs strictly when `tvalid && tready` is true on posedge aclk.

โš ๏ธ Pitfalls & Edge Cases

Counting bytes when tvalid is high but tready is low (stalled beat); ignoring partial bytes in final beat marked by tkeep.

๐Ÿ’ก View Engineering Hint

Use a 4-bit popcount on tkeep to determine valid bytes per beat: $countones(tkeep). Accumulate on handshake beats until tlast.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module axis_packet_checker #(
  parameter MAX_MTU = 1500
)(
  input  wire        aclk,
  input  wire        aresetn,
  input  wire        tvalid,
  input  wire        tready,
  input  wire        tlast,
  input  wire [3:0]  tkeep,
  output reg  [15:0] pkt_bytes,
  output reg         frame_err
);
  reg [15:0] byte_accumulator;

  // Popcount for 4-bit TKEEP
  function [2:0] get_keep_count(input [3:0] k);
    get_keep_count = k[0] + k[1] + k[2] + k[3];
  endfunction

  wire beat_handshake = tvalid && tready;
  wire [2:0] beat_bytes = get_keep_count(tkeep);

  always @(posedge aclk or negedge aresetn) begin
    if (!aresetn) begin
      byte_accumulator <= 16'd0;
      pkt_bytes        <= 16'd0;
      frame_err        <= 1'b0;
    end else begin
      if (beat_handshake) begin
        if (tlast) begin
          pkt_bytes        <= byte_accumulator + beat_bytes;
          frame_err        <= (byte_accumulator + beat_bytes > MAX_MTU);
          byte_accumulator <= 16'd0; // Reset for next packet
        end else begin
          byte_accumulator <= byte_accumulator + beat_bytes;
          if (byte_accumulator + beat_bytes > MAX_MTU) frame_err <= 1'b1;
        end
      end
    end
  end
endmodule

Hardware Trade-off: Real-time TKEEP popcount decoding requires minimal lookup table gates but enables immediate line-rate Ethernet filtering.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
SVA & Verification Medium CH-17

SVA: AXI4 Ready-Valid Handshake Stability Rule

Write concurrent SystemVerilog Assertions (SVA) verifying the official ARM AMBA specification: once TVALID is asserted, TVALID and TDATA must remain completely stable until TREADY is asserted.

Signal Interface Specification

PortDirectionEngineering Description
clkinputInterface clock
rst_ninputActive-low reset
tvalidinputValid handshake signal
treadyinputReady handshake signal
tdata[31:0]inputData payload

โฑ๏ธ Timing & Latency Constraint

A dropped TVALID without TREADY assertion causes protocol deadlock in AXI interconnect fabrics.

โš ๏ธ Pitfalls & Edge Cases

Using immediate assertions `assert(...)` inside always block instead of concurrent SVA properties; omitting `disable iff (!rst_n)`.

๐Ÿ’ก View Engineering Hint

Use the overlapping non-overlapping implication operator `|=>` and the `$stable()` system function.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module sva_axi_handshake (
  input wire        clk,
  input wire        rst_n,
  input wire        tvalid,
  input wire        tready,
  input wire [31:0] tdata
);
  // ARM AMBA Rule: Once TVALID is asserted, it MUST remain high until TREADY
  property p_tvalid_stable;
    @(posedge clk) disable iff (!rst_n)
    tvalid && !tready |=> tvalid;
  endproperty
  assert_tvalid_stable: assert property (p_tvalid_stable)
    else $error("[AXI PROTOCOL VIOLATION]: TVALID dropped before TREADY assertion!");

  // ARM AMBA Rule: TDATA must not glitch or change value while waiting for TREADY
  property p_tdata_stable;
    @(posedge clk) disable iff (!rst_n)
    tvalid && !tready |=> $stable(tdata);
  endproperty
  assert_tdata_stable: assert property (p_tdata_stable)
    else $error("[AXI PROTOCOL VIOLATION]: TDATA changed while waiting for TREADY!");
endmodule

Hardware Trade-off: Formal assertion synthesis allows formal EDA tools (JasperGold, VC Formal) to mathematically prove handshake safety in 0 simulation cycles.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
SVA & Verification Easy CH-18

SVA: Mutual Exclusion & One-Hot Grant Verification

Write formal assertion properties for a 4-channel arbiter: verify that at most one grant is asserted at any time ($onehot0(grant)) and that grants never appear without active requests.

Signal Interface Specification

PortDirectionEngineering Description
clkinputClock
rst_ninputReset
req[3:0]inputRequest bus
grant[3:0]inputGrant bus

โฑ๏ธ Timing & Latency Constraint

Prevents two bus masters from driving shared tri-state data buses simultaneously (bus contention).

โš ๏ธ Pitfalls & Edge Cases

Using `$onehot` instead of `$onehot0`: `$onehot` fails when grant=4'b0000 (idle state).

๐Ÿ’ก View Engineering Hint

`$onehot0(grant)` returns 1 if exactly 1 bit is high or if all bits are 0. Spurious grant check: `|grant |-> (grant & req) != 0`.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module sva_arbiter_check (
  input wire       clk,
  input wire       rst_n,
  input wire [3:0] req,
  input wire [3:0] grant
);
  // Property 1: Mutual Exclusion (At most 1 grant active)
  property p_onehot_grant;
    @(posedge clk) disable iff (!rst_n)
    $onehot0(grant);
  endproperty
  assert_onehot: assert property (p_onehot_grant)
    else $error("[ARBITER VIOLATION]: Multiple grants asserted simultaneously! Grant = %b", grant);

  // Property 2: No Spurious Grants (Only grant to active requests)
  property p_no_spurious_grant;
    @(posedge clk) disable iff (!rst_n)
    |grant |-> ((grant & req) == grant);
  endproperty
  assert_valid_req: assert property (p_no_spurious_grant)
    else $error("[ARBITER VIOLATION]: Grant issued to inactive request! Req = %b, Grant = %b", req, grant);
endmodule

Hardware Trade-off: Catches critical bus contention bugs in testbenches before standard cell synthesis.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
SVA & Verification Medium CH-19

SVA: FIFO Overflow & Underflow Formal Guard

Write concurrent assertions to catch FIFO fatal errors: writing when full without simultaneous read (overflow), reading when empty (underflow), and reset pointer consistency.

Signal Interface Specification

PortDirectionEngineering Description
clkinputClock
rst_ninputReset
wr_eninputWrite enable
rd_eninputRead enable
fullinputFull flag
emptyinputEmpty flag

โฑ๏ธ Timing & Latency Constraint

A single overflow or underflow corrupts circular memory structures and desynchronizes packet streams.

โš ๏ธ Pitfalls & Edge Cases

Failing to account for simultaneous `wr_en && rd_en` on full, which is valid in fall-through or continuous throughput FIFOs.

๐Ÿ’ก View Engineering Hint

Underflow condition: `empty && rd_en |-> 0`. Overflow condition: `full && wr_en && !rd_en |-> 0`.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module sva_fifo_guards (
  input wire clk,
  input wire rst_n,
  input wire wr_en,
  input wire rd_en,
  input wire full,
  input wire empty
);
  // Guard 1: Never read from an empty FIFO
  property p_no_underflow;
    @(posedge clk) disable iff (!rst_n)
    empty |-> !rd_en;
  endproperty
  assert_no_underflow: assert property (p_no_underflow)
    else $error("[FIFO FATAL ERROR]: Underflow detected! Read attempted while empty.");

  // Guard 2: Never write to a full FIFO unless simultaneously reading
  property p_no_overflow;
    @(posedge clk) disable iff (!rst_n)
    full && !rd_en |-> !wr_en;
  endproperty
  assert_no_overflow: assert property (p_no_overflow)
    else $error("[FIFO FATAL ERROR]: Overflow detected! Write attempted while full.");
endmodule

Hardware Trade-off: Provides continuous formal safety coverage across multi-day regression simulations.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL
SVA & Verification Hard CH-20

SVA: Minimum Pulse Width & Glitch-Free Clock Switch

Write verification assertions for a clock multiplexer output: verify that high and low pulse durations are never shorter than the minimum allowable half-period (Tmin / 2).

Signal Interface Specification

PortDirectionEngineering Description
clk_outinputSwitched clock output to inspect
rst_ninputReset

โฑ๏ธ Timing & Latency Constraint

A glitch or runt pulse is defined as any transition that reverses before meeting minimal standard cell setup/hold pulse width constraints (e.g. 1.2ns).

โš ๏ธ Pitfalls & Edge Cases

Simulating glitch assertions in event-driven simulators requires real-time delta cycle measurement with `$realtime`.

๐Ÿ’ก View Engineering Hint

Record timestamp on posedge and negedge using `$realtime`. On every transition, assert `($realtime - last_transition_time) >= MIN_PULSE_WIDTH`.

๐Ÿ” View Verified Reference Solution & Trade-off Analysis
module sva_clock_pulse_checker #(
  parameter real MIN_HALF_PERIOD = 1.25 // In nanoseconds (e.g. 400 MHz max)
)(
  input wire clk_out,
  input wire rst_n
);
  real last_edge_time;

  always @(posedge clk_out or negedge clk_out) begin
    if (rst_n) begin
      if (last_edge_time > 0.0) begin
        real pulse_width;
        pulse_width = $realtime - last_edge_time;
        if (pulse_width < MIN_HALF_PERIOD) begin
          $error("[CLOCK GLITCH DETECTED]: Runt pulse of %0.2f ns detected on clk_out! Min required is %0.2f ns",
                 pulse_width, MIN_HALF_PERIOD);
        end
      end
      last_edge_time = $realtime;
    end else begin
      last_edge_time = 0.0;
    end
  end
endmodule

Hardware Trade-off: Enforces zero physical runt pulse contamination before packaging netlists for tapeout.

โšก Solve in Verilog Simulator โ†’ Verified Synthesizable RTL