1. 工厂模式基础
任务目标
本案例演示UVM工厂模式的基础用法:通过uvm_factory::create()方法创建uvm_driver实例,并验证创建对象的类型ID(type_id)与实例ID(inst_id)是否正确。工厂模式允许在运行时按需创建组件,是实现UVM组件覆盖与替换的核心机制。
环境依赖
- UVM库(推荐版本:UVM-1.2或IEEE 1800.2)
- 仿真器:QuestaSim / VCS / Xcelium 任一支持UVM的仿真工具
关键完整代码
// 文件: factory_basic_test.sv
`include "uvm_macros.svh"
import uvm_pkg::*;
// 1. 定义自定义driver类(继承自uvm_driver)
class my_driver extends uvm_driver #(uvm_sequence_item);
`uvm_component_utils(my_driver)
function new(string name, uvm_component parent);
super.new(name, parent);
endfunction
// 打印组件路径,便于验证
function void display_info();
`uvm_info("DRV", $sformatf("组件路径: %s", get_full_name()), UVM_LOW)
endfunction
endclass
// 2. 测试类:验证工厂创建机制
class factory_basic_test extends uvm_test;
`uvm_component_utils(factory_basic_test)
my_driver drv;
function new(string name, uvm_component parent);
super.new(name, parent);
endfunction
task run_phase(uvm_phase phase);
uvm_factory factory;
uvm_object_wrapper wrapper;
string type_id_str, inst_id_str;
phase.raise_objection(phase);
// 方法1:通过类型ID(type_id)创建
drv = my_driver::type_id::create("drv0", this);
drv.display_info();
// 获取并验证类型ID
factory = uvm_factory::get();
wrapper = factory.find_wrapper_by_name("my_driver");
if (wrapper == null)
`uvm_error("FACTORY", "未找到my_driver的工厂包装器")
else begin
type_id_str = wrapper.get_type_name();
`uvm_info("FACTORY", $sformatf("类型ID验证: %s", type_id_str), UVM_LOW)
end
// 获取并验证实例ID(即组件层次路径)
inst_id_str = drv.get_full_name();
`uvm_info("FACTORY", $sformatf("实例ID验证: %s", inst_id_str), UVM_LOW)
// 断言检查
assert(type_id_str == "my_driver") else
`uvm_error("FACTORY", "类型ID不匹配")
assert(inst_id_str == "uvm_test_top.factory_basic_test_inst.drv0") else
`uvm_error("FACTORY", "实例ID不匹配")
phase.drop_objection(phase);
endtask
endclass
// 3. 顶层模块:启动测试
module top;
initial begin
run_test("factory_basic_test");
end
endmodule
运行方式
# QuestaSim 示例
vlib work
vlog +incdir+$UVM_HOME/src $UVM_HOME/src/uvm_pkg.sv factory_basic_test.sv
vsim -c -do "run -all; quit" work.top
验证方法与判定标准
- 类型ID验证:仿真日志中应出现
类型ID验证: my_driver,且无FACTORY错误。 - 实例ID验证:日志中应出现
实例ID验证: uvm_test_top.factory_basic_test_inst.drv0,表明组件被正确挂载到测试层次中。 - 通过条件:仿真结束无UVM_ERROR或UVM_FATAL,且两条断言均通过(无断言失败报告)。
预期输出(关键片段)
UVM_INFO @ 0: uvm_test_top.factory_basic_test_inst [DRV] 组件路径: uvm_test_top.factory_basic_test_inst.drv0
UVM_INFO @ 0: uvm_test_top.factory_basic_test_inst [FACTORY] 类型ID验证: my_driver
UVM_INFO @ 0: uvm_test_top.factory_basic_test_inst [FACTORY] 实例ID验证: uvm_test_top.factory_basic_test_inst.drv0
常见问题
- 类型ID不匹配:检查
`uvm_component_utils宏是否已添加到自定义类中,且类名拼写一致。 - 实例ID路径不同:若测试类实例名被仿真器自动修改(如添加后缀),断言中的硬编码路径需相应调整,或改用
get_full_name()动态获取后比对。