Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
SpinalHDL
https://github.com/spinalhdl/spinaldoc-rtd
Admin
The sources of the online SpinalHDL doc
Tokens:
263,785
Snippets:
1,759
Trust Score:
9.4
License:
CC0-1.0
Update:
6 months ago
Context
Chat
Benchmark
66.33
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Basic Simulation Example Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/bootstraps.rst Demonstrates a simple identity component testbench showing basic simulation setup, input application, output reading, and assertion checking. ```APIDOC ## Basic Simulation Example ### Description Simple testbench for an Identity component that passes input bits directly to output. ### Hardware Component ```scala import spinal.core._ class Identity(n: Int) extends Component { val io = new Bundle { val a = in Bits(n bits) val z = out Bits(n bits) } io.z := io.a } ``` ### Testbench Code ```scala import spinal.core.sim._ object TestIdentity extends App { // Use the component with n = 3 bits as "dut" (device under test) SimConfig.withWave.compile(new Identity(3)).doSim{ dut => // For each number from 3'b000 to 3'b111 included for (a <- 0 to 7) { // Apply input dut.io.a #= a // Wait for a simulation time unit sleep(1) // Read output val z = dut.io.z.toInt // Check result assert(z == a, s"Got $z, expected $a") } } } ``` ### Key Operations - **Apply Input**: `dut.io.a #= value` - Assign value to input signal - **Wait**: `sleep(cycles)` - Wait for simulation time units - **Read Output**: `dut.io.z.toInt` - Convert output to integer - **Assert**: `assert(condition, message)` - Verify expected behavior ``` -------------------------------- ### Install Verilator on Windows from source via MSYS2 MinGW Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/install/Verilator.rst This script provides a detailed guide for compiling and installing Verilator from its source code within the MSYS2 MinGW 64-bit environment on Windows. It covers installing prerequisites, cloning the Verilator repository, configuring, compiling, and installing. Special attention is given to setting environment variables and copying `FlexLexer.h` to ensure a successful build. Remember to manually add the MSYS2 paths to your Windows PATH environment variable after installation. ```sh pacman -Syuu # Close the MSYS2 shell once you're asked to pacman -Syuu pacman -S --needed base-devel mingw-w64-x86_64-toolchain \ git flex\ mingw-w64-x86_64-cmake git clone https://github.com/verilator/verilator.git unset VERILATOR_ROOT cd verilator git pull git checkout v4.218 # Can use newer v4.228 and v5.xxx autoconf ./configure export CPLUS_INCLUDE_PATH=/usr/include:$CPLUS_INCLUDE_PATH export PATH=/usr/bin/core_perl:$PATH cp /usr/include/FlexLexer.h ./src make -j$(nproc) make install echo "DONE" # Add C:\\msys64\\usr\\bin;C:\\msys64\\mingw64\\bin to your Windows PATH ``` -------------------------------- ### Install Verilator on Linux from source Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/install/Verilator.rst This script outlines the complete process for installing Verilator on a Linux system. It covers installing initial prerequisites, cloning the Verilator repository, checking out a recommended version (v4.218), and compiling the software from its source code using standard build tools. ```sh sudo apt-get install git make autoconf g++ flex bison # First time prerequisites git clone https://github.com/verilator/verilator.git # Only first time unsetenv VERILATOR_ROOT # For csh; ignore error if on bash unset VERILATOR_ROOT # For bash cd verilator git pull # Make sure we're up-to-date git checkout v4.218 # Can use newer v4.228 and v5.xxx autoconf # Create ./configure script ./configure make -j$(nproc) sudo make install echo "DONE" ``` -------------------------------- ### macOS Installation - SBT Setup with Homebrew Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Install and setup.rst Installs Scala's interactive build tool (SBT) on macOS using Homebrew. This completes the basic SpinalHDL development environment setup after Java and jenv are configured. ```shell brew install sbt ``` -------------------------------- ### Linux Installation - Debian/Ubuntu Setup with Coursier Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Install and setup.rst Installs Java JDK 17, curl, git, and sets up Coursier for Scala and SBT installation on Debian/Ubuntu systems. Coursier automatically configures the Java environment and updates the PATH. This is the recommended installation method for Linux users. ```shell sudo apt-get update sudo apt-get install openjdk-17-jdk-headless curl git curl -fL "https://github.com/coursier/launchers/raw/master/cs-x86_64-pc-linux.gz" | gzip -d > cs chmod +x cs # should find the just installed jdk, agree to cs' questions for adding to your PATH ./cs setup source ~/.profile ``` -------------------------------- ### Linux Installation - C++ Toolchain and oss-cad-suite Setup Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Install and setup.rst Installs C++ build tools and downloads oss-cad-suite, which provides simulation tools (Verilator, iverilog, GHDL) and waveform viewer (Gtkwave). The environment must be sourced for each shell session to avoid interfering with system Python. Tested with version 2023-10-22. ```shell sudo apt-get install make gcc g++ zlib1g-dev curl -fLO <download link> tar xzf <file that you downloaded> ``` -------------------------------- ### CONFIG SimConfig.withVCSSimSetup Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/install/VCS.rst Define custom environment setup files and pre-analysis execution blocks for VCS simulations. ```APIDOC ## CONFIG SimConfig.withVCSSimSetup ### Description Copies a user-defined synopsys_sim.setup file to the workspace and executes a provided code block before the VCS analysis step begins. ### Method CONFIG ### Endpoint SimConfig.withVCSSimSetup(setupFile, beforeAnalysis) ### Parameters #### Request Body - **setupFile** (String) - Required - The file path to the synopsys_sim.setup configuration. - **beforeAnalysis** (Function) - Optional - A Scala code block or script to execute immediately before VCS analysis. ### Request Example { "setupFile": "~/work/myproj/sim/synopsys_sim.setup", "beforeAnalysis": "() => { println(\"Hello, VCS\") }" } ### Response #### Success Response (200) - **status** (Unit) - Setup file is copied and hook is registered. ``` -------------------------------- ### GET /flow/example-code Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/flow.rst Provides a Scala code example demonstrating the usage of the SpinalHDL Flow interface. ```scala case class FlowExample() { // Placeholder for actual Scala code from /../examples/src/main/scala/spinaldoc/libraries/flow/FlowExample.scala // This would contain an example of how to use the Flow interface. // For instance: // val flowIn = Flow(UInt(8 bits)) // val flowOut = Flow(UInt(8 bits)) // flowOut << flowIn.m2sPipe() // val myReg = flowIn.toReg() // flowIn.push(U(42, 8 bits)) } ``` -------------------------------- ### BitVector Declaration Examples Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Developers area/types.rst Practical examples demonstrating various ways to declare and initialize BitVector types (Bits, UInt, SInt) with different bases, widths, and element specifications. ```APIDOC ## BitVector Declaration Examples ### Usage Examples ```scala val myUInt = UInt(8 bits) myUInt := U(2,8 bits) myUInt := U(2) myUInt := U"0000_0101" // Base per default is binary => 5 myUInt := U"h1A" // Base could be x (base 16) // h (base 16) // d (base 10) // o (base 8) // b (base 2) myUInt := U"8'h1A" myUInt := 2 // You can use scala Int as literal value ``` ### Literal Formats #### Base Specifiers - `b` - Binary (base 2) - `o` - Octal (base 8) - `d` - Decimal (base 10) - `h` or `x` - Hexadecimal (base 16) - Default (no specifier) - Binary #### Width Specification - Format: `[size']base]value` - Example: `U"8'h1A"` - 8-bit unsigned value in hexadecimal - Underscores can be used for readability: `U"0000_0101"` #### Direct Scala Integration - Scala Int values can be used directly as literals - Example: `myUInt := 2` ``` -------------------------------- ### Advanced Configuration Example Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/bootstraps.rst Demonstrates comprehensive simulation configuration with custom SpinalConfig, wave capture, optimizations, and workspace settings. ```APIDOC ## Advanced Simulation Configuration ### Description Complete example showing multiple SimConfig options including custom SpinalConfig, wave capture, optimizations, and workspace path. ### Configuration Template ```scala val spinalConfig = SpinalConfig(defaultClockDomainFrequency = FixedFrequency(10 MHz)) SimConfig .withConfig(spinalConfig) .withWave .allOptimisation .workspacePath("~/tmp") .compile(new TopLevel) .doSim { dut => SimTimeout(1000) // Simulation code here } ``` ### Configuration Breakdown - **SpinalConfig**: Sets default clock frequency to 10 MHz - **withConfig()**: Applies custom SpinalConfig to hardware generation - **withWave**: Enables wave capture in default format - **allOptimisation**: Enables all RTL optimizations - **workspacePath()**: Sets output directory to ~/tmp - **SimTimeout()**: Limits simulation to 1000 cycles ### TopLevel Component ```scala class TopLevel extends Component { val counter = out(Reg(UInt(8 bits)) init (0)) counter := counter + 1 } ``` ``` -------------------------------- ### macOS Installation - Java 17 Setup with Homebrew Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Install and setup.rst Installs Java 17 (LTS) on macOS using Homebrew and adds it to the system PATH. Java 17 is required for compatibility with Scala 2.12.16 used in SpinalTemplateSbt, as Java 21 is not supported. This setup is necessary before installing Scala and SBT. ```shell brew install openjdk@17 export PATH="/opt/homebrew/opt/openjdk@17/bin:$PATH" ``` -------------------------------- ### APB3 Usage Example Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Examples/Simple ones/apb3.rst Demonstrates how to instantiate the APB3 configuration and use the APB3 bundle as a slave interface within a hardware component. ```scala val config = Apb3Config( addressWidth = 12, dataWidth = 32, selWidth = 1 ) val io = new Bundle { val bus = slave(Apb3(config)) } ``` -------------------------------- ### Start SBT Interactive Shell Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/SBT.rst Launch SBT in interactive mode to access the SBT prompt. This mode supports autocompletion and avoids repeated boot time overhead. Can be started with 'sbt shell' or 'sbt' with no arguments. ```shell sbt ``` -------------------------------- ### Bit Assignment Examples Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Developers area/types.rst Demonstrates various ways to assign values to `myUInt` using bitfield specifications and default values. ```APIDOC ## Bit Assignment Examples ### Description This section illustrates how to assign values to `myUInt` using different bitfield specifications, including setting specific bits, ranges, and using default values. ### Usage Examples ```scala val myBool := myUInt === U(7 -> true,(6 downto 0) -> false) val myBool := myUInt === U(myUInt.range -> true) // For assignment purposes, you can omit the B/U/S, which also alow the use of the [default -> ???] feature myUInt := (default -> true) // Assign myUInt with "11111111" myUInt := (myUInt.range -> true) // Assign myUInt with "11111111" myUInt := (7 -> true,default -> false) // Assign myUInt with "10000000" myUInt := ((4 downto 1) -> true,default -> false) // Assign myUInt with "00011110" ``` ``` -------------------------------- ### Bits Declaration and Initialization Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Data types/bits.rst Examples demonstrating how to declare and initialize "Bits" variables with different widths and values in SpinalHDL. ```APIDOC ## Bits Declaration and Initialization ### Description This section details the various ways to declare and initialize `Bits` variables in SpinalHDL, including inferred width, explicit width, and initialization with specific values and bases. ### Method N/A (Declaration/Initialization) ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example N/A ### Response N/A ### Declaration Syntax - **Bits [()]**: Create Bits, bit count is inferred from the widest assignment statement after construction. - **Bits(x bits)**: Create Bits with x bits. - **B(value: Int[, x bits]) / B(value: BigInt[, x bits])**: Create Bits with x bits assigned with 'value'. - **B"[[size']base]value"**: Create Bits assigned with 'value' (base: 'h', 'd', 'o', 'b'). - **B([x bits,] elements: Element*)**: Create Bits assigned with the value specified by elements. ### Code Example (Scala) ```scala val myBits1 = Bits(32 bits) val myBits2 = B(25, 8 bits) val myBits3 = B"8'xFF" // Base could be x,h (base 16) // d (base 10) // o (base 8) // b (base 2) val myBits4 = B"1001_0011" // _ can be used for readability // Bits with all ones ("11111111") val myBits5 = B(8 bits, default -> True) // initialize with "10111000" through a few elements val myBits6 = B(8 bits, (7 downto 5) -> B"101", 4 -> true, 3 -> True, default -> false) // "10000000" (For assignment purposes, you can omit the B) val myBits7 = Bits(8 bits) myBits7 := (7 -> true, default -> false) // Width inference example val myBits = Bits() // the size is inferred from the widest assignment // .... // .resized needed to prevent WIDTH MISMATCH error as the constants // width does not match size that is inferred from assignment below myBits := B("1010").resized // auto-widen Bits(4 bits) to Bits(6 bits) when(condxMaybe) { // Bits(6 bits) is inferred for myBits, this is the widest assignment myBits := B("110000") } ``` ``` -------------------------------- ### Demonstrate SimpleJtagTap Component in SpinalHDL Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Examples/Advanced ones/jtag.rst A complete example showing how to use the custom JTAG instructions and wrappers to create an application-specific JTAG TAP. ```scala class SimpleJtagTap extends Component { // Application specific JTAG TAP implementation // Instantiates instructions without manual logic or interconnections } ``` -------------------------------- ### Custom ClockDomain Configuration Example Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Structuring/clock_domain.rst Illustrates how to create a ClockDomain with a custom ClockDomainConfig to specify clock edge, reset kind, and active levels, and then apply it to a ClockingArea. ```APIDOC ## ClockDomain(..., config: ClockDomainConfig) ### Description Illustrates how to create a ClockDomain with a custom ClockDomainConfig to specify clock edge, reset kind, and active levels, and then apply it to a ClockingArea. ### Method SpinalHDL Construct ### Endpoint ClockDomain(clock: Bool, reset: Bool, config: ClockDomainConfig) ### Parameters #### Path Parameters - No path parameters. #### Query Parameters - No query parameters. #### Request Body - **clock** (Bool) - Required - The clock signal. - **reset** (Bool) - Required - The reset signal. - **config** (ClockDomainConfig) - Required - A ClockDomainConfig object specifying custom settings. ### Request Example ```scala class CustomClockExample extends Component { val io = new Bundle { val clk = in Bool() val resetn = in Bool() val result = out UInt (4 bits) } // Configure the clock domain val myClockDomain = ClockDomain( clock = io.clk, reset = io.resetn, config = ClockDomainConfig( clockEdge = RISING, resetKind = ASYNC, resetActiveLevel = LOW ) ) // Define an Area which use myClockDomain val myArea = new ClockingArea(myClockDomain) { val myReg = Reg(UInt(4 bits)) init(7) myReg := myReg + 1 io.result := myReg } } ``` ### Response #### Success Response (N/A) - Defines a design area with the custom configured clock domain. #### Response Example No direct response body. ``` -------------------------------- ### Instantiate and Use Scala Classes Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Scala Guide/basics.rst Demonstrates class instantiation using the new keyword and calling instance methods. Shows how to create a Color instance and invoke its getGrayLevel method. ```Scala val blue = new Color(0, 0, 1) val grayLevelOfBlue = blue.getGrayLevel() ``` -------------------------------- ### Configure VCS Simulation with Custom Setup File and Pre-Analysis Script (Scala) Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/install/VCS.rst This Scala code demonstrates how to configure a VCS simulation using SimConfig.withVCS and withVCSSimSetup. It specifies a custom synopsys_sim.setup file and includes a beforeAnalysis code block that executes shell commands and prints messages before the VCS analysis step begins. ```scala val simConfig = SimConfig .withVCS .withVCSSimSetup( setupFile = "~/work/myproj/sim/synopsys_sim.setup", beforeAnalysis = () => { // this code block will be run before VCS analysis step. "pwd".! println("Hello, VCS") } ) ``` -------------------------------- ### GET /flow/simulation-code Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/flow.rst Provides a Scala code example demonstrating the usage of Flow simulation support classes. -------------------------------- ### MSYS2 Package Installation and Verilator Setup Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Install and setup.rst Shell script for installing development tools and Verilator 4.228 on Windows via MSYS2. Installs base development tools, MinGW-w64 toolchain, Iverilog, GHDL, Git, and downloads/installs Verilator package. Run commands sequentially in MSYS2 MINGW64 terminal. ```shell pacman -Syuu # will (request) close down terminal # open 'MSYS2 MINGW64' from start menu pacman -Syuu pacman -S --needed base-devel mingw-w64-x86_64-toolchain mingw-w64-x86_64-iverilog mingw-w64-x86_64-ghdl-llvm git curl -O https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-verilator-4.228-1-any.pkg.tar.zst pacman -U mingw-w64-x86_64-verilator-4.228-1-any.pkg.tar.zst ``` -------------------------------- ### Configure Instant Entry State (SpinalHDL) Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/fsm.rst This example shows how to use `makeInstantEntry()` to define an entry state (`IDLE`) that becomes active immediately after reset, bypassing the default boot state. This allows for direct entry into a user-defined state, though `onEntry` for this state will only be called on subsequent transitions. ```scala // State sequence: IDLE, STATE_A, STATE_B, ... val fsm = new StateMachine { // IDLE is named BOOT in simulation val IDLE = makeInstantEntry() val STATE_A, STATE_B, STATE_C = new State IDLE.whenIsActive(goto(STATE_A)) STATE_A.whenIsActive(goto(STATE_B)) STATE_B.whenIsActive(goto(STATE_C)) STATE_C.whenIsActive(goto(STATE_B)) } ``` -------------------------------- ### Build SpinalDoc documentation using Make Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/README.rst This snippet provides commands to build the SpinalDoc documentation into various formats (HTML, LaTeX, PDF) using `make`. It also shows how to list all available output formats. This applies to both `venv` and native setups. ```shell make html make latex make latexpdf make ``` -------------------------------- ### FUNCTION / Entry Point Configuration Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/fsm.rst Methods to define the initial state of the FSM, including options for instant entry to bypass the default boot state. ```APIDOC ## FUNCTION Entry Management ### Description Configures how the FSM starts after reset. makeInstantEntry bypasses the default BOOT state to make a user state active immediately. ### Method Function ### Endpoint makeInstantEntry() / setEntry(state) ### Parameters #### Path Parameters - **state** (State) - Required (for setEntry) - The state to be used as the entry point. ### Request Example val fsm = new StateMachine { val IDLE = makeInstantEntry() val STATE_A = new State IDLE.whenIsActive(goto(STATE_A)) } ``` -------------------------------- ### OHMasking.roundRobin Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/utils.rst Apply a mask on x to only keep the bit set from requests. it start looking in requests from the ohPriority position. For example if requests is "1001" and ohPriority is "0010", the roundRobin function will start looking in requests from its second bit and will return "1000". ```APIDOC ## State less utilities: OHMasking.roundRobin ### Description Apply a mask on `x` to only keep the bit set from `requests`. It starts looking in `requests` from the `ohPriority` position. For example if `requests` is "1001" and `ohPriority` is "0010", the `roundRobin` function will start looking in `requests` from its second bit and will return "1000". ### Parameters - **requests** (Bits) - Required - The bit vector representing requests. - **ohPriority** (Bits) - Required - The one-hot encoded priority indicating where to start looking. ### Return Value - **Bits** - A masked bit vector based on requests and priority. ``` -------------------------------- ### Example Verilog HDL Attributes for RAM Style Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Sequential logic/memory.rst This Verilog code snippet illustrates how HDL attributes might be generated and applied to memory components when `SpinalConfig#setDevice(Device)` is configured in SpinalHDL. These attributes, such as `ram_style` and `ramsyle`, are crucial for guiding synthesis tools to implement memories using specific hardware resources like distributed RAM or block RAM, and to control read-write behavior. ```Verilog (* ram_style = "distributed" *) (* ramsyle = "no_rw_check" *) ``` -------------------------------- ### Signal Instantiation and Cloning Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Scala Guide/interaction.rst Shows how to create a new signal instance from a Bundle and how to use the cloneOf function to create a signal with the same hardware type configuration. ```scala // Define an Rgb signal val myRgbSignal = Rgb(5, 6, 5) // Define another Rgb signal of the same data type as the preceding one val myRgbCloned = cloneOf(myRgbSignal) ``` -------------------------------- ### macOS Installation - jenv Configuration for Multiple Java Versions Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Install and setup.rst Installs jenv on macOS to manage multiple Java versions and configures shell environment variables. These lines are automatically added to .bash_profile by jenv during installation, enabling seamless switching between Java versions. ```shell brew install jenv export PATH="$HOME/.jenv/bin:$PATH" eval "$(jenv init -)" ``` -------------------------------- ### Install Verilator on Windows via MSYS2 MinGW package manager Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/install/Verilator.rst Execute these commands within the MSYS2 MinGW 64-bit shell to install Verilator and its dependencies using the `pacman` package manager. This includes updating the system, installing essential development tools, and directly installing a specific Verilator package. Remember to manually add the MSYS2 paths to your Windows PATH environment variable after completion. ```sh pacman -Syuu # Close the MSYS2 shell once you're asked to pacman -Syuu pacman -S --needed base-devel mingw-w64-x86_64-toolchain \ git flex\ mingw-w64-x86_64-cmake pacman -U http://repo.msys2.org/mingw/x86_64/mingw-w64-x86_64-verilator-4.032-1-any.pkg.tar.xz # Add C:\\msys64\\usr\\bin;C:\\msys64\\mingw64\\bin to your Windows PATH ``` -------------------------------- ### Configure a SpinalHDL simulation with multiple options Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/bootstraps.rst This example demonstrates how to apply various `SimConfig` options to a simulation. It sets a custom `SpinalConfig` with a fixed clock frequency, enables waveform capture, applies all RTL optimizations, specifies a custom workspace path, compiles a `TopLevel` component, and runs the simulation with a timeout. ```scala val spinalConfig = SpinalConfig(defaultClockDomainFrequency = FixedFrequency(10 MHz)) SimConfig .withConfig(spinalConfig) .withWave .allOptimisation .workspacePath("~/tmp") .compile(new TopLevel) .doSim { dut => SimTimeout(1000) // Simulation code here } ``` -------------------------------- ### Run Docker to build SpinalDoc documentation Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/README.rst This snippet shows how to run the previously built Docker image to compile the SpinalDoc documentation. It mounts the current directory into the container to access the source files and output the built documentation. ```shell docker run -it --rm -v $PWD:/docs spinaldoc-rtd ``` -------------------------------- ### Parameterize Components using Scala Constructors Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Structuring/components_hierarchy.rst Illustrates how to create generic hardware by passing parameters to the component constructor. It also demonstrates using Scala case classes to manage complex configuration sets for a System-on-Chip (SoC). ```scala class MyAdder(width: BitCount) extends Component { val io = new Bundle { val a, b = in port UInt(width) val result = out port UInt(width) } io.result := io.a + io.b } case class MySocConfig(axiFrequency : HertzNumber, onChipRamSize : BigInt, cpu : RiscCoreConfig, iCache : InstructionCacheConfig) class MySoc(config: MySocConfig) extends Component { // Component logic using config parameters } ``` -------------------------------- ### Define Color Bundle Example Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Data types/bundle.rst A practical example of a Bundle representing an RGB color with a parameterized channel width using UInt signals. ```scala case class Color(channelWidth: Int) extends Bundle { val r, g, b = UInt(channelWidth bits) } ``` -------------------------------- ### Install SpinalHDL Dependencies on MINGW Windows Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Install and setup.rst Installs required packages for SpinalHDL development on Windows using MINGW including Z3, Yices, autotools, and Python3 with pip. Downloads and installs Yosys and SBY tools from GitHub releases. These packages provide the necessary hardware synthesis and verification tools. ```bash pacman -S mingw-w64-x86_64-z3 mingw-w64-x86_64-yices mingw-w64-x86_64-autotools mingw-w64-x86_64-python3-pip python3 -m pip install click curl -OL https://github.com/Readon/MINGW-SpinalHDL/releases/download/v0.4.9/mingw-w64-x86_64-yosys-0.31-1-any.pkg.tar.zst curl -OL https://github.com/Readon/MINGW-SpinalHDL/releases/download/v0.4.9/mingw-w64-x86_64-python-sby-0.31-1-any.pkg.tar.zst pacman -U *-yosys-*.pkg.tar.* pacman -U *-python-sby-*.pkg.tar* ``` -------------------------------- ### VHDL Component Instantiation with Port Mapping Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Help for VHDL people/vhdl_comp.rst Illustrates VHDL's verbose component instantiation pattern requiring explicit signal declarations for all sub-component ports and manual one-by-one binding. This example shows an UnsignedDivider component with command and response interfaces, demonstrating the repetitive nature of VHDL port mapping. ```vhdl divider_cmd_valid : in std_logic; divider_cmd_ready : out std_logic; divider_cmd_numerator : in unsigned(31 downto 0); divider_cmd_denominator : in unsigned(31 downto 0); divider_rsp_valid : out std_logic; divider_rsp_ready : in std_logic; divider_rsp_quotient : out unsigned(31 downto 0); divider_rsp_remainder : out unsigned(31 downto 0); divider : entity work.UnsignedDivider port map ( clk => clk, reset => reset, cmd_valid => divider_cmd_valid, cmd_ready => divider_cmd_ready, cmd_numerator => divider_cmd_numerator, cmd_denominator => divider_cmd_denominator, rsp_valid => divider_rsp_valid, rsp_ready => divider_rsp_ready, rsp_quotient => divider_rsp_quotient, rsp_remainder => divider_rsp_remainder ); ``` -------------------------------- ### Install GHDL from source on Linux Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/install/GHDL.rst Commands to install build dependencies (libboost-dev, gnat), clone the GHDL repository, and compile the source code on Debian-based systems. ```sh sudo apt-get install build-essential libboost-dev git sudo apt-get install gnat # Ada compiler used to buid GHDL git clone https://github.com/ghdl/ghdl.git cd ghdl mkdir build cd build ../configure make sudo make install ``` -------------------------------- ### Define a Basic Class and Instantiate in Scala Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Scala Guide/basics.rst Demonstrates the definition of a simple class 'Color' with constructor parameters and how to create an instance of it. It also shows accessing a member variable. ```scala class Color(val r: Float, val g: Float, val b: Float) { ... } val blue = new Color(0, 0, 1) val redLevelOfBlue = blue.r ``` -------------------------------- ### Handshake Logic Assertion Example Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Other language features/assertion.rst A practical example of a hardware assertion used to verify that a 'valid' signal does not transition from high to low while 'ready' is low in a handshake protocol. ```scala class TopLevel extends Component { val valid = RegInit(False) val ready = in Bool() when(ready) { valid := False } // some logic assert( assertion = !(valid.fall && !ready), message = "Valid dropped when ready was low", severity = ERROR ) } ``` -------------------------------- ### Defining Plugin Execution Phases Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/Misc/service_plugin.rst Demonstrates how to define a FiberPlugin with distinct setup and build phases. The setup phase allows for interlocking, while the build phase handles hardware elaboration. ```scala class MyPlugin extends FiberPlugin { val logic = during setup new Area { // Here we are executing code in the setup phase awaitBuild() // Here we are executing code in the build phase } } class MyPlugin2 extends FiberPlugin { val logic = during build new Area { // Here we are executing code in the build phase } } ``` -------------------------------- ### Run Docker to build SpinalDoc PDF documentation Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/README.rst This snippet shows how to execute the Docker image designed for PDF builds. It runs the container, mounts the current directory, and compiles the documentation into PDF format. ```shell docker run -it --rm -v $PWD:/docs spinaldoc-pdf ``` -------------------------------- ### Clone and Initialize SpinalHDL Template Project Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Install and setup.rst Clones the SpinalTemplateSbt repository with shallow history, removes the original git history, and initializes a new git repository for a fresh SpinalHDL project. Creates a new directory named MySpinalProject with all necessary build configuration files and project structure. ```bash git clone --depth 1 https://github.com/SpinalHDL/SpinalTemplateSbt.git MySpinalProject cd MySpinalProject rm -rf .git git init git add . git commit -m "Initial commit from template" ``` -------------------------------- ### Install Icarus Verilog and Dependencies on Linux Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Simulation/install/Icarus Verilog.rst Uses the apt package manager to install build-essential, libboost-dev, and iverilog. These packages are necessary for compiling and simulating hardware designs with SpinalHDL using Icarus Verilog. ```sh sudo apt-get install build-essential libboost-dev iverilog ``` -------------------------------- ### RISC-V Core Configuration with Plugin Extensions Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/Help for VHDL people/vhdl_comp.rst Illustrates SpinalHDL's object-oriented configuration pattern for complex hardware designs. Creates a CoreConfig object with multiple parameters and demonstrates the plugin system for adding extensions (MulExtension, DivExtension, BarrelShifterFullExtension) without modifying core implementation. Also shows instruction cache configuration and RiscvCoreAxi4 instantiation. ```scala val coreConfig = CoreConfig( pcWidth = 32, addrWidth = 32, startAddress = 0x00000000, regFileReadyKind = sync, branchPrediction = dynamic, bypassExecute0 = true, bypassExecute1 = true, bypassWriteBack = true, bypassWriteBackBuffer = true, collapseBubble = false, fastFetchCmdPcCalculation = true, dynamicBranchPredictorCacheSizeLog2 = 7 ) // The CPU has a system of plugins which allows adding new features into the core. // Those extensions are not directly implemented in the core, but are kind of an additive logic patch defined in a separate area. coreConfig.add(new MulExtension) coreConfig.add(new DivExtension) coreConfig.add(new BarrelShifterFullExtension) val iCacheConfig = InstructionCacheConfig( cacheSize = 4096, bytePerLine = 32, wayCount = 1, // Can only be one for the moment wrappedMemAccess = true, addressWidth = 32, cpuDataWidth = 32, memDataWidth = 32 ) new RiscvCoreAxi4( coreConfig = coreConfig, iCacheConfig = iCacheConfig, dCacheConfig = null, debug = debug, interruptCount = interruptCount ) ``` -------------------------------- ### Output of getMemoryTransfers for Example SoC Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/Bus/tilelink/tilelink_fabric.rst This block displays the expected console output when running the `getMemoryTransfers` tool on the example SoC configuration. It illustrates how memory mappings and transfer capabilities are reported for connected components, including address transformations. ```text - toplevel/ram_up mapped=SM(0x10000, 0x200) through=List(OT(0x10000)) -> GF - toplevel/peripherals_gpioA_up mapped=SM(0x20000, 0x1000) through=List(OT(0x20000), OT(0x0)) -> GF - toplevel/peripherals_gpioB_up mapped=SM(0x21000, 0x1000) through=List(OT(0x20000), OT(0x1000)) -> GF ``` -------------------------------- ### Watch Mode Execution Output Example Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Getting Started/SBT.rst Example output from running watch mode with SpinalHDL code generation. Shows SpinalHDL version, JVM memory allocation, compilation progress stages (Elaborate, Checks, Generate), and monitoring status for automatic re-execution. ```shell sbt:SpinalTemplateSbt> ~ runMain mylib.MyTopLevelVerilog [info] running (fork) mylib.MyTopLevelVerilog [info] [Runtime] SpinalHDL v1.7.3 git head : aeaeece704fe43c766e0d36a93f2ecbb8a9f2003 [info] [Runtime] JVM max memory : 3968,0MiB [info] [Runtime] Current date : 2022.11.17 21:35:10 [info] running (fork) projectname.MyTopLevelVerilog [info] [Runtime] SpinalHDL v1.9.3 git head : 029104c77a54c53f1edda327a3bea333f7d65fd9 [info] [Runtime] JVM max memory : 4096.0MiB [info] [Runtime] Current date : 2023.10.05 19:30:19 [info] [Progress] at 0.000 : Elaborate components [info] [Progress] at 0.508 : Checks and transforms [info] [Progress] at 0.560 : Generate Verilog [info] [Done] at 0.603 [success] Total time: 1 s, completed Oct 5, 2023, 7:30:19 PM [info] 1. Monitoring source files for projectname/runMain projectname.MyTopLevelVerilog... [info] Press <enter> to interrupt or '?' for more options. ``` -------------------------------- ### Generated Verilog for SpinalHDL Plugin Example Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/Misc/service_plugin.rst This Verilog code is the hardware output generated by the SpinalHDL Scala example. It shows the `TopLevel` and `SubComponent` modules. The `StatePlugin_logic_signal` in `SubComponent` is incremented by 2, which is a direct result of having two `SetupPlugin` instances in the Scala code, each contributing an increment of 1. ```verilog module TopLevel ( input wire clk, input wire reset ); SubComponent sub ( .clk (clk ), // i .reset (reset) // i ); endmodule module SubComponent ( input wire clk, input wire reset ); reg [31:0] StatePlugin_logic_signal; always @(posedge clk) begin // + 2 as we have two SetupPlugin StatePlugin_logic_signal <= (StatePlugin_logic_signal + 32'h00000002); end endmodule ``` -------------------------------- ### Example Usage of ReadableOpenDrain Bundle in SpinalHDL Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/IO/readableOpenDrain.rst This example demonstrates how to instantiate and use the `ReadableOpenDrain` bundle within a SpinalHDL design. It shows how to declare a master `dataBus` of type `ReadableOpenDrain` with 32-bit data, assign a value to its `write` signal, and conditionally check the value of its `read` signal. ```scala val io = new Bundle { val dataBus = master(ReadableOpenDrain(Bits(32 bits))) } io.dataBus.write := 0x12345678 when(io.dataBus.read === 42) { } ``` -------------------------------- ### GET /core/utils/isPow2 Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/miscelenea/core/core_components.rst Checks if a given BigInt value is a power of two. ```APIDOC ## GET /core/utils/isPow2 ### Description Utility function to determine if a value is a power of two, useful for memory alignment and bus sizing. ### Method GET ### Endpoint /core/utils/isPow2 ### Parameters #### Path Parameters - **x** (BigInt) - Required - The value to check. ### Response #### Success Response (200) - **result** (Boolean) - True if x is a power of two. ### Response Example { "result": true } ``` -------------------------------- ### Create and Instantiate Axi4 Bus Configuration Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/Bus/amba4/axi4.rst Demonstrates how to create an Axi4Config object with specified address width, data width, and ID width, then instantiate two Axi4 bus instances with the same configuration. Shows basic usage pattern for accessing bus signals like the aw.valid flag. ```Scala val axiConfig = Axi4Config( addressWidth = 32, dataWidth = 32, idWidth = 4 ) val axiX = Axi4(axiConfig) val axiY = Axi4(axiConfig) when(axiY.aw.valid) { // ... } ``` -------------------------------- ### GET /register/FRAME Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/Com/usb_device.rst Read the current USB frame identifier from the controller. ```APIDOC ## GET /register/FRAME ### Description Returns the current USB frame ID as tracked by the hardware controller. ### Method GET (Read-Only) ### Endpoint 0xFF00 ### Parameters #### Response Body - **usbFrameId** (uint32) - Required - Current USB frame ID (Bits 31-0). ### Request Example N/A (Memory-mapped read) ### Response #### Success Response (200) - **usbFrameId** (uint32) - The 32-bit frame identifier. #### Response Example { "usbFrameId": 1024 } ``` -------------------------------- ### Initialize USB Device Controller in SpinalHDL Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/Com/usb_device.rst This snippet demonstrates how to define a top-level component for a USB device. It configures the controller and PHY with specific clock domains, sets up BMB bus parameters, and exports the necessary I/O ports for external connectivity. ```scala import spinal.core._ import spinal.core.sim._ import spinal.lib.bus.bmb.BmbParameter import spinal.lib.com.usb.phy.UsbDevicePhyNative import spinal.lib.com.usb.sim.UsbLsFsPhyAbstractIoAgent import spinal.lib.com.usb.udc.{UsbDeviceCtrl, UsbDeviceCtrlParameter} case class UsbDeviceTop() extends Component { val ctrlCd = ClockDomain.external("ctrlCd", frequency = FixedFrequency(100 MHz)) val phyCd = ClockDomain.external("phyCd", frequency = FixedFrequency(48 MHz)) val ctrl = ctrlCd on new UsbDeviceCtrl( p = UsbDeviceCtrlParameter( addressWidth = 14 ), bmbParameter = BmbParameter( addressWidth = UsbDeviceCtrl.ctrlAddressWidth, dataWidth = 32, sourceWidth = 0, contextWidth = 0, lengthWidth = 2 ) ) val phy = phyCd on new UsbDevicePhyNative(sim = true) ctrl.io.phy.cc(ctrlCd, phyCd) <> phy.io.ctrl val bmb = ctrl.io.ctrl.toIo() val usb = phy.io.usb.toIo() val power = phy.io.power.toIo() val pullup = phy.io.pullup.toIo() val interrupts = ctrl.io.interrupt.toIo() } object UsbDeviceGen extends App { SpinalVerilog(new UsbDeviceTop()) } ``` -------------------------------- ### CountLeadingZeroes(x : Bits) Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Libraries/utils.rst Return the number of consecutive zero bits starting from the MSB ```APIDOC ## State less utilities: CountLeadingZeroes ### Description Return the number of consecutive zero bits starting from the MSB ### Parameters - **x** (Bits) - Required - The bit vector to count leading zeroes from. ### Return Value - **UInt** - The count of consecutive zero bits from the MSB. ``` -------------------------------- ### GET /core/utils/log2Up Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/miscelenea/core/core_components.rst Calculates the number of bits required to represent a specific number of states. ```APIDOC ## GET /core/utils/log2Up ### Description Returns the number of bits needed to represent a specific number of states (x). ### Method GET ### Endpoint /core/utils/log2Up ### Parameters #### Path Parameters - **x** (BigInt) - Required - The number of states to represent. ### Response #### Success Response (200) - **result** (Int) - The number of bits needed. ### Response Example { "result": 8 } ``` -------------------------------- ### Configure and Instantiate RISC-V CPU in SpinalHDL Source: https://github.com/spinalhdl/spinaldoc-rtd/blob/master/source/SpinalHDL/Legacy/pinsec/hardware_toplevel.rst This snippet demonstrates how to configure a RISC-V CPU core with various parameters like PC width, address width, and branch prediction. It also shows how to add extensions (Mul, Div, BarrelShifter) and instantiate the CPU with instruction cache settings, resulting in a complete CPU instance. ```scala val coreConfig = CoreConfig( pcWidth = 32, addrWidth = 32, startAddress = 0x00000000, regFileReadyKind = sync, branchPrediction = dynamic, bypassExecute0 = true, bypassExecute1 = true, bypassWriteBack = true, bypassWriteBackBuffer = true, collapseBubble = false, fastFetchCmdPcCalculation = true, dynamicBranchPredictorCacheSizeLog2 = 7 ) // The CPU has a systems of plugin which allow to add new feature into the core. // Those extension are not directly implemented into the core, but are kind of additive logic patch defined in a separated area. coreConfig.add(new MulExtension) coreConfig.add(new DivExtension) coreConfig.add(new BarrelShifterFullExtension) val iCacheConfig = InstructionCacheConfig( cacheSize =4096, bytePerLine =32, wayCount = 1, // Can only be one for the moment wrappedMemAccess = true, addressWidth = 32, cpuDataWidth = 32, memDataWidth = 32 ) // There is the instantiation of the CPU by using all those construction parameters new RiscvAxi4( coreConfig = coreConfig, iCacheConfig = iCacheConfig, dCacheConfig = null, debug = true, interruptCount = 2 ) } ```