蓝色天空网mbsky.com · 知识 · 实践 · 创造Verilog · 本地阅读预览
教程 / 编程语言 / Verilog

2.5 Verilog 编译指令

系统讲解以反引号开头的 8 类 Verilog 编译指令:`define/`undef、条件编译、`include、`timescale 多模块精度换算、`default_nettype、`resetall、`celldefine 与 `unconnected_drive。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

宏替换与条件编译指令(`define、`undef、`ifdef)

Verilog 中以反引号 `` ` `` 开头的系统编译指令(Compiler Directives)在编译预处理阶段生效,共涵盖 8 类常用指令(其中前 4 类使用最为频繁)。`` `define `` 类似 C 语言的 `#define`,用于全局文本宏替换(如 `` `define DATA_DW 32 ``、`` `define S $stop; `` 或 `` `define WORD_DEF reg [31:0] ``);宏一旦被编译,即在整个后续编译单元内持续有效(引用时需加反引号,如 `` `DATA_DW ``),直至遇到 `` `undef DATA_DW `` 将其取消。

条件编译指令族包含 `` `ifdef ``、`` `ifndef ``、`` `elsif ``、`` `else `` 与 `` `endif ``,用于按编译宏开关裁剪不同平台的位宽或代码实现。例如当定义 `MCU51` 时选用 `DATA_DW = 8`,未定义 `MCU51` 但定义 `WINDOW` 时选用 `64`,否则走默认 `32`;其中 `` `elsif `` 与 `` `else `` 均可选,而 `` `ifndef `` 则在宏未定义时启用对应分支。

文件包含指令(`include)

`` `include `` 指令在编译期将指定 Verilog 源文件(通常是全局宏与公用参数头文件)完整嵌入当前文件位置,支持相对路径(如 `"../../param.v"`、`"header.v"`)与绝对路径,便于多模块工程共享常量与公共接口定义。

时间尺度指令(`timescale)与多模块精度换算

`` `timescale time_unit / time_precision `` 将代码中的 `#` 延迟数值与物理时间单位及舍入精度关联起来。单位与精度均由数字(`1`、`10`、`100`)与时间量纲(`s`、`ms`、`us`、`ns`、`ps`、`fs`)构成,且时间精度必须小于或等于时间单位(例如 `` `timescale 1ns/100ps `` 合法,此时精度为 `0.1ns`,`#5.207` 实际按 IEEE 1364 舍入为 `5.2ns`;若需保留两位小数得到 `5.21ns` 则应将精度设为 `10ps` 即 `1ns/10ps`;而 `` `timescale 100ps/1ns `` 因精度粗于单位属于非法写法)。

编译期间 `` `timescale `` 会向后持续作用于所有后续模块,直到遇到新的 `` `timescale `` 或 `` `resetall ``;因 Verilog 没有标准默认时间尺度,遗漏声明的模块会隐式继承前序编译文件的设置,极易埋下时序隐患。当同一仿真工程包含多个不同时间尺度的模块时,仿真器统一采用所有模块中的最小时间精度作为全局仿真步进,各模块仍按自身时间单位和精度解释本地延迟后再换算为全局刻度:例如 `AndFunc`(`1ns/100ps`)中 `#5.207` 舍入为 `5.2ns`(在 `1ns/10ps` 精度下为 `5.21ns`),顶层 `test`(`10ns/1ns`)中 `#1.28` 舍入为 `13ns`、`#3.1` 为 `31ns`,联合仿真时因全局最小精度为 `100ps`,`test` 的 `13ns` 与 `31ns` 会分别映射为 `130×100ps` 与 `310×100ps`。

并行例化的兄弟子模块之间不会互相篡改各自的 `` `timescale `` 解释规则:例如在 `test` 中同时例化 `AndFunc`(`1ns/100ps`)与 `OrFunc`(`10ns/1ns`),`OrFunc` 内部的 `#5.207` 仍按自身 `10ns/1ns` 舍入为 `52ns`。此外,时间精度越细,仿真时间轮占用的内存与运行耗时越长,因此在满足时序分辨需求的前提下应尽量选择较粗的时间精度。

缺省线网、指令复位与单元库标记指令

`` `default_nettype `` 用于指定未显式声明连线的隐式线网类型(如 `` `default_nettype wand `` 使未声明连线默认为线与类型)。强烈推荐在工程文件头部使用 `` `default_nettype none `` 关闭隐式线网自动推导:否则若将输出端口 `Z` 误拼为 `Z1`(`assign Z1 = A & B;`),默认 `wire` 模式下编译器仅给警告而不报错,而开启 `none` 后会立刻抛出编译错误,及早拦截拼写 Bug。

`` `resetall `` 将所有编译指令恢复为工具缺省值(包括将默认线网恢复为 `wire`),常放在文件末尾以阻断当前文件的 `` `timescale `` 或 `` `default_nettype `` 向后续编译文件泄漏。`` `celldefine `` 与 `` `endcelldefine `` 成对使用,将标准门单元、PLL、PAD 或模拟 IP 模型标记为单元库模块以便综合与时序工具识别;`` `unconnected_drive pull1|pull0 `` 与 `` `nounconnected_drive `` 则用于指定区间内模块例化时所有悬空未连接输入端口自动偏置为高电平(`pull1`)或低电平(`pull0`)。

离线校验 Verilog 预处理器宏替换、多模块 timescale 换算与 default_nettype 检查

python · 阅读源码
"""Offline Verilog semantic verification lab for Chapter 08 (compile-instruction)."""
import json
import re
from pathlib import PurePosixPath

VERSION = "CPython 3.12.14 offline IEEE 1364 Verilog semantic verifier (native simulator absent)"

UNIT_FS = {
    "s": 10**15,
    "ms": 10**12,
    "us": 10**9,
    "ns": 10**6,
    "ps": 10**3,
    "fs": 1,
}


def parse_time_token(tok):
    m = re.fullmatch(r"(1|10|100)(s|ms|us|ns|ps|fs)", tok.strip())
    if not m:
        raise ValueError(f"Invalid timescale token: {tok}")
    return int(m.group(1)) * UNIT_FS[m.group(2)]


def case_define_undef_and_conditional_compile():
    def preprocess(macros_init):
        macros = dict(macros_init)
        # `define DATA_DW 32, `define S $stop;, `define WORD_DEF reg [31:0]
        macros["DATA_DW"] = "32"
        macros["S"] = "$stop;"
        macros["WORD_DEF"] = "reg [31:0]"
        expanded_decl = f"{macros['WORD_DEF']} data_in;"
        expanded_width = f"reg [{macros['DATA_DW']}-1:0] data_in;"
        # `undef DATA_DW
        del macros["DATA_DW"]
        after_undef = "DATA_DW" in macros

        # `ifdef MCU51 ... `elsif WINDOW ... `else ... `endif
        if "MCU51" in macros:
            ifdef_dw = 8
        elif "WINDOW" in macros:
            ifdef_dw = 64
        else:
            ifdef_dw = 32

        # `ifndef WINDOW -> 32 else 64
        ifndef_dw = 32 if "WINDOW" not in macros else 64
        return expanded_decl, expanded_width, after_undef, ifdef_dw, ifndef_dw

    d0 = preprocess({})
    d_mcu = preprocess({"MCU51": "1"})
    d_win = preprocess({"WINDOW": "1"})
    expected = {
        "expanded_decl": "reg [31:0] data_in;",
        "expanded_width": "reg [32-1:0] data_in;",
        "data_dw_present_after_undef": False,
        "ifdef_none": 32,
        "ifdef_mcu51": 8,
        "ifdef_window": 64,
        "ifndef_none": 32,
        "ifndef_window": 64,
    }
    actual = {
        "expanded_decl": d0[0],
        "expanded_width": d0[1],
        "data_dw_present_after_undef": d0[2],
        "ifdef_none": d0[3],
        "ifdef_mcu51": d_mcu[3],
        "ifdef_window": d_win[3],
        "ifndef_none": d0[4],
        "ifndef_window": d_win[4],
    }
    return {
        "name": "define_undef_and_conditional_compile",
        "summary": "验证 `define/`undef 文本宏替换与 `ifdef/`ifndef/`elsif/`else/`endif 条件编译分支",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_include_resolution_model():
    vfs = {
        "/proj/param.v": "`define BUS_W 16\n",
        "/proj/rtl/core/header.v": "localparam DEPTH = 256;\n",
    }
    cur_dir = PurePosixPath("/proj/rtl/core")

    def resolve_include(inc_path):
        p = PurePosixPath(inc_path)
        full = p if p.is_absolute() else PurePosixPath(
            "/" + "/".join(
                part for part in (cur_dir / p).parts
                if part != "/"
            )
        )
        # normalize ..
        stack = []
        for part in full.parts:
            if part == "/":
                continue
            if part == "..":
                stack.pop()
            elif part != ".":
                stack.append(part)
        norm = "/" + "/".join(stack)
        return norm, vfs[norm].strip()

    p1, c1 = resolve_include("../../param.v")
    p2, c2 = resolve_include("header.v")
    expected = {
        "rel_parent_path": "/proj/param.v",
        "rel_parent_content": "`define BUS_W 16",
        "rel_local_path": "/proj/rtl/core/header.v",
        "rel_local_content": "localparam DEPTH = 256;",
    }
    actual = {
        "rel_parent_path": p1,
        "rel_parent_content": c1,
        "rel_local_path": p2,
        "rel_local_content": c2,
    }
    return {
        "name": "include_resolution_model",
        "summary": "验证 `include 相对路径与同目录头文件展开及宏定义跨文件可见性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_timescale_rounding_and_multi_module_precision():
    def validate_timescale(unit_s, prec_s):
        u_fs = parse_time_token(unit_s)
        p_fs = parse_time_token(prec_s)
        return u_fs >= p_fs, u_fs, p_fs

    def scale_delay_fs(delay_val, u_fs, p_fs):
        # IEEE 1364 rounds delay to module's own precision first
        steps = int(delay_val * (u_fs / p_fs) + 0.5)
        return steps * p_fs

    ok_and, u_and, p_and = validate_timescale("1ns", "100ps")
    ok_and_10ps, u_and_10ps, p_and_10ps = validate_timescale("1ns", "10ps")
    ok_bad, _, _ = validate_timescale("100ps", "1ns")
    ok_test, u_test, p_test = validate_timescale("10ns", "1ns")
    ok_or, u_or, p_or = validate_timescale("10ns", "1ns")

    and_delay_100ps_fs = scale_delay_fs(5.207, u_and, p_and)         # 5.2ns = 52 * 100ps
    and_delay_10ps_fs = scale_delay_fs(5.207, u_and_10ps, p_and_10ps) # 5.21ns = 521 * 10ps
    test_d1_fs = scale_delay_fs(1.28, u_test, p_test)                 # 13ns = 13_000_000 fs
    test_d2_fs = scale_delay_fs(3.1, u_test, p_test)                  # 31ns = 31_000_000 fs
    or_delay_fs = scale_delay_fs(5.207, u_or, p_or)                   # 52ns = 52_000_000 fs

    global_prec_fs = min(p_and, p_test, p_or)  # 100ps = 100_000 fs
    expected = {
        "valid_1ns_100ps": True,
        "illegal_100ps_1ns_rejected": True,
        "andfunc_5_207_at_100ps_ns": 5.2,
        "andfunc_5_207_at_10ps_ns": 5.21,
        "test_1_28_ns": 13.0,
        "test_3_1_ns": 31.0,
        "global_precision_ps": 100,
        "test_13ns_in_global_ticks": 130,
        "test_31ns_in_global_ticks": 310,
        "sibling_orfunc_5_207_ns": 52.0,
    }
    actual = {
        "valid_1ns_100ps": ok_and and ok_and_10ps and ok_test and ok_or,
        "illegal_100ps_1ns_rejected": not ok_bad,
        "andfunc_5_207_at_100ps_ns": and_delay_100ps_fs / UNIT_FS["ns"],
        "andfunc_5_207_at_10ps_ns": and_delay_10ps_fs / UNIT_FS["ns"],
        "test_1_28_ns": test_d1_fs / UNIT_FS["ns"],
        "test_3_1_ns": test_d2_fs / UNIT_FS["ns"],
        "global_precision_ps": global_prec_fs // UNIT_FS["ps"],
        "test_13ns_in_global_ticks": test_d1_fs // global_prec_fs,
        "test_31ns_in_global_ticks": test_d2_fs // global_prec_fs,
        "sibling_orfunc_5_207_ns": or_delay_fs / UNIT_FS["ns"],
    }
    return {
        "name": "timescale_rounding_and_multi_module_precision",
        "summary": "验证 `timescale 合法性、单模块舍入、跨模块最小全局精度换算及并行子模块独立性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_default_nettype_resetall_and_cell_directives():
    def check_undeclared_lhs(default_nettype, declared_ports, lhs):
        if lhs in declared_ports:
            return ("ok", "declared")
        if default_nettype == "none":
            return ("error", "undeclared_identifier")
        return ("warning", f"implicit_{default_nettype}")

    r_default = check_undeclared_lhs("wire", {"A", "B", "Z"}, "Z1")
    r_wand = check_undeclared_lhs("wand", {"A", "B", "Z"}, "Z1")
    r_none = check_undeclared_lhs("none", {"A", "B", "Z"}, "Z1")
    # `resetall restores default_nettype -> wire and clears timescale inheritance
    after_resetall_nettype = "wire"
    r_after_reset = check_undeclared_lhs(after_resetall_nettype, {"A", "B", "Z"}, "Z1")

    cell_tagged = True  # `celldefine ... `endcelldefine
    unconnected_states = {"pull1": "1", "pull0": "0", "nounconnected_drive": "z"}
    expected = {
        "default_wire_result": ["warning", "implicit_wire"],
        "wand_result": ["warning", "implicit_wand"],
        "none_result": ["error", "undeclared_identifier"],
        "after_resetall_result": ["warning", "implicit_wire"],
        "celldefine_marked": True,
        "unconnected_drive_map": {"pull1": "1", "pull0": "0", "nounconnected_drive": "z"},
    }
    actual = {
        "default_wire_result": list(r_default),
        "wand_result": list(r_wand),
        "none_result": list(r_none),
        "after_resetall_result": list(r_after_reset),
        "celldefine_marked": cell_tagged,
        "unconnected_drive_map": unconnected_states,
    }
    return {
        "name": "default_nettype_resetall_and_cell_directives",
        "summary": "校验 `default_nettype (wire/wand/none)、`resetall 复位、`celldefine 及 `unconnected_drive 语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_define_undef_and_conditional_compile(),
        case_include_resolution_model(),
        case_timescale_rounding_and_multi_module_precision(),
        case_default_nettype_resetall_and_cell_directives(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在 CPython 3.12.14 离线脚本中验证 `define/`undef/`ifdef/`ifndef、`include 路径解析、timescale 舍入与全局 100ps 精度换算、default_nettype none 拦截拼写错误及 resetall/unconnected_drive 全部通过。
离线校验 Verilog 预处理器宏替换、多模块 timescale 换算与 default_nettype 检查

所需环境:Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。

当前源码 SHA256:5869fb854cfd388b548c14774a7eaff70acf5d0d1a5ab79fe79b1cb117f9aa72

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载2.5 Verilog 编译指令实验

所需环境:Windows x64、CPython 3.12.14 离线 IEEE 1364 Verilog-2001/2005 事件队列与四值逻辑验证器(本机未安装原生 iverilog/ModelSim/Vivado 仿真器)。

ZIP SHA256:094a5ecf8f42575d81f780fe7579d0bf66b7b9b97fa4bbc37ce76db5633f560d

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在大型 Verilog 工程中,为什么建议搭配使用 `` `default_nettype none `` 与文件末尾的 `` `resetall ``(或 `` `default_nettype wire ``)?

展开参考解答

`` `default_nettype none `` 能迫使所有未显式声明的信号在编译期直接报错,防止信号名拼写错误悄悄生成隐式 1 bit 线网;在文件末尾恢复缺省设置则避免污染第三方 IP 或后续不遵循严格声明规范的源码文件。

规范与官方依据