SystemVerilog queue:可变长度队列与 FIFO 建模

队列(queue)是可变长度的连续元素集合,支持在两端高效增删。验证平台中的事务流、命令队列和scoreboard 期望队列通常用 queue 实现。

1. 声明与基本操作

1
2
3
4
5
6
7
8
int q[$];                    // 元素为 int 的队列
logic [7:0] bytes[$]; // 字节队列

initial begin
q.push_back(1); // 队尾插入
q.push_front(0); // 队首插入
$display("%0d", q.size());
end

$ 作为索引表示最大范围,声明 q[$] 表示长度不限。

2. 取出与删除

1
2
3
4
5
6
int item;

item = q.pop_front(); // 取队首并删除
item = q.pop_back(); // 取队尾并删除
q.delete(); // 清空
q.delete(2); // 删除索引 2 的元素

空队列上执行 pop_front() 的结果由工具定义,通常返回 0 或 X,因此取出前必须检查 size()。

3. slicing 与查找

1
2
3
4
5
int a[$] = '{1,2,3,4,5};
int b[$];

b = a[1:3]; // {2,3,4}
int pos = a.find with (item == 3);

find 系列方法返回满足条件的元素或索引,适合在期望队列中定位特定事务。

4. FIFO 建模

1
2
3
4
5
6
7
class fifo #(type T = int);
T q[$];

function void push(T t); q.push_back(t); endfunction
function T pop(); return q.pop_front(); endfunction
function int size(); return q.size(); endfunction
endclass

参数化类让同一套 FIFO 逻辑可用于不同类型的事务,是 UVM 之前常见的轻量建模方式。

5. 常见误区

  1. 在 RTL 综合代码中使用 queue:不可综合。
  2. 未检查 size() 就 pop:空队列行为不确定。
  3. 把 queue 当随机访问表:中间插入/删除代价高于关联数组。

小结

queue 适合“先进先出、两端增删”的数据流。若需要频繁按地址随机索引,应换用关联数组或 unpacked 数组。

参考文献:ChipVerify SystemVerilog Tutorial — SystemVerilog Queue 章节(https://chipverify.com/systemverilog/systemverilog-queue)。本文为原创中文讲解。