Packages, Typedefs and $unit in a Design

Share one type, one constant and one function between RTL modules through a package. Know what each tool does with file order.

You Will Be Able To

  • Write a package that holds the types, constants and functions several modules share.
  • Choose between pkg::name, an explicit import and a wildcard import, and place the import.
  • Predict which name wins when a local declaration and an import collide.
  • Explain why a declaration outside any module depends on how the tool reads the files.
Lesson
R9.3
Time
30 min
Runs on
Verilator
Check
5 questions

A calculator block ran AND when the command said subtract. The decoder and the ALU each had a private copy of the opcode type. Someone had sorted one copy by name. Every tool was silent.

Two Copies of One TypeArrows show the 2-bit opcode on its way from the decoder to the ALU. Each module reads the number with its own copy of the enum.
  • I/O
  • Control / FSM
  • Datapath
  • Result
  • Neutral
  • Data
  • Control
  • Structure
Two copies of one typeArrows show the 2-bit opcode on its way from the decoder to the ALU. Each module reads the number with its own copy of the enum. io ch = "-" the commandcharacter control cmd_dec its copy: ADD SUBAND XOR io op = 1 two plain bits datapath alu its copy: ADD ANDSUB XOR result y = a & b the wrong operation neutral calc_pkg one copy for both decodeOP_SUB is 11 is OP_ANDrunsimport
  1. io ch = "-"the command character
    • decode → cmd_dec
  2. control cmd_decits copy: ADD SUB AND XOR
    • OP_SUB is 1 → op = 1
  3. io op = 1two plain bits
    • 1 is OP_AND → alu
  4. datapath aluits copy: ADD AND SUB XOR
    • runs → y = a & b
  5. result y = a & bthe wrong operation
  6. neutral calc_pkgone copy for both
    • import → cmd_dec
  1. The decoder

    For "-" the decoder sends OP_SUB. In its copy of the enum that label is the number 1.

  2. The ALU

    The ALU receives 1. In its copy, sorted by name, 1 is OP_AND. It runs a & b.

  3. One copy

    A package holds the type once. Both modules import it, so a label has one number everywhere.

Read the diagram as text
  • ch = "-": the command character
  • cmd_dec: its copy: ADD SUB AND XOR
  • op = 1: two plain bits
  • alu: its copy: ADD AND SUB XOR
  • y = a & b: the wrong operation
  • calc_pkg: one copy for both
  • ch = "-" → cmd_dec: decode
  • cmd_dec → op = 1: OP_SUB is 1
  • op = 1 → alu: 1 is OP_AND
  • alu → y = a & b: runs
  • calc_pkg → cmd_dec: import

Two typedefs with the same name in two modules are two types. Nothing compares them.

A Package: One Declaration, Many Users

A typedef gives a type a name. Declared inside a module, the name is private to that module. A package is a named box of declarations that any module can use.

A module that imports lim_pkg and calls clamp builds 13 cells on this flow. The package itself builds nothing.
package lim_pkg;
  typedef logic [7:0] level_t;                     // a type
  localparam level_t TOP = 8'd200;                 // a constant
  function automatic level_t clamp(input level_t v);
    return (v > TOP) ? TOP : v;                    // a function: logic, copied at each call
  endfunction
endpackage

A package describes no hardware of its own. Synthesis copies what each module uses into that module. That decides what a package may hold.

In the packageThis flowMeasured
typedef, enum, structbuildsthe lab: 122 cells
localparam or parameter constantbuildsa constant, folded into the logic
function automaticbuildsa copy of the logic at each call (lesson R11.3)
a variable, such as logic [3:0] hits;, that a module writesrefusedYosys stops with Internal frontend error; Lint is silent; Verilator simulates it as shared state
const logic [7:0] MAGIC = 8'ha5;refusedthe same Yosys error: a const is still a variable
a function with no automaticdo not useLint: IMPLICITSTATIC; its variables are shared between calls in simulation

A package variable would be a wire between modules with no port. Use localparam for a constant in a package.

Three Ways to Reach an Item

FormExampleWhat it makes visible
Scope operatorcalc_pkg::op_tthat one use; nothing is imported
Explicit importimport calc_pkg::op_t;the name op_t only
Wildcard importimport calc_pkg::*;every name in the package, each one only when the code uses it

Place the import between the module name and the port list. Then the ports can use the types, as the lab fix does.

Imports can collide with each other and with local names. The tools do not agree on every case.

CaseIcarus 12Verilator 5.052Yosys (slang)
A local LIMIT and a wildcard import that has LIMITthe local one winsthe local one wins; Lint warns VARHIDDENthe local one wins
A local LIMIT and import lim_pkg::LIMIT;'LIMIT' has already been imported into this scopeaccepted, the local one winsredefinition of 'LIMIT'
Two wildcard imports that both have data_t, and the code uses itAmbiguous use of 'data_t'accepted: it took the first package, 32 bitsmultiple imports found for identifier 'data_t'
The same two imports, data_t never used barerunsrunsbuilds
import st_pkg::state_t; and then the label RUNUnable to bind wire/reg/memory 'RUN'Can't find definition of variable: 'RUN'use of undeclared identifier 'RUN'

Row 3 is the dangerous one. Verilator 5.052 picked a type without a message, and Lint is the same tool. The other two refused.

export: Passing a Package On

A package can import another package. Its own importers do not see those names unless it exports them.

Verilator prints q=5a for d=a5. With the export line removed it stops: Can't find typedef/interface: 'byte_t', and Yosys says use of undeclared identifier 'byte_t'.
package base_pkg;
  typedef logic [7:0] byte_t;
endpackage

package soc_pkg;
  import base_pkg::*;
  export base_pkg::byte_t;         // pass byte_t on to whoever imports soc_pkg
  function automatic byte_t swap(input byte_t b);
    return {b[3:0], b[7:4]};
  endfunction
endpackage

module m
  import soc_pkg::*;               // one import; byte_t arrives through the chain
(
  input  byte_t d,
  output byte_t q
);
  assign q = swap(d);
endmodule

Compile Order

A package must be read before the code that uses it. With one file per package and per module, the order of the file list matters.

Who Must Be Read FirstArrows point from a file to the files that need it. A file list must name a file before every file its arrows reach.
  • File
  • Structure
Who must be read firstArrows point from a file to the files that need it. A file list must name a file before every file its arrows reach. file calc_pkg.sv types and constants file cmd_dec.sv imports calc_pkg file alu.sv imports calc_pkg file calc.sv instantiates both beforebeforeany orderany order
  1. file calc_pkg.svtypes and constants
    • before → cmd_dec.sv
    • before → alu.sv
  2. file cmd_dec.svimports calc_pkg
    • any order → calc.sv
  3. file alu.svimports calc_pkg
    • any order → calc.sv
  4. file calc.svinstantiates both
  1. Packages first

    Both modules name types from calc_pkg in their port lists. The tool must know those types when it reads the ports.

  2. Modules in any order

    An instance is resolved after all files are read. calc.sv can come before or after the modules it instantiates.

Read the diagram as text
  • calc_pkg.sv: types and constants
  • cmd_dec.sv: imports calc_pkg
  • alu.sv: imports calc_pkg
  • calc.sv: instantiates both
  • calc_pkg.sv → cmd_dec.sv: before
  • calc_pkg.sv → alu.sv: before
  • cmd_dec.sv → calc.sv: any order
  • alu.sv → calc.sv: any order

Only declarations need an order. Module instances do not.

ToolPackage file firstModule file first
Icarus 12runsalu.sv:2: syntax error then I give up.
Verilator 5.052 (Run and Lint)runsReference to 'op_t' before declaration
Yosys 0.70 with slang (Synthesize)133 cells133 cells: it reads every file before it resolves names

A recorded run: an 8-bit ALU in alu.sv and its package in alu_pkg.sv, given to each tool in both orders.

On this site, Run reads the bench first and then main.sv. Lint and Synthesize read main.sv alone. So the lab keeps its package at the top of main.sv.

$unit: Declarations Outside Any Module

A typedef written outside every module and package lands in a space called $unit. It looks global. What it reaches depends on how the tool was started.

FilesIcarus 12Verilator 5.052Yosys (slang)
a.sv declares data_t outside its module; b.sv uses it; order a, brunsrunsuse of undeclared identifier 'data_t'
the same two files; order b, asyntax errorReference to 'data_t' before declarationuse of undeclared identifier 'data_t'
a.sv and b.sv each declare their own data_t, 8 and 4 bitsType identifier 'data_t' has already been declared in this scopeDuplicate declaration of TYPEDEF 'data_t'builds: 14 cells, each file with its own type

The two simulators put all files in one $unit. Yosys gives each file its own. The same source means three different things.

A package has none of this. Its name says where a declaration lives, and every tool agrees on it. Keep nothing in $unit.

define, parameter or a Package Constant

A macro (the define directive)parameter int WIDTH = 8package localparam int WIDTH = 8
What it istext, pasted where it is useda typed constant of one modulea typed constant with one home
Who sees itevery line read after it, in every later filethat modulewhoever names or imports the package
Can differ per instancenoyes: #(.WIDTH(12))no
Depends on file orderyesnoonly that the package comes first
Use it forconditional compilation, such as the SYNTHESIS guard of lesson R7.2a size that each instance choosesa value that the whole design shares

One more kind of constant exists. const makes a variable that is assigned once. It is useful inside a function, where a parameter cannot be declared. On this flow a function with a local const built 13 cells.

The Lab: One Copy of the Opcode Type

Design brief
PortDirectionWidthMeaning
chinput[7:0]the command: +, -, & or ^
a, binput[7:0]the operands
youtput[7:0]the result of the command
Latency
combinational
Corner cases
the two opcodes that sit in the middle of the list. Done when: Run prints 12 - 10 = 2 and 12 & 10 = 8, and both modules take op_t from one package
  1. Run as shipped

    The + and ^ lines are right. The - line prints 8 and the & line prints 2. Lint prints nothing.

  2. Find the two copies

    Each module has its own op_t. The decoder lists ADD, SUB, AND, XOR. The ALU lists ADD, AND, SUB, XOR. The port between them is two plain bits.

  3. Make one package

    Add calc_pkg at the top of main.sv with the type. Delete both local typedefs. Import the package in each module header and type the op ports as op_t.

  4. Run and Synthesize

    Run prints 22, 2, 8 and 6. Synthesize reports 122 cells and 21 levels. The shipped file was 121 cells: the package costs nothing.

The fix: calc_pkg and three headers
The ports are now typed. A second copy of the enum can no longer exist without a compile error.
package calc_pkg;
  typedef enum logic [1:0] { OP_ADD, OP_SUB, OP_AND, OP_XOR } op_t;   // the one copy
  typedef logic [7:0] word_t;
endpackage

module cmd_dec
  import calc_pkg::*;              // in the header, so the ports can use op_t
(
  input  logic [7:0] ch,
  output op_t        op
);
  // the same case statement
endmodule

module alu
  import calc_pkg::*;
(
  input  op_t   op,
  input  word_t a, b,
  output word_t y
);
  // the same case statement
endmodule

module calc
  import calc_pkg::*;
(
  input  logic [7:0] ch,
  input  word_t      a, b,
  output word_t      y
);
  op_t op;
  cmd_dec u_dec (.ch(ch), .op(op));
  alu     u_alu (.op(op), .a(a), .b(b), .y(y));
endmodule
Asked in interviews
  1. Why use a package and not a header file of macros?

    A package item has a type and one home. A macro is text that reaches every file read after it. It depends on file order and can be redefined without a message.

  2. What may a synthesizable package contain?

    Types, localparam constants and automatic functions. Synthesis copies them into each module that uses them. It does not build package variables, because they would connect modules without ports.

  3. What is $unit, and why avoid it?

    It is the space for declarations outside any module or package. Tools that compile all files together share one. Tools that compile files separately have one per file. The same source can mean different things.

Try It

The bench sends four command characters with a at 12 and b at 10. Subtract should give 2 and AND should give 8. The shipped design swaps them.

The decoder sends 1 for -. The ALU reads 1 with its own copy of the enum, where 1 means AND.

Synthesize reports 121 cells, 0 flops, 0 latches and 21 levels. With one package the count is 122 cells and the same 21 levels.

RTLVerilator · simulator service · Lint: Verilator service · Synthesize: Yosys service
Edit the design, then Run, Lint or Synthesize
Expected: 12 + 10 = 22 12 - 10 = 8 12 & 10 = 2 12 ^ 10 = 6

Original design · 121 cells · 0 flip-flops · 0 latches · 21 logic levels. Synthesis uses Yosys; counts depend on the toolchain.

Read included file: tb.sv
// The bench uses plain vectors. It compiles before main.sv, so it cannot import a package from it.
module tb;
  logic [7:0] ch, a = 8'd12, b = 8'd10, y;
  calc dut (.*);
  task automatic show(input logic [7:0] c);
    ch = c; #1;
    $display("12 %s 10 = %0d", ch, y);
  endtask
  initial begin
    show("+"); show("-"); show("&"); show("^");
    $finish(0);
  end
endmodule

Check Yourself

Predict the outputThe file defines the macro W, uses it in module a, redefines it, and uses it in module b. What does the bench print?
`define W 4
module a (output int n);
  logic [`W-1:0] v;
  assign n = $bits(v);
endmodule
`undef W
`define W 8
module b (output int n);
  logic [`W-1:0] v;
  assign n = $bits(v);
endmodule
module tb;
  int na, nb;
  a ua (.n(na));
  b ub (.n(nb));
  initial begin
    #1 $display("%0d %0d", na, nb);
    $finish(0);
  end
endmodule
Spot the bugEach option declares the opcode type in a package. The brief gives the encoding ADD 0, SUB 1, AND 2, XOR 3, and the bench checks it. Which option fails?
Concepta.sv declares a typedef outside its module. b.sv uses that type and does not declare it. The file list is a, b. What did the three tools do?
ConceptTwo modules must both count events into one total. A designer puts logic [3:0] hits; in a package and writes it from both. What happened on this flow?
ConceptA module needs op_t from calc_pkg for one of its ports. Where does the import go?

Common Mistakes

Wrong Import the package inside the module body and then use its types in the port list.

The port list is read before the body, so the type names are not known there yet.

Fix Put the import between the module name and the port list.

Before
module alu (
  input  op_t op,          // op_t is not known yet
  output word_t y
);
  import calc_pkg::*;
After
module alu
  import calc_pkg::*;
(
  input  op_t op,
  output word_t y
);

Wrong Keep a counter or a flag as a variable in a package so that two modules can share it.

A package variable is a hidden wire between modules with no port, and synthesis does not build it.

Fix Pass shared state through ports. Keep only types, localparam constants and automatic functions in a package.

Wrong Import only the enum type, as import st_pkg::state_t;, and then write its labels.

An explicit import brings one name, and the labels of an enum are names of their own.

Fix Use a wildcard import, or write st_pkg::RUN, or import each label you use.

Wrong Trust a build that passes in simulation to pass in synthesis with the same file list.

The tools read file lists differently: here the simulators needed the package first, and Yosys did not care.

Fix List packages first in every file list, so that the strictest tool is satisfied.

Remember

  • Two typedefs with one name in two modules are two types. A package holds the one copy.
  • A synthesizable package holds types, localparam constants and automatic functions. It holds no variables.
  • Import in the module header. A local name wins over a wildcard import, and an enum type does not bring its labels.
  • Read packages before their users. The simulators here require it; list them first for every tool.
  • Keep nothing in $unit: the simulators here share one across files, and Yosys gives each file its own.

Practice

Quick reference: typedef enum and Its Methods

Report a problem with this page