Icarus Verilog may be installed from source code, or from pre-packaged binary
distributions. If you don’t have need for the very latest, and prepackaged
binaries are available, that would be the best place to start.
Installation From Source¶
Icarus is developed for Unix-like environments but can also be compiled on
Windows systems using the Cygwin environment or MinGW compilers. The following
instructions are the common steps for obtaining the Icarus Verilog source,
compiling and installing. Note that there are precompiled and/or prepackaged
versions for a variety of systems, so if you find an appropriate packaged
version, then that is the easiest way to install.
The source code for Icarus is stored under the git source code control
system. You can use git to get the latest development head or the latest of a
specific branch. Stable releases are placed on branches, and in particular v11
stable releases are on the branch “v11-branch” To get the development version
of the code follow these steps:
% git config --global user.name "Your Name Goes Here" % git config --global user.email you@yourpublicemail.example.com % git clone https://github.com/steveicarus/iverilog.git
The first two lines are optional and are used to tell git who you are. This
information is important if/when you submit a patch. We suggest that you add
this information now so you don’t forget to do it later. The clone will create
a directory, named iverilog, containing the source tree, and will populate
that directory with the most current source from the HEAD of the repository.
Change into this directory using:
Normally, this is enough as you are now pointing at the most current
development code, and you have implicitly created a branch “master” that
tracks the development head. However, If you want to actually be working on
the v11-branch (the branch where the latest v11 patches are) then you checkout
that branch with the command:
% git checkout --track -b v11-branch origin/v11-branch
This creates a local branch that tracks the v11-branch in the repository, and
switches you over to your new v11-branch. The tracking is important as it
causes pulls from the repository to re-merge your local branch with the remote
v11-branch. You always work on a local branch, then merge only when you
push/pull from the remote repository.
Now that you’ve cloned the repository and optionally selected the branch you
want to work on, your local source tree may later be synced up with the
development source by using the git command:
The git system remembers the repository that it was cloned from, so you don’t
need to re-enter it when you pull.
Finally, configuration files are built by the extra step:
The source is then compiled as appropriate for your system. See the specific
build instructions below for your operation system for what to do next.
You will need autoconf and gperf installed in order for the script to work.
If you get errors such as:
Autoconf in root... autoconf.sh: 10: autoconf: not found Precompiling lexor_keyword.gperf autoconf.sh: 13: gperf: not found.
You will need to install download and install the autoconf and gperf tools.
Icarus Specific Configuration Options¶
Icarus takes many of the standard configuration options and those will not be
described here. The following are specific to Icarus:
This option allows the user to build Icarus with a default suffix or when
provided a user defined suffix. Older stable releases have this flag on by
default e.g.(V0.8 by default will build with a “-0.8” suffix). All versions
have an appropriate default suffix (“-<base_version>”).
All programs or directories are tagged with this suffix. e.g.(iverilog-0.8,
vvp-0.8, etc.). The output of iverilog will reference the correct run time
files and directories. The run time will check that it is running a file with
a compatible version e.g.(you can not run a V0.9 file with the V0.8 run
time).
This option adds extra memory cleanup code and pool management code to allow
better memory leak checking when valgrind is available. This option is not
need when checking for basic errors with valgrind.
The vvp progam is built as a small stub linked to a shared library,
libvvp.so, that may be linked with other programs so that they can host
a vvp simulation.
Compiling on Linux/Unix¶
(Note: You will need to install bison, flex, g++ and gcc) This is probably the
easiest case. Given that you have the source tree from the above instructions,
the compile and install is generally as simple as:
% ./configure % make (su to root) # make install
The “make install” typically needs to be done as root so that it can install
in directories such as “/usr/local/bin” etc. You can change where you want to
install by passing a prefix to the “configure” command:
% ./configure --prefix=/my/special/directory
This will configure the source for eventual installation in the directory that
you specify. Note that “rpm” packages of binaries for Linux are typically
configured with “–prefix=/usr” per the Linux File System Standard.
Make sure you have the latest version of flex otherwise you will get an error
when parsing lexor.lex.
Compiling on Macintosh OS X¶
Since Mac OS X is a BSD flavor of Unix, you can install Icarus Verilog from
source using the procedure described above. You need to install the Xcode
software, which includes the C and C++ compilers for Mac OS X. The package is
available for free download from Apple’s developer site. Once Xcode is
installed, you can build Icarus Verilog in a terminal window just like any
other Unix install.
For versions newer than 10.3 the GNU Bison tool (packaged with Xcode) needs to
be updated to version 3.
brew install bison echo 'export PATH="/usr/local/opt/bison/bin:$PATH"' >> ~/.bash_profile
Icarus Verilog is also available through the Homebrew package manager: “brew
install icarus-verilog”.
Compiling for Windows¶
These are instructions for building Icarus Verilog binaries for
Windows using mingw cross compiler tools on Linux.
To start with, you need the mingw64-cross-* packages for your linux
distribution, which gives you the x86_64-w64-mingw32-* commands
installed on your system. Installing the cross environment is outside
the scope of this writeup.
First, configure with this command:
$ ./configure --host=x86_64-w64-mingw32
This generates the Makefiles needed to cross compile everything with
the mingw32 compiler. The configure script will generate the command
name paths, so long as commands line x86_64-w64-mingw32-gcc
et. al. are in your path.
Next, compile with the command:
The configure generated the cross compiler flags, but there are a few
bits that need to be compiled with the native compiler. (version.exe
for example is used by the build process but is not installed.) The
configure script should have gotten all that right.
There is also a MSYS2 build recipe which you can find under msys2/ in the repository.
The ICARUS Verilog Compilation System
Copyright 2000-2019 Stephen Williams
Table of Contents
- What is ICARUS Verilog?
- Building/Installing Icarus Verilog From Source
- Compile Time Prerequisites
- Compilation
- (Optional) Testing
- Installation
- How Icarus Verilog Works
- Preprocessing
- Parse
- Elaboration
- Optimization
- Code Generation
- Attributes
- Running iverilog
- Examples
- Unsupported Constructs
- Nonstandard Constructs or Behaviors
- Builtin system functions
- Preprocessing Library Modules
- Width in %t Time Formats
- vpiScope iterator on vpiScope objects
- Time 0 Race Resolution
- Nets with Types
- Credits
What is ICARUS Verilog?
Icarus Verilog is intended to compile ALL of the Verilog HDL, as
described in the IEEE-1364 standard. Of course, it’s not quite there
yet. It does currently handle a mix of structural and behavioural
constructs. For a view of the current state of Icarus Verilog, see its
home page at https://steveicarus.github.io/iverilog/.
Icarus Verilog is not aimed at being a simulator in the traditional
sense, but a compiler that generates code employed by back-end
tools.
For instructions on how to run Icarus Verilog, see the
iverilog
man page.
Building/Installing Icarus Verilog from Source
If you are starting from the source, the build process is designed to be
as simple as practical. Someone basically familiar with the target
system and C/C++ compilation should be able to build the source
distribution with little effort. Some actual programming skills are
not required, but helpful in case of problems.
If you are building on Windows, see the mingw.txt file.
Compile Time Prerequisites
You can use:
apt install -y autoconf gperf make gcc g++ bison flex
You need the following software to compile Icarus Verilog from source
on a UNIX-like system:
-
GNU Make
The Makefiles use some GNU extensions, so a basic POSIX
make will not work. Linux systems typically come with a
satisfactory make. BSD based systems (i.e., NetBSD, FreeBSD)
typically have GNU make as the gmake program. -
ISO C++ Compiler
The ivl and ivlpp programs are written in C++ and make use
of templates and some of the standard C++ library. egcs and
recent gcc compilers with the associated libstdc++ are known
to work. MSVC++ 5 and 6 are known to definitely not work. -
bison and flex
OSX note: bison 2.3 shipped with MacOS including Catalina generates
broken code, but bison 3+ works. We recommend using the Fink
project version of bison and flex (finkproject.org), brew version
works fine either. -
gperf 3.0 or later
The lexical analyzer doesn’t recognize keywords directly,
but instead matches symbols and looks them up in a hash
table in order to get the proper lexical code. The gperf
program generates the lookup table.A version problem with this program is the most common cause
of difficulty. See the Icarus Verilog FAQ. -
readline 4.2 or later
On Linux systems, this usually means the readline-devel
rpm. In any case, it is the development headers of readline
that are needed. -
termcap
The readline library, in turn, uses termcap.If you are building from git, you will also need software to generate the configure scripts.
-
autoconf 2.53 or later
This generates configure scripts from configure.ac. The 2.53
or later versions are known to work, autoconf 2.13 is
reported to not work.
Compilation
Compiling From Release
Unpack the tar-ball, cd
into the verilog-#########
directory,
and compile the source with the commands:
Compiling From GitHub
If you are building from git, you have to run the command below before
compiling the source. This will generate the «configure» file, which is
automatically done when building from tarball.
sh autoconf.sh ./configure make
Normally, this command automatically figures out everything it needs
to know. It generally works pretty well. There are a few flags to the
configure script that modify its behaviour:
--prefix=<root>
The default is /usr/local, which causes the tool suite to
be compiled for install in /usr/local/bin,
/usr/local/share/ivl, etc.
I recommend that if you are configuring for precompiled
binaries, use --prefix=/usr. On Solaris systems, it is
common to use --prefix=/opt. You can configure for a non-root
install with --prefix=$HOME.
--enable-suffix
--enable-suffix=<your-suffix>
--disable-suffix
Enable/disable changing the names of install files to use
a suffix string so that this version or install can co-
exist with other versions. This renames the installed
commands (iverilog, iverilog-vpi, vvp) and the installed
library files and include directory so that installations
with the same prefix but different suffix are guaranteed
to not interfere with each other.
--host=<host-type>
Compile iverilog for a different platform. You can use:
x64_64-w64-mingw32 for building 64-bit Windows executables
i686-w64-mingw32 for building 32-bit Windows executables
Both options require installing the required mingw-w64 packages.
(Optional) Testing
To run a simple test before installation, execute
The commands printed by this run might help you in running Icarus
Verilog on your own Verilog sources before the package is installed
by root.
Installation
Now install the files in an appropriate place. (The makefiles by
default install in /usr/local unless you specify a different prefix
with the --prefix=<path>
flag to the configure command.) You may need
to do this as root to gain access to installation directories.
Uninstallation
The generated Makefiles also include the uninstall target. This should
remove all the files that make install
creates.
How Icarus Verilog Works
This tool includes a parser which reads in Verilog (plus extensions)
and generates an internal netlist. The netlist is passed to various
processing steps that transform the design to more optimal/practical
forms, then is passed to a code generator for final output. The
processing steps and the code generator are selected by command line
switches.
Preprocessing
There is a separate program, ivlpp
, that does the preprocessing. This
program implements the `include
and `define
directives producing
output that is equivalent but without the directives. The output is a
single file with line number directives, so that the actual compiler
only sees a single input file. See ivlpp/ivlpp.txt
for details.
Parse
The Verilog compiler starts by parsing the Verilog source file. The
output of the parse is a list of Module objects in «pform». The pform
(see pform.h
) is mostly a direct reflection of the compilation
step. There may be dangling references, and it is not yet clear which
module is the root.
One can see a human-readable version of the final pform by using the
-P <path>
flag to the ivl
subcommand. This will cause ivl
to dump the pform into the file named <path>
. (Note that this is not
normally done, unless debugging the ivl
subcommand.)
Elaboration
This phase takes the pform and generates a netlist. The driver selects
(by user request or lucky guess) the root module to elaborate,
resolves references and expands the instantiations to form the design
netlist. (See netlist.txt.) Final semantic checks are performed during
elaboration, and some simple optimizations are performed. The netlist
includes all the behavioural descriptions, as well as gates and wires.
The elaborate()
function performs the elaboration.
One can see a human-readable version of the final, elaborated and
optimized netlist by using the -N <path>
flag to the compiler. If
elaboration succeeds, the final netlist (i.e., after optimizations but
before code generation) will be dumped into the file named <path>
.
Elaboration is performed in two steps: scopes and parameters
first, followed by the structural and behavioural elaboration.
Scope Elaboration
This pass scans through the pform looking for scopes and parameters. A
tree of NetScope objects is built up and placed in the Design object,
with the root module represented by the root NetScope object. The
elab_scope.cc
file contains most of the code for handling this phase.
The tail of the elaborate_scope behaviour (after the pform is
traversed) includes a scan of the NetScope tree to locate defparam
assignments that were collected during scope elaboration. This is when
the defparam overrides are applied to the parameters.
Netlist Elaboration
After the scopes and parameters are generated and the NetScope tree
fully formed, the elaboration runs through the pform again, this time
generating the structural and behavioural netlist. Parameters are
elaborated and evaluated by now so all the constants of code
generation are now known locally, so the netlist can be generated by
simply passing through the pform.
Optimization
This is a collection of processing steps that perform
optimizations that do not depend on the target technology. Examples of
some useful transformations are
- eliminate null effect circuitry
- combinational reduction
- constant propagation
The actual functions performed are specified on the ivl
command line by
the -F
flags (see below).
Code Generation
This step takes the design netlist and uses it to drive the code
generator (see target.h). This may require transforming the
design to suit the technology.
The emit()
method of the Design class performs this step. It runs
through the design elements, calling target functions as the need arises
to generate actual output.
The user selects the target code generator with the -t
flag on the
command line.
Attributes
NOTE: The $attribute syntax will soon be deprecated in favour of the Verilog-2001 attribute syntax, which is cleaner and standardized.
The parser accepts, as an extension to Verilog, the $attribute module
item. The syntax of the $attribute item is:
$attribute (<identifier>, <key>, <value>);
The $attribute keyword looks like a system task invocation. The
difference here is that the parameters are more restricted than those
of a system task. The <identifier>
must be an identifier. This will be
the item to get an attribute. The <key>
and <value>
are strings, not
expressions, that give the key and the value of the attribute to be
attached to the identified object.
Attributes are [<key> <value>]
pairs and are used to communicate with
the various processing steps. See the documentation for the processing
step for a list of the pertinent attributes.
Attributes can also be applied to gate types. When this is done, the
attribute is given to every instantiation of the primitive. The syntax
for the attribute statement is the same, except that the <identifier>
names a primitive earlier in the compilation unit and the statement is
placed in the global scope, instead of within a module. The semicolon is
not part of a type attribute.
Note that attributes are also occasionally used for communication
between processing steps. Processing steps that are aware of others
may place attributes on netlist objects to communicate information to
later steps.
Icarus Verilog also accepts the Verilog 2001 syntax for
attributes. They have the same general meaning as with the $attribute
syntax, but they are attached to objects by position instead of by
name. Also, the key is a Verilog identifier instead of a string.
Running iverilog
The preferred way to invoke the compiler is with the iverilog
(1)
command. This program invokes the preprocessor (ivlpp
) and the
compiler (ivl
) with the proper command line options to get the job
done in a friendly way. See the iverilog
(1) man page for usage details.
EXAMPLE: Hello World
Example: Compiling "hello.vl"
// ------------------------ hello.vl ---------------------------- module main(); initial begin $display("Hello World"); $finish ; end endmodule // --------------------------------------------------------------
Ensure that iverilog
is on your search path, and the vpi library
is available.
To compile the program:
(The above presumes that /usr/local/include
and /usr/local/lib
are
part of the compiler search path, which is usually the case for gcc
.)
To run the generated program:
You can use the -o
switch to name the output command to be generated
by the compiler. See the iverilog
(1) man page.
Unsupported Constructs
Icarus Verilog is in development — as such it still only supports a
(growing) subset of Verilog. Below is a description of some of the
currently unsupported Verilog features. This list is not exhaustive
and does not account for errors in the compiler. See the Icarus
Verilog web page for the current state of support for Verilog, and in
particular, browse the bug report database for reported unsupported
constructs.
-
System functions are supported, but the return value is a little
tricky. See SYSTEM FUNCTION TABLE FILES in the iverilog man page. -
Specify blocks are parsed but ignored in general.
-
trireg
is not supported.tri0
andtri1
are supported. -
tran primitives, i.e.
tran
,tranif1
,tranif0
,rtran
,rtranif1
,
andrtranif0
are not supported. -
Net delays, of the form
wire #N foo;
do not work. Delays in
every other context do work properly, including the V2001 form
wire #5 foo = bar;
-
Event controls inside non-blocking assignments are not supported.
i.e.:a <= @(posedge clk) b;
-
Macro arguments are not supported.
`define
macros are supported,
but they cannot take arguments.
Nonstandard Constructs or Behaviors
Icarus Verilog includes some features that are not part of the
IEEE1364 standard, but have well-defined meaning, and also sometimes
gives nonstandard (but extended) meanings to some features of the
language that are defined. See the «extensions.txt» documentation for
more details.
-
$is_signed(<expr>)
This system function returns 1 if the expression contained is
signed, or 0 otherwise. This is mostly of use for compiler
regression tests. -
$sizeof(<expr>)
,$bits(<expr>)
The
$bits
system function returns the size in bits of the
expression that is its argument. The result of this
function is undefined if the argument doesn’t have a
self-determined size.The
$sizeof
function is deprecated in favour of$bits
, which is
the same thing, but included in the SystemVerilog definition. -
$simtime
The
$simtime
system function returns as a 64bit value the
simulation time, unscaled by the time units of local
scope. This is different from the $time and $stime functions
which return the scaled times. This function is added for
regression testing of the compiler and run time, but can be
used by applications who really want the simulation time.Note that the simulation time can be confusing if there are
lots of different`timescales
within a design. It is not in
general possible to predict what the simulation precision will
turn out to be. -
$mti_random()
,$mti_dist_uniform
These functions are similar to the IEEE1364 standard $random
functions, but they use the Mersenne Twister (MT19937)
algorithm. This is considered an excellent random number
generator, but does not generate the same sequence as the
standardized $random.
Builtin system functions
Certain of the system functions have well-defined meanings, so
can theoretically be evaluated at compile-time, instead of
using runtime VPI code. Doing so means that VPI cannot
override the definitions of functions handled in this
manner. On the other hand, this makes them synthesizable, and
also allows for more aggressive constant propagation. The
functions handled in this manner are:
$bits
$signed
$sizeof
$unsigned
Implementations of these system functions in VPI modules will be ignored.
Preprocessing Library Modules
Icarus Verilog does preprocess modules that are loaded from
libraries via the -y mechanism. However, the only macros
defined during the compilation of that file are those that it
defines itself (or includes) or that are defined in the
command line or command file.
Specifically, macros defined in the non-library source files
are not remembered when the library module is loaded. This is
intentional. If it were otherwise, then compilation results
might vary depending on the order that libraries are loaded,
and that is too unpredictable.
It is said that some commercial compilers do allow macro
definitions to span library modules. That’s just plain weird.
Width in %t
Time Formats
Standard Verilog does not allow width fields in the %t formats
of display strings. For example, this is illegal:
$display("Time is %0t", $time);
Standard Verilog instead relies on the $timeformat to
completely specify the format.
Icarus Verilog allows the programmer to specify the field
width. The %t
format in Icarus Verilog works exactly as it
does in standard Verilog. However, if the programmer chooses
to specify a minimum width (i.e., %5t
), then for that display
Icarus Verilog will override the $timeformat
minimum width and
use the explicit minimum width.
vpiScope Iterator on vpiScope Objects
In the VPI, the normal way to iterate over vpiScope objects
contained within a vpiScope object, is the vpiInternalScope
iterator. Icarus Verilog adds support for the vpiScope
iterator of a vpiScope object, that iterates over everything
the is contained in the current scope. This is useful in cases
where one wants to iterate over all the objects in a scope
without iterating over all the contained types explicitly.
Time 0 Race Resolution
Combinational logic is routinely modelled using always
blocks. However, this can lead to race conditions if the
inputs to the combinational block are initialized in initial
statements. Icarus Verilog slightly modifies time 0 scheduling
by arranging for always statements with ANYEDGE sensitivity
lists to be scheduled before any other threads. This causes
combinational always blocks to be triggered when the values in
the sensitivity list are initialized by initial threads.
Nets with Types
Icarus Verilog supports an extended syntax that allows nets
and regs to be explicitly typed. The currently supported types
are logic, bool and real. This implies that logic
and bool
are new keywords. Typical syntax is:
wire real foo = 1.0; reg logic bar, bat;
… and so forth. The syntax can be turned off by using the
-g2
flag to iverilog, and turned on explicitly with the -g2x
flag to iverilog.
Credits
Except where otherwise noted, Icarus Verilog, ivl, and ivlpp are
Copyright Stephen Williams. The proper notices are in the head of each
file. However, I have early on received aid in the form of fixes,
Verilog guidance, and especially testing from many people. Testers, in
particular, include a larger community of people interested in a GPL
Verilog for Linux.
How to install Icarus Verilog to start coding Verilog:
When it comes to learning Verilog, many of the popular tools like Xilinx, Intel Quartus Prime, Vivado Design Suite, and ModelSim are often the first names that come to mind. However, these tools can be quite heavy, usually more than 20 GBs and in some cases near to 100 GB, consuming significant system resources, and they may not always be free or fully compatible with the latest versions of Windows, such as Windows 11.
If your primary goal is to learn Verilog without the overhead of these resource-intensive tools, there’s a much simpler solution which is Icarus Verilog —a lightweight tool that’s incredibly easy to install, occupies just a few hundred megabytes including all dependencies, and is fully compatible with Windows 11. A couple of 100’s of MBs for Icarus Verilog versus more than 20 GBs in case of many commercial tools, is a huge difference. Icarus Verilog is the perfect choice for anyone looking to master Verilog without the hassle.
In this article, we will see how to:
- Download and install the Icarus Verilog
- Write Verilog code using Icarus Verilog
- Write the test bench for our design
- View the signal waveforms.
- Integrate Icarus Verilog with Visual Studio Code IDE, for a smooth and professional code-writing experience.
To install Icarus Verilog, one prerequisite is having the C compiler (GCC) installed on your system. If you have the C compiler installed on your system, you can continue for the next steps. If C compiler is not installed, please refer to this article in which all steps are shown to install the C compiler and integrated that with Visual Studio Code.
Two methods of installing Icarus Verilog:
We will explore two methods to install Icarus Verilog:
- Using installer from the website
- Using MSYS2 (MSYS2 is a software installation and building platform for windows. MSYS2 can handle the dependencies and updates very effectively)
1. Installation using Installer from Website:
Go to the link: https://bleyer.org/icarus/
Choose the latest stable release available there. At present the latest stable release is shown here:
Run the installer and follow the simple steps to install. It will be installed in the C drive. Don’t forget to install GTKWave which will be used to view the waveforms, when asked in a window as shown:
After the installation, we should verify if the Icarus Verilog has been successfully installed. For that, we need to open the command prompt. Go to the Windows Search Bar and type CMD and hit enter. The command prompt window will open as shown below:
Write the following command:
>iverilog
You might see the error that iverilog is not recognize as internal or external command, as shown below:
The reason is that Icarus Verilog was installed in the C drive:
And inside iverilog folder there is a folder bin, inside which we have the iverilog application.
So we need to tell Windows about this path (C:\iverilog\bin) so that it is accessible in the whole system.
Now go to Windows Search bar and search for “Environment Variables” and click “Edit the system environment variables”. This window will open:
Click “Environment Variables” at the bottom of the above window. A new window will open and we need to edit the path variable in the lower section:
Select the Path variable and Click “Edit” to edit it. This window will open:
Here click “New” to add a new path and paste the path C:\iverilog\bin. Then Click “OK” a couple of times.
Now you can open the command prompt again (using CMD in Windows search bar) and verify the installation of Icarus Verilog with this command:
>iverilog
Now you should get the information similar to this:
We can also view the version of Icarus Verilog installed by the command
>iverilog -V
The output will show full details of Icarus Verilog along with the version installed.
2. Installation using MSYS2:
Now let’s see how to install Icarus Verilog by using MSYS2. First, you should have MSYS2 installed and for that you can follow the same previous article.
With MSYS2 installed, go to the Windows Search Bar and look for MSYS2MinGW64. A command-based interface will open. The first step is always updating the package databases using pacman package manager. Use this command:
$ pacman -Syu
It will ask for yes or no as [Y/n], then press Y.
Now to install Icarus Verilog, use this command.
$ pacman -S mingw-w64-x86_64-iverilog
We also need to install GTK Wave for the Signal Waveforms. For that, we will use this command:
$ pacman -S mingw-w64-x86_64-gtkwave
To verify the installation, use the command:
$iverilog -V
You should get the version information. The command we used will automatically install the latest version. Also verify the installation of GTK-Wave with the following command:
$gtkwave
It should open the GTK-Wave window as shown below, which means it has been installed.
How to write Verilog Codes:
First, we will see the method where we can write the code on simple text files and then we will integrate Icarus Verilog with Visual Studio Code IDE for better experience.
Use the following steps to write and execute the Verilog Codes in the text file.
Create a Verilog File:
- Go to the folder where you want to keep the files e.g. D:\VerilogCodes
- Create a new text file and name it something like test.v where the extension V is for the Verilog files.
- One very important point here is that you go to “View” tab on your Folder and select the option to view the file name extension.
- You would see the file name as test.v.txt which means the format is still .txt. Remove that .txt and ignore any warning. Now the file will be a Verilog extension file.
- Open the file in notepad where we can type the code.
- Copy this basic “Hello World” program in that file. This code is very basic code which simply displays “Hello World” on the screen.
module hello;
initial
begin
$display(“Hello, World”);
$finish ;
end
endmodule
Compile and Run the Verilog file:
It is all command base. You need to open the command prompt or better on MSYS2. For MSYS2, search for MSYS2 MinGW64 on the Windows Search Bar and MSYS2 command prompt will open.
Use the following steps to compile and run the code:
- The first step will be changing the directory to the one having the source file. Use the command cd to change directory followed by the path of the folder as (assuming the path is D:\VerilogCodes):
$ cd/d/VerilogCodes
- To compile the source file test.v available inside the selected folder use this command:
$ iverilog -o test.vvp test.v
(here -o means the output file and we specified the name of the output file as test.vvp. The name is preferably same as of the original source file i.e. test and the extension is VVP which is an intermediate file containing the compiled simulation code. Then we specify the source file which we are compiling i.e. test.v)
- The above command should not generate any error which means the code has been compiled correctly.
- If you go to the folder, you should see the output file test.vvp generated there.
The next step is running the VPP file. For that use the following steps:
- To run the vvp file you created in last step use this command on MSYS2 command prompt:
$ vvp test.vvp
And you should get the Hello World printed on the output as shown here:
This was the basic testing. Now let’s do something meaningful and also create the test bench and the waveforms.
Full Adder with Test Bench and Waveforms:
Let’s create a Full Adder circuit code and then create the test bench for it and also view the wave forms. Follow these steps:
Create Source Module:
- Create a file fullAdder.v
- Copy this code:
`timescale 1ns / 1ps
module full_adder (
input a,
input b,
input c_in,
output wire sum,
output wire carry_out
);
// Assign sum using XOR for efficient bitwise addition
assign sum = a ^ b ^ c_in;
// Assign carry based on two-bit product terms for clarity
assign carry_out = (a & b) | (a & c_in) | (c_in & b);
endmodule
This module has three inputs (a, b, c_in) and two outputs (sum and carry_out). The outputs sum and carry_out are as per the full adder equations.
- One important point to mention here is that the name of the module is “full_adder” while the file name is fullAdder.v without any space or underscore. The file name and the module names are different. To compile and use the file we will have to use the file name i.e. fullAdder.v while to use the module in some other module like the test bench, we will use the module name i.e. full_adder. The naming conventions are just personal preferences.
- Now compile the full adder Verilog file using this command:
$ iverilog -o fullAdder.vvp fullAdder.v
- There should not be any error and the output file fullAdder.vvp should have been generated in the folder.
- You may run the VVP file with the command:
> vvp fullAdder.vvp
But there will be no output since we did not display anything.
Create Test Bench:
Now let’s do the next important step of creating and executing the test bench for the full adder. A test bench in Verilog is another Verilog program which verifies the functionality of the design. Follow these steps:
- Create the Verilog file for the test bench and name it as fullAdderTB.v
- Copy this code:
`timescale 1ns / 1ps
module tb_full_adder;
// Declare testbench signals
reg a, b, c_in;
wire sum, carry_out;
// Instantiate the full adder module
full_adder dut (a, b, c_in, sum, carry_out);
// Apply test stimulus
initial begin
$display(“Testing Full Adder”);
$monitor(“a = %b, b = %b, c_in = %b, sum = %b, carry_out = %b”, a, b, c_in, sum, carry_out);
// Apply various test cases
a = 0; b = 0; c_in = 0; #10; // Expect sum = 0, carry_out = 0
a = 0; b = 0; c_in = 1; #10; // Expect sum = 1, carry_out = 0
a = 0; b = 1; c_in = 0; #10; // Expect sum = 1, carry_out = 0
a = 0; b = 1; c_in = 1; #10; // Expect sum = 0, carry_out = 1
a = 1; b = 0; c_in = 0; #10; // Expect sum = 1, carry_out = 0
// … Add more test cases as needed
$finish;
end
endmodule
- Note that the name of this module we specified is “tb_full_adder” which is different from the file name i.e. fullAdderTB.v
- In the code we are instantiating an instance of full adder as: full_adder dut (a, b, c_in, sum, carry_out). The dut is just the variable name; it could be anything. The dut means design under test. Then in the code there is a block inside which we are displaying a simple message followed by a few variable values we want to see, using the monitor function. The monitor function displays all the values specified whenever there is some change in any of the variable values specified. And finally, we are assigning different values to input variables and would like to see the values of output variables.
- After creating the test bench file we need to compile that using this command on MSYS2 command window:
$ iverilog -o fullAdderTB.vcd fullAdderTB.v fullAdder.v
The extension VCD is Value Change Dump file that logs signal value changes over time during a Verilog simulation for waveform analysis and debugging. As the source file, we will have to specify the test bench file but also the full adder module file.
- There should be no error and we should have the VCD file generated in the folder.
- You can run the VCD file on the command prompt as:
$ vvp fullAdderTB.vcd
You will see the output as where we have the display message and then the five variables we specified in the monitor function every time some value is updated:
You can verify for any set of three inputs, the carry and sum are correct.
- We got the correct output of the test bench but we need to view the signal values as waveform. For that we first need one change in the test bench code. Before applying different simulation values, we need a couple of lines:
// Dumpfile and dumpvars for waveform generation
initial begin
$dumpfile(“fullAdderTB.vcd”); // Specify dump file name
$dumpvars(0, tb_full_adder); // Dump all signals in the testbench
end
We need to add the above lines in the test bench code just after the line full_adder dut (a, b, c_in, sum, carry_out);
Let’s discuss the purpose of the two lines we added. We are specifying a file where the signal values will be saved:
- The first is the dumpfile function where the name of the file should be specified that will hold the values of different variables: $dumpfile(“fullAdderTB.vcd”); We specified the output VCD file.
- The second line is dumpvars function where we specified the name of the module of the test bench meaning all variables of this test bench will be dumped.
- Compile the test bench again since the code has been updated.
$ iverilog -o fullAdderTB.vcd fullAdderTB.v fullAdder.v
- You can run the VCD file if you wish but we want to view the signal waveforms.
- Open the GTK-Wave with the command:
$ gtkwave
This will open the GTK-Wave window.
- You need to drag the VCD file onto this window.
- Double-click the signals from the signals section to view.
- You might initially see the flat lines as shown here:
- Use the Zoom buttons and preferably “Fit to Window” option and you should be able to see the waveforms as:
Integrating Icarus Verilog with Visual Studio Code (VSC):
You see coding on the text files is very cumbersome and it will be good if we could code this in some IDE like Visual Studio Code. To add the Verilog support, go to the extension tab and search for Verilog. You will see a bunch of extensions. You can choose any of these based on ratings and downloads.
After installing the extension you will get the proper IntelliSense help as well.
To run the code, you will have to use the commands on the terminal. For that go to the Menu bar option as TerminalàNew Terminal. It will open the terminal in VSC where you can write all the commands we discussed previously.
All steps are shown in this YouTube video.
by Stephen Williams
Icarus Verilog is a Verilog compiler and simulator for synthesis and verification of digital logic designs.
Operating system: Windows
Publisher:
Stephen Williams
Release : Icarus Verilog 0.9.7
Antivirus check: passed
Report a Problem
Icarus Verilog is an open source software package for designing, verifying, simulating, and synthesizing digital logic circuits. It is a free Verilog compiler that supports the IEEE-1364 Verilog HDL standard and provides a wide range of features, making it a powerful tool for designing complex digital logic circuits.
Icarus Verilog is designed to be easy to use and understand. It is written in the C programming language and runs on most popular platforms, including Linux, Windows, and Mac OS X. It has a wide range of features, including:
• A sophisticated Verilog parser that supports the IEEE-1364 Verilog HDL standard
• Support for the SystemVerilog IEEE 1800-2009 standard
• Support for Advanced Verification Methodology (AVM)
• Synthesis support for Xilinx and Altera FPGAs
• Support for digital design, including RTL, gate-level, and behavioural modelling
• Support for simulation, including VCD and FST trace files
• Support for design verification, including assertion-based verification (ABV)
• Built-in testbench generation and debugging
• Support for automated design rule checking (DRC)
• Support for SDF annotations
• Support for VHDL, including VHDL-2008
• Support for Verilog-AMS
• Support for PLI/VPI
• Support for the Verilator Verilog simulation tool
• Support for the Verilator trace format
• Support for OpenVera and e language
• Support for graphical waveform viewers
• Support for source code documentation tools
• Support for source code version control systems
• Support for scripting languages
• Support for various hardware description languages (HDLs)
• Support for various design automation tools
• Support for various design automation languages (DALs)
• Support for various synthesis tools
• Support for various verification tools
• Support for various design entry methods
• Support for various design optimization techniques
• Support for various design entry languages (DELs)
• Support for various synthesis languages (SELs)
• Support for various verification languages (VELs)
• Support for various languages for testbench creation
• Support for various GUI tools
• Support for various code coverage tools
• Support for various formal verification tools
• Support for various debuggers
• Support for various emulators
• Support for various target architectures
• Support for various input/output formats
• Support for various verification languages
Icarus Verilog allows users to quickly and easily simulate their designs, providing fast feedback on their designs.
• Operating System: Windows, Linux, macOS
• Compiler: GCC 4.2 or later
• Memory: 4GB RAM
• Hard Disk: 100MB of available space
• Graphics: Any graphics card with at least 1024×768 resolution
• Internet Access: Required for downloading the software and support materials
• Access to a text editor: Required for writing Verilog code
Open-source platform, making it free and customizable.
Simulates and synthesizes Verilog designs.
Supports a wide range of Verilog standards.
Limited hardware description language support.
Steep learning curve for beginners.
Lack of comprehensive debugging tools.
👨💻️ USER REVIEWS AND COMMENTS 💬
image/svg+xmlBotttsPablo Stanleyhttps://bottts.com/Florian Körner
Noah S*******d
Icarus Verilog is an open source software for hardware design. It provides a great feature set for doing hardware design. I find the software easy to use and it has a wide range of support for different hardware designs. The syntax is very simple and it allows for a clear design. The support for debugging is also great as it provides detailed information about the design and errors. The software also has a great library of components and IPs which can make designing easier. The output is also very easy to read and understand. Finally, the software is quite fast and efficient.
image/svg+xmlBotttsPablo Stanleyhttps://bottts.com/Florian Körner
Caleb U.
I’ve been using Icarus Verilog for a few months now and it’s been a great experience, it’s easy to use and the documentation is thorougly explanitory.
image/svg+xmlBotttsPablo Stanleyhttps://bottts.com/Florian Körner
Muhammad W********g
Icarus Verilog is an open-source software for designing and simulating digital circuits. It supports Verilog 2005 standard and includes a wide range of features such as cross-module optimization, multiple language support, and interactive debugging. The software is platform-independent and can be used on various operating systems such as Windows, Linux, and macOS. It also offers support for mixed-language designs and provides a user-friendly interface for efficient circuit design and analysis. Additionally, it allows for the creation of testbenches for verifying the functionality of the designed circuits.
image/svg+xmlBotttsPablo Stanleyhttps://bottts.com/Florian Körner
Archie N.
Icarus Verilog software is an open-source digital circuit simulator and synthesizer that supports the IEEE 1364-2005 Verilog hardware description language.
image/svg+xmlBotttsPablo Stanleyhttps://bottts.com/Florian Körner
Alfie
Versatile, user-friendly, supports diverse hardware description languages.
image/svg+xmlBotttsPablo Stanleyhttps://bottts.com/Florian Körner
Hunter
Robust, intuitive, reliable simulation tool.
A highly popular open-source platform for professional Java developers
MPLAB is an integrated development environment (IDE) for developing and debugging embedded applications on Microchip microcontrollers and digital signal controllers.
NDepend is a static analysis tool that helps developers and teams to measure, understand and improve the quality of their .NET and .NET Core code.
PyOpenGL is a cross-platform library providing Python bindings to the modern OpenGL API.
MockFlow is a web-based prototyping tool that enables users to quickly and easily create interactive wireframes and mockups of web and mobile applications.
30 октября прошло первое занятие Сколковской Школы Синтеза Цифровых Схем. Из-за Ковида его пришлось провести в онлайн-формате. Трансляция первого занятия:
Возможно онлайн-формат — это и к лучшему, так как в офлайне в Технопарке Сколково есть только 25 посадочных мест, и мы приготовили только 25 FPGA плат, а количество заявок привысило 300. Теперь мы на спонсорские деньги от компании Ядро Микропроцессоры и Максима Маслова @Armmaster заказали еще 100 плат и собираемся их раздать бесплатно для занятий дома, преподавателям вузов и руководителям кружков в других городах.
Чтобы быть уверенным, что получатели плат смогут их использовать, мы поставили в качестве пререквизита их получения прохождение короткого онлайн-курса от Роснано (см. детали в хабрапосте Готовимся к Сколковской Школе Синтеза Цифровых Схем: литература, FPGA платы и сенсоры). 40 с чем-то участников школы прошли этот курс и им будут высланы платы, как только заказанные платы прибудут из Китая.
При этом, так как школа уже началась, а до следующего занятия 13 ноября еще есть время, мы решили попробовать другой пререквизит — решение последовательности коротких задач на верилоге, используя не плату, а бесплатный симулятор Icarus Verilog. Всем участникам, которые собираются дойти в курсе до проектирования процессоров, все равно нужно будет освоить механику кодирования на верилоге, а для этого симулятор просто быстрее, чем учить это на FPGA платах.
Учить верилог в симуляторе Icarus так же просто, как учить программирование на питоне, за исключением того, что у верилога есть синтезируемое подмножество. То есть не все что вы можете сделать в симуляторе вы можете превратить в схему на фабрике или в прошивку в ПЛИС. Кроме этого в верилоге, в отличие от питона, есть физический тайминг, задержки в пикосекундах и максимальная тактовая частота, которые выясняются во время синтеза, то бишь одной симуляцией для обучения не обойтись. Тем не менее, упражнения на симуляторе — это оптимальный способ набить руку на многих вещах.
Идея та же, что научиться игре в шахматы или игре Го с помощью решения большого количества задач в несколько ходов. В качестве справочника для решения верилоговских задач можно использовать учебник Харрис & Харрис (планшетная версия, краткие слайды для лекций), лабник Цифровой Синтез и книгу Дональда Томаса (PDF начала к ней).
Пререквизит для получения плат будет состоять из двух групп упражнений. Первую группу мы уже выложили в составе пакета упражнений для школы:
ChipEXPO 2021 Digital Design School package v2.3
Ссылка через bit.ly — https://bit.ly/chipexpo2021dds23
Прямая ссылка
Если вы хотите не скачивать готовый пакет, а клонировать его из GitHub с некоторой настройкой, см. в конце поста инструкцию Приложение. Как клонировать пакет упражнений из GitHub и наcтроить его после этого.
Упражнения находятся в директории ce2020labs/quizes/problems_001_011. Это 11 файлов на верилоге. В каждом из них вначале пример модуля, потом незаконченный модуль, который вам нужно изменить (с комментарием TODO), а потом тест (модуль testbench). Как работает тест, вам понимать необязательно, про тесты объяснит Александр Силантьев из МИЭТ и Илья Кудрявцев из Самарского Университета на следующем занятии. Пока все что вам нужно сделать — это:
-
Установить Icarus Verilog по инструкциям ниже. Для него есть версии для Линукса, Windows и MacOS.
-
Прочитать модуль в начале файла.
-
Проконсультироваться со слайдами Александра Силантьева с первого занятия, а также возможно с книгами Харрис & Харрис, лабником Цифровой Синтез и книжкой Дональда Томаса, что все это значит.
-
Прочитать задание под комментарием TODO. Задание я написал на английском, если вы учили в школе другой язык, спросите на телеграм-канале DigitalDesignSchool объяснение задания.
-
Написать код из нескольких строчек под заданием.
-
Под Линуксом или MacOS: запустить скрипт run_all_using_iverilog_under_linux_or_macos_brew.sh . Его можно запустить из командной строки в терминале (на Apple тоже есть приложение Terminal если вы не знали) или просто кликнуть на него из менеджера файлов.
-
Под Windows: запустить пакетный файл run_all_using_iverilog_under_windows.bat . Его можно запустить из командной строки в терминале (на Apple тоже есть приложение Terminal если вы не знали) или просто кликнуть на него из менеджера файлов.
-
Скрипт или пакетный файл создаст файл log.txt с результатами компиляции и симуляции всех 11 файлов. Если что-то не скомпилировалось, там будет сообщение об ошибке syntax error. Если тест не прошел, там будет сообщение FAIL и информация об ожидаемом значении.
-
Когда все тесты пройдут, зазипуйте все что вы написали в один файл и пришлите в емейле мне ( yuri@panchul.com с копией yuri.panchul@gmail.com ), с копией Александру Силантьеву в МИЭТ ( olmer.aod@gmail.com ), Илье Кудрявцеву в Самарский Университет ( rtf@ssau.ru ) и Сергею Иванцу ( sergey.ivanets@gmail.com ) в Черниговский НПУ.
-
Если что-то непонятно, задавайте вопросы в телеграм-канал.
Задачи можно решать с любым симулятором верилога, который поддерживает SystemVerilog. А также c бесплатным симулятором Icarus Verilog, который хотя и не поддерживает весь SystemVerilog, но поддерживает Verilog 2005 с некоторыми элементами SystemVerilog, достаточных для решения наших задач.
.
Icarus Verilog чаcто используют с GTKWave, программой для работы с временными диаграммами. Для первых десяти задач GTKWave нам не понадобится, но его стоит установить вместе с Icarus Verilog на будущее.
Под Linux Icarus Verilog и GTKWave ставится «sudo apt-get install verilog gtkwave».
Версия Icarus Verilog и GTKWave для Windows здесь. !!! Важно !!! Нужно брать свежую версию iverilog-v11-20210204-x64_setup.exe [44.1MB] в которой есть поддержка некоторых конструкций SystemVerilog которые мы используем в примерах.
Icarus можно поставить даже на Apple Mac, что необычно для EDA tools (EDA — Electronic Design Automation). Это можно сделать в консоли с помощью программы brew: brew install icarus-verilog.
Видео установки Icarus Verilog для Windows
Примечание: если видео рекомендует старую версию, нужно скачивать новую (см. выше).
Видео установки Icarus Verilog для MacOS
Примечание: если видео рекомендует старую версию, нужно скачивать новую (см. выше).
Теперь про первые 11 задачек. Общая тема — мультиплексор — блок выбора. Если селектор стоит в 0, на выход идет значение из входа d0, иначе — значение из входа d1. Но даже такую незамысловатую функциональность в верилоге можно выразить минимум пятью способами:
-
Через операцию «?» и непрерывное присваивание (continuous assignment) — s001_mux_question.v
-
Через оператор «if» и блокирующее присваивание внутри комбинационного always-блока — s002_mux_if.v
-
Через оператор «case» и блокирующее присваивание внутри комбинационного always-блокаs — 003_mux_case.v
-
Через индекс двумерного массива типа logic — s004_mux_index.v
-
И даже просто через логические операции и/или/не, вместе с операцией размножения последовательности битов { n { m } } — что значит «построй последовательность состоящую из n копий последовательности m — s005_mux_gates.v
Можно строить большие мультиплексоры с многими входами из мультиплексоров с небольшим количеством входов. Этому посвящено упражнение s006_mux_2n_using_muxes_n.v, которое также вводит иерархию экземпляров модулей:
Также можно строить мультиплексоры для широких данных из мультиплексоров для узких данных — про это упражнение s007_mux_using_narrow_data_muxes.v.
Выше мы строили мультиплексоры из логических элементов И, ИЛИ, НЕ. А можно ли строить логические элементы И, ИЛИ, НЕ из мультиплексоров? Это посвящены четыре задачки, в которых нужно построить модули, реализующие комбинационную логику И, ИЛИ, НЕ и ИСКЛЮЧАЮЩЕЕ-ИЛИ (xor) только из мультиплексоров, констант 0 и 1, а также соединений между ними:
-
s008_not_gate_using_mux.v
-
s009_and_gate_using_mux.v
-
s010_or_gate_using_mux.v
-
s011_xor_gate_using_mux.v
Я не обещаю, что мы дойдем до задачи номер 999 (наверное это будет алгоритм Томасуло, который показывает девушка Ирина на рисунке 7.71 на фотографии ниже, и про который любят спрашивать недавних студентов на собеседованиях в электронные компании) но мы будем работать в этом направлении. Загружаем, приступаем и ждем вас на занятии 13 ноября, которое по-видимому начнется с разбора этих задачек.
Приложение. Как клонировать пакет упражнений из GitHub и наcтроить его после этого
Вместо использования готового пакета упражнений (и для симуляции, и для синтеза) вы можете клонировать его код из двух репозиторий GitHub-а:
https://github.com/DigitalDesignSchool/ce2020labs
https://github.com/zhelnio/schoolRISCV
После клонирования вам нужно запустить башевский скрипт ce2020labs/scripts/create_run_directories.bash, находясь при этом в директории ce2020labs/scripts. Этот скрипт создает временные директории run с копиями скриптов для синтеза и симуляции в каждой поддиректории, в которой есть файл top.v. В директориях run потом скапливаются все временные файлы, которые создает Intel FPGA Quartus и другие программы. Сами run директории игнорируются в .gitinfo чтобы случайно не занести временные файлы в github.
Под Линуксом и MacOS скрипт запускается прямолинейно:
cd ce2020labs/scripts
./create_run_directories.bash
Под Windows это тоже будет работать, так как если вы установили Git для Windows то у него внутри есть встроенный интерпретатор bash в директории «C:\Program Files\Git\usr\bin», а также другие нужные для скрипта утилиты: sed и линуксный вариант find. Вам нужно будет точно так же пойти в директорию скрипта и запустить его, используя bash:
cd ce2020labs\scripts
bash create_run_directories.bash
Если у вас под Windows что-то не работает, проверьте, какие директории стоят у вас в path. Вот что стоит у меня:
-
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
Java понадобиться на занятии про архитектуру RISC-V, так как ее использует симулятор RARS -
C:\Program Files\Git\cmd
C:\Program Files\Git\mingw64\bin
C:\Program Files\Git\usr\bin -
C:\intelFPGA_lite\20.1\quartus\bin64
C:\intelFPGA_lite\20.1\modelsim_ase\win32aloem
ModelSim внутри пакета intelFPGA — это симулятор Verilog, мощнее и быстрее чем Icarus. Однако версия ModelSim в последнем бесплатном пакете intelFPGA не поддерживает черты SystemVerilog, которые мы используем в задачах, например тип logic. -
C:\Program Files (x86)\GnuWin32\bin
Здесь установлены GNU утилита make.exe, которая нужна для занятий про микроархитектуру RISC-V, а также линуксная версия zip.exe для формирования пакета скриптом create_ce2020labs_zip.bash -
C:\iverilog\bin
C:\iverilog\gtkwave\bin
Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.
Как вы относитесь к идее учить язык через решение тысячи задач с повышением сложности?
53.73% Идеальный формат для меня. Учебники читать мне лень, а на лекциях я засыпаю.36
32.84% Как вспомогательный формат пойдет, чтобы набить руку. Мне нужна плата, чтобы делать свой проект.22
13.43% Нет уж, я не буду писать код бесплатно. Поставьте меня сразу делать чип для айфона, пусть из-за каждого бага делают перевыпуск на фабрике за $20 миллионов.9
Проголосовали 67 пользователей. Воздержались 6 пользователей.