diff --git a/.dockerignore b/.dockerignore index 73a8918..4e1627f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,6 +1,7 @@ .git .gitignore *.md +!Install.md *.patch .ipynb_checkpoints **/.ipynb_checkpoints @@ -16,3 +17,11 @@ __pycache__ build/ target/ out/ +pyproject.toml +.scalafmt.conf +riscv/build +riscv/target +riscv/project/target +riscv/project/project +riscv/.bsp +riscv/solutions diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 54d141e..b65f1b1 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,3 +1,5 @@ +# Versions that Dependabot cannot see (the Dockerfile ENVs, `source/load-ivy.sc`, `binder/postBuild`, +# `Install.md` and `README.md`) are kept in agreement by `tools/check-versions.py` instead. version: 2 updates: # Keep the GitHub Actions used by the workflows current diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000..eac838b --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,41 @@ +name: Checks + +on: + push: + branches: [dev] + pull_request: + branches: [dev] + +concurrency: + group: checks-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + checks: + name: Versions, style and notebooks + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + - name: Pinned versions agree (and firtool matches Chisel) + run: python3 tools/check-versions.py + - name: Pre-commit hooks (notebook outputs, Python and shell style) + # the hooks and pinned versions of .pre-commit-config.yaml; fails if a hook would change a file + run: pipx run pre-commit run --all-files --show-diff-on-failure + - name: Scala style (scalafmt, version from .scalafmt.conf) + env: + # sha256 of scalafmt-linux-glibc for the version in .scalafmt.conf; update both together + SCALAFMT_SHA256: 4a29c3651f64fbaf9adcca01c6ac2ba0e8281a3d20e08c12b152582139fae290 + run: | + version=$(sed -n 's/^version *= *"\{0,1\}\([0-9.]*\).*/\1/p' .scalafmt.conf) + curl -fsSL --retry 3 -o "$RUNNER_TEMP/scalafmt" \ + "https://github.com/scalameta/scalafmt/releases/download/v$version/scalafmt-linux-glibc" + echo "$SCALAFMT_SHA256 $RUNNER_TEMP/scalafmt" | sha256sum -c - + chmod +x "$RUNNER_TEMP/scalafmt" + python3 tools/format-scala.py --check --scalafmt "$RUNNER_TEMP/scalafmt" + - name: Notebook lint (each rule is first checked against a seeded violation) + run: python3 tests/test_notebooks.py --self-test + - name: The imported riscv-tests match their pinned revision (expanded with the runner's cpp) + run: python3 tools/import-riscv-tests.py --check diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 11cffa7..9589d8b 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,28 +1,193 @@ name: Publish Docker image to DockerHub +# Which notebooks run (tools/ci-notebooks.py): +# - pull request: the smoke subset plus the changed notebooks when only notebooks or inert files +# (docs, images, tools, tests) change; every notebook otherwise. +# - push to dev, nightly and manual runs: every notebook. +# Each notebook runs in its own job, on amd64 and natively on Arm64, after one image build per +# architecture. Wall time, measured locally (64 cores, one container per notebook, all at once): +# the notebooks take 50 s (1_intro_to_scala) to 232 s (3.2_collections), so a run is about +# image build + 4 minutes when the runners are free. Each job adds its time to the run summary. + on: push: branches: [dev] pull_request: branches: [dev] + schedule: + - cron: "23 3 * * *" # nightly, catches breakage from moving parts such as base images + workflow_dispatch: # runs every test; publishing happens only on push concurrency: - group: docker-dev-${{ github.ref }} - cancel-in-progress: true + group: docker-${{ github.event_name }}-${{ github.ref }} + # A newer push to a pull request supersedes the older run. On dev a running publication is + # never cancelled, but GitHub keeps only the newest pending run per group, so a commit pushed + # while another run is pending is skipped (and gets no sha- tag). Each event has its own group, + # so a nightly run never cancels the publication of a push. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +env: + IMAGE: chisel-bootcamp:test + # Per-cell timeout of runtest.py in seconds (its default, stated here so that CI can tune it) + BOOTCAMP_CELL_TIMEOUT: "600" # https://docs.docker.com/build/ci/github-actions/multi-platform/ jobs: - docker: - name: Build Docker Image and Publish (only on push) + select: + name: Choose the tests runs-on: ubuntu-24.04 + outputs: + notebooks: ${{ steps.select.outputs.notebooks }} + riscv: ${{ steps.select.outputs.riscv }} + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 # to list the files a pull request changes + - id: select + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + riscv=true + if [ "$GITHUB_EVENT_NAME" = pull_request ]; then + changed=$(git diff --name-only "$BASE_SHA"...HEAD) + notebooks=$(echo "$changed" | python3 tools/ci-notebooks.py changed) + # the riscv/ tests depend only on riscv/ and the image + echo "$changed" | grep -qE '^(riscv/|source/load-(riscv|ivy)\.sc$|tools/check-solutions\.sh$|tests/(kernel|test_riscv_import)\.py$|Dockerfile$|\.dockerignore$|\.github/workflows/docker\.yml$)' || riscv=false + else + notebooks=$(python3 tools/ci-notebooks.py all) + fi + echo "notebooks=$notebooks" >> "$GITHUB_OUTPUT" + echo "riscv=$riscv" >> "$GITHUB_OUTPUT" + echo "Notebooks: $notebooks; riscv/ tests: $riscv" + + build: + name: Build the ${{ matrix.arch }} image + runs-on: ${{ matrix.runner }} permissions: contents: read - actions: write + actions: write # the gha build cache + strategy: + matrix: + include: + - { arch: amd64, runner: ubuntu-24.04 } + # The Arm64 image runs firtool (x86-64 only) under qemu-user; build and test it on a + # native Arm64 runner rather than trusting the cross-build. + - { arch: arm64, runner: ubuntu-24.04-arm } + steps: + - uses: actions/checkout@v7 + - uses: docker/setup-buildx-action@v4 + - name: Build image + uses: docker/build-push-action@v7 + with: + context: . + platforms: linux/${{ matrix.arch }} + tags: ${{ env.IMAGE }} + outputs: type=docker,dest=${{ runner.temp }}/image.tar + cache-from: type=gha,scope=build-${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=build-${{ matrix.arch }} + - name: Share the image with the notebook jobs + uses: actions/upload-artifact@v7 + with: + name: image-${{ matrix.arch }} + path: ${{ runner.temp }}/image.tar + retention-days: 1 + compression-level: 1 + - name: Visualizer and chiseltest-compatibility tests + if: matrix.arch == 'amd64' + run: | + docker load --input "$RUNNER_TEMP/image.tar" + docker run --rm --network none "$IMAGE" python3 tests/test_visualizer.py + docker run --rm --network none "$IMAGE" python3 tests/test_chiseltest_compat.py + + notebooks: + name: ${{ matrix.notebook }} (${{ matrix.arch }}) + needs: [select, build] + runs-on: ${{ matrix.runner }} + # Each notebook gets a fresh runner and kernel. The limit leaves room for slow runners and + # for firtool under qemu on Arm64. + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + arch: [amd64, arm64] + notebook: ${{ fromJSON(needs.select.outputs.notebooks) }} + include: # the runner of each architecture, as in the build job + - { arch: amd64, runner: ubuntu-24.04 } + - { arch: arm64, runner: ubuntu-24.04-arm } + steps: + - uses: actions/download-artifact@v8 + with: + name: image-${{ matrix.arch }} + path: ${{ runner.temp }} + - run: docker load --input "$RUNNER_TEMP/image.tar" + - name: Run the notebook (offline) + # The image bundles every dependency, so no network is needed. + env: + NOTEBOOK: ${{ matrix.notebook }} + run: | + start=$(date +%s) + docker run --rm --network none -e BOOTCAMP_CELL_TIMEOUT "$IMAGE" python3 runtest.py "$NOTEBOOK" + echo "$NOTEBOOK (${{ matrix.arch }}): $(( $(date +%s) - start )) s" >> "$GITHUB_STEP_SUMMARY" + riscv: + name: riscv/ tests (${{ matrix.arch }}) + needs: [select, build] + if: needs.select.outputs.riscv == 'true' + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - { arch: amd64, runner: ubuntu-24.04 } + - { arch: arm64, runner: ubuntu-24.04-arm } + steps: + - uses: actions/download-artifact@v8 + with: + name: image-${{ matrix.arch }} + path: ${{ runner.temp }} + - uses: actions/checkout@v7 # for riscv/solutions, which the image leaves out + - run: docker load --input "$RUNNER_TEMP/image.tar" + - name: The scaffold compiles and the solutions pass every test (offline) + run: | + docker run --rm --network none -v "$PWD/riscv/solutions:/solutions:ro" -e SOLUTIONS=/solutions \ + "$IMAGE" tools/check-solutions.sh + - name: Notebooks can use riscv/ (source/load-riscv.sc) + run: docker run --rm --network none "$IMAGE" python3 tests/test_riscv_import.py + + publish: + # Build every platform on pull requests too, so a platform-specific break fails before + # merge; only a push to dev publishes. + name: Build all platforms (publish only on push) + needs: [notebooks, riscv] + # riscv is skipped on pull requests that do not touch it; that must not skip publishing + if: >- + !cancelled() && github.event_name != 'schedule' && needs.notebooks.result == 'success' && + contains(fromJSON('["success", "skipped"]'), needs.riscv.result) + runs-on: ubuntu-24.04 + permissions: + contents: read + actions: write # the gha build cache steps: - name: Check out the repo uses: actions/checkout@v7 + - name: Image tags + id: tags + # latest, chisel- and sha- + run: | + chisel=$(python3 tools/check-versions.py --print chisel) + { + echo "tags<> "$GITHUB_OUTPUT" + - name: Set up QEMU uses: docker/setup-qemu-action@v4 @@ -36,31 +201,14 @@ jobs: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_ACCESS_TOKEN }} - - name: Build image for the smoke test (amd64) - uses: docker/build-push-action@v7 - with: - context: . - platforms: linux/amd64 - load: true - tags: chisel-bootcamp:test - cache-from: type=gha,scope=build - cache-to: type=gha,mode=max,scope=build - - - name: Run notebooks (smoke test, offline) - # The image bundles every dependency, so no network is needed. - run: | - docker run --rm --network none chisel-bootcamp:test \ - python3 runtest.py 0_demo.ipynb 2.1_first_module.ipynb 2.6_chiselsim.ipynb 4.1_firrtl_ast.ipynb - docker run --rm --network none chisel-bootcamp:test python3 tests/test_visualizer.py - - # Build every platform on pull requests too, so a platform-specific break (such as a - # package missing for Arm64) fails before merge; only a push to dev publishes. - - name: Build all platforms (push only on push) + - name: Build all platforms uses: docker/build-push-action@v7 with: context: . platforms: linux/amd64,linux/arm64 push: ${{ github.event_name == 'push' }} - tags: sysprog21/chisel-bootcamp:latest - cache-from: type=gha,scope=build - cache-to: type=gha,mode=max,scope=build + tags: ${{ steps.tags.outputs.tags }} + # reuse the layers of the tested per-architecture builds + cache-from: | + type=gha,scope=build-amd64 + type=gha,scope=build-arm64 diff --git a/.github/workflows/install.yml b/.github/workflows/install.yml new file mode 100644 index 0000000..65ab612 --- /dev/null +++ b/.github/workflows/install.yml @@ -0,0 +1,51 @@ +name: Install + +# The non-Docker install (tools/install.sh) on a clean Ubuntu, then a notebook on it: a change that +# breaks the install fails here. Weekly too, as apt, PyPI and the downloads change on their own. +on: + push: + branches: [dev] + paths: [tools/install.sh, source/**, runtest.py, 2.1_first_module.ipynb, .github/workflows/install.yml] + pull_request: + branches: [dev] + paths: [tools/install.sh, source/**, runtest.py, 2.1_first_module.ipynb, .github/workflows/install.yml] + schedule: + - cron: "0 4 * * 1" + workflow_dispatch: + +concurrency: + group: install-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + install: + name: tools/install.sh on Ubuntu 24.04 + runs-on: ubuntu-24.04 + # a bare Ubuntu, not the runner's image, which already has many of the packages + container: ubuntu:24.04 + timeout-minutes: 45 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v7 + - name: Verilator version to build + id: verilator + run: echo "version=$(sed -n 's/^VERILATOR_VERSION=//p' tools/install.sh)" >>"$GITHUB_OUTPUT" + # the Verilator that the script builds (Ubuntu 24.04's is too old) takes minutes: reuse it, + # but for the weekly run, which tests the build itself + - name: Cache the built Verilator + if: github.event_name != 'schedule' + uses: actions/cache@v6 + with: + path: ~/.local/share/chisel-bootcamp/verilator-${{ steps.verilator.outputs.version }} + key: verilator-${{ steps.verilator.outputs.version }}-ubuntu24.04 + - name: Install + run: tools/install.sh + - name: Run a notebook + run: | + . "$HOME/.local/share/chisel-bootcamp/venv/bin/activate" + python3 runtest.py 2.1_first_module.ipynb diff --git a/.gitignore b/.gitignore index b37318c..0905cb7 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,13 @@ coursier almond /build *.sv + +# Python +__pycache__/ + +# sbt (riscv/) +target/ +/riscv/build/ +/riscv/project/project/ +/riscv/.bsp/ +/riscv/fpga/build/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..06c43d0 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,19 @@ +# Install once with `pip install pre-commit && pre-commit install` (see CONTRIBUTING.md). +# Scala formatting (scalafmt) is checked by CI; run it locally as CONTRIBUTING.md explains. +repos: + # Notebooks are committed without outputs or execution counts. + - repo: https://github.com/kynan/nbstripout + rev: 0.9.1 + hooks: + - id: nbstripout + # Python style (settings in pyproject.toml) + - repo: https://github.com/psf/black-pre-commit-mirror + rev: 26.10.1 + hooks: + - id: black + # Shell style: 4-space indentation + - repo: https://github.com/scop/pre-commit-shfmt + rev: v3.14.1-1 + hooks: + - id: shfmt + args: [-w, -i, "4"] diff --git a/.scalafmt.conf b/.scalafmt.conf new file mode 100644 index 0000000..54e4d2a --- /dev/null +++ b/.scalafmt.conf @@ -0,0 +1,8 @@ +# Scala style for source/*.sc, the riscv/ project and the notebooks' code cells (applied by +# tools/format-scala.py), close to the configuration of the Chisel repository. +version = 3.11.5 +runner.dialect = scala213 +maxColumn = 120 +align.preset = more +assumeStandardLibraryStripMargin = true +docstrings.style = keep diff --git a/0_demo.ipynb b/0_demo.ipynb index e961dd6..6ef5cce 100644 --- a/0_demo.ipynb +++ b/0_demo.ipynb @@ -25,15 +25,15 @@ "## Setup\n", "Before we start, we need to download and imports the dependencies needed for the demo. \n", "\n", - "**Please run the following two cell blocks by either pressing SHIFT+ENTER on your keyboard or the Run button in the menu**." + "**Please run the following two cell blocks by either pressing SHIFT+ENTER on your keyboard or the Run button in the menu**.\n", + "\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { "cell_type": "code", "execution_count": null, - "metadata": { - "scrolled": false - }, + "metadata": {}, "outputs": [], "source": [ "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" @@ -47,14 +47,12 @@ "source": [ "import chisel3._\n", "import chisel3.Input // avoid a name clash with almond.input.Input\n", - "import chisel3.util._\n" + "import chisel3.util._" ] }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "## Hardware Generators: Type-Safe Meta-Programming for RTL\n", "\n", @@ -64,7 +62,7 @@ "\n", "Take the following example of a 3-point moving average implemented in the style of a FIR filter.\n", "\n", - "\n", + "\"3-point\n", "\n", "Chisel provides similar base primitives as synthesizable Verilog and *can* be used as such! Run next cell to declare our Chisel module." ] @@ -78,7 +76,7 @@ "// 3-point moving average implemented in the style of a FIR filter\n", "class MovingAverage3(bitWidth: Int) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(bitWidth.W))\n", + " val in = Input(UInt(bitWidth.W))\n", " val out = Output(UInt(bitWidth.W))\n", " })\n", "\n", @@ -99,9 +97,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "scrolled": true - }, + "metadata": {}, "outputs": [], "source": [ "// same 3-point moving average filter as before\n", @@ -112,7 +108,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "In this visualization of the Chisel instance, the inputs on the left, and the z1 and z2 registers in gold. Both registers and io_in are multiplied by their coefficients and which are then added successively. The `tail` and `bits` elements are used to keep the additions from growing.\n", + "This visualization of the Chisel instance shows the input `io.in` (a blue circle) on the left, the output (an orange double circle) on the right, and the z1 and z2 registers (purple 3D boxes). Both registers and `io.in` are multiplied by their coefficients, and the products are added successively. The `tail` elements keep the additions from growing.\n", "\n", "You may now ask: \"Oh well and good - you can do stuff in Verilog in Chisel, but then why would I want to use Chisel?\"\n", "\n", @@ -130,14 +126,14 @@ "// Generalized FIR filter parameterized by the convolution coefficients\n", "class FirFilter(bitWidth: Int, coeffs: Seq[UInt]) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(bitWidth.W))\n", + " val in = Input(UInt(bitWidth.W))\n", " val out = Output(UInt())\n", " })\n", " // Create the serial-in, parallel-out shift register\n", " val zs = Reg(Vec(coeffs.length, UInt(bitWidth.W)))\n", " zs(0) := io.in\n", " for (i <- 1 until coeffs.length) {\n", - " zs(i) := zs(i-1)\n", + " zs(i) := zs(i - 1)\n", " }\n", "\n", " // Do the multiplies\n", diff --git a/1_intro_to_scala.ipynb b/1_intro_to_scala.ipynb index b8cde9a..17d4fc4 100644 --- a/1_intro_to_scala.ipynb +++ b/1_intro_to_scala.ipynb @@ -14,7 +14,23 @@ "# Module 1: Introduction to Scala\n", "**Next: [Your First Chisel Module](2.1_first_module.ipynb)**\n", "\n", - "## Motivation\n", + "## Which sections you need\n", + "\n", + "Each section below is tagged by what the later modules need from it:\n", + "\n", + "- *Required*: Modules 2 to 5 use it all the time. If you know another language well, these are\n", + " the sections to read: values and variables, conditionals, methods, lists, `for`, imports, classes\n", + " and their instances, code blocks (a block's value is its last expression) and functions as values\n", + " (as in `xs.map(x => x + 1)`), and named and default parameters.\n", + "- *Recommended*: background that makes the rest easier to read (why Scala, how to read it, nested\n", + " and recursive methods).\n", + "- *Optional*: not needed for the hardware modules.\n", + "\n", + "Later modules teach more Scala along the way. The Module 5 notebooks, which build a RISC-V\n", + "processor, also use `match`, `Option` and case classes from [Module 3.1](3.1_parameters.ipynb), and\n", + "the collection methods of [Module 3.3](3.3_higher-order_functions.ipynb).\n", + "\n", + "## Motivation *(Optional)*\n", "These tutorials use the *Jupyter* notebook environment so you can read code, make changes, and then run code snippets in place. We encourage you to experiment with tutorial code blocks to speed your way to Chisel mastery.\n", "\n", "In this first module, you will learn how to write basic Scala code and how to read more advanced Scala code." @@ -25,7 +41,7 @@ "metadata": {}, "source": [ "---\n", - "# Understanding Scala\n", + "# Understanding Scala *(Recommended)*\n", "Scala is yet another programming language which supports common programming paradigms. We chose to use it for several reasons:\n", "\n", "- It is a good language for hosting an embedded DSL.\n", @@ -42,13 +58,13 @@ "metadata": {}, "source": [ "---\n", - "# Variables and Constants - var and val\n", + "# Variables and Constants - var and val *(Required)*\n", "Statements that create (mutable) variables and constant values (immutable variables) are preceded with the keywords *var* and *val* respectively. It is common practice to use *val* whenever possible. Why? Mostly to reduce the chances of re-using variables in ways that are error prone or make your code difficult to read. The structure of Scala makes this practice easier than you might expect.\n", "\n", "**Example:**
\n", "The subsequent code block is executable right here, within this notebook. To run it, focus on it by clicking it. When the cell is active, a box with a green bar on the left appears around it. Once selected, the active *code block* cell may be run using the **play** button found at the top of the notebook (highlighted in red below for reference). \n", "\n", - "![](images/playbutton.png)\n", + "![Run button in the notebook toolbar](images/playbutton.png)\n", "\n", "Alternatively, you may use keyboard shortcuts. **Shift+enter** runs the currently active cell and moves the focus to the next cell. **Ctrl+enter** runs the current cell and keeps it in focus. \n", "\n", @@ -63,8 +79,8 @@ "source": [ "var numberOfKittens = 6\n", "val kittensPerHouse = 101\n", - "val alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n", - "var done = false" + "val alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n", + "var done = false" ] }, { @@ -96,7 +112,7 @@ "metadata": {}, "source": [ "---\n", - "# Conditionals\n", + "# Conditionals *(Required)*\n", "\n", "Scala implements conditionals like other programming languages." ] @@ -108,33 +124,31 @@ "outputs": [], "source": [ "// A simple conditional; by the way, this is a comment\n", - "if (numberOfKittens > kittensPerHouse) { \n", - " println(\"Too many kittens!!!\") \n", + "if (numberOfKittens > kittensPerHouse) {\n", + " println(\"Too many kittens!!!\")\n", "}\n", - "// The braces are not required when all branches are one liners. However, the \n", + "// The braces are not required when all branches are one liners. However, the\n", "// Scala Style Guide prefers brace omission only if an \"else\" clause is included.\n", "// (Preferably not this, even though it compiles...)\n", - "if (numberOfKittens > kittensPerHouse) \n", - " println(\"Too many kittens!!!\")\n", + "if (numberOfKittens > kittensPerHouse)\n", + " println(\"Too many kittens!!!\")\n", "\n", "// ifs have else clauses, of course\n", "// This is where you can omit braces!\n", - "if (done) \n", - " println(\"we are done\")\n", - "else \n", - " numberOfKittens += 1\n", + "if (done)\n", + " println(\"we are done\")\n", + "else\n", + " numberOfKittens += 1\n", "\n", "// And else ifs\n", - "// For style, keep braces because not all branches are one liners. \n", + "// For style, keep braces because not all branches are one liners.\n", "if (done) {\n", - " println(\"we are done\")\n", - "}\n", - "else if (numberOfKittens < kittensPerHouse) {\n", - " println(\"more kittens!\")\n", - " numberOfKittens += 1\n", - "}\n", - "else {\n", - " done = true\n", + " println(\"we are done\")\n", + "} else if (numberOfKittens < kittensPerHouse) {\n", + " println(\"more kittens!\")\n", + " numberOfKittens += 1\n", + "} else {\n", + " done = true\n", "}" ] }, @@ -151,9 +165,10 @@ "metadata": {}, "outputs": [], "source": [ - "val likelyCharactersSet = if (alphabet.length == 26)\n", + "val likelyCharactersSet =\n", + " if (alphabet.length == 26)\n", " \"english\"\n", - "else \n", + " else\n", " \"not english\"\n", "\n", "println(likelyCharactersSet)" @@ -171,13 +186,13 @@ "metadata": {}, "source": [ "---\n", - "# Methods (Functions)\n", + "# Methods (Functions) *(Required)*\n", "\n", "Methods are defined with the keyword `def`. Here, we'll abuse notation and also refer to them as functions. Function arguments (or parameters) are specified in a comma separated list that specifies the name of the argument, its type, and optionally a default value for it. Return types should be specified for clarity.\n", "\n", "Scala functions that do not have any arguments do not require empty parentheses. This often makes life easier for a developer in the situation where a member of a class becomes a function because there is some computation associated with referencing it. By convention, argument-less functions that do not have side effects (i.e. calling them does not change anything and they simply return a value) do not use parentheses, and functions that do have side effects (perhaps they change class variables or print stuff out) should require parentheses.\n", "\n", - "## Simple Declarations" + "## Simple Declarations *(Required)*" ] }, { @@ -192,8 +207,8 @@ "\n", "// More complicated function\n", "def distance(x: Int, y: Int, returnPositive: Boolean): Int = {\n", - " val xy = x * y\n", - " if (returnPositive) xy.abs else -xy.abs\n", + " val xy = x * y\n", + " if (returnPositive) xy.abs else -xy.abs\n", "}" ] }, @@ -201,7 +216,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Overloading Functions\n", + "## Overloading Functions *(Optional)*\n", "The same function name can be used in more than one way. The parameters and their types determine a signature that allows the compiler to figure out which version of the function should be called. Overloaded functions should be avoided, though." ] }, @@ -212,7 +227,7 @@ "outputs": [], "source": [ "// Overloaded function\n", - "def times2(x: Int): Int = 2 * x\n", + "def times2(x: Int): Int = 2 * x\n", "def times2(x: String): Int = 2 * x.toInt\n", "\n", "times2(5)\n", @@ -223,7 +238,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Recursive and Nested Functions\n", + "## Recursive and Nested Functions *(Recommended)*\n", "Curly braces define code scopes. Within a function's scope may exist more functions or recursive function calls. Functions defined in a certain scope are only accessible within that scope." ] }, @@ -236,15 +251,15 @@ "/** Prints a triangle made of \"X\"s\n", " * This is another style of comment\n", " */\n", - "def asciiTriangle(rows: Int) {\n", - " \n", - " // This is cute: multiplying \"X\" makes a string with many copies of \"X\"\n", - " def printRow(columns: Int): Unit = println(\"X\" * columns)\n", - " \n", - " if(rows > 0) {\n", - " printRow(rows)\n", - " asciiTriangle(rows - 1) // Here is the recursive call\n", - " }\n", + "def asciiTriangle(rows: Int): Unit = {\n", + "\n", + " // This is cute: multiplying \"X\" makes a string with many copies of \"X\"\n", + " def printRow(columns: Int): Unit = println(\"X\" * columns)\n", + "\n", + " if (rows > 0) {\n", + " printRow(rows)\n", + " asciiTriangle(rows - 1) // Here is the recursive call\n", + " }\n", "}\n", "\n", "// printRow(1) // This would not work, since we're calling printRow outside its scope\n", @@ -256,7 +271,7 @@ "metadata": {}, "source": [ "---\n", - "# Lists\n", + "# Lists *(Required)*\n", "Scala implements a variety of aggregate or sequence objects. Lists are a lot like arrays but support additional operations for appending and extracting. " ] }, @@ -266,19 +281,19 @@ "metadata": {}, "outputs": [], "source": [ - "val x = 7\n", - "val y = 14\n", + "val x = 7\n", + "val y = 14\n", "val list1 = List(1, 2, 3)\n", - "val list2 = x :: y :: y :: Nil // An alternate notation for assembling a list\n", + "val list2 = x :: y :: y :: Nil // An alternate notation for assembling a list\n", "\n", - "val list3 = list1 ++ list2 // Appends the second list to the first list\n", - "val m = list2.length\n", - "val s = list2.size\n", + "val list3 = list1 ++ list2 // Appends the second list to the first list\n", + "val m = list2.length\n", + "val s = list2.size\n", "\n", - "val headOfList = list1.head // Gets the first element of the list\n", - "val restOfList = list1.tail // Get a new list with first element removed\n", + "val headOfList = list1.head // Gets the first element of the list\n", + "val restOfList = list1.tail // Get a new list with first element removed\n", "\n", - "val third = list1(2) // Gets the third element of a list (0-indexed)" + "val third = list1(2) // Gets the third element of a list (0-indexed)" ] }, { @@ -286,7 +301,7 @@ "metadata": {}, "source": [ "---\n", - "# `for` Statement\n", + "# `for` Statement *(Required)*\n", "\n", "Scala has a `for` statement and it works like traditional for statements. You\n", "can iterate over a range of values." @@ -298,7 +313,7 @@ "metadata": {}, "outputs": [], "source": [ - "for (i <- 0 to 7) { print(i + \" \") }\n", + "for (i <- 0 to 7) { print(s\"$i \") }\n", "println()" ] }, @@ -315,7 +330,7 @@ "metadata": {}, "outputs": [], "source": [ - "for (i <- 0 until 7) { print(i + \" \") }\n", + "for (i <- 0 until 7) { print(s\"$i \") }\n", "println()" ] }, @@ -332,7 +347,7 @@ "metadata": {}, "outputs": [], "source": [ - "for(i <- 0 to 10 by 2) { print(i + \" \") }\n", + "for (i <- 0 to 10 by 2) { print(s\"$i \") }\n", "println()" ] }, @@ -350,7 +365,12 @@ "metadata": {}, "outputs": [], "source": [ - "val randomList = List(scala.util.Random.nextInt(), scala.util.Random.nextInt(), scala.util.Random.nextInt(), scala.util.Random.nextInt())\n", + "val randomList = List(\n", + " scala.util.Random.nextInt(),\n", + " scala.util.Random.nextInt(),\n", + " scala.util.Random.nextInt(),\n", + " scala.util.Random.nextInt()\n", + ")\n", "var listSum = 0\n", "for (value <- randomList) {\n", " listSum += value\n", @@ -371,7 +391,7 @@ "metadata": {}, "source": [ "---\n", - "# Reading Scala\n", + "# Reading Scala *(Recommended)*\n", "Being able to read Scala code and understand common naming conventions, design patterns, and best practices is an important step in becoming an effective Chisel designer. The potential for code reuse is one of the advantages of Chisel, but reuse is difficult if you can't read other people's code. Effectively parsing other people's code also makes it easier to seek out help, especially from resources like StackOverflow.\n", "\n", "The following sections show common code patterns you will see." @@ -382,7 +402,7 @@ "metadata": {}, "source": [ "---\n", - "# Packages and Imports \n", + "# Packages and Imports *(Required)*\n", "\n", "```scala\n", "package mytools\n", @@ -411,7 +431,7 @@ "metadata": {}, "source": [ "---\n", - "# Scala Is an Object Oriented Language\n", + "# Scala Is an Object Oriented Language *(Required)*\n", "Scala is object oriented, and it's important to understand a bit about this to take maximum advantage of both Scala and Chisel. Note that, without a doubt, there is more than one way to describe all this.\n", "1. Variables are objects.\n", "1. Constants in the sense of *Scala's* `val` declarative are also objects.\n", @@ -438,7 +458,7 @@ "metadata": {}, "source": [ "---\n", - "# A Class Example\n", + "# A Class Example *(Required)*\n", "An example of creating a Scala class might be" ] }, @@ -452,17 +472,17 @@ "class WrapCounter(counterBits: Int) {\n", "\n", " val max: Long = (1 << counterBits) - 1\n", - " var counter = 0L\n", - " \n", + " var counter = 0L\n", + "\n", " def inc(): Long = {\n", " counter = counter + 1\n", " if (counter > max) {\n", - " counter = 0\n", + " counter = 0\n", " }\n", " counter\n", " }\n", " println(s\"counter created with max value $max\")\n", - "}\n" + "}" ] }, { @@ -502,7 +522,7 @@ "metadata": {}, "source": [ "---\n", - "# Creating an Instance of a Class\n", + "# Creating an Instance of a Class *(Required)*\n", "Let's use our example above to create a class. Scala instances are created via the built-in magic keyword `new`." ] }, @@ -534,8 +554,8 @@ "x.inc() // Increments the counter\n", "\n", "// Member variables of the instance x are visible to the outside, unless they are declared private\n", - "if(x.counter == x.max) { \n", - " println(\"counter is about to wrap\")\n", + "if (x.counter == x.max) {\n", + " println(\"counter is about to wrap\")\n", "}\n", "\n", "// Scala allows the dot and parentheses to be omitted when a method takes exactly one argument;\n", @@ -548,10 +568,10 @@ "metadata": {}, "source": [ "---\n", - "# Code Blocks\n", + "# Code Blocks *(Required)*\n", "Code blocks are delimited by braces. A block can contain zero or more lines of Scala code. The last line of Scala code becomes the return value (which may be ignored) of the code block. A code block with no lines would return a special null-like object called `Unit`. Code blocks are used throughout Scala: they are the bodies of class definitions, they form function and method definitions, they are the clauses of `if` statements, and they are the bodies of `for` and many other Scala operators.\n", "\n", - "## Parameterized Code Blocks\n", + "## Parameterized Code Blocks *(Required)*\n", "Code blocks can take parameters. In the case of class and method definitions, these parameters look like those in most conventional programming languages. In the example below, `c` and `s` are parameters of the code blocks." ] }, @@ -582,7 +602,7 @@ "metadata": {}, "outputs": [], "source": [ - "val intList = List(1, 2, 3)\n", + "val intList = List(1, 2, 3)\n", "val stringList = intList.map { i =>\n", " i.toString\n", "}" @@ -607,7 +627,7 @@ "metadata": {}, "source": [ "---\n", - "# Named Parameters and Parameter Defaults\n", + "# Named Parameters and Parameter Defaults *(Required)*\n", "Consider the following method definition.\n", "```scala\n", "def myMethod(count: Int, wrap: Boolean, wrapValue: Int = 24): Unit = { ... }\n", diff --git a/2.1_first_module.ipynb b/2.1_first_module.ipynb index 299ee81..6523aa2 100644 --- a/2.1_first_module.ipynb +++ b/2.1_first_module.ipynb @@ -9,9 +9,7 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "# Module 2.1: Your First Chisel Module\n", "**Prev: [Introduction to Scala](1_intro_to_scala.ipynb)**
\n", @@ -26,7 +24,9 @@ "metadata": {}, "source": [ "## Setup\n", - "The following cell downloads the dependencies needed for Chisel. You will see it in all future notebooks. **Run this cell now**." + "The following cell downloads the dependencies needed for Chisel. You will see it in all future notebooks. **Run this cell now**.\n", + "\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -78,7 +78,7 @@ "// Chisel Code: Declare a new module definition\n", "class Passthrough extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(4.W))\n", + " val in = Input(UInt(4.W))\n", " val out = Output(UInt(4.W))\n", " })\n", " io.out := io.in\n", @@ -148,9 +148,9 @@ "outputs": [], "source": [ "// Chisel Code, but pass in a parameter to set widths of ports\n", - "class PassthroughGenerator(width: Int) extends Module { \n", + "class PassthroughGenerator(width: Int) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(width.W))\n", + " val in = Input(UInt(width.W))\n", " val out = Output(UInt(width.W))\n", " })\n", " io.out := io.in\n", @@ -191,18 +191,18 @@ "metadata": {}, "outputs": [], "source": [ - "// Scala Code: `test` runs the unit test. \n", - "// test takes a user Module and has a code block that applies pokes and expects to the \n", + "// Scala Code: `test` runs the unit test.\n", + "// test takes a user Module and has a code block that applies pokes and expects to the\n", "// circuit under test (c)\n", "simulate(new Passthrough()) { c =>\n", - " c.io.in.poke(0.U) // Set our input to value 0\n", - " c.io.out.expect(0.U) // Assert that the output correctly has 0\n", - " c.io.in.poke(1.U) // Set our input to value 1\n", - " c.io.out.expect(1.U) // Assert that the output correctly has 1\n", - " c.io.in.poke(2.U) // Set our input to value 2\n", - " c.io.out.expect(2.U) // Assert that the output correctly has 2\n", + " c.io.in.poke(0.U) // Set our input to value 0\n", + " c.io.out.expect(0.U) // Assert that the output correctly has 0\n", + " c.io.in.poke(1.U) // Set our input to value 1\n", + " c.io.out.expect(1.U) // Assert that the output correctly has 1\n", + " c.io.in.poke(2.U) // Set our input to value 2\n", + " c.io.out.expect(2.U) // Assert that the output correctly has 2\n", "}\n", - "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!\n" + "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!" ] }, { @@ -235,13 +235,13 @@ "// Test with width 10\n", "\n", "simulate(???) { c =>\n", - " ???\n", + " ???\n", "}\n", "\n", "// Test with width 20\n", "\n", "simulate(???) { c =>\n", - " ???\n", + " ???\n", "}\n", "\n", "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!" @@ -340,24 +340,24 @@ "outputs": [], "source": [ "class PrintingModule extends Module {\n", - " val io = IO(new Bundle {\n", - " val in = Input(UInt(4.W))\n", - " val out = Output(UInt(4.W))\n", - " })\n", - " io.out := io.in\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(4.W))\n", + " val out = Output(UInt(4.W))\n", + " })\n", + " io.out := io.in\n", "\n", - " printf(\"Print during simulation: Input is %d\\n\", io.in)\n", - " // chisel printf has its own string interpolator too\n", - " printf(p\"Print during simulation: IO is $io\\n\")\n", + " printf(\"Print during simulation: Input is %d\\n\", io.in)\n", + " // chisel printf has its own string interpolator too\n", + " printf(p\"Print during simulation: IO is $io\\n\")\n", "\n", - " println(s\"Print during generation: Input is ${io.in}\")\n", + " println(s\"Print during generation: Input is ${io.in}\")\n", "}\n", "\n", - "simulate(new PrintingModule ) { c =>\n", - " c.io.in.poke(3.U)\n", - " c.clock.step(5) // circuit will print\n", - " \n", - " println(s\"Print during testing: Input is ${c.io.in.peek()}\")\n", + "simulate(new PrintingModule) { c =>\n", + " c.io.in.poke(3.U)\n", + " c.clock.step(5) // circuit will print\n", + "\n", + " println(s\"Print during testing: Input is ${c.io.in.peek()}\")\n", "}" ] } diff --git a/2.2_comb_logic.ipynb b/2.2_comb_logic.ipynb index fa73a1c..ccc553b 100644 --- a/2.2_comb_logic.ipynb +++ b/2.2_comb_logic.ipynb @@ -9,9 +9,7 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "# Module 2.2: Combinational Logic\n", "**Prev: [Your First Chisel Module](2.1_first_module.ipynb)**
\n", @@ -24,7 +22,8 @@ "Never use a Scala `var` for a hardware construct, since the construct itself may never change once defined; only its value may change when running the hardware.\n", "Wires may be used for parameterized types.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -93,11 +92,11 @@ " val out = Output(UInt(4.W))\n", " })\n", "\n", - " val two = 1 + 1\n", + " val two = 1 + 1\n", " println(two)\n", " val utwo = 1.U + 1.U\n", " println(utwo)\n", - " \n", + "\n", " io.out := io.in\n", "}\n", "println(getVerilog(new MyModule))" @@ -129,7 +128,7 @@ "\n", " val twotwo = 1.U + 1\n", " println(twotwo)\n", - " \n", + "\n", " io.out := io.in\n", "}\n", "println(getVerilog(new MyModuleTwo))" @@ -179,7 +178,7 @@ "metadata": {}, "outputs": [], "source": [ - "simulate(new MyOperators) {c =>\n", + "simulate(new MyOperators) { c =>\n", " c.io.out_add.expect(5.U)\n", " c.io.out_sub.expect(1.U)\n", " c.io.out_mul.expect(8.U)\n", @@ -224,13 +223,11 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "Notice how the Verilog contains constants instead of actual mux or concatenation logic. This is because FIRRTL transformations have simplified the circuit, eliminating obvious logic. \n", "\n", - "For a more complete list of Chisel operators, see the [Chisel cheatsheet](https://github.com/freechipsproject/chisel-cheatsheet/releases/latest/download/chisel_cheatsheet.pdf). For the most complete list of operators and their implementation details, look through the [Chisel API](https://chisel-lang.org/api/latest/)." + "For a more complete list of Chisel operators, see the [Chisel cheatsheet](https://github.com/freechipsproject/chisel-cheatsheet/releases/latest/download/chisel_cheatsheet.pdf) (written for Chisel 3, but still accurate for these basics; the [Chisel documentation](https://www.chisel-lang.org/docs) covers Chisel 7). For the most complete list of operators and their implementation details, look through the [Chisel API](https://chisel-lang.org/api/latest/)." ] }, { @@ -307,14 +304,12 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "**Exercise: Arbiter**
\n", "The following circuit arbitrates data coming from a FIFO into two parallel processing units. The FIFO and processing elements (PEs) communicate with ready-valid interfaces. Construct the arbiter to send data to whichever PE is ready to receive data, prioritizing PE0 if both are ready to receive data. Remember that the arbiter should tell the FIFO that it's ready to receive data when at least one of the PEs can receive data. Also, wait for a PE to assert that it's ready before asserting that the data are valid. You will likely need binary operators to complete this exercise.\n", "\n", - "" + "\"Arbiter" ] }, { @@ -329,16 +324,16 @@ " val fifo_valid = Input(Bool())\n", " val fifo_ready = Output(Bool())\n", " val fifo_data = Input(UInt(16.W))\n", - " \n", + "\n", " // PE0\n", - " val pe0_valid = Output(Bool())\n", - " val pe0_ready = Input(Bool())\n", - " val pe0_data = Output(UInt(16.W))\n", - " \n", + " val pe0_valid = Output(Bool())\n", + " val pe0_ready = Input(Bool())\n", + " val pe0_data = Output(UInt(16.W))\n", + "\n", " // PE1\n", - " val pe1_valid = Output(Bool())\n", - " val pe1_ready = Input(Bool())\n", - " val pe1_data = Output(UInt(16.W))\n", + " val pe1_valid = Output(Bool())\n", + " val pe1_ready = Input(Bool())\n", + " val pe1_data = Output(UInt(16.W))\n", " })\n", "\n", " ???\n", @@ -348,17 +343,17 @@ " import scala.util.Random\n", " val data = Random.nextInt(65536)\n", " c.io.fifo_data.poke(data.U)\n", - " \n", + "\n", " for (i <- 0 until 8) {\n", " c.io.fifo_valid.poke((((i >> 0) % 2) != 0).B)\n", - " c.io.pe0_ready.poke((((i >> 1) % 2) != 0).B)\n", - " c.io.pe1_ready.poke((((i >> 2) % 2) != 0).B)\n", + " c.io.pe0_ready.poke((((i >> 1) % 2) != 0).B)\n", + " c.io.pe1_ready.poke((((i >> 2) % 2) != 0).B)\n", "\n", " c.io.fifo_ready.expect((i > 1).B)\n", " c.io.pe0_valid.expect((i == 3 || i == 7).B)\n", " c.io.pe1_valid.expect((i == 5).B)\n", - " \n", - " if (i == 3 || i ==7) {\n", + "\n", + " if (i == 3 || i == 7) {\n", " c.io.pe0_data.expect((data).U)\n", " } else if (i == 5) {\n", " c.io.pe1_data.expect((data).U)\n", @@ -442,7 +437,7 @@ " c.io.out.expect(((in_a + in_b) % 16).U)\n", " }\n", " }\n", - " \n", + "\n", " // ensure we test saturation vs. truncation\n", " c.io.in_a.poke(15.U)\n", " c.io.in_b.poke(15.U)\n", diff --git a/2.3_control_flow.ipynb b/2.3_control_flow.ipynb index 1fdfc00..3a12f6c 100644 --- a/2.3_control_flow.ipynb +++ b/2.3_control_flow.ipynb @@ -9,9 +9,7 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "# Module 2.3: Control Flow\n", "**Prev: [Combinational Logic](2.2_comb_logic.ipynb)**
\n", @@ -25,7 +23,8 @@ "How can you make a mux with more than two inputs?\n", "The answers to these questions and more can be yours by completing this module.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -70,7 +69,7 @@ "source": [ "class LastConnect extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(4.W))\n", + " val in = Input(UInt(4.W))\n", " val out = Output(UInt(4.W))\n", " })\n", " io.out := 1.U\n", @@ -79,8 +78,8 @@ " io.out := 4.U\n", "}\n", "\n", - "// Test LastConnect\n", - "simulate(new LastConnect) { c => c.io.out.expect(4.U) } // Assert that the output correctly has 4\n", + "// Test LastConnect: assert that the output correctly has 4\n", + "simulate(new LastConnect) { c => c.io.out.expect(4.U) }\n", "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!" ] }, @@ -131,11 +130,11 @@ " val in3 = Input(UInt(16.W))\n", " val out = Output(UInt(16.W))\n", " })\n", - " \n", + "\n", " when(io.in1 >= io.in2 && io.in1 >= io.in3) {\n", - " io.out := io.in1 \n", + " io.out := io.in1\n", " }.elsewhen(io.in2 >= io.in3) {\n", - " io.out := io.in2 \n", + " io.out := io.in2\n", " }.otherwise {\n", " io.out := io.in3\n", " }\n", @@ -147,17 +146,17 @@ " c.io.in1.poke(6.U)\n", " c.io.in2.poke(4.U)\n", " c.io.in3.poke(2.U)\n", - " c.io.out.expect(6.U) // input 1 should be biggest\n", + " c.io.out.expect(6.U) // input 1 should be biggest\n", " c.io.in2.poke(7.U)\n", - " c.io.out.expect(7.U) // now input 2 is\n", + " c.io.out.expect(7.U) // now input 2 is\n", " c.io.in3.poke(11.U)\n", " c.io.out.expect(11.U) // and now input 3\n", " c.io.in3.poke(3.U)\n", - " c.io.out.expect(7.U) // show that decreasing an input works as well\n", + " c.io.out.expect(7.U) // show that decreasing an input works as well\n", " c.io.in1.poke(9.U)\n", " c.io.in2.poke(9.U)\n", " c.io.in3.poke(6.U)\n", - " c.io.out.expect(9.U) // still get max with tie\n", + " c.io.out.expect(9.U) // still get max with tie\n", "}\n", "\n", "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!" @@ -185,18 +184,16 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "scrolled": true - }, + "metadata": {}, "outputs": [], "source": [ "/** Sort4 sorts its 4 inputs to its 4 outputs */\n", "class Sort4 extends Module {\n", " val io = IO(new Bundle {\n", - " val in0 = Input(UInt(16.W))\n", - " val in1 = Input(UInt(16.W))\n", - " val in2 = Input(UInt(16.W))\n", - " val in3 = Input(UInt(16.W))\n", + " val in0 = Input(UInt(16.W))\n", + " val in1 = Input(UInt(16.W))\n", + " val in2 = Input(UInt(16.W))\n", + " val in3 = Input(UInt(16.W))\n", " val out0 = Output(UInt(16.W))\n", " val out1 = Output(UInt(16.W))\n", " val out2 = Output(UInt(16.W))\n", @@ -209,18 +206,18 @@ " val row13 = Wire(UInt(16.W))\n", "\n", " when(io.in0 < io.in1) {\n", - " row10 := io.in0 // preserve first two elements\n", + " row10 := io.in0 // preserve first two elements\n", " row11 := io.in1\n", " }.otherwise {\n", - " row10 := io.in1 // swap first two elements\n", + " row10 := io.in1 // swap first two elements\n", " row11 := io.in0\n", " }\n", "\n", " when(io.in2 < io.in3) {\n", - " row12 := io.in2 // preserve last two elements\n", + " row12 := io.in2 // preserve last two elements\n", " row13 := io.in3\n", " }.otherwise {\n", - " row12 := io.in3 // swap last two elements\n", + " row12 := io.in3 // swap last two elements\n", " row13 := io.in2\n", " }\n", "\n", @@ -228,41 +225,40 @@ " val row22 = Wire(UInt(16.W))\n", "\n", " when(row11 < row12) {\n", - " row21 := row11 // preserve middle 2 elements\n", + " row21 := row11 // preserve middle 2 elements\n", " row22 := row12\n", " }.otherwise {\n", - " row21 := row12 // swap middle two elements\n", + " row21 := row12 // swap middle two elements\n", " row22 := row11\n", " }\n", "\n", " val row20 = Wire(UInt(16.W))\n", " val row23 = Wire(UInt(16.W))\n", " when(row10 < row13) {\n", - " row20 := row10 // preserve middle 2 elements\n", + " row20 := row10 // preserve middle 2 elements\n", " row23 := row13\n", " }.otherwise {\n", - " row20 := row13 // swap middle two elements\n", + " row20 := row13 // swap middle two elements\n", " row23 := row10\n", " }\n", "\n", " when(row20 < row21) {\n", - " io.out0 := row20 // preserve first two elements\n", + " io.out0 := row20 // preserve first two elements\n", " io.out1 := row21\n", " }.otherwise {\n", - " io.out0 := row21 // swap first two elements\n", + " io.out0 := row21 // swap first two elements\n", " io.out1 := row20\n", " }\n", "\n", " when(row22 < row23) {\n", - " io.out2 := row22 // preserve first two elements\n", + " io.out2 := row22 // preserve first two elements\n", " io.out3 := row23\n", " }.otherwise {\n", - " io.out2 := row23 // swap first two elements\n", + " io.out2 := row23 // swap first two elements\n", " io.out3 := row22\n", " }\n", "}\n", "\n", - "\n", "// Here's the tester\n", "simulate(new Sort4) { c =>\n", " // verify the inputs are sorted\n", @@ -293,7 +289,7 @@ " c.io.out2.expect(6.U)\n", " c.io.out3.expect(13.U)\n", "}\n", - "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!\n" + "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!" ] }, { @@ -329,9 +325,7 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "---\n", "# Exercises\n", @@ -443,22 +437,22 @@ "class Polynomial extends Module {\n", " val io = IO(new Bundle {\n", " val select = Input(UInt(2.W))\n", - " val x = Input(SInt(32.W))\n", - " val fOfX = Output(SInt(32.W))\n", + " val x = Input(SInt(32.W))\n", + " val fOfX = Output(SInt(32.W))\n", " })\n", - " \n", - " val result = Wire(SInt(32.W)) \n", - " val square = Wire(SInt(32.W)) \n", - " \n", + "\n", + " val result = Wire(SInt(32.W))\n", + " val square = Wire(SInt(32.W))\n", + "\n", " ???\n", "\n", - " io.fOfX := result \n", + " io.fOfX := result\n", "}\n", "\n", "// Test Polynomial\n", "simulate(new Polynomial) { c =>\n", - " for(x <- 0 to 20) {\n", - " for(select <- 0 to 2) {\n", + " for (x <- 0 to 20) {\n", + " for (select <- 0 to 2) {\n", " c.io.select.poke(select.U)\n", " c.io.x.poke(x.S)\n", " c.io.fOfX.expect(poly(select, x).S)\n", @@ -497,7 +491,7 @@ "\n", "Grad students pass through four states in their career: Idle, Coding, Writing, and Graduating. These states transition based off three inputs: Coffee, Ideas they come up with, and Pressure from their advisor to make progress. Once they Graduate, they return to the Idle state. The FSM diagram below shows these states and transitions. Any unlabelled transition (i.e. when there are no inputs) returns a grad student to the Idle state instead of staying in the current state. The input precedence is coffee > idea > pressure, so when in the Idle state and receiving both coffee and pressure, a graduate student will move to the Coding state.\n", "\n", - "\n", + "\"Grad\n", "\n", "First we'll construct a model to test against our hardware. Complete the following functional description of our state machine. It has four inputs. The output is the next state. The state map is provided for you. You can access it like `states(\"grad\")`." ] @@ -512,14 +506,14 @@ "def states = Map(\"idle\" -> 0, \"coding\" -> 1, \"writing\" -> 2, \"grad\" -> 3)\n", "\n", "// life is full of question marks\n", - "def gradLife (state: Int, coffee: Boolean, idea: Boolean, pressure: Boolean): Int = {\n", + "def gradLife(state: Int, coffee: Boolean, idea: Boolean, pressure: Boolean): Int = {\n", " var nextState = states(\"idle\")\n", " ???\n", " nextState\n", "}\n", "\n", "// some sanity checks\n", - "(0 until states.size).foreach{ state => assert(gradLife(state, false, false, false) == states(\"idle\")) }\n", + "(0 until states.size).foreach { state => assert(gradLife(state, false, false, false) == states(\"idle\")) }\n", "assert(gradLife(states(\"writing\"), true, false, true) == states(\"writing\"))\n", "assert(gradLife(states(\"idle\"), true, true, true) == states(\"coding\"))\n", "assert(gradLife(states(\"idle\"), false, true, true) == states(\"idle\"))\n", @@ -565,19 +559,18 @@ "// life gets hard-er\n", "class GradLife extends Module {\n", " val io = IO(new Bundle {\n", - " val state = Input(UInt(2.W))\n", - " val coffee = Input(Bool())\n", - " val idea = Input(Bool())\n", - " val pressure = Input(Bool())\n", + " val state = Input(UInt(2.W))\n", + " val coffee = Input(Bool())\n", + " val idea = Input(Bool())\n", + " val pressure = Input(Bool())\n", " val nextState = Output(UInt(2.W))\n", " })\n", - " \n", + "\n", " val idle :: coding :: writing :: grad :: Nil = Enum(4)\n", - " \n", + "\n", " ???\n", "}\n", "\n", - "\n", "// Test\n", "simulate(new GradLife) { c =>\n", " // verify that the hardware matches the golden model\n", @@ -624,9 +617,7 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "---\n", "# You're done!\n", diff --git a/2.4_sequential_logic.ipynb b/2.4_sequential_logic.ipynb index 47b2f0e..e3a6de5 100644 --- a/2.4_sequential_logic.ipynb +++ b/2.4_sequential_logic.ipynb @@ -24,7 +24,8 @@ "\n", "It's important to emphasize that this section will probably not dramatically impress you. Chisel's power is not in new sequential logic patterns, but in the parameterization of a design. Before we demonstrate that capability, we have to learn what these sequential patterns are. Thus, this section will show you that Chisel can do pretty much what Verilog can do - you just need to learn the Chisel syntax.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -75,10 +76,10 @@ " val in = Input(UInt(12.W))\n", " val out = Output(UInt(12.W))\n", " })\n", - " \n", + "\n", " val register = Reg(UInt(12.W))\n", " register := io.in + 1.U\n", - " io.out := register\n", + " io.out := register\n", "}\n", "\n", "simulate(new RegisterModule) { c =>\n", @@ -158,7 +159,7 @@ " val in = Input(UInt(12.W))\n", " val out = Output(UInt(12.W))\n", " })\n", - " \n", + "\n", " // register bitwidth is inferred from io.out\n", " io.out := RegNext(io.in + 1.U)\n", "}\n", @@ -229,16 +230,16 @@ " val in = Input(UInt(12.W))\n", " val out = Output(UInt(12.W))\n", " })\n", - " \n", + "\n", " val register = RegInit(0.U(12.W))\n", " register := io.in + 1.U\n", - " io.out := register\n", + " io.out := register\n", "}\n", "\n", "println(getVerilog(new RegInitModule))\n", "\n", "simulate(new RegInitModule) { c =>\n", - " c.io.out.expect(0.U) // right after the reset: the register holds its reset value, not random junk\n", + " c.io.out.expect(0.U) // right after the reset: the register holds its reset value, not random junk\n", " c.io.in.poke(41.U)\n", " c.clock.step(1)\n", " c.io.out.expect(42.U)\n", @@ -290,26 +291,26 @@ " })\n", "\n", " val max = RegInit(0.U(10.W))\n", - " when (io.in > max) {\n", + " when(io.in > max) {\n", " max := io.in\n", " }\n", " io.max := max\n", "}\n", "\n", "simulate(new FindMax) { c =>\n", - " c.io.max.expect(0.U)\n", - " c.io.in.poke(1.U)\n", - " c.clock.step(1)\n", - " c.io.max.expect(1.U)\n", - " c.io.in.poke(3.U)\n", - " c.clock.step(1)\n", - " c.io.max.expect(3.U)\n", - " c.io.in.poke(2.U)\n", - " c.clock.step(1)\n", - " c.io.max.expect(3.U)\n", - " c.io.in.poke(24.U)\n", - " c.clock.step(1)\n", - " c.io.max.expect(24.U)\n", + " c.io.max.expect(0.U)\n", + " c.io.in.poke(1.U)\n", + " c.clock.step(1)\n", + " c.io.max.expect(1.U)\n", + " c.io.in.poke(3.U)\n", + " c.clock.step(1)\n", + " c.io.max.expect(3.U)\n", + " c.io.in.poke(2.U)\n", + " c.clock.step(1)\n", + " c.io.max.expect(3.U)\n", + " c.io.in.poke(24.U)\n", + " c.clock.step(1)\n", + " c.io.max.expect(24.U)\n", "}\n", "println(\"SUCCESS!!\")" ] @@ -348,7 +349,7 @@ " })\n", "\n", " val delay: SInt = Reg(SInt(12.W))\n", - " delay := io.in\n", + " delay := io.in\n", " io.out := io.in - delay\n", "}\n", "println(getVerilog(new Comb))" @@ -455,14 +456,14 @@ " simulate(new MyOptionalShiftRegister(n = i)) { c =>\n", " val inSeq = Seq(0, 1, 1, 1, 0, 1, 1, 0, 0, 1)\n", " var state = c.init\n", - " var i = 0\n", + " var i = 0\n", " c.io.en.poke(true.B)\n", " while (i < 10 * c.n) {\n", " // poke in repeated inSeq\n", " val toPoke = inSeq(i % inSeq.length)\n", " c.io.in.poke((toPoke != 0).B)\n", " // update expected state\n", - " state = ((state * 2) + toPoke) & BigInt(\"1\"*c.n, 2)\n", + " state = ((state * 2) + toPoke) & BigInt(\"1\" * c.n, 2)\n", " c.clock.step(1)\n", " c.io.out.expect(state.U)\n", "\n", @@ -516,15 +517,13 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "scrolled": true - }, + "metadata": {}, "outputs": [], "source": [ "// withClock, withReset and withClockAndReset are part of chisel3._, which we already imported\n", "class ClockExamples extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(10.W))\n", + " val in = Input(UInt(10.W))\n", " val alternateReset = Input(Bool())\n", " val alternateClock = Input(Clock())\n", " val outImplicit = Output(UInt(10.W))\n", @@ -534,25 +533,25 @@ " })\n", "\n", " val imp = RegInit(0.U(10.W))\n", - " imp := io.in\n", + " imp := io.in\n", " io.outImplicit := imp\n", "\n", " withReset(io.alternateReset) {\n", " // everything in this scope with have alternateReset as the reset\n", " val altRst = RegInit(0.U(10.W))\n", - " altRst := io.in\n", + " altRst := io.in\n", " io.outAlternateReset := altRst\n", " }\n", "\n", " withClock(io.alternateClock) {\n", " val altClk = RegInit(0.U(10.W))\n", - " altClk := io.in\n", + " altClk := io.in\n", " io.outAlternateClock := altClk\n", " }\n", "\n", " withClockAndReset(io.alternateClock, io.alternateReset) {\n", " val alt = RegInit(0.U(10.W))\n", - " alt := io.in\n", + " alt := io.in\n", " io.outAlternateBoth := alt\n", " }\n", "}\n", @@ -560,6 +559,86 @@ "println(getVerilog(new ClockExamples))" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Example: Synchronous and Asynchronous Reset**
\n", + "A register with a reset value (`RegInit`) takes that value when reset is asserted. *When* depends on the\n", + "kind of reset:\n", + "\n", + "- a **synchronous** reset (type `Bool`) is sampled at the clock edge, like any other input;\n", + "- an **asynchronous** reset (type `AsyncReset`) takes effect immediately, without waiting for the clock.\n", + "\n", + "The `reset` of a `Module` has the abstract type `Reset`; Chisel infers its kind from how it is driven,\n", + "and a top-level module gets a synchronous reset. Mixing `RequireAsyncReset` (or `RequireSyncReset`) into\n", + "a module fixes the kind instead. The helper below prints only the lines of the SystemVerilog that show\n", + "how a register is reset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// each `always @(...)` line and the `if (...)` reset check that follows it\n", + "def resetLines(sv: String): Unit =\n", + " sv.linesIterator\n", + " .sliding(2)\n", + " .collect { case Seq(a, b) if a.trim.startsWith(\"always @\") => s\"$a\\n$b\" }\n", + " .foreach(println)\n", + "\n", + "class SyncResetReg extends Module {\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(8.W))\n", + " val out = Output(UInt(8.W))\n", + " })\n", + " io.out := RegNext(io.in, 0.U)\n", + "}\n", + "\n", + "// the same register, with the reset kind fixed to asynchronous\n", + "class AsyncResetReg extends SyncResetReg with RequireAsyncReset\n", + "\n", + "println(\"Synchronous reset (the default):\")\n", + "resetLines(getVerilog(new SyncResetReg))\n", + "println(\"\\nAsynchronous reset (RequireAsyncReset):\")\n", + "resetLines(getVerilog(new AsyncResetReg))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The asynchronous register is sensitive to `posedge reset` as well as `posedge clock`. Most FPGA and ASIC\n", + "flows have a preferred kind, so pick one per design and keep it consistent.\n", + "\n", + "Inside a module, `withReset` also accepts an asynchronous reset, so one group of registers can use a\n", + "different kind of reset than the rest. `asAsyncReset` turns a `Bool` into an `AsyncReset`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class MixedResets extends Module {\n", + " val io = IO(new Bundle {\n", + " val asyncReset = Input(Bool())\n", + " val in = Input(UInt(8.W))\n", + " val syncOut = Output(UInt(8.W))\n", + " val asyncOut = Output(UInt(8.W))\n", + " })\n", + " io.syncOut := RegNext(io.in, 0.U) // the module's synchronous reset\n", + " withReset(io.asyncReset.asAsyncReset) {\n", + " io.asyncOut := RegNext(io.in, 0.U) // reset asynchronously by io.asyncReset\n", + " }\n", + "}\n", + "\n", + "resetLines(getVerilog(new MixedResets))" + ] + }, { "cell_type": "markdown", "metadata": {}, diff --git a/2.5_exercise.ipynb b/2.5_exercise.ipynb index c8b40e4..73b015d 100644 --- a/2.5_exercise.ipynb +++ b/2.5_exercise.ipynb @@ -18,7 +18,8 @@ "## Motivation\n", "Now that you've learned the basics of Chisel, let's use that knowledge to build a FIR (finite impulse response) filter module! FIR filters are very common in digital signal processing applications. Also, the FIR filter will reappear frequently in module 3, so it's important that you don't filter out this module by skipping ahead! If you are unfamiliar with FIR filters, head over to the article on [trusty Wikipedia](https://en.wikipedia.org/wiki/Finite_impulse_response) to learn more.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -55,7 +56,7 @@ "\n", "The FIR filter you will design performs the following operation.\n", "\n", - "\n", + "\"FIR\n", "\n", "Basically, this does a elementwise multiplication of the element of the filter coefficients with the elements of the input signal and outputs the sum (also called a _convolution_).\n", "\n", @@ -88,7 +89,7 @@ "source": [ "class My4ElementFir(b0: Int, b1: Int, b2: Int, b3: Int) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(8.W))\n", + " val in = Input(UInt(8.W))\n", " val out = Output(UInt(8.W))\n", " })\n", "\n", @@ -108,17 +109,17 @@ "source": [ "// Simple sanity check: a element with all zero coefficients should always produce zero\n", "simulate(new My4ElementFir(0, 0, 0, 0)) { c =>\n", - " c.io.in.poke(0.U)\n", - " c.io.out.expect(0.U)\n", - " c.clock.step(1)\n", - " c.io.in.poke(4.U)\n", - " c.io.out.expect(0.U)\n", - " c.clock.step(1)\n", - " c.io.in.poke(5.U)\n", - " c.io.out.expect(0.U)\n", - " c.clock.step(1)\n", - " c.io.in.poke(2.U)\n", - " c.io.out.expect(0.U)\n", + " c.io.in.poke(0.U)\n", + " c.io.out.expect(0.U)\n", + " c.clock.step(1)\n", + " c.io.in.poke(4.U)\n", + " c.io.out.expect(0.U)\n", + " c.clock.step(1)\n", + " c.io.in.poke(5.U)\n", + " c.io.out.expect(0.U)\n", + " c.clock.step(1)\n", + " c.io.in.poke(2.U)\n", + " c.io.out.expect(0.U)\n", "}" ] }, @@ -130,23 +131,23 @@ "source": [ "// Simple 4-point moving average\n", "simulate(new My4ElementFir(1, 1, 1, 1)) { c =>\n", - " c.io.in.poke(1.U)\n", - " c.io.out.expect(1.U) // 1, 0, 0, 0\n", - " c.clock.step(1)\n", - " c.io.in.poke(4.U)\n", - " c.io.out.expect(5.U) // 4, 1, 0, 0\n", - " c.clock.step(1)\n", - " c.io.in.poke(3.U)\n", - " c.io.out.expect(8.U) // 3, 4, 1, 0\n", - " c.clock.step(1)\n", - " c.io.in.poke(2.U)\n", - " c.io.out.expect(10.U) // 2, 3, 4, 1\n", - " c.clock.step(1)\n", - " c.io.in.poke(7.U)\n", - " c.io.out.expect(16.U) // 7, 2, 3, 4\n", - " c.clock.step(1)\n", - " c.io.in.poke(0.U)\n", - " c.io.out.expect(12.U) // 0, 7, 2, 3\n", + " c.io.in.poke(1.U)\n", + " c.io.out.expect(1.U) // 1, 0, 0, 0\n", + " c.clock.step(1)\n", + " c.io.in.poke(4.U)\n", + " c.io.out.expect(5.U) // 4, 1, 0, 0\n", + " c.clock.step(1)\n", + " c.io.in.poke(3.U)\n", + " c.io.out.expect(8.U) // 3, 4, 1, 0\n", + " c.clock.step(1)\n", + " c.io.in.poke(2.U)\n", + " c.io.out.expect(10.U) // 2, 3, 4, 1\n", + " c.clock.step(1)\n", + " c.io.in.poke(7.U)\n", + " c.io.out.expect(16.U) // 7, 2, 3, 4\n", + " c.clock.step(1)\n", + " c.io.in.poke(0.U)\n", + " c.io.out.expect(12.U) // 0, 7, 2, 3\n", "}" ] }, @@ -158,23 +159,23 @@ "source": [ "// Nonsymmetric filter\n", "simulate(new My4ElementFir(1, 2, 3, 4)) { c =>\n", - " c.io.in.poke(1.U)\n", - " c.io.out.expect(1.U) // 1*1, 0*2, 0*3, 0*4\n", - " c.clock.step(1)\n", - " c.io.in.poke(4.U)\n", - " c.io.out.expect(6.U) // 4*1, 1*2, 0*3, 0*4\n", - " c.clock.step(1)\n", - " c.io.in.poke(3.U)\n", - " c.io.out.expect(14.U) // 3*1, 4*2, 1*3, 0*4\n", - " c.clock.step(1)\n", - " c.io.in.poke(2.U)\n", - " c.io.out.expect(24.U) // 2*1, 3*2, 4*3, 1*4\n", - " c.clock.step(1)\n", - " c.io.in.poke(7.U)\n", - " c.io.out.expect(36.U) // 7*1, 2*2, 3*3, 4*4\n", - " c.clock.step(1)\n", - " c.io.in.poke(0.U)\n", - " c.io.out.expect(32.U) // 0*1, 7*2, 2*3, 3*4\n", + " c.io.in.poke(1.U)\n", + " c.io.out.expect(1.U) // 1*1, 0*2, 0*3, 0*4\n", + " c.clock.step(1)\n", + " c.io.in.poke(4.U)\n", + " c.io.out.expect(6.U) // 4*1, 1*2, 0*3, 0*4\n", + " c.clock.step(1)\n", + " c.io.in.poke(3.U)\n", + " c.io.out.expect(14.U) // 3*1, 4*2, 1*3, 0*4\n", + " c.clock.step(1)\n", + " c.io.in.poke(2.U)\n", + " c.io.out.expect(24.U) // 2*1, 3*2, 4*3, 1*4\n", + " c.clock.step(1)\n", + " c.io.in.poke(7.U)\n", + " c.io.out.expect(36.U) // 7*1, 2*2, 3*3, 4*4\n", + " c.clock.step(1)\n", + " c.io.in.poke(0.U)\n", + " c.io.out.expect(32.U) // 0*1, 7*2, 2*3, 3*4\n", "}" ] }, @@ -219,7 +220,7 @@ "and 1 output:\n", "* out, the filtered input\n", "\n", - "" + "\"FIR" ] }, { @@ -230,15 +231,15 @@ "source": [ "class MyManyDynamicElementVecFir(length: Int) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(8.W))\n", - " val valid = Input(Bool())\n", - " val out = Output(UInt(8.W))\n", + " val in = Input(UInt(8.W))\n", + " val valid = Input(Bool())\n", + " val out = Output(UInt(8.W))\n", " val consts = Input(Vec(length, UInt(8.W)))\n", " })\n", - " \n", + "\n", " // Such concision! You'll learn what all this means later.\n", " val taps = Seq(io.in) ++ Seq.fill(io.consts.length - 1)(RegInit(0.U(8.W)))\n", - " taps.zip(taps.tail).foreach { case (a, b) => when (io.valid) { b := a } }\n", + " taps.zip(taps.tail).foreach { case (a, b) => when(io.valid) { b := a } }\n", "\n", " io.out := taps.zip(io.consts).map { case (a, b) => a * b }.reduce(_ + _)\n", "}\n", diff --git a/2.6_chiselsim.ipynb b/2.6_chiselsim.ipynb index dd6519d..c529c9d 100644 --- a/2.6_chiselsim.ipynb +++ b/2.6_chiselsim.ipynb @@ -13,7 +13,7 @@ "source": [ "# Module 2.6: Testing with ChiselSim\n", "**Prev: [Putting it all Together: An FIR Filter](2.5_exercise.ipynb)**
\n", - "**Next: [Generators: Parameters](3.1_parameters.ipynb)**\n", + "**Next: [Enums, Decoders and Bundles](2.7_enums_and_bundles.ipynb)**\n", "\n", "## Motivation\n", "So far we have used `simulate(...)` to test our circuits without saying much about how it works.\n", @@ -29,7 +29,8 @@ "\n", "In this module we review the basic operations (`poke`, `peek`, `expect` and `step`), and then learn how to test modules with `Decoupled` (ready/valid) interfaces by writing small helper functions ourselves.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -61,8 +62,9 @@ ">This bootcamp requires some slight differences from the imports you might see \n", "elsewhere for Chisel. The `import chisel3.simulator.PeekPokeAPI._` brings in the \n", "`poke`, `peek`, `expect` and `step` methods on Chisel signals, and the `simulate(...)` function\n", - "used below is a thin wrapper (defined in `source/load-ivy.sc`) around ChiselSim's `EphemeralSimulator.simulate`\n", - "that prints failures nicely in the notebook." + "used below is a thin wrapper (defined in `source/load-ivy.sc`) around ChiselSim's simulator: it does what\n", + "`EphemeralSimulator.simulate` does, prints failures nicely in the notebook, and adds the `waves` option\n", + "shown at the end of this module." ] }, { @@ -81,7 +83,12 @@ "| peek | peek(c.io.out1) | c.io.out1.peek() |\n", "| expect | expect(c.io.out1, 6) | c.io.out1.expect(6.U) |\n", "| step | step(1) | c.clock.step(1) |\n", - "| initiate | Driver.execute(...) { c => | simulate(...) { c => |\n" + "| initiate | Driver.execute(...) { c => | simulate(...) { c => |\n", + "\n", + "To port tests written for ChiselTest, Chisel 7 still ships a small `chiseltest` compatibility package\n", + "(`test`, `poke`, `peek`, `expect`, `step`) on top of ChiselSim. Its `test` resets the module for one\n", + "cycle first, as `simulate` does, but its `fork` runs its body at once instead of concurrently, so write\n", + "new tests with ChiselSim directly, as this notebook does." ] }, { @@ -98,9 +105,9 @@ "outputs": [], "source": [ "// Chisel Code, but pass in a parameter to set widths of ports\n", - "class PassthroughGenerator(width: Int) extends Module { \n", + "class PassthroughGenerator(width: Int) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(width.W))\n", + " val in = Input(UInt(width.W))\n", " val out = Output(UInt(width.W))\n", " })\n", " io.out := io.in\n", @@ -138,12 +145,12 @@ "outputs": [], "source": [ "simulate(new PassthroughGenerator(16)) { c =>\n", - " c.io.in.poke(0.U) // Set our input to value 0\n", - " c.io.out.expect(0.U) // Assert that the output correctly has 0\n", - " c.io.in.poke(1.U) // Set our input to value 1\n", - " c.io.out.expect(1.U) // Assert that the output correctly has 1\n", - " c.io.in.poke(2.U) // Set our input to value 2\n", - " c.io.out.expect(2.U) // Assert that the output correctly has 2\n", + " c.io.in.poke(0.U) // Set our input to value 0\n", + " c.io.out.expect(0.U) // Assert that the output correctly has 0\n", + " c.io.in.poke(1.U) // Set our input to value 1\n", + " c.io.out.expect(1.U) // Assert that the output correctly has 1\n", + " c.io.in.poke(2.U) // Set our input to value 2\n", + " c.io.out.expect(2.U) // Assert that the output correctly has 2\n", "}" ] }, @@ -162,15 +169,15 @@ "outputs": [], "source": [ "simulate(new PassthroughGenerator(16)) { c =>\n", - " c.io.in.poke(0.U) // Set our input to value 0\n", - " c.clock.step(1) // advance the clock\n", - " c.io.out.expect(0.U) // Assert that the output correctly has 0\n", - " c.io.in.poke(1.U) // Set our input to value 1\n", - " c.clock.step(1) // advance the clock\n", - " c.io.out.expect(1.U) // Assert that the output correctly has 1\n", - " c.io.in.poke(2.U) // Set our input to value 2\n", - " c.clock.step(1) // advance the clock\n", - " c.io.out.expect(2.U) // Assert that the output correctly has 2\n", + " c.io.in.poke(0.U) // Set our input to value 0\n", + " c.clock.step(1) // advance the clock\n", + " c.io.out.expect(0.U) // Assert that the output correctly has 0\n", + " c.io.in.poke(1.U) // Set our input to value 1\n", + " c.clock.step(1) // advance the clock\n", + " c.io.out.expect(1.U) // Assert that the output correctly has 1\n", + " c.io.in.poke(2.U) // Set our input to value 2\n", + " c.clock.step(1) // advance the clock\n", + " c.io.out.expect(2.U) // Assert that the output correctly has 2\n", "}" ] }, @@ -217,7 +224,7 @@ "outputs": [], "source": [ "class QueueModule[T <: Data](ioType: T, entries: Int) extends Module {\n", - " val in = IO(Flipped(Decoupled(ioType)))\n", + " val in = IO(Flipped(Decoupled(ioType)))\n", " val out = IO(Decoupled(ioType))\n", " out <> Queue(in, entries)\n", "}" @@ -243,7 +250,7 @@ " cycles += 1\n", " assert(cycles < timeout, s\"timeout: ready was not asserted after $timeout cycles\")\n", " }\n", - " clock.step(1) // the handshake (valid && ready) completes on this edge\n", + " clock.step(1) // the handshake (valid && ready) completes on this edge\n", " port.valid.poke(false.B)\n", "}\n", "\n", @@ -259,7 +266,7 @@ " assert(cycles < timeout, s\"timeout: valid was not asserted after $timeout cycles\")\n", " }\n", " check(port.bits)\n", - " clock.step(1) // the handshake completes on this edge\n", + " clock.step(1) // the handshake completes on this edge\n", " port.ready.poke(false.B)\n", "}" ] @@ -293,15 +300,15 @@ "outputs": [], "source": [ "simulate(new QueueModule(UInt(9.W), entries = 200)) { c =>\n", - " c.out.ready.poke(false.B)\n", - " c.in.valid.poke(false.B)\n", + " c.out.ready.poke(false.B)\n", + " c.in.valid.poke(false.B)\n", "\n", - " val testVector = Seq.tabulate(200){ i => i.U }\n", + " val testVector = Seq.tabulate(200) { i => i.U }\n", "\n", - " testVector.foreach { value =>\n", - " enqueue(c.in, c.clock)(_.poke(value))\n", - " expectDequeue(c.out, c.clock)(_.expect(value))\n", - " }\n", + " testVector.foreach { value =>\n", + " enqueue(c.in, c.clock)(_.poke(value))\n", + " expectDequeue(c.out, c.clock)(_.expect(value))\n", + " }\n", "}\n", "println(\"SUCCESS!!\")" ] @@ -328,13 +335,13 @@ "outputs": [], "source": [ "simulate(new QueueModule(UInt(9.W), entries = 200)) { c =>\n", - " c.out.ready.poke(false.B)\n", - " c.in.valid.poke(false.B)\n", + " c.out.ready.poke(false.B)\n", + " c.in.valid.poke(false.B)\n", "\n", - " val testVector = Seq.tabulate(100){ i => i.U }\n", + " val testVector = Seq.tabulate(100) { i => i.U }\n", "\n", - " testVector.foreach { v => enqueue(c.in, c.clock)(_.poke(v)) }\n", - " testVector.foreach { v => expectDequeue(c.out, c.clock)(_.expect(v)) }\n", + " testVector.foreach { v => enqueue(c.in, c.clock)(_.poke(v)) }\n", + " testVector.foreach { v => expectDequeue(c.out, c.clock)(_.expect(v)) }\n", "}\n", "println(\"SUCCESS!!\")" ] @@ -376,37 +383,36 @@ "outputs": [], "source": [ "simulate(new QueueModule(UInt(9.W), entries = 200)) { c =>\n", + " val n = 300 // more elements than the queue can hold!\n", + " var sent = 0\n", + " var received = 0\n", + " var cycles = 0\n", + "\n", + " c.out.ready.poke(true.B) // the consumer is always ready\n", + "\n", + " while (received < n) {\n", + " // producer: offer the next element while there are some left\n", + " if (sent < n) {\n", + " c.in.valid.poke(true.B)\n", + " c.in.bits.poke(sent.U)\n", + " } else {\n", + " c.in.valid.poke(false.B)\n", + " }\n", "\n", - " val n = 300 // more elements than the queue can hold!\n", - " var sent = 0\n", - " var received = 0\n", - " var cycles = 0\n", - "\n", - " c.out.ready.poke(true.B) // the consumer is always ready\n", - "\n", - " while (received < n) {\n", - " // producer: offer the next element while there are some left\n", - " if (sent < n) {\n", - " c.in.valid.poke(true.B)\n", - " c.in.bits.poke(sent.U)\n", - " } else {\n", - " c.in.valid.poke(false.B)\n", - " }\n", - "\n", - " // sample the handshakes that are about to happen on the next clock edge\n", - " val enqFires = sent < n && c.in.ready.peekBoolean()\n", - " val deqFires = c.out.valid.peekBoolean() // out.ready is always true\n", - "\n", - " if (deqFires) {\n", - " c.out.bits.expect(received.U) // data must come out in order\n", - " received += 1\n", - " }\n", - " if (enqFires) sent += 1\n", - "\n", - " c.clock.step(1)\n", - " cycles += 1\n", - " assert(cycles < 10 * n, \"timeout\")\n", + " // sample the handshakes that are about to happen on the next clock edge\n", + " val enqFires = sent < n && c.in.ready.peekBoolean()\n", + " val deqFires = c.out.valid.peekBoolean() // out.ready is always true\n", + "\n", + " if (deqFires) {\n", + " c.out.bits.expect(received.U) // data must come out in order\n", + " received += 1\n", " }\n", + " if (enqFires) sent += 1\n", + "\n", + " c.clock.step(1)\n", + " cycles += 1\n", + " assert(cycles < 10 * n, \"timeout\")\n", + " }\n", "}\n", "println(\"SUCCESS!!\")" ] @@ -466,20 +472,20 @@ " */\n", "class DecoupledGcd(width: Int) extends Module {\n", "\n", - " val input = IO(Flipped(Decoupled(new GcdInputBundle(width))))\n", + " val input = IO(Flipped(Decoupled(new GcdInputBundle(width))))\n", " val output = IO(Decoupled(new GcdOutputBundle(width)))\n", "\n", - " val xInitial = Reg(UInt())\n", - " val yInitial = Reg(UInt())\n", - " val x = Reg(UInt())\n", - " val y = Reg(UInt())\n", - " val busy = RegInit(false.B)\n", + " val xInitial = Reg(UInt())\n", + " val yInitial = Reg(UInt())\n", + " val x = Reg(UInt())\n", + " val y = Reg(UInt())\n", + " val busy = RegInit(false.B)\n", "\n", - " input.ready := ! busy\n", + " input.ready := !busy\n", " output.valid := false.B\n", - " output.bits := DontCare\n", + " output.bits := DontCare\n", "\n", - " when(busy) {\n", + " when(busy) {\n", " // during computation keep subtracting the smaller from the larger\n", " when(x > y) {\n", " x := x - y\n", @@ -491,19 +497,19 @@ " // signal valid data to output if the output is ready\n", " output.bits.value1 := xInitial\n", " output.bits.value2 := yInitial\n", - " output.bits.gcd := x | y\n", - " output.valid := true.B\n", - " busy := ! output.ready\n", + " output.bits.gcd := x | y\n", + " output.valid := true.B\n", + " busy := !output.ready\n", " }\n", " }.otherwise {\n", " when(input.valid) {\n", " // valid data available and no computation in progress, grab new values and start\n", " val bundle = input.deq()\n", - " x := bundle.value1\n", - " y := bundle.value2\n", + " x := bundle.value1\n", + " y := bundle.value2\n", " xInitial := bundle.value1\n", " yInitial := bundle.value2\n", - " busy := true.B\n", + " busy := true.B\n", " }\n", " }\n", "}" @@ -543,10 +549,10 @@ " dut.input.valid.poke(false.B)\n", " dut.output.ready.poke(false.B)\n", "\n", - " val testValues = for { x <- 1 to 10; y <- 1 to 10} yield (x, y)\n", + " val testValues = for { x <- 1 to 10; y <- 1 to 10 } yield (x, y)\n", "\n", " for ((x, y) <- testValues) {\n", - " val input = new GcdInputBundle(16).Lit(_.value1 -> x.U, _.value2 -> y.U)\n", + " val input = new GcdInputBundle(16).Lit(_.value1 -> x.U, _.value2 -> y.U)\n", " val expected = new GcdOutputBundle(16).Lit(_.value1 -> x.U, _.value2 -> y.U, _.gcd -> BigInt(x).gcd(BigInt(y)).U)\n", "\n", " enqueue(dut.input, dut.clock)(_.poke(input))\n", @@ -557,6 +563,385 @@ "println(\"SUCCESS!!\")" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# When a test fails\n", + "\n", + "A failing `expect` stops the test with a `FailedExpectationException` whose message shows the observed\n", + "value, the expected one, and where in your test the check is. The optional second argument of `expect`\n", + "adds your own explanation, which is worth it whenever the same `expect` runs many times (in a loop,\n", + "say). Normally you let the exception fail the cell; here it is caught so that the notebook can go on:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "try {\n", + " simulate(new PassthroughGenerator(4)) { c =>\n", + " c.io.in.poke(3.U)\n", + " c.io.out.expect(4.U, \"the output follows the input\")\n", + " }\n", + "} catch {\n", + " case e: chisel3.simulator.FailedExpectationException[_] => println(e.getMessage)\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Random tests with a seed\n", + "\n", + "Hand-picked test vectors miss the cases you did not think of, so it pays to also drive random inputs and\n", + "compare the outputs with a model written in plain Scala. Use a `scala.util.Random` with a fixed seed: a\n", + "failure then happens again, identically, every time you run the test, and you can debug it. Putting the\n", + "seed (and the inputs) in the `expect` message tells you how to reproduce a failure." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class Max3 extends Module {\n", + " val io = IO(new Bundle {\n", + " val in = Input(Vec(3, UInt(8.W)))\n", + " val out = Output(UInt(8.W))\n", + " })\n", + " io.out := io.in.reduce((a, b) => Mux(a > b, a, b))\n", + "}\n", + "\n", + "val seed = 42\n", + "val rnd = new scala.util.Random(seed)\n", + "simulate(new Max3) { c =>\n", + " for (_ <- 0 until 200) {\n", + " val inputs = Seq.fill(3)(rnd.nextInt(256))\n", + " inputs.zipWithIndex.foreach { case (v, i) => c.io.in(i).poke(v.U) }\n", + " c.io.out.expect(inputs.max.U, s\"seed $seed, inputs $inputs\")\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Timeouts\n", + "\n", + "A test that waits for the design (`while (!done) step()`) hangs forever when the design is broken, and\n", + "so does the notebook. Bound every wait instead. `clock.stepUntil(signal, value, maxCycles)` steps the\n", + "clock until `signal` equals `value`, or until `maxCycles` cycles have passed; it does not fail by\n", + "itself, so follow it with an `expect` on the signal:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class SlowDone(latency: Int) extends Module {\n", + " val io = IO(new Bundle {\n", + " val done = Output(Bool())\n", + " })\n", + " val count = RegInit(0.U(8.W))\n", + " when(count =/= latency.U) { count := count + 1.U }\n", + " io.done := count === latency.U\n", + "}\n", + "\n", + "simulate(new SlowDone(10)) { c =>\n", + " c.clock.stepUntil(c.io.done, 1, maxCycles = 50)\n", + " c.io.done.expect(true.B, \"done within 50 cycles\")\n", + "}\n", + "println(\"SUCCESS!!\")\n", + "\n", + "try {\n", + " simulate(new SlowDone(100)) { c =>\n", + " c.clock.stepUntil(c.io.done, 1, maxCycles = 50)\n", + " c.io.done.expect(true.B, \"done within 50 cycles\")\n", + " }\n", + "} catch {\n", + " case e: chisel3.simulator.FailedExpectationException[_] => println(e.getMessage)\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A design can also end the simulation itself by calling `stop()`, which becomes a Verilog `$finish`. The\n", + "stimulus `RunUntilFinished(maxCycles)` runs the clock until that happens and throws a timeout exception\n", + "if it does not happen within `maxCycles` cycles (the message counts them as \"timesteps\"). Make it the\n", + "last thing in the test body: after `$finish`, the simulation is over and nothing can be poked or peeked." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3.simulator.stimulus.RunUntilFinished\n", + "\n", + "class CountAndStop(n: Int) extends Module {\n", + " val count = RegInit(0.U(8.W))\n", + " count := count + 1.U\n", + " when(count === n.U) { stop() }\n", + "}\n", + "\n", + "simulate(new CountAndStop(10)) { c =>\n", + " RunUntilFinished.module(maxCycles = 50)(c)\n", + "}\n", + "println(\"SUCCESS!!\")\n", + "\n", + "try {\n", + " simulate(new CountAndStop(100)) { c =>\n", + " RunUntilFinished.module(maxCycles = 50)(c)\n", + " }\n", + "} catch {\n", + " case e: chisel3.simulator.Exceptions.Timeout => println(e.getMessage)\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Assertions in the design\n", + "\n", + "An `expect` checks a value from the test. An assertion written *in the module* checks a condition in\n", + "every cycle of every simulation of it, whoever wrote the test. The tests above call `assert` on a\n", + "Scala `Boolean`, which checks the test as it runs; called on a `Bool` in a module, `assert` becomes\n", + "hardware.\n", + "`assert(condition, \"message\")` fails when `condition` is false at a clock edge out of reset, and stops\n", + "the simulation with an `AssertionFailed` exception; its `simulatorOutput` gives the message and the\n", + "time of the failure (in timesteps, 10 per clock cycle):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3.simulator.Exceptions.AssertionFailed\n", + "\n", + "class CountTo9 extends Module {\n", + " val io = IO(new Bundle {\n", + " val enable = Input(Bool())\n", + " val count = Output(UInt(4.W))\n", + " })\n", + " val count = RegInit(0.U(4.W))\n", + " when(io.enable) { count := count + 1.U }\n", + " io.count := count\n", + " assert(count =/= 10.U, \"the count must stay below 10\")\n", + "}\n", + "\n", + "try {\n", + " simulate(new CountTo9) { c =>\n", + " c.io.enable.poke(true.B)\n", + " c.clock.step(9) // 0 to 9: fine\n", + " println(\"up to 9: no failure\")\n", + " c.clock.step(11)\n", + " }\n", + " println(\"no assertion fired\")\n", + "} catch {\n", + " case e: AssertionFailed => println(e.simulatorOutput)\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Chisel 7 puts assertions in a *verification layer*: a separate SystemVerilog file bound to the module\n", + "(`getVerilog` shows it after the module). ChiselSim includes the layers by default, and the `simulate`\n", + "of this bootcamp says so (`verilogLayers = LayerControl.EnableAll`); another tool flow must include\n", + "those files too, or the assertions are silently gone.\n", + "\n", + "`assume(condition)` and `cover(condition)` go in layers of their own. They are for formal tools: an\n", + "`assume` states what may be taken for granted about the inputs (a simulation checks it like an\n", + "`assert`), and a `cover` asks for a run in which the condition happens (a simulation reports nothing).\n", + "\n", + "## Properties over several cycles\n", + "\n", + "`assert` checks one cycle. `chisel3.ltl` describes properties over time, as SystemVerilog assertions\n", + "do: `a |=> b` says that whenever `a` holds, `b` holds in the next cycle, and `AssertProperty` checks it\n", + "at every edge. A handshake must acknowledge each request one cycle later; this one never does, and the\n", + "report names the property by its label:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3.ltl._\n", + "import chisel3.ltl.Sequence._ // |=> and the other operators on Bools\n", + "\n", + "class Handshake extends Module {\n", + " val io = IO(new Bundle {\n", + " val req = Input(Bool())\n", + " val ack = Output(Bool())\n", + " })\n", + " io.ack := false.B // the bug: it should be RegNext(io.req, false.B)\n", + " AssertProperty(io.req |=> io.ack, label = Some(\"ack_after_req\"))\n", + "}\n", + "\n", + "try {\n", + " simulate(new Handshake) { c =>\n", + " c.io.req.poke(true.B)\n", + " c.clock.step(5)\n", + " }\n", + " println(\"no assertion fired\")\n", + "} catch {\n", + " case e: AssertionFailed => println(e.simulatorOutput)\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Waveforms\n", + "\n", + "When a test fails and the reason is not obvious, look at the waveform: every signal of the design, cycle\n", + "by cycle. `simulate(..., waves = \"name\")` makes Verilator dump a VCD (Value Change Dump) file from the\n", + "start of the simulation into `build/name/`, and prints the path of the file (even when the test fails).\n", + "In an sbt project whose tests use ChiselSim's ScalaTest support, the test option `-DemitVcd=1` does the\n", + "same." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class Counter4 extends Module {\n", + " val io = IO(new Bundle {\n", + " val enable = Input(Bool())\n", + " val count = Output(UInt(4.W))\n", + " })\n", + " val count = RegInit(0.U(4.W))\n", + " when(io.enable) { count := count + 1.U }\n", + " io.count := count\n", + "}\n", + "\n", + "simulate(new Counter4, waves = \"counter4\") { c =>\n", + " c.io.enable.poke(true.B)\n", + " c.clock.step(5)\n", + " c.io.enable.poke(false.B)\n", + " c.clock.step(2)\n", + " c.io.count.expect(5.U)\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A VCD file is text, so you can peek at it here, but it is meant for a waveform viewer:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val vcd = wavesFile(\"counter4\").get // the file printed above\n", + "println(os.read.lines(vcd).filter(_.trim.startsWith(\"$var\")).take(6).mkString(\"\\n\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The Docker image has no graphical viewer. To look at the waves, get the file out of the container and\n", + "open it on your computer:\n", + "\n", + "- copy the file (the path that `simulate` printed) out of the running container:\n", + " `docker cp : .`\n", + " (`docker ps` shows the container's name; start it with `--name bootcamp` to choose one); or\n", + "- mount a directory of your computer as `build`:\n", + " `mkdir -p build && docker run -it --rm -p 8888:8888 -v \"$PWD/build:/chisel-bootcamp/build\" sysprog21/chisel-bootcamp`.\n", + " The container's user has id 1000, so on Linux this works only if yours does too (`id -u`); Docker\n", + " Desktop on macOS and Windows does not care;\n", + "- open it with [GTKWave](https://gtkwave.sourceforge.net/) (`gtkwave trace.vcd`) or in the browser with\n", + " [Surfer](https://app.surfer-project.org/) (drop the file onto the page).\n", + "\n", + "In a long simulation, dump only the part you care about: `disableWaves()` and `enableWaves()` (defined\n", + "by this bootcamp's setup) stop and restart the dump from inside the body of a\n", + "`simulate(..., waves = \"name\")`. This setup dumps VCD; FSDB, for example, needs Synopsys VCS." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new Counter4, waves = \"counter4-window\") { c =>\n", + " disableWaves() // skip the 100 cycles after reset\n", + " c.io.enable.poke(true.B)\n", + " c.clock.step(100)\n", + " enableWaves()\n", + " c.clock.step(5)\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Tests in files\n", + "\n", + "A notebook is the place to explore a design. A project keeps its tests in files instead, and runs all\n", + "of them, unattended, with a test framework. ChiselSim works with ScalaTest. A test class extends\n", + "`AnyFlatSpec with ChiselSim`. Each `\"thing\" should \"do something\" in { ... }` is one test, and its\n", + "body calls `simulate` as the cells above do (that `simulate` also holds `reset` high for one cycle\n", + "first, like ours).\n", + "\n", + "Module 5 builds a processor in such a project, `riscv/`, whose tests are in\n", + "`riscv/src/test/scala/riscv/`. Here is one; it tests two parts of Module 5's processor (a memory and\n", + "its handshake), so only its shape matters now:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"test\" / \"scala\" / \"riscv\" / \"MemorySpec.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To run it, open a terminal in `riscv/` and use sbt, the project's build tool (`Install.md` says how):\n", + "\n", + "- `sbt test` runs every test;\n", + "- `sbt \"testOnly riscv.MemorySpec\"` runs the tests of one class;\n", + "- `sbt \"testOnly riscv.MemorySpec -- -DemitVcd=1\"` also dumps the waveforms of its simulations." + ] + }, { "cell_type": "markdown", "metadata": {}, diff --git a/2.7_enums_and_bundles.ipynb b/2.7_enums_and_bundles.ipynb new file mode 100644 index 0000000..15ff4bc --- /dev/null +++ b/2.7_enums_and_bundles.ipynb @@ -0,0 +1,705 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 2.7: Enums, Decoders and Bundles\n", + "**Prev: [Testing with ChiselSim](2.6_chiselsim.ipynb)**
\n", + "**Next: [Memories](2.8_memories.ipynb)**\n", + "\n", + "## Motivation\n", + "A processor is full of small encodings: the state of a controller, the operation an ALU performs,\n", + "the fields of an instruction word. Writing them as bare `UInt` constants works, but the compiler then\n", + "cannot tell an ALU operation from a register number. This module shows the Chisel tools that give\n", + "these encodings names and types:\n", + "\n", + "- `ChiselEnum` for named states and operation codes, and `switch`/`is` to branch on them;\n", + "- `BitPat` to match bit patterns with don't-care bits, with `ListLookup` and `decoder`;\n", + "- `MixedVec` for a vector whose elements have different types;\n", + "- the connection operators `:<>=`, `:<=` and `:>=` for bundles with signals in both directions.\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.Input // avoid a name clash with almond.input.Input\n", + "import chisel3.util._\n", + "import chisel3.simulator.PeekPokeAPI._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# ChiselEnum\n", + "\n", + "A `ChiselEnum` is a hardware type with a fixed set of named values. Each `Value` gets the next\n", + "encoding, starting at 0, and the width is the smallest that holds them all:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "object Color extends ChiselEnum {\n", + " val Red, Green, Blue = Value\n", + "}\n", + "\n", + "println(Color.all.map(c => s\"${c} = ${c.litValue}\").mkString(\", \"))\n", + "println(s\"width: ${Color.getWidth} bits\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also choose the encodings, for example to match a specification. They must be literals in\n", + "increasing order. A value declared without an encoding takes the next one:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "object Opcode extends ChiselEnum {\n", + " val Load = Value(\"b0000011\".U)\n", + " val Fence = Value(\"b0001111\".U)\n", + " val OpImm = Value(\"b0010011\".U)\n", + " val Auipc = Value(\"b0010111\".U)\n", + " val Store = Value(\"b0100011\".U)\n", + " val Op = Value(\"b0110011\".U)\n", + " val Lui = Value(\"b0110111\".U)\n", + " val Branch = Value(\"b1100011\".U)\n", + " val Jalr = Value(\"b1100111\".U)\n", + " val Jal = Value(\"b1101111\".U)\n", + " val System = Value(\"b1110011\".U)\n", + "}\n", + "println(s\"width: ${Opcode.getWidth} bits\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "These are the 11 major opcodes of RV32I. An enum is used like any other Chisel type: `Opcode()`\n", + "makes a port or wire of that type, and the values are compared with `===`. Converting between an\n", + "enum and its encoding is explicit: `.asUInt` gives the encoding, and `Opcode(x)` turns a `UInt`\n", + "back into an `Opcode`.\n", + "\n", + "That last conversion is risky when `x` can hold an encoding that is not a member: `Opcode` uses\n", + "7 bits, but only 11 of the 128 values are opcodes. Chisel warns at elaboration time about such a\n", + "cast (and rejects a `UInt` wider than the enum). `Opcode.safe(x)` is the cast without the warning:\n", + "it returns the enum together with a `Bool` that says whether `x` is a valid member, so the design\n", + "handles the other values explicitly (here, with an illegal-instruction flag):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class OpcodeCheck extends Module {\n", + " val io = IO(new Bundle {\n", + " val bits = Input(UInt(7.W))\n", + " val isStore = Output(Bool())\n", + " val illegal = Output(Bool())\n", + " })\n", + " val (opcode, valid) = Opcode.safe(io.bits)\n", + " io.isStore := valid && opcode === Opcode.Store\n", + " io.illegal := !valid\n", + "}\n", + "\n", + "simulate(new OpcodeCheck) { c =>\n", + " c.io.bits.poke(\"b0100011\".U)\n", + " c.io.isStore.expect(true.B)\n", + " c.io.illegal.expect(false.B)\n", + " c.io.bits.poke(\"b1111111\".U)\n", + " c.io.illegal.expect(true.B)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# switch and is\n", + "\n", + "`switch`/`is` is a `when` chain that compares one signal against literal values. It reads well with\n", + "enums, so it is the usual way to write a state machine. Here is a controller that waits for a request,\n", + "spends two cycles working, and then reports that it is done:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "object State extends ChiselEnum {\n", + " val Idle, Busy1, Busy2, Done = Value\n", + "}\n", + "\n", + "class Controller extends Module {\n", + " val io = IO(new Bundle {\n", + " val start = Input(Bool())\n", + " val done = Output(Bool())\n", + " })\n", + " val state = RegInit(State.Idle)\n", + " switch(state) {\n", + " is(State.Idle) { when(io.start) { state := State.Busy1 } }\n", + " is(State.Busy1) { state := State.Busy2 }\n", + " is(State.Busy2) { state := State.Done }\n", + " is(State.Done) { state := State.Idle }\n", + " }\n", + " io.done := state === State.Done\n", + "}\n", + "\n", + "println(getVerilog(new Controller))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the SystemVerilog, `state` is a plain 2-bit register and the states are the constants 0 to 3:\n", + "enums cost nothing in hardware. The names live in your Chisel code, where the compiler checks that a\n", + "`State` is never compared with, say, an `Opcode`.\n", + "\n", + "**Exercise: Traffic Light**
\n", + "Complete the traffic light below. It shows `Green` for 3 cycles, then `Yellow` for 1 cycle, then\n", + "`Red` for 2 cycles, and starts again with `Green`. The counter `timer` counts down; when it reaches 0,\n", + "move to the next state and load `timer` with the duration of that state minus one." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "object Light extends ChiselEnum {\n", + " val Green, Yellow, Red = Value\n", + "}\n", + "\n", + "class TrafficLight extends Module {\n", + " val io = IO(new Bundle {\n", + " val light = Output(Light())\n", + " })\n", + " val state = RegInit(Light.Green)\n", + " val timer = RegInit(2.U(2.W)) // Green lasts 3 cycles: 2, 1, 0\n", + " io.light := state\n", + "\n", + " when(timer =/= 0.U) {\n", + " timer := timer - 1.U\n", + " }.otherwise {\n", + " ???\n", + " }\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new TrafficLight) { c =>\n", + " val expected = Seq.fill(3)(Light.Green) ++ Seq(Light.Yellow) ++ Seq.fill(2)(Light.Red)\n", + " for (cycle <- 0 until 12) {\n", + " c.io.light.expect(expected(cycle % expected.length))\n", + " c.clock.step()\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "    switch(state) {\n",
+    "      is(Light.Green)  { state := Light.Yellow; timer := 0.U }\n",
+    "      is(Light.Yellow) { state := Light.Red;    timer := 1.U }\n",
+    "      is(Light.Red)    { state := Light.Green;  timer := 2.U }\n",
+    "    }\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# BitPat: matching with don't-care bits\n", + "\n", + "A `BitPat` is a bit pattern in which `?` matches either value. It is compared with a `UInt` using `===`.\n", + "RISC-V instructions are a good example: the `ADDI` instruction is any 32-bit word whose `funct3` field\n", + "(bits 14 to 12) is `000` and whose opcode (bits 6 to 0) is `0010011`; the other bits are operands." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val ADDI = BitPat(\"b?????????????????000?????0010011\")\n", + "val ADD = BitPat(\"b0000000??????????000?????0110011\")\n", + "\n", + "class IsAddi extends Module {\n", + " val io = IO(new Bundle {\n", + " val inst = Input(UInt(32.W))\n", + " val addi = Output(Bool())\n", + " })\n", + " io.addi := ADDI === io.inst\n", + "}\n", + "\n", + "simulate(new IsAddi) { c =>\n", + " c.io.inst.poke(\"h00500093\".U) // addi x1, x0, 5\n", + " c.io.addi.expect(true.B)\n", + " c.io.inst.poke(\"h002081b3\".U) // add x3, x1, x2\n", + " c.io.addi.expect(false.B)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`ListLookup(key, default, mapping)` matches a key against a list of `BitPat`s and returns the list of\n", + "signals of the first match (or `default`). Each entry of the list is one control signal, so one table\n", + "describes a whole decoder:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class TinyDecoder extends Module {\n", + " val io = IO(new Bundle {\n", + " val inst = Input(UInt(32.W))\n", + " val regWrite = Output(Bool())\n", + " val useImm = Output(Bool())\n", + " })\n", + " // each list is (regWrite, useImm)\n", + " val signals = ListLookup(\n", + " io.inst,\n", + " List(false.B, false.B),\n", + " Array(\n", + " ADDI -> List(true.B, true.B),\n", + " ADD -> List(true.B, false.B)\n", + " )\n", + " )\n", + " io.regWrite := signals(0)\n", + " io.useImm := signals(1)\n", + "}\n", + "println(getVerilog(new TinyDecoder))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Why not `MuxLookup`? `MuxLookup(key, default)(Seq(k1 -> v1, ...))` compares `key === k` exactly, for\n", + "keys that are hardware `UInt`s (or values of a `ChiselEnum`), so every bit takes part\n", + "in the comparison. A `BitPat` is not a hardware value: it describes a set of values, so it cannot be a\n", + "`MuxLookup` key. Use `MuxLookup` for exact keys and `ListLookup` (or `decoder`, below) for patterns.\n", + "\n", + "`chisel3.util.experimental.decode.decoder` goes one step further: it takes a whole truth table of\n", + "input and output `BitPat`s and minimizes the logic. `decoder.qmc` uses the Quine-McCluskey minimizer\n", + "that is built into Chisel (`decoder(...)` tries the external `espresso` tool first, and logs an error\n", + "and falls back to Quine-McCluskey when it is not installed). Here the outputs are the two signals of `TinyDecoder`, packed into 2 bits:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3.util.experimental.decode.{decoder, TruthTable}\n", + "\n", + "class TableDecoder extends Module {\n", + " val io = IO(new Bundle {\n", + " val inst = Input(UInt(32.W))\n", + " val regWrite = Output(Bool())\n", + " val useImm = Output(Bool())\n", + " })\n", + " val table = TruthTable(\n", + " Seq(\n", + " ADDI -> BitPat(\"b11\"),\n", + " ADD -> BitPat(\"b10\")\n", + " ),\n", + " default = BitPat(\"b00\")\n", + " )\n", + " val out = decoder.qmc(io.inst, table)\n", + " io.regWrite := out(1)\n", + " io.useImm := out(0)\n", + "}\n", + "\n", + "simulate(new TableDecoder) { c =>\n", + " c.io.inst.poke(\"h00500093\".U) // addi\n", + " c.io.regWrite.expect(true.B)\n", + " c.io.useImm.expect(true.B)\n", + " c.io.inst.poke(\"h002081b3\".U) // add\n", + " c.io.regWrite.expect(true.B)\n", + " c.io.useImm.expect(false.B)\n", + " c.io.inst.poke(\"h00000000\".U) // not in the table\n", + " c.io.regWrite.expect(false.B)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Exercise: Instruction Format**
\n", + "Every RISC-V instruction has one of six formats (R, I, S, B, U and J) that says where its operands and\n", + "its immediate are. The format depends only on the opcode, the low 7 bits of the instruction:\n", + "\n", + "| Opcode (bits 6-0) | Instructions | Format |\n", + "| :--- | :--- | :--- |\n", + "| `0110011` | register-register (`add`, ...) | R |\n", + "| `0010011`, `0000011`, `1100111`, `0001111`, `1110011` | register-immediate (`addi`, ...), loads, `jalr`, `fence`, `ecall`/`ebreak` | I |\n", + "| `0100011` | stores | S |\n", + "| `1100011` | branches | B |\n", + "| `0110111`, `0010111` | `lui`, `auipc` | U |\n", + "| `1101111` | `jal` | J |\n", + "\n", + "Complete `FormatDecoder` with `ListLookup` (or `decoder.qmc`) so that `format` is the format of `inst`,\n", + "and `valid` is false for every other opcode (then `format` does not matter). The helper `op` builds a\n", + "`BitPat` that matches any instruction with the given opcode." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "object Format extends ChiselEnum {\n", + " val R, I, S, B, U, J = Value\n", + "}\n", + "\n", + "class FormatDecoder extends Module {\n", + " val io = IO(new Bundle {\n", + " val inst = Input(UInt(32.W))\n", + " val format = Output(Format())\n", + " val valid = Output(Bool())\n", + " })\n", + " def op(bits: String) = BitPat(\"b\" + \"?\" * 25 + bits) // matches any instruction with this opcode\n", + "\n", + " ???\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new FormatDecoder) { c =>\n", + " val cases = Seq(\n", + " \"h002081b3\" -> Format.R, // add x3, x1, x2\n", + " \"h00500093\" -> Format.I, // addi x1, x0, 5\n", + " \"h0040a103\" -> Format.I, // lw x2, 4(x1)\n", + " \"h000080e7\" -> Format.I, // jalr x1, 0(x1)\n", + " \"h0ff0000f\" -> Format.I, // fence\n", + " \"h00000073\" -> Format.I, // ecall\n", + " \"h0020a223\" -> Format.S, // sw x2, 4(x1)\n", + " \"h00208463\" -> Format.B, // beq x1, x2, 8\n", + " \"h000010b7\" -> Format.U, // lui x1, 1\n", + " \"h00001097\" -> Format.U, // auipc x1, 1\n", + " \"h008000ef\" -> Format.J // jal x1, 8\n", + " )\n", + " for ((inst, format) <- cases) {\n", + " c.io.inst.poke(inst.U)\n", + " c.io.valid.expect(true.B, s\"instruction $inst\")\n", + " c.io.format.expect(format, s\"instruction $inst\")\n", + " }\n", + " c.io.inst.poke(\"h0000000b\".U) // custom-0 opcode: not RV32I\n", + " c.io.valid.expect(false.B)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  val signals = ListLookup(io.inst, List(false.B, Format.R), Array(\n",
+    "    op(\"0110011\") -> List(true.B, Format.R),\n",
+    "    op(\"0010011\") -> List(true.B, Format.I),\n",
+    "    op(\"0000011\") -> List(true.B, Format.I),\n",
+    "    op(\"1100111\") -> List(true.B, Format.I),\n",
+    "    op(\"0001111\") -> List(true.B, Format.I),\n",
+    "    op(\"1110011\") -> List(true.B, Format.I),\n",
+    "    op(\"0100011\") -> List(true.B, Format.S),\n",
+    "    op(\"1100011\") -> List(true.B, Format.B),\n",
+    "    op(\"0110111\") -> List(true.B, Format.U),\n",
+    "    op(\"0010111\") -> List(true.B, Format.U),\n",
+    "    op(\"1101111\") -> List(true.B, Format.J)\n",
+    "  ))\n",
+    "  io.valid  := signals(0)\n",
+    "  io.format := signals(1)\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# MixedVec\n", + "\n", + "A `Vec` holds elements of one type. When a generator needs a vector whose elements have different\n", + "widths or even different types, use `MixedVec`. Its elements are indexed with Scala integers\n", + "(`v(0)`, `v(1)`), not with hardware signals, because there is no single type a dynamic index could return." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class Widths extends Module {\n", + " val io = IO(new Bundle {\n", + " val out = Output(MixedVec(Seq(UInt(4.W), UInt(8.W), Bool())))\n", + " })\n", + " io.out(0) := 15.U\n", + " io.out(1) := 255.U\n", + " io.out(2) := true.B\n", + "}\n", + "println(getVerilog(new Widths))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Exercise: Field Splitter**
\n", + "Write a generator that splits a word into fields of the given widths, starting at the least significant\n", + "bit. For `widths = Seq(7, 5, 3)` and a 15-bit input, `fields(0)` is bits 6-0, `fields(1)` is bits 11-7\n", + "and `fields(2)` is bits 14-12 (these are the `opcode`, `rd` and `funct3` fields of a RISC-V instruction)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class FieldSplitter(widths: Seq[Int]) extends Module {\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(widths.sum.W))\n", + " val fields = Output(MixedVec(widths.map(w => UInt(w.W))))\n", + " })\n", + " ???\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def checkSplitter(widths: Seq[Int]): Unit = simulate(new FieldSplitter(widths)) { c =>\n", + " val rnd = new scala.util.Random(0)\n", + " val offsets = widths.scanLeft(0)(_ + _)\n", + " for (_ <- 0 until 50) {\n", + " val word = BigInt(widths.sum, rnd)\n", + " c.io.in.poke(word.U)\n", + " for (i <- widths.indices) {\n", + " val field = (word >> offsets(i)) & ((BigInt(1) << widths(i)) - 1)\n", + " c.io.fields(i).expect(field.U, s\"widths $widths, field $i\")\n", + " }\n", + " }\n", + "}\n", + "checkSplitter(Seq(7, 5, 3))\n", + "checkSplitter(Seq(1, 4, 8, 3))\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  // the offset of each field is the sum of the widths before it\n",
+    "  val offsets = widths.scanLeft(0)(_ + _)\n",
+    "  for (i <- widths.indices) {\n",
+    "    io.fields(i) := io.in(offsets(i) + widths(i) - 1, offsets(i))\n",
+    "  }\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Connecting bundles with signals in both directions\n", + "\n", + "A ready-valid interface (`Decoupled`) has signals that flow forward (`valid`, `bits`) and one that\n", + "flows backward (`ready`). Seen from the bundle named on one side of a connection (say `io.out`), the\n", + "fields that point the same way as that bundle are *aligned*, and the ones under a `Flipped` are\n", + "*flipped*. Chisel 7 has a family of connection operators that say which of them to connect, always\n", + "written `consumer producer`:\n", + "\n", + "| Operator | Connects | Typical use |\n", + "| :--- | :--- | :--- |\n", + "| `c :<>= p` | aligned fields from `p` to `c`, and flipped fields from `c` to `p` | pass an interface through |\n", + "| `c :<= p` | only the aligned fields, from `p` to `c` | the forward half |\n", + "| `c :>= p` | only the flipped fields, from `c` to `p` | the backward half |\n", + "\n", + "`:<>=` is exactly `:<=` and `:>=` together. Splitting it lets you insert logic in one direction. Below,\n", + "a `Gate` passes a stream through but only lets data through while `enable` is set: the forward\n", + "signals are connected with `:<=` and then `valid` is overridden (last connect wins); `ready` is driven\n", + "by hand instead of `:>=`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class Gate extends Module {\n", + " val io = IO(new Bundle {\n", + " val enable = Input(Bool())\n", + " val in = Flipped(Decoupled(UInt(8.W)))\n", + " val out = Decoupled(UInt(8.W))\n", + " })\n", + " io.out :<= io.in // valid and bits forward\n", + " io.out.valid := io.in.valid && io.enable // then override valid\n", + " io.in.ready := io.out.ready && io.enable\n", + "}\n", + "\n", + "simulate(new Gate) { c =>\n", + " c.io.in.valid.poke(true.B)\n", + " c.io.in.bits.poke(42.U)\n", + " c.io.out.ready.poke(true.B)\n", + " c.io.enable.poke(false.B)\n", + " c.io.out.valid.expect(false.B)\n", + " c.io.in.ready.expect(false.B)\n", + " c.io.enable.poke(true.B)\n", + " c.io.out.valid.expect(true.B)\n", + " c.io.out.bits.expect(42.U)\n", + " c.io.in.ready.expect(true.B)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When nothing needs to be inserted, `:<>=` passes the whole interface through in one line, and the\n", + "SystemVerilog shows both directions connected:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class PassThrough extends Module {\n", + " val io = IO(new Bundle {\n", + " val in = Flipped(Decoupled(UInt(8.W)))\n", + " val out = Decoupled(UInt(8.W))\n", + " })\n", + " io.out :<>= io.in\n", + "}\n", + "println(getVerilog(new PassThrough))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The older `<>` also connects both directions, but it decides which side drives each field from where\n", + "each side lives (a port of this module, a port of a child, or a wire). The new operators use only the\n", + "types, so ports and wires behave the same.\n", + "\n", + "They also check more: both sides must have the same fields, flipped the same way, and a connection\n", + "that could truncate a value is an error (mark the producer with `.squeeze` if you mean it).\n", + "\n", + "---\n", + "# You're done!\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/2.8_memories.ipynb b/2.8_memories.ipynb new file mode 100644 index 0000000..5cc35c1 --- /dev/null +++ b/2.8_memories.ipynb @@ -0,0 +1,649 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 2.8: Memories\n", + "**Prev: [Enums, Decoders and Bundles](2.7_enums_and_bundles.ipynb)**
\n", + "**Next: [Generators: Parameters](3.1_parameters.ipynb)**\n", + "\n", + "## Motivation\n", + "Registers are fine for a few values, but a processor needs memories: a register file, an instruction\n", + "memory, a data memory, caches. A memory is an array of words with *ports*, each of which reads or\n", + "writes one word per cycle. This module shows the memories Chisel provides and how they behave in\n", + "simulation:\n", + "\n", + "- `Mem`: reads are combinational (the data comes back in the same cycle);\n", + "- `SyncReadMem`: reads take one clock cycle, like the SRAM blocks of FPGAs and ASICs;\n", + "- write masks, to write only some bytes of a word;\n", + "- `SRAM`, a memory described by its ports, and initializing a memory from a file;\n", + "- a register file with two read ports, which you will reuse when building a RISC-V processor.\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.Input // avoid a name clash with almond.input.Input\n", + "import chisel3.util._\n", + "import chisel3.simulator.PeekPokeAPI._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Mem: combinational read\n", + "\n", + "`Mem(n, t)` is `n` words of type `t`. `mem(addr)` (or `mem.read(addr)`) reads a word and\n", + "`mem.write(addr, data)` writes one. Writes take effect at the next rising clock edge, like a\n", + "register; reads of a `Mem` are combinational, so the data is available in the same cycle as the\n", + "address." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// the ports of the memories below: one write port and one read port\n", + "class MemPorts extends Bundle {\n", + " val wen = Input(Bool())\n", + " val waddr = Input(UInt(4.W))\n", + " val wdata = Input(UInt(8.W))\n", + " val raddr = Input(UInt(4.W))\n", + " val rdata = Output(UInt(8.W))\n", + "}\n", + "\n", + "class CombMemory extends Module {\n", + " val io = IO(new MemPorts)\n", + " val mem = Mem(16, UInt(8.W))\n", + " when(io.wen) { mem.write(io.waddr, io.wdata) }\n", + " io.rdata := mem(io.raddr)\n", + "}\n", + "\n", + "simulate(new CombMemory) { c =>\n", + " c.io.wen.poke(true.B)\n", + " c.io.waddr.poke(3.U)\n", + " c.io.wdata.poke(42.U)\n", + " c.io.raddr.poke(3.U)\n", + " c.clock.step() // the write happens at this clock edge\n", + " c.io.wen.poke(false.B)\n", + " c.io.rdata.expect(42.U) // and the read sees it without another edge\n", + " c.io.wdata.poke(7.U)\n", + " c.io.wen.poke(true.B) // overwrite address 3 ...\n", + " c.io.rdata.expect(42.U) // ... but until the edge, the read returns the old value\n", + " c.clock.step()\n", + " c.io.rdata.expect(7.U)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "> The contents of a memory are unknown until they are written (simulators may start them at zero or\n", + "> at random values), so never rely on the initial value.\n", + "\n", + "A combinational read is convenient (a single-cycle processor reads its register file and its memory\n", + "in the same cycle as it decodes), but large memories cannot be built that way. SRAM macros and FPGA\n", + "block RAMs register the address (or the data), so their reads take one cycle.\n", + "\n", + "---\n", + "# SyncReadMem: one-cycle read\n", + "\n", + "`SyncReadMem` reads synchronously: the address is sampled at the clock edge and the data is valid\n", + "after it. Compare with `CombMemory`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class SyncMemory extends Module {\n", + " val io = IO(new MemPorts)\n", + " val mem = SyncReadMem(16, UInt(8.W))\n", + " when(io.wen) { mem.write(io.waddr, io.wdata) }\n", + " io.rdata := mem.read(io.raddr)\n", + "}\n", + "\n", + "simulate(new SyncMemory) { c =>\n", + " c.io.wen.poke(true.B)\n", + " c.io.waddr.poke(3.U)\n", + " c.io.wdata.poke(42.U)\n", + " c.clock.step()\n", + " c.io.wen.poke(false.B)\n", + " c.io.raddr.poke(3.U)\n", + " c.clock.step() // the read address is sampled here\n", + " c.io.rdata.expect(42.U) // the data appears one cycle after the address\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What does a read return when the same address is written in the same cycle? A `SyncReadMem` takes\n", + "the answer as an optional third argument:\n", + "\n", + "| `SyncReadMem(n, t, ...)` | A read of the address being written returns |\n", + "| :--- | :--- |\n", + "| `SyncReadMem.ReadFirst` | the old data |\n", + "| `SyncReadMem.WriteFirst` | the new data |\n", + "| `SyncReadMem.Undefined` (the default) | either: do not rely on it |\n", + "\n", + "The argument is a request to the tools that build the memory, not a promise. Let's check what this\n", + "toolchain does: the test below writes and reads address 5 in the same cycle with both policies." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class ReadUnderWrite(ruw: SyncReadMem.ReadUnderWrite) extends Module {\n", + " val io = IO(new Bundle {\n", + " val wen = Input(Bool())\n", + " val addr = Input(UInt(4.W))\n", + " val wdata = Input(UInt(8.W))\n", + " val rdata = Output(UInt(8.W))\n", + " })\n", + " val mem = SyncReadMem(16, UInt(8.W), ruw)\n", + " when(io.wen) { mem.write(io.addr, io.wdata) }\n", + " io.rdata := mem.read(io.addr)\n", + "}\n", + "\n", + "for (ruw <- Seq(SyncReadMem.ReadFirst, SyncReadMem.WriteFirst)) {\n", + " simulate(new ReadUnderWrite(ruw)) { c =>\n", + " c.io.addr.poke(5.U)\n", + " c.io.wen.poke(true.B)\n", + " c.io.wdata.poke(1.U)\n", + " c.clock.step() // address 5 now holds 1\n", + " c.io.wdata.poke(2.U) // write 2 and read address 5 in the same cycle\n", + " c.clock.step()\n", + " println(s\"$ruw: the read returned ${c.io.rdata.peek().litValue} (old data 1, new data 2)\")\n", + " assert(c.io.rdata.peek().litValue == 2) // what firtool 1.160.0 builds, whatever the policy\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Both return the new data. `firtool` (version 1.160.0 here) builds every `SyncReadMem` the same way: it\n", + "registers the read address and reads the array after the clock edge, when the write has already\n", + "happened. So the policy is lost on the way to Verilog, and an FPGA or ASIC memory may behave\n", + "differently again. If a design needs one behavior, build it explicitly: for example, compare the read\n", + "and write addresses and forward the write data (or keep the old word in a register).\n", + "\n", + "---\n", + "# Write masks\n", + "\n", + "When the word type is a `Vec`, a write can take a mask with one `Bool` per element, and only the\n", + "elements whose mask bit is set are written. A memory of `Vec(4, UInt(8.W))` is a 32-bit memory\n", + "with a byte mask: exactly what a processor needs for byte (`sb`) and halfword (`sh`) stores." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class ByteMemory extends Module {\n", + " val io = IO(new Bundle {\n", + " val wen = Input(Bool())\n", + " val addr = Input(UInt(4.W))\n", + " val wdata = Input(Vec(4, UInt(8.W)))\n", + " val mask = Input(Vec(4, Bool()))\n", + " val rdata = Output(Vec(4, UInt(8.W)))\n", + " })\n", + " val mem = Mem(16, Vec(4, UInt(8.W)))\n", + " when(io.wen) { mem.write(io.addr, io.wdata, io.mask) }\n", + " io.rdata := mem(io.addr)\n", + "}\n", + "\n", + "simulate(new ByteMemory) { c =>\n", + " c.io.addr.poke(0.U)\n", + " c.io.wen.poke(true.B)\n", + " for (i <- 0 until 4) { c.io.wdata(i).poke((0x10 + i).U); c.io.mask(i).poke(true.B) }\n", + " c.clock.step() // the word is 13 12 11 10\n", + " for (i <- 0 until 4) { c.io.wdata(i).poke(0xff.U); c.io.mask(i).poke((i == 2).B) }\n", + " c.clock.step() // only byte 2 is written\n", + " c.io.wen.poke(false.B)\n", + " for ((expected, i) <- Seq(0x10, 0x11, 0xff, 0x13).zipWithIndex) c.io.rdata(i).expect(expected.U)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Exercise: Store Unit**
\n", + "RISC-V stores write a byte (`sb`), a halfword (`sh`) or a word (`sw`) at a byte address. Complete\n", + "`StoreUnit`, a 16-word memory that takes a byte address `addr`, a size (`0` for a byte, `1` for a\n", + "halfword, `2` for a word) and the value to store in the low bits of `wdata`. Bits 1-0 of the address\n", + "select the byte within the word (little-endian: byte 0 holds bits 7-0 of the word), and bits 5-2\n", + "select the word. Stores are aligned: a halfword starts at an even address and a word at a multiple of 4.\n", + "\n", + "Compute `mask` (which bytes to write) and `lanes` (the value moved to the bytes where it belongs).\n", + "For example, `sb` of `0xab` at address 6 writes byte 2 of word 1: `mask` is `false, false, true,\n", + "false` and `lanes(2)` is `0xab`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class StoreUnit extends Module {\n", + " val io = IO(new Bundle {\n", + " val wen = Input(Bool())\n", + " val addr = Input(UInt(6.W)) // byte address\n", + " val size = Input(UInt(2.W)) // 0: byte, 1: halfword, 2: word\n", + " val wdata = Input(UInt(32.W))\n", + " val raddr = Input(UInt(4.W)) // word address of the read port\n", + " val rdata = Output(UInt(32.W))\n", + " })\n", + " val mem = Mem(16, Vec(4, UInt(8.W)))\n", + " val offset = io.addr(1, 0)\n", + " val mask = Wire(Vec(4, Bool()))\n", + " val lanes = Wire(Vec(4, UInt(8.W)))\n", + "\n", + " ???\n", + "\n", + " when(io.wen) { mem.write(io.addr(5, 2), lanes, mask) }\n", + " io.rdata := mem(io.raddr).asUInt\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new StoreUnit) { c =>\n", + " val model = Array.fill(64)(0) // the memory, byte by byte\n", + " def wordOf(w: Int) = (0 until 4).map(i => BigInt(model(4 * w + i)) << (8 * i)).sum\n", + " val rnd = new scala.util.Random(1)\n", + " // the memory starts with random values: clear it with word stores first\n", + " c.io.wen.poke(true.B)\n", + " c.io.size.poke(2.U)\n", + " c.io.wdata.poke(0.U)\n", + " for (word <- 0 until 16) { c.io.addr.poke((4 * word).U); c.clock.step() }\n", + " for (_ <- 0 until 200) {\n", + " val size = rnd.nextInt(3)\n", + " val addr = rnd.nextInt(64) & ~((1 << size) - 1) // aligned\n", + " val data = rnd.nextLong() & 0xffffffffL\n", + " c.io.wen.poke(true.B)\n", + " c.io.addr.poke(addr.U)\n", + " c.io.size.poke(size.U)\n", + " c.io.wdata.poke(data.U)\n", + " c.clock.step()\n", + " for (i <- 0 until (1 << size)) model(addr + i) = ((data >> (8 * i)) & 0xff).toInt\n", + " // check the word just written, so a wrong mask is caught at the store that caused it\n", + " val word = addr >> 2\n", + " c.io.raddr.poke(word.U)\n", + " c.io.rdata.expect(wordOf(word).U, f\"store of size $size at 0x$addr%x\")\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  // the bytes the store covers, before shifting: 0001, 0011 or 1111\n",
+    "  val sizeMask = MuxLookup(io.size, \"b1111\".U(4.W))(Seq(0.U -> \"b0001\".U(4.W), 1.U -> \"b0011\".U(4.W)))\n",
+    "  mask  := (sizeMask << offset)(3, 0).asBools\n",
+    "  // move the data up by `offset` bytes\n",
+    "  lanes := (io.wdata << (offset ## 0.U(3.W)))(31, 0).asTypeOf(Vec(4, UInt(8.W)))\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "One caveat about masks. A memory can have several write ports, but `firtool` (version 1.160.0 here,\n", + "and 1.163.0 too; reported as [llvm/circt#11591](https://github.com/llvm/circt/issues/11591)) drops the write masks of a memory that has a masked write port and a write port\n", + "**without** a mask: each masked write then writes every byte. A constant mask of all ones counts as\n", + "no mask (it is optimized away). It happens to a `Mem` and a `SyncReadMem` alike. The Chisel side is\n", + "fine (the FIRRTL still has the mask); the masks disappear when `firtool` turns the memory into\n", + "Verilog. Write ports whose masks are all signals keep them. The simplest rule: give a memory that\n", + "needs a mask a single write port, with `Mux`es that select its address, data and mask from the\n", + "sources (all ones for a source that writes whole words), as the RAM of the Module 5 processor does\n", + "for its program loader and the processor's stores. Here, a second port without a mask, never even\n", + "used, is enough to lose the mask:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// the ByteMemory above, plus a second write port, without a mask\n", + "class TwoWritePorts extends Module {\n", + " val io = IO(new Bundle {\n", + " val wen = Input(Bool())\n", + " val mask = Input(Vec(4, Bool()))\n", + " val wdata = Input(Vec(4, UInt(8.W)))\n", + " val other = Input(Bool()) // never enabled below: the unmasked port's existence alone drops the mask\n", + " val rdata = Output(Vec(4, UInt(8.W)))\n", + " })\n", + " val mem = Mem(16, Vec(4, UInt(8.W)))\n", + " when(io.wen) { mem.write(0.U, io.wdata, io.mask) }\n", + " when(io.other) { mem.write(1.U, io.wdata) }\n", + " io.rdata := mem(0.U)\n", + "}\n", + "\n", + "simulate(new TwoWritePorts) { c =>\n", + " def pokeBytes(bytes: Seq[Int]) = for ((b, i) <- bytes.zipWithIndex) c.io.wdata(i).poke(b.U)\n", + " c.io.other.poke(false.B)\n", + " c.io.wen.poke(true.B)\n", + " c.io.mask.foreach(_.poke(true.B))\n", + " pokeBytes(Seq(0x44, 0x33, 0x22, 0x11)) // 0x11223344\n", + " c.clock.step()\n", + " c.io.mask(0).poke(false.B) // now write only bytes 2 and 3 of 0xaabbccdd\n", + " c.io.mask(1).poke(false.B)\n", + " pokeBytes(Seq(0xdd, 0xcc, 0xbb, 0xaa))\n", + " c.clock.step()\n", + " val bytes = c.io.rdata.map(_.peek().litValue.toInt)\n", + " val maskLost = bytes == Seq(0xdd, 0xcc, 0xbb, 0xaa) // 0xaabb3344 if the mask had been kept\n", + " println(bytes.reverse.map(b => f\"$b%02x\").mkString(\"0x\", \"\", \"\") + (if (maskLost) \": the mask was lost\" else \"\"))\n", + " assert(maskLost, \"firtool now keeps the mask: this section can be updated\")\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# SRAM: a memory described by its ports\n", + "\n", + "`SRAM(size, type, numReadPorts, numWritePorts, numReadwritePorts)` builds a synchronous-read memory\n", + "(like a `SyncReadMem`) and returns its ports as a bundle: `readPorts`, `writePorts` and `readwritePorts`, each port with an\n", + "`address`, an `enable` and its data. Describing a memory by its ports is how memory compilers and\n", + "FPGA tools see memories. The read port's `enable` saves power when the data is not needed." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class TwoPortSram extends Module {\n", + " val io = IO(new MemPorts)\n", + " val sram = SRAM(16, UInt(8.W), 1, 1, 0) // 1 read port, 1 write port, 0 read-write ports\n", + " sram.writePorts(0).enable := io.wen\n", + " sram.writePorts(0).address := io.waddr\n", + " sram.writePorts(0).data := io.wdata\n", + " sram.readPorts(0).enable := true.B\n", + " sram.readPorts(0).address := io.raddr\n", + " io.rdata := sram.readPorts(0).data\n", + "}\n", + "\n", + "simulate(new TwoPortSram) { c =>\n", + " c.io.wen.poke(true.B)\n", + " c.io.waddr.poke(9.U)\n", + " c.io.wdata.poke(99.U)\n", + " c.clock.step()\n", + " c.io.wen.poke(false.B)\n", + " c.io.raddr.poke(9.U)\n", + " c.clock.step() // synchronous read, as for a SyncReadMem\n", + " c.io.rdata.expect(99.U)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`SRAM` also has variants that take a `HexMemoryFile` or `BinaryMemoryFile` to load the memory when\n", + "the simulation starts. In Chisel 7.16.0, `SRAM` accepts that file and silently ignores it, in the\n", + "default implementation above and in the SRAM black-box flow alike. To initialize a memory, use the\n", + "method below.\n", + "\n", + "---\n", + "# Initializing a memory from a file\n", + "\n", + "`chisel3.util.experimental.loadMemoryFromFileInline(mem, path)` loads a `Mem` or `SyncReadMem` from a\n", + "file; each line of a hex file holds one word, and the optional third argument\n", + "`MemoryLoadFileType.Binary` selects binary instead. It only *emits* a Verilog `$readmemh` (or\n", + "`$readmemb`) directive with the file's path: the file is read when the simulation starts, not when\n", + "Chisel runs. So the file must exist by then, and its path must be valid from the simulator's working\n", + "directory, which ChiselSim chooses: use an absolute path.\n", + "\n", + "There is one more catch in simulation. By default ChiselSim fills every memory with random values at\n", + "start (to catch designs that read memory before writing it), and that happens *after* `$readmemh`,\n", + "overwriting the file's contents. Pass `randomization = Randomization.random.copy(memories = false)`\n", + "to `simulate` to turn it off for memories only (registers still start random, which catches a missing\n", + "reset)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3.util.experimental.loadMemoryFromFileInline\n", + "import chisel3.simulator.Randomization\n", + "\n", + "val romFile = os.pwd / \"build\" / \"rom.hex\"\n", + "val romWords = Seq(0x11, 0x22, 0x33, 0x44)\n", + "os.write.over(romFile, romWords.map(w => f\"$w%02x\\n\").mkString, createFolders = true) // one hex word per line\n", + "\n", + "class Rom(path: String) extends Module {\n", + " val io = IO(new Bundle {\n", + " val addr = Input(UInt(2.W))\n", + " val data = Output(UInt(8.W))\n", + " })\n", + " val mem = Mem(4, UInt(8.W))\n", + " loadMemoryFromFileInline(mem, path)\n", + " io.data := mem(io.addr)\n", + "}\n", + "\n", + "println(getVerilog(new Rom(romFile.toString)).split(\"\\n\").filter(_.contains(\"readmem\")).mkString(\"\\n\"))\n", + "simulate(new Rom(romFile.toString), randomization = Randomization.random.copy(memories = false)) { c =>\n", + " for (i <- 0 until 4) {\n", + " c.io.addr.poke(i.U)\n", + " c.io.data.expect(romWords(i).U)\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Register file\n", + "\n", + "A RISC-V processor has 32 registers `x0`-`x31` of 32 bits. Each instruction reads up to two of them\n", + "(`rs1` and `rs2`) and writes at most one (`rd`), so the register file has two combinational read\n", + "ports and one write port. Register `x0` is special: it always reads as zero, and writes to it are\n", + "ignored.\n", + "\n", + "ChiselSim's `peek` and `poke` only reach the ports of the module under test, not the contents of\n", + "a memory inside it. To check the whole register file, the module also has a *debug* read port,\n", + "`dbgAddr`/`dbgData`, that tests (and later, debuggers) can use without disturbing the processor's\n", + "ports.\n", + "\n", + "**Exercise: Register File**
\n", + "Complete `RegFile`: the two read ports and the debug port read the register at their address (0 for\n", + "`x0`), and a write with `wen` set stores `wdata` into register `rd` at the clock edge, unless `rd`\n", + "is 0. A read in the same cycle as a write to the same register returns the old value; the new value\n", + "is visible from the next cycle." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class RegFile extends Module {\n", + " val io = IO(new Bundle {\n", + " val rs1 = Input(UInt(5.W))\n", + " val rs2 = Input(UInt(5.W))\n", + " val rs1Data = Output(UInt(32.W))\n", + " val rs2Data = Output(UInt(32.W))\n", + " val wen = Input(Bool())\n", + " val rd = Input(UInt(5.W))\n", + " val wdata = Input(UInt(32.W))\n", + " val dbgAddr = Input(UInt(5.W))\n", + " val dbgData = Output(UInt(32.W))\n", + " })\n", + " val regs = Mem(32, UInt(32.W))\n", + "\n", + " ???\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The test compares the register file with a Scala model (an array of 32 values) on random reads and\n", + "writes. It uses a fixed seed, so a failure is the same every time you run it. Writes to `x0` are\n", + "made more frequent than random, since that is the case most likely to be wrong. The registers start\n", + "with random values in simulation (as in hardware), so the test first writes every one of them." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new RegFile) { c =>\n", + " val model = Array.fill(32)(BigInt(0))\n", + " val rnd = new scala.util.Random(2)\n", + " // the registers start with random values: give each one a known value first\n", + " c.io.wen.poke(true.B)\n", + " for (r <- 1 until 32) {\n", + " model(r) = BigInt(32, rnd)\n", + " c.io.rd.poke(r.U)\n", + " c.io.wdata.poke(model(r).U)\n", + " c.clock.step()\n", + " }\n", + " def reg() = if (rnd.nextInt(8) == 0) 0 else rnd.nextInt(32)\n", + " for (cycle <- 0 until 500) {\n", + " val (rs1, rs2, rd) = (reg(), reg(), reg())\n", + " val wen = rnd.nextBoolean()\n", + " val wdata = BigInt(32, rnd)\n", + " c.io.rs1.poke(rs1.U)\n", + " c.io.rs2.poke(rs2.U)\n", + " c.io.rd.poke(rd.U)\n", + " c.io.wen.poke(wen.B)\n", + " c.io.wdata.poke(wdata.U)\n", + " c.io.rs1Data.expect(model(rs1).U, s\"cycle $cycle: x$rs1\")\n", + " c.io.rs2Data.expect(model(rs2).U, s\"cycle $cycle: x$rs2\")\n", + " c.clock.step()\n", + " if (wen && rd != 0) model(rd) = wdata\n", + " }\n", + " c.io.wen.poke(false.B)\n", + " for (r <- 0 until 32) {\n", + " c.io.dbgAddr.poke(r.U)\n", + " c.io.dbgData.expect(model(r).U, s\"x$r\")\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  def read(addr: UInt): UInt = Mux(addr === 0.U, 0.U, regs(addr))\n",
+    "  io.rs1Data := read(io.rs1)\n",
+    "  io.rs2Data := read(io.rs2)\n",
+    "  io.dbgData := read(io.dbgAddr)\n",
+    "  when(io.wen && io.rd =/= 0.U) {\n",
+    "    regs.write(io.rd, io.wdata)\n",
+    "  }\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You will use this register file again when you build a RISC-V processor.\n", + "\n", + "---\n", + "# You're done!\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/3.1_parameters.ipynb b/3.1_parameters.ipynb index 1b051cb..2b4e56d 100644 --- a/3.1_parameters.ipynb +++ b/3.1_parameters.ipynb @@ -12,7 +12,7 @@ "metadata": {}, "source": [ "# Module 3.1: Generators: Parameters\n", - "**Prev: [Testing with ChiselSim](2.6_chiselsim.ipynb)**
\n", + "**Prev: [Memories](2.8_memories.ipynb)**
\n", "**Next: [Generators: Collections](3.2_collections.ipynb)**\n", "\n", "## Motivation\n", @@ -22,7 +22,8 @@ "Parameters should provide useful default values, be easy to set, and protect against illegal or non-sensical values.\n", "For more complicated system it is very useful if they can be locally overriden in a way that does not inadvertantly affect other modules usages.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -70,7 +71,7 @@ "class ParameterizedScalaObject(param1: Int, param2: String) {\n", " println(s\"I have parameters: param1 = $param1 and param2 = $param2\")\n", "}\n", - "val obj1 = new ParameterizedScalaObject(4, \"Hello\")\n", + "val obj1 = new ParameterizedScalaObject(4, \"Hello\")\n", "val obj2 = new ParameterizedScalaObject(4 + 2, \"World\")" ] }, @@ -135,22 +136,22 @@ "/** Sort4 sorts its 4 inputs to its 4 outputs */\n", "class Sort4(ascending: Boolean) extends Module {\n", " val io = IO(new Bundle {\n", - " val in0 = Input(UInt(16.W))\n", - " val in1 = Input(UInt(16.W))\n", - " val in2 = Input(UInt(16.W))\n", - " val in3 = Input(UInt(16.W))\n", + " val in0 = Input(UInt(16.W))\n", + " val in1 = Input(UInt(16.W))\n", + " val in2 = Input(UInt(16.W))\n", + " val in3 = Input(UInt(16.W))\n", " val out0 = Output(UInt(16.W))\n", " val out1 = Output(UInt(16.W))\n", " val out2 = Output(UInt(16.W))\n", " val out3 = Output(UInt(16.W))\n", " })\n", - " \n", + "\n", " // this comparison funtion decides < or > based on the module's parameterization\n", " def comp(l: UInt, r: UInt): Bool = {\n", - " if (ascending) {\n", - " l < r\n", - " } else {\n", - " l > r\n", + " if (ascending) {\n", + " l < r\n", + " } else {\n", + " l > r\n", " }\n", " }\n", "\n", @@ -160,18 +161,18 @@ " val row13 = Wire(UInt(16.W))\n", "\n", " when(comp(io.in0, io.in1)) {\n", - " row10 := io.in0 // preserve first two elements\n", + " row10 := io.in0 // preserve first two elements\n", " row11 := io.in1\n", " }.otherwise {\n", - " row10 := io.in1 // swap first two elements\n", + " row10 := io.in1 // swap first two elements\n", " row11 := io.in0\n", " }\n", "\n", " when(comp(io.in2, io.in3)) {\n", - " row12 := io.in2 // preserve last two elements\n", + " row12 := io.in2 // preserve last two elements\n", " row13 := io.in3\n", " }.otherwise {\n", - " row12 := io.in3 // swap last two elements\n", + " row12 := io.in3 // swap last two elements\n", " row13 := io.in2\n", " }\n", "\n", @@ -179,44 +180,42 @@ " val row22 = Wire(UInt(16.W))\n", "\n", " when(comp(row11, row12)) {\n", - " row21 := row11 // preserve middle 2 elements\n", + " row21 := row11 // preserve middle 2 elements\n", " row22 := row12\n", " }.otherwise {\n", - " row21 := row12 // swap middle two elements\n", + " row21 := row12 // swap middle two elements\n", " row22 := row11\n", " }\n", "\n", " val row20 = Wire(UInt(16.W))\n", " val row23 = Wire(UInt(16.W))\n", " when(comp(row10, row13)) {\n", - " row20 := row10 // preserve the first and the forth elements\n", + " row20 := row10 // preserve the first and the forth elements\n", " row23 := row13\n", " }.otherwise {\n", - " row20 := row13 // swap the first and the forth elements\n", + " row20 := row13 // swap the first and the forth elements\n", " row23 := row10\n", " }\n", "\n", " when(comp(row20, row21)) {\n", - " io.out0 := row20 // preserve first two elements\n", + " io.out0 := row20 // preserve first two elements\n", " io.out1 := row21\n", " }.otherwise {\n", - " io.out0 := row21 // swap first two elements\n", + " io.out0 := row21 // swap first two elements\n", " io.out1 := row20\n", " }\n", "\n", " when(comp(row22, row23)) {\n", - " io.out2 := row22 // preserve first two elements\n", + " io.out2 := row22 // preserve first two elements\n", " io.out3 := row23\n", " }.otherwise {\n", - " io.out2 := row23 // swap first two elements\n", + " io.out2 := row23 // swap first two elements\n", " io.out3 := row22\n", " }\n", "}\n", "\n", - "\n", - "\n", "// Here are the testers\n", - "simulate(new Sort4(true)) { c => \n", + "simulate(new Sort4(true)) { c =>\n", " c.io.in0.poke(3.U)\n", " c.io.in1.poke(6.U)\n", " c.io.in2.poke(9.U)\n", @@ -295,7 +294,7 @@ "outputs": [], "source": [ "val map = Map(\"a\" -> 1)\n", - "val a = map(\"a\")\n", + "val a = map(\"a\")\n", "println(a)\n", "val b = map(\"b\")\n", "println(b)" @@ -316,7 +315,7 @@ "outputs": [], "source": [ "val map = Map(\"a\" -> 1)\n", - "val a = map.get(\"a\")\n", + "val a = map.get(\"a\")\n", "println(a)\n", "val b = map.get(\"b\")\n", "println(b)" @@ -340,7 +339,7 @@ "source": [ "val some = Some(1)\n", "val none = None\n", - "println(some.get) // Returns 1\n", + "println(some.get) // Returns 1\n", "// println(none.get) // Errors!\n", "println(some.getOrElse(2)) // Returns 1\n", "println(none.getOrElse(2)) // Returns 2" @@ -370,17 +369,17 @@ "outputs": [], "source": [ "class DelayBy1(resetValue: Option[UInt] = None) extends Module {\n", - " val io = IO(new Bundle {\n", - " val in = Input( UInt(16.W))\n", - " val out = Output(UInt(16.W))\n", - " })\n", - " val reg = if (resetValue.isDefined) { // resetValue = Some(number)\n", - " RegInit(resetValue.get)\n", - " } else { //resetValue = None\n", - " Reg(UInt())\n", - " }\n", - " reg := io.in\n", - " io.out := reg\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(16.W))\n", + " val out = Output(UInt(16.W))\n", + " })\n", + " val reg = if (resetValue.isDefined) { // resetValue = Some(number)\n", + " RegInit(resetValue.get)\n", + " } else { // resetValue = None\n", + " Reg(UInt())\n", + " }\n", + " reg := io.in\n", + " io.out := reg\n", "}\n", "\n", "println(getVerilog(new DelayBy1))\n", @@ -418,9 +417,9 @@ "val x = y match {\n", " case 0 => \"zero\" // One common syntax, preferred if fits in one line\n", " case 1 => // Another common syntax, preferred if does not fit in one line.\n", - " \"one\" // Note the code block continues until the next case\n", + " \"one\" // Note the code block continues until the next case\n", " case 2 => { // Another syntax, but curly braces are not required\n", - " \"two\"\n", + " \"two\"\n", " }\n", " case _ => \"many\" // _ is a wildcard that matches all values\n", "}\n", @@ -449,9 +448,9 @@ "source": [ "def animalType(biggerThanBreadBox: Boolean, meanAsCanBe: Boolean): String = {\n", " (biggerThanBreadBox, meanAsCanBe) match {\n", - " case (true, true) => \"wolverine\"\n", - " case (true, false) => \"elephant\"\n", - " case (false, true) => \"shrew\"\n", + " case (true, true) => \"wolverine\"\n", + " case (true, false) => \"elephant\"\n", + " case (false, true) => \"shrew\"\n", " case (false, false) => \"puppy\"\n", " }\n", "}\n", @@ -478,7 +477,7 @@ " case s: String => println(s\"$x is a String\")\n", " case s: Int => println(s\"$x is an Int\")\n", " case s: Double => println(s\"$x is a Double\")\n", - " case _ => println(s\"$x is an unknown type!\")\n", + " case _ => println(s\"$x is an unknown type!\")\n", " }\n", "}" ] @@ -501,7 +500,7 @@ "sequence.foreach { x =>\n", " x match {\n", " case _: Int | _: Double => println(s\"$x is a number!\")\n", - " case _ => println(s\"$x is an unknown type!\")\n", + " case _ => println(s\"$x is an unknown type!\")\n", " }\n", "}" ] @@ -548,14 +547,14 @@ "source": [ "class DelayBy1(resetValue: Option[UInt] = None) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input( UInt(16.W))\n", + " val in = Input(UInt(16.W))\n", " val out = Output(UInt(16.W))\n", " })\n", " val reg = resetValue match {\n", " case Some(r) => RegInit(r)\n", " case None => Reg(UInt())\n", " }\n", - " reg := io.in\n", + " reg := io.in\n", " io.out := reg\n", "}\n", "\n", @@ -589,14 +588,14 @@ "source": [ "class HalfFullAdder(val hasCarry: Boolean) extends Module {\n", " val io = IO(new Bundle {\n", - " val a = Input(UInt(1.W))\n", - " val b = Input(UInt(1.W))\n", - " val carryIn = if (hasCarry) Some(Input(UInt(1.W))) else None\n", - " val s = Output(UInt(1.W))\n", + " val a = Input(UInt(1.W))\n", + " val b = Input(UInt(1.W))\n", + " val carryIn = if (hasCarry) Some(Input(UInt(1.W))) else None\n", + " val s = Output(UInt(1.W))\n", " val carryOut = Output(UInt(1.W))\n", " })\n", " val sum = io.a +& io.b +& io.carryIn.getOrElse(0.U)\n", - " io.s := sum(0)\n", + " io.s := sum(0)\n", " io.carryOut := sum(1)\n", "}\n", "\n", @@ -684,14 +683,14 @@ "source": [ "class HalfFullAdder(val hasCarry: Boolean) extends Module {\n", " val io = IO(new Bundle {\n", - " val a = Input(UInt(1.W))\n", - " val b = Input(UInt(1.W))\n", - " val carryIn = Input(if (hasCarry) UInt(1.W) else UInt(0.W))\n", - " val s = Output(UInt(1.W))\n", + " val a = Input(UInt(1.W))\n", + " val b = Input(UInt(1.W))\n", + " val carryIn = Input(if (hasCarry) UInt(1.W) else UInt(0.W))\n", + " val s = Output(UInt(1.W))\n", " val carryOut = Output(UInt(1.W))\n", " })\n", " val sum = io.a +& io.b +& io.carryIn\n", - " io.s := sum(0)\n", + " io.s := sum(0)\n", " io.carryOut := sum(1)\n", "}\n", "println(\"Half Adder:\")\n", @@ -723,10 +722,10 @@ "source": [ "object CatDog {\n", " implicit val numberOfCats: Int = 3\n", - " //implicit val numberOfDogs: Int = 5\n", + " // implicit val numberOfDogs: Int = 5\n", "\n", " def tooManyCats(nDogs: Int)(implicit nCats: Int): Boolean = nCats > nDogs\n", - " \n", + "\n", " val imp = tooManyCats(2) // Argument passed implicitly!\n", " val exp = tooManyCats(2)(1) // Argument passed explicitly!\n", "}\n", @@ -758,12 +757,12 @@ "source": [ "sealed trait Verbosity\n", "implicit case object Silent extends Verbosity\n", - "case object Verbose extends Verbosity\n", + "case object Verbose extends Verbosity\n", "\n", "class ParameterizedWidthAdder(in0Width: Int, in1Width: Int, sumWidth: Int)(implicit verbosity: Verbosity)\n", - "extends Module {\n", + " extends Module {\n", " def log(msg: => String): Unit = verbosity match {\n", - " case Silent =>\n", + " case Silent =>\n", " case Verbose => println(msg)\n", " }\n", " require(in0Width >= 0)\n", @@ -806,7 +805,7 @@ "class Animal(val name: String, val species: String)\n", "class Human(val name: String)\n", "implicit def human2animal(h: Human): Animal = new Animal(h.name, \"Homo sapiens\")\n", - "val me = new Human(\"Adam\")\n", + "val me = new Human(\"Adam\")\n", "println(me.species)" ] }, @@ -839,14 +838,14 @@ "source": [ "// Mealy machine has\n", "case class BinaryMealyParams(\n", - " // number of states\n", - " nStates: Int,\n", - " // initial state\n", - " s0: Int,\n", - " // function describing state transition\n", - " stateTransition: (Int, Boolean) => Int,\n", - " // function describing output\n", - " output: (Int, Boolean) => Int\n", + " // number of states\n", + " nStates: Int,\n", + " // initial state\n", + " s0: Int,\n", + " // function describing state transition\n", + " stateTransition: (Int, Boolean) => Int,\n", + " // function describing output\n", + " output: (Int, Boolean) => Int\n", ") {\n", " require(nStates >= 0)\n", " require(s0 < nStates && s0 >= 0)\n", @@ -854,7 +853,7 @@ "\n", "class BinaryMealy(val mp: BinaryMealyParams) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(Bool())\n", + " val in = Input(Bool())\n", " val out = Output(UInt(1.W))\n", " })\n", "\n", @@ -863,8 +862,8 @@ " // output zero if no states\n", " io.out := 0.U\n", " for (i <- 0 until mp.nStates) {\n", - " when (state === i.U) {\n", - " when (io.in) {\n", + " when(state === i.U) {\n", + " when(io.in) {\n", " state := mp.stateTransition(i, true).U\n", " io.out := mp.output(i, true).U\n", " }.otherwise {\n", @@ -876,8 +875,8 @@ "}\n", "\n", "// example from https://en.wikipedia.org/wiki/Mealy_machine\n", - "val nStates = 3\n", - "val s0 = 2\n", + "val nStates = 3\n", + "val s0 = 2\n", "def stateTransition(state: Int, in: Boolean): Int = {\n", " if (in) {\n", " 1\n", diff --git a/3.2_collections.ipynb b/3.2_collections.ipynb index ab44d76..83b3d6d 100644 --- a/3.2_collections.ipynb +++ b/3.2_collections.ipynb @@ -21,7 +21,8 @@ "Collections are important building blocks for dealing with situations like this.\n", "This module will introduce Scala collections and how to use them with Chisel generators.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -75,7 +76,7 @@ "source": [ "class My4ElementFir(b0: Int, b1: Int, b2: Int, b3: Int) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(8.W))\n", + " val in = Input(UInt(8.W))\n", " val out = Output(UInt(8.W))\n", " })\n", "\n", @@ -84,7 +85,7 @@ " val x_n3 = RegNext(x_n2, 0.U)\n", " io.out := io.in * b0.U(8.W) + x_n1 * b1.U(8.W) +\n", " x_n2 * b2.U(8.W) + x_n3 * b3.U(8.W)\n", - "}\n" + "}" ] }, { @@ -118,7 +119,7 @@ " def poke(value: Int): Int = {\n", " pseudoRegisters = value :: pseudoRegisters.take(taps.length - 1)\n", " var accumulator = 0\n", - " for(i <- taps.indices) {\n", + " for (i <- taps.indices) {\n", " accumulator += taps(i) * pseudoRegisters(i)\n", " }\n", " accumulator\n", @@ -156,26 +157,26 @@ "\n", "out = filter.poke(1)\n", "println(s\"out = $out\")\n", - "assert(out == 1) // 1, 0, 0, 0\n", + "assert(out == 1) // 1, 0, 0, 0\n", "\n", "out = filter.poke(4)\n", - "assert(out == 5) // 4, 1, 0, 0\n", + "assert(out == 5) // 4, 1, 0, 0\n", "println(s\"out = $out\")\n", "\n", "out = filter.poke(3)\n", - "assert(out == 8) // 3, 4, 1, 0\n", + "assert(out == 8) // 3, 4, 1, 0\n", "println(s\"out = $out\")\n", "\n", "out = filter.poke(2)\n", - "assert(out == 10) // 2, 3, 4, 1\n", + "assert(out == 10) // 2, 3, 4, 1\n", "println(s\"out = $out\")\n", "\n", "out = filter.poke(7)\n", - "assert(out == 16) // 7, 2, 3, 4\n", + "assert(out == 16) // 7, 2, 3, 4\n", "println(s\"out = $out\")\n", "\n", "out = filter.poke(0)\n", - "assert(out == 12) // 0, 7, 2, 3\n", + "assert(out == 12) // 0, 7, 2, 3\n", "println(s\"out = $out\")" ] }, @@ -204,19 +205,19 @@ "val goldenModel = new ScalaFirFilter(Seq(1, 1, 1, 1))\n", "\n", "simulate(new My4ElementFir(1, 1, 1, 1)) { c =>\n", - " for(i <- 0 until 100) {\n", - " val input = scala.util.Random.nextInt(8)\n", + " for (i <- 0 until 100) {\n", + " val input = scala.util.Random.nextInt(8)\n", "\n", - " val goldenModelResult = goldenModel.poke(input)\n", + " val goldenModelResult = goldenModel.poke(input)\n", "\n", - " c.io.in.poke(input.U)\n", + " c.io.in.poke(input.U)\n", "\n", - " c.io.out.expect(goldenModelResult.U, s\"i $i, input $input, gm $goldenModelResult, ${c.io.out.peek().litValue}\")\n", + " c.io.out.expect(goldenModelResult.U, s\"i $i, input $input, gm $goldenModelResult, ${c.io.out.peek().litValue}\")\n", "\n", - " c.clock.step(1)\n", - " }\n", + " c.clock.step(1)\n", + " }\n", "\n", - "}\n" + "}" ] }, { @@ -252,25 +253,25 @@ "source": [ "class MyManyElementFir(consts: Seq[Int], bitWidth: Int) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(bitWidth.W))\n", + " val in = Input(UInt(bitWidth.W))\n", " val out = Output(UInt(bitWidth.W))\n", " })\n", "\n", " val regs = mutable.ArrayBuffer[UInt]()\n", - " for(i <- 0 until consts.length) {\n", - " if(i == 0) regs += io.in\n", - " else regs += RegNext(regs(i - 1), 0.U)\n", + " for (i <- 0 until consts.length) {\n", + " if (i == 0) regs += io.in\n", + " else regs += RegNext(regs(i - 1), 0.U)\n", " }\n", - " \n", + "\n", " val muls = mutable.ArrayBuffer[UInt]()\n", - " for(i <- 0 until consts.length) {\n", - " muls += regs(i) * consts(i).U\n", + " for (i <- 0 until consts.length) {\n", + " muls += regs(i) * consts(i).U\n", " }\n", "\n", " val scan = mutable.ArrayBuffer[UInt]()\n", - " for(i <- 0 until consts.length) {\n", - " if(i == 0) scan += muls(i)\n", - " else scan += muls(i) + scan(i - 1)\n", + " for (i <- 0 until consts.length) {\n", + " if (i == 0) scan += muls(i)\n", + " else scan += muls(i) + scan(i - 1)\n", " }\n", "\n", " io.out := scan.last\n", @@ -315,17 +316,17 @@ "val goldenModel = new ScalaFirFilter(Seq(1, 1, 1, 1))\n", "\n", "simulate(new MyManyElementFir(Seq(1, 1, 1, 1), 8)) { c =>\n", - " for(i <- 0 until 100) {\n", - " val input = scala.util.Random.nextInt(8)\n", + " for (i <- 0 until 100) {\n", + " val input = scala.util.Random.nextInt(8)\n", "\n", - " val goldenModelResult = goldenModel.poke(input)\n", + " val goldenModelResult = goldenModel.poke(input)\n", "\n", - " c.io.in.poke(input.U)\n", + " c.io.in.poke(input.U)\n", "\n", - " c.io.out.expect(goldenModelResult.U, s\"i $i, input $input, gm $goldenModelResult, ${c.io.out.peek().litValue}\")\n", + " c.io.out.expect(goldenModelResult.U, s\"i $i, input $input, gm $goldenModelResult, ${c.io.out.peek().litValue}\")\n", "\n", - " c.clock.step(1)\n", - " }\n", + " c.clock.step(1)\n", + " }\n", "}" ] }, @@ -354,27 +355,27 @@ " * run for at least twice as many samples as taps\n", " */\n", "def runOneTest(taps: Seq[Int]): Unit = {\n", - " val goldenModel = new ScalaFirFilter(taps)\n", + " val goldenModel = new ScalaFirFilter(taps)\n", "\n", - " simulate(new MyManyElementFir(taps, 32)) { c =>\n", - " for(i <- 0 until 2 * taps.length) {\n", - " val input = r()\n", + " simulate(new MyManyElementFir(taps, 32)) { c =>\n", + " for (i <- 0 until 2 * taps.length) {\n", + " val input = r()\n", "\n", - " val goldenModelResult = goldenModel.poke(input)\n", + " val goldenModelResult = goldenModel.poke(input)\n", "\n", - " c.io.in.poke(input.U)\n", + " c.io.in.poke(input.U)\n", "\n", - " c.io.out.expect(goldenModelResult.U, s\"i $i, input $input, gm $goldenModelResult, ${c.io.out.peek().litValue}\")\n", + " c.io.out.expect(goldenModelResult.U, s\"i $i, input $input, gm $goldenModelResult, ${c.io.out.peek().litValue}\")\n", "\n", - " c.clock.step(1)\n", - " }\n", + " c.clock.step(1)\n", " }\n", + " }\n", "}\n", "\n", - "for(tapSize <- 2 until 100 by 10) {\n", - " val taps = Seq.fill(tapSize)(r()) // create a sequence of random coefficients\n", + "for (tapSize <- 2 until 100 by 10) {\n", + " val taps = Seq.fill(tapSize)(r()) // create a sequence of random coefficients\n", "\n", - " runOneTest(taps)\n", + " runOneTest(taps)\n", "}" ] }, @@ -422,28 +423,28 @@ "source": [ "class MyManyDynamicElementVecFir(length: Int) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(8.W))\n", - " val out = Output(UInt(8.W))\n", + " val in = Input(UInt(8.W))\n", + " val out = Output(UInt(8.W))\n", " val consts = Input(Vec(length, UInt(8.W)))\n", " })\n", "\n", " // Reference solution\n", " val regs = RegInit(VecInit(Seq.fill(length - 1)(0.U(8.W))))\n", - " for(i <- 0 until length - 1) {\n", - " if(i == 0) regs(i) := io.in\n", - " else regs(i) := regs(i - 1)\n", + " for (i <- 0 until length - 1) {\n", + " if (i == 0) regs(i) := io.in\n", + " else regs(i) := regs(i - 1)\n", " }\n", - " \n", + "\n", " val muls = Wire(Vec(length, UInt(8.W)))\n", - " for(i <- 0 until length) {\n", - " if(i == 0) muls(i) := io.in * io.consts(i)\n", - " else muls(i) := regs(i - 1) * io.consts(i)\n", + " for (i <- 0 until length) {\n", + " if (i == 0) muls(i) := io.in * io.consts(i)\n", + " else muls(i) := regs(i - 1) * io.consts(i)\n", " }\n", "\n", " val scan = Wire(Vec(length, UInt(8.W)))\n", - " for(i <- 0 until length) {\n", - " if(i == 0) scan(i) := muls(i)\n", - " else scan(i) := muls(i) + scan(i - 1)\n", + " for (i <- 0 until length) {\n", + " if (i == 0) scan(i) := muls(i)\n", + " else scan(i) := muls(i) + scan(i - 1)\n", " }\n", "\n", " io.out := scan(length - 1)\n", @@ -459,22 +460,22 @@ "val goldenModel = new ScalaFirFilter(Seq(1, 1, 1, 1))\n", "\n", "simulate(new MyManyDynamicElementVecFir(4)) { c =>\n", - " c.io.consts(0).poke(1.U)\n", - " c.io.consts(1).poke(1.U)\n", - " c.io.consts(2).poke(1.U)\n", - " c.io.consts(3).poke(1.U)\n", - " for(i <- 0 until 100) {\n", - " val input = scala.util.Random.nextInt(8)\n", + " c.io.consts(0).poke(1.U)\n", + " c.io.consts(1).poke(1.U)\n", + " c.io.consts(2).poke(1.U)\n", + " c.io.consts(3).poke(1.U)\n", + " for (i <- 0 until 100) {\n", + " val input = scala.util.Random.nextInt(8)\n", "\n", - " val goldenModelResult = goldenModel.poke(input)\n", + " val goldenModelResult = goldenModel.poke(input)\n", "\n", - " c.io.in.poke(input.U)\n", + " c.io.in.poke(input.U)\n", "\n", - " c.io.out.expect(goldenModelResult.U, s\"i $i, input $input, gm $goldenModelResult, ${c.io.out.peek().litValue}\")\n", + " c.io.out.expect(goldenModelResult.U, s\"i $i, input $input, gm $goldenModelResult, ${c.io.out.peek().litValue}\")\n", "\n", - " c.clock.step(1)\n", - " }\n", - "}\n" + " c.clock.step(1)\n", + " }\n", + "}" ] }, { @@ -502,21 +503,20 @@ "outputs": [], "source": [ "class RegisterFile(readPorts: Int) extends Module {\n", - " require(readPorts >= 0)\n", - " val io = IO(new Bundle {\n", - " val wen = Input(Bool())\n", - " val waddr = Input(UInt(5.W))\n", - " val wdata = Input(UInt(32.W))\n", - " val raddr = Input(Vec(readPorts, UInt(5.W)))\n", - " val rdata = Output(Vec(readPorts, UInt(32.W)))\n", - " })\n", - " \n", - " // A Register of a vector of UInts\n", - " val reg = RegInit(VecInit(Seq.fill(32)(0.U(32.W))))\n", - " \n", - " ???\n", - "\n", - " \n", + " require(readPorts >= 0)\n", + " val io = IO(new Bundle {\n", + " val wen = Input(Bool())\n", + " val waddr = Input(UInt(5.W))\n", + " val wdata = Input(UInt(32.W))\n", + " val raddr = Input(Vec(readPorts, UInt(5.W)))\n", + " val rdata = Output(Vec(readPorts, UInt(32.W)))\n", + " })\n", + "\n", + " // A Register of a vector of UInts\n", + " val reg = RegInit(VecInit(Seq.fill(32)(0.U(32.W))))\n", + "\n", + " ???\n", + "\n", "}" ] }, @@ -526,7 +526,7 @@ "metadata": {}, "outputs": [], "source": [ - "simulate(new RegisterFile(2) ) { c =>\n", + "simulate(new RegisterFile(2)) { c =>\n", " def readExpect(addr: Int, value: Int, port: Int = 0): Unit = {\n", " c.io.raddr(port).poke(addr.U)\n", " c.io.rdata(port).expect(value.U)\n", diff --git a/3.2_interlude.ipynb b/3.2_interlude.ipynb index 983c29a..e67c03e 100644 --- a/3.2_interlude.ipynb +++ b/3.2_interlude.ipynb @@ -18,7 +18,8 @@ "## Motivation\n", "Chisel is all about re-use, so it only makes sense to provide a standard library of interfaces (encouraging interoperability of RTL) and generators for commonly-used hardware blocks.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -48,7 +49,7 @@ "source": [ "---\n", "# The Cheatsheet\n", - "The [Chisel3 cheatsheet](https://github.com/freechipsproject/chisel-cheatsheet/releases/latest/download/chisel_cheatsheet.pdf) contains a summary of all the major hardware construction APIs, including some of the standard library utilities that we'll introduce below.\n", + "The [Chisel3 cheatsheet](https://github.com/freechipsproject/chisel-cheatsheet/releases/latest/download/chisel_cheatsheet.pdf) contains a summary of all the major hardware construction APIs, including some of the standard library utilities that we'll introduce below. It was written for Chisel 3; the [Chisel documentation](https://www.chisel-lang.org/docs) covers Chisel 7.\n", "\n", "# Decoupled: A Standard Ready-Valid Interface\n", "One of the commonly used interfaces provided by Chisel is `DecoupledIO`, providing a ready-valid interface for transferring data. The idea is that the source drives the `bits` signal with the data to be transferred and the `valid` signal when there is data to be transferred. The sink drives the `ready` signal when it is ready to accept data, and data is considered transferred when both `ready` and `valid` are asserted on a cycle.\n", @@ -89,52 +90,52 @@ "outputs": [], "source": [ "simulate(new Module {\n", - " // Example circuit using a Queue\n", - " val io = IO(new Bundle {\n", - " val in = Flipped(Decoupled(UInt(8.W)))\n", - " val out = Decoupled(UInt(8.W))\n", - " })\n", - " val queue = Queue(io.in, 2) // 2-element queue\n", - " io.out <> queue\n", - " }) { c =>\n", - " c.io.out.ready.poke(false.B)\n", - " c.io.in.valid.poke(true.B) // Enqueue an element\n", - " c.io.in.bits.poke(42.U)\n", - " println(s\"Starting:\")\n", - " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", - " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", - " c.clock.step(1)\n", - "\n", - " c.io.in.valid.poke(true.B) // Enqueue another element\n", - " c.io.in.bits.poke(43.U)\n", - " // What do you think io.out.valid and io.out.bits will be?\n", - " println(s\"After first enqueue:\")\n", - " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", - " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", - " c.clock.step(1)\n", - "\n", - " c.io.in.valid.poke(true.B) // Read a element, attempt to enqueue\n", - " c.io.in.bits.poke(44.U)\n", - " c.io.out.ready.poke(true.B)\n", - " // What do you think io.in.ready will be, and will this enqueue succeed, and what will be read?\n", - " println(s\"On first read:\")\n", - " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", - " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", - " c.clock.step(1)\n", - "\n", - " c.io.in.valid.poke(false.B) // Read elements out\n", - " c.io.out.ready.poke(true.B)\n", - " // What do you think will be read here?\n", - " println(s\"On second read:\")\n", - " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", - " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", - " c.clock.step(1)\n", - "\n", - " // Will a third read produce anything?\n", - " println(s\"On third read:\")\n", - " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", - " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", - " c.clock.step(1)\n", + " // Example circuit using a Queue\n", + " val io = IO(new Bundle {\n", + " val in = Flipped(Decoupled(UInt(8.W)))\n", + " val out = Decoupled(UInt(8.W))\n", + " })\n", + " val queue = Queue(io.in, 2) // 2-element queue\n", + " io.out <> queue\n", + "}) { c =>\n", + " c.io.out.ready.poke(false.B)\n", + " c.io.in.valid.poke(true.B) // Enqueue an element\n", + " c.io.in.bits.poke(42.U)\n", + " println(s\"Starting:\")\n", + " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", + " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", + " c.clock.step(1)\n", + "\n", + " c.io.in.valid.poke(true.B) // Enqueue another element\n", + " c.io.in.bits.poke(43.U)\n", + " // What do you think io.out.valid and io.out.bits will be?\n", + " println(s\"After first enqueue:\")\n", + " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", + " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", + " c.clock.step(1)\n", + "\n", + " c.io.in.valid.poke(true.B) // Read a element, attempt to enqueue\n", + " c.io.in.bits.poke(44.U)\n", + " c.io.out.ready.poke(true.B)\n", + " // What do you think io.in.ready will be, and will this enqueue succeed, and what will be read?\n", + " println(s\"On first read:\")\n", + " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", + " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", + " c.clock.step(1)\n", + "\n", + " c.io.in.valid.poke(false.B) // Read elements out\n", + " c.io.out.ready.poke(true.B)\n", + " // What do you think will be read here?\n", + " println(s\"On second read:\")\n", + " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", + " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", + " c.clock.step(1)\n", + "\n", + " // Will a third read produce anything?\n", + " println(s\"On third read:\")\n", + " println(s\"\\tio.in: ready=${c.io.in.ready.peek().litValue}\")\n", + " println(s\"\\tio.out: valid=${c.io.out.valid.peek().litValue}, bits=${c.io.out.bits.peek().litValue}\")\n", + " c.clock.step(1)\n", "}" ] }, @@ -160,40 +161,40 @@ "outputs": [], "source": [ "simulate(new Module {\n", - " // Example circuit using a priority arbiter\n", - " val io = IO(new Bundle {\n", - " val in = Flipped(Vec(2, Decoupled(UInt(8.W))))\n", - " val out = Decoupled(UInt(8.W))\n", - " })\n", - " // Arbiter doesn't have a convenience constructor, so it's built like any Module\n", - " val arbiter = Module(new Arbiter(UInt(8.W), 2)) // 2 to 1 Priority Arbiter\n", - " arbiter.io.in <> io.in\n", - " io.out <> arbiter.io.out\n", - " }) { c =>\n", - " c.io.in(0).valid.poke(false.B)\n", - " c.io.in(1).valid.poke(false.B)\n", - " c.io.out.ready.poke(false.B)\n", - " println(s\"Start:\")\n", - " println(s\"\\tin(0).ready=${c.io.in(0).ready.peek().litValue}, in(1).ready=${c.io.in(1).ready.peek().litValue}\")\n", - " println(s\"\\tout.valid=${c.io.out.valid.peek().litValue}, out.bits=${c.io.out.bits.peek().litValue}\")\n", - " c.io.in(1).valid.poke(true.B) // Valid input 1\n", - " c.io.in(1).bits.poke(42.U)\n", - " c.io.out.ready.poke(true.B)\n", - " // What do you think the output will be?\n", - " println(s\"valid input 1:\")\n", - " println(s\"\\tin(0).ready=${c.io.in(0).ready.peek().litValue}, in(1).ready=${c.io.in(1).ready.peek().litValue}\")\n", - " println(s\"\\tout.valid=${c.io.out.valid.peek().litValue}, out.bits=${c.io.out.bits.peek().litValue}\")\n", - " c.io.in(0).valid.poke(true.B) // Valid inputs 0 and 1\n", - " c.io.in(0).bits.poke(43.U)\n", - " // What do you think the output will be? Which inputs will be ready?\n", - " println(s\"valid inputs 0 and 1:\")\n", - " println(s\"\\tin(0).ready=${c.io.in(0).ready.peek().litValue}, in(1).ready=${c.io.in(1).ready.peek().litValue}\")\n", - " println(s\"\\tout.valid=${c.io.out.valid.peek().litValue}, out.bits=${c.io.out.bits.peek().litValue}\")\n", - " c.io.in(1).valid.poke(false.B) // Valid input 0\n", - " // What do you think the output will be?\n", - " println(s\"valid input 0:\")\n", - " println(s\"\\tin(0).ready=${c.io.in(0).ready.peek().litValue}, in(1).ready=${c.io.in(1).ready.peek().litValue}\")\n", - " println(s\"\\tout.valid=${c.io.out.valid.peek().litValue}, out.bits=${c.io.out.bits.peek().litValue}\")\n", + " // Example circuit using a priority arbiter\n", + " val io = IO(new Bundle {\n", + " val in = Flipped(Vec(2, Decoupled(UInt(8.W))))\n", + " val out = Decoupled(UInt(8.W))\n", + " })\n", + " // Arbiter doesn't have a convenience constructor, so it's built like any Module\n", + " val arbiter = Module(new Arbiter(UInt(8.W), 2)) // 2 to 1 Priority Arbiter\n", + " arbiter.io.in <> io.in\n", + " io.out <> arbiter.io.out\n", + "}) { c =>\n", + " c.io.in(0).valid.poke(false.B)\n", + " c.io.in(1).valid.poke(false.B)\n", + " c.io.out.ready.poke(false.B)\n", + " println(s\"Start:\")\n", + " println(s\"\\tin(0).ready=${c.io.in(0).ready.peek().litValue}, in(1).ready=${c.io.in(1).ready.peek().litValue}\")\n", + " println(s\"\\tout.valid=${c.io.out.valid.peek().litValue}, out.bits=${c.io.out.bits.peek().litValue}\")\n", + " c.io.in(1).valid.poke(true.B) // Valid input 1\n", + " c.io.in(1).bits.poke(42.U)\n", + " c.io.out.ready.poke(true.B)\n", + " // What do you think the output will be?\n", + " println(s\"valid input 1:\")\n", + " println(s\"\\tin(0).ready=${c.io.in(0).ready.peek().litValue}, in(1).ready=${c.io.in(1).ready.peek().litValue}\")\n", + " println(s\"\\tout.valid=${c.io.out.valid.peek().litValue}, out.bits=${c.io.out.bits.peek().litValue}\")\n", + " c.io.in(0).valid.poke(true.B) // Valid inputs 0 and 1\n", + " c.io.in(0).bits.poke(43.U)\n", + " // What do you think the output will be? Which inputs will be ready?\n", + " println(s\"valid inputs 0 and 1:\")\n", + " println(s\"\\tin(0).ready=${c.io.in(0).ready.peek().litValue}, in(1).ready=${c.io.in(1).ready.peek().litValue}\")\n", + " println(s\"\\tout.valid=${c.io.out.valid.peek().litValue}, out.bits=${c.io.out.bits.peek().litValue}\")\n", + " c.io.in(1).valid.poke(false.B) // Valid input 0\n", + " // What do you think the output will be?\n", + " println(s\"valid input 0:\")\n", + " println(s\"\\tin(0).ready=${c.io.in(0).ready.peek().litValue}, in(1).ready=${c.io.in(1).ready.peek().litValue}\")\n", + " println(s\"\\tout.valid=${c.io.out.valid.peek().litValue}, out.bits=${c.io.out.bits.peek().litValue}\")\n", "}" ] }, @@ -219,25 +220,25 @@ "outputs": [], "source": [ "simulate(new Module {\n", - " // Example circuit using PopCount\n", - " val io = IO(new Bundle {\n", - " val in = Input(UInt(8.W))\n", - " val out = Output(UInt(8.W))\n", - " })\n", - " io.out := PopCount(io.in)\n", - " }) { c =>\n", - " // Integer.parseInt is used create an Integer from a binary specification\n", - " c.io.in.poke(Integer.parseInt(\"00000000\", 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", - "\n", - " c.io.in.poke(Integer.parseInt(\"00001111\", 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", - "\n", - " c.io.in.poke(Integer.parseInt(\"11001010\", 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", - "\n", - " c.io.in.poke(Integer.parseInt(\"11111111\", 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", + " // Example circuit using PopCount\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(8.W))\n", + " val out = Output(UInt(8.W))\n", + " })\n", + " io.out := PopCount(io.in)\n", + "}) { c =>\n", + " // Integer.parseInt is used create an Integer from a binary specification\n", + " c.io.in.poke(Integer.parseInt(\"00000000\", 2).U)\n", + " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", + "\n", + " c.io.in.poke(Integer.parseInt(\"00001111\", 2).U)\n", + " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", + "\n", + " c.io.in.poke(Integer.parseInt(\"11001010\", 2).U)\n", + " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", + "\n", + " c.io.in.poke(Integer.parseInt(\"11111111\", 2).U)\n", + " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", "\n", "}" ] @@ -249,25 +250,33 @@ "outputs": [], "source": [ "simulate(new Module {\n", - " // Example circuit using Reverse\n", - " val io = IO(new Bundle {\n", - " val in = Input(UInt(8.W))\n", - " val out = Output(UInt(8.W))\n", - " })\n", - " io.out := Reverse(io.in)\n", - " }) { c =>\n", - " // Integer.parseInt is used create an Integer from a binary specification\n", - " c.io.in.poke(Integer.parseInt(\"01010101\", 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", - "\n", - " c.io.in.poke(Integer.parseInt(\"00001111\", 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", - "\n", - " c.io.in.poke(Integer.parseInt(\"11110000\", 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", - "\n", - " c.io.in.poke(Integer.parseInt(\"11001010\", 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", + " // Example circuit using Reverse\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(8.W))\n", + " val out = Output(UInt(8.W))\n", + " })\n", + " io.out := Reverse(io.in)\n", + "}) { c =>\n", + " // Integer.parseInt is used create an Integer from a binary specification\n", + " c.io.in.poke(Integer.parseInt(\"01010101\", 2).U)\n", + " println(\n", + " s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\"\n", + " )\n", + "\n", + " c.io.in.poke(Integer.parseInt(\"00001111\", 2).U)\n", + " println(\n", + " s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\"\n", + " )\n", + "\n", + " c.io.in.poke(Integer.parseInt(\"11110000\", 2).U)\n", + " println(\n", + " s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\"\n", + " )\n", + "\n", + " c.io.in.poke(Integer.parseInt(\"11001010\", 2).U)\n", + " println(\n", + " s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\"\n", + " )\n", "}" ] }, @@ -290,24 +299,24 @@ "outputs": [], "source": [ "simulate(new Module {\n", - " // Example circuit using UIntToOH\n", - " val io = IO(new Bundle {\n", - " val in = Input(UInt(4.W))\n", - " val out = Output(UInt(16.W))\n", - " })\n", - " io.out := UIntToOH(io.in)\n", - " }) { c =>\n", - " c.io.in.poke(0.U)\n", - " println(s\"in=${c.io.in.peek().litValue}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", - "\n", - " c.io.in.poke(1.U)\n", - " println(s\"in=${c.io.in.peek().litValue}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", - "\n", - " c.io.in.poke(8.U)\n", - " println(s\"in=${c.io.in.peek().litValue}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", - "\n", - " c.io.in.poke(15.U)\n", - " println(s\"in=${c.io.in.peek().litValue}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", + " // Example circuit using UIntToOH\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(4.W))\n", + " val out = Output(UInt(16.W))\n", + " })\n", + " io.out := UIntToOH(io.in)\n", + "}) { c =>\n", + " c.io.in.poke(0.U)\n", + " println(s\"in=${c.io.in.peek().litValue}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", + "\n", + " c.io.in.poke(1.U)\n", + " println(s\"in=${c.io.in.peek().litValue}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", + "\n", + " c.io.in.poke(8.U)\n", + " println(s\"in=${c.io.in.peek().litValue}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", + "\n", + " c.io.in.poke(15.U)\n", + " println(s\"in=${c.io.in.peek().litValue}, out=0b${c.io.out.peek().litValue.toInt.toBinaryString}\")\n", "}" ] }, @@ -318,31 +327,31 @@ "outputs": [], "source": [ "simulate(new Module {\n", - " // Example circuit using OHToUInt\n", - " val io = IO(new Bundle {\n", - " val in = Input(UInt(16.W))\n", - " val out = Output(UInt(4.W))\n", - " })\n", - " io.out := OHToUInt(io.in)\n", + " // Example circuit using OHToUInt\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(16.W))\n", + " val out = Output(UInt(4.W))\n", + " })\n", + " io.out := OHToUInt(io.in)\n", "}) { c =>\n", - " c.io.in.poke(Integer.parseInt(\"0000 0000 0000 0001\".replace(\" \", \"\"), 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", + " c.io.in.poke(Integer.parseInt(\"0000 0000 0000 0001\".replace(\" \", \"\"), 2).U)\n", + " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", "\n", - " c.io.in.poke(Integer.parseInt(\"0000 0000 1000 0000\".replace(\" \", \"\"), 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", + " c.io.in.poke(Integer.parseInt(\"0000 0000 1000 0000\".replace(\" \", \"\"), 2).U)\n", + " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", "\n", - " c.io.in.poke(Integer.parseInt(\"1000 0000 0000 0001\".replace(\" \", \"\"), 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", + " c.io.in.poke(Integer.parseInt(\"1000 0000 0000 0001\".replace(\" \", \"\"), 2).U)\n", + " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", "\n", - " // Some invalid inputs:\n", - " // None high\n", - " c.io.in.poke(Integer.parseInt(\"0000 0000 0000 0000\".replace(\" \", \"\"), 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", + " // Some invalid inputs:\n", + " // None high\n", + " c.io.in.poke(Integer.parseInt(\"0000 0000 0000 0000\".replace(\" \", \"\"), 2).U)\n", + " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", "\n", - " // Multiple high\n", - " c.io.in.poke(Integer.parseInt(\"0001 0100 0010 0000\".replace(\" \", \"\"), 2).U)\n", - " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", - "}\n" + " // Multiple high\n", + " c.io.in.poke(Integer.parseInt(\"0001 0100 0010 0000\".replace(\" \", \"\"), 2).U)\n", + " println(s\"in=0b${c.io.in.peek().litValue.toInt.toBinaryString}, out=${c.io.out.peek().litValue}\")\n", + "}" ] }, { @@ -368,31 +377,31 @@ "outputs": [], "source": [ "simulate(new Module {\n", - " // Example circuit using PriorityMux\n", - " val io = IO(new Bundle {\n", - " val in_sels = Input(Vec(2, Bool()))\n", - " val in_bits = Input(Vec(2, UInt(8.W)))\n", - " val out = Output(UInt(8.W))\n", - " })\n", - " io.out := PriorityMux(io.in_sels, io.in_bits)\n", - " }) { c =>\n", - " c.io.in_bits(0).poke(10.U)\n", - " c.io.in_bits(1).poke(20.U)\n", - "\n", - " // Select higher index only\n", - " c.io.in_sels(0).poke(false.B)\n", - " c.io.in_sels(1).poke(true.B)\n", - " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", - "\n", - " // Select both - arbitration needed\n", - " c.io.in_sels(0).poke(true.B)\n", - " c.io.in_sels(1).poke(true.B)\n", - " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", - "\n", - " // Select lower index only\n", - " c.io.in_sels(0).poke(true.B)\n", - " c.io.in_sels(1).poke(false.B)\n", - " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", + " // Example circuit using PriorityMux\n", + " val io = IO(new Bundle {\n", + " val in_sels = Input(Vec(2, Bool()))\n", + " val in_bits = Input(Vec(2, UInt(8.W)))\n", + " val out = Output(UInt(8.W))\n", + " })\n", + " io.out := PriorityMux(io.in_sels, io.in_bits)\n", + "}) { c =>\n", + " c.io.in_bits(0).poke(10.U)\n", + " c.io.in_bits(1).poke(20.U)\n", + "\n", + " // Select higher index only\n", + " c.io.in_sels(0).poke(false.B)\n", + " c.io.in_sels(1).poke(true.B)\n", + " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", + "\n", + " // Select both - arbitration needed\n", + " c.io.in_sels(0).poke(true.B)\n", + " c.io.in_sels(1).poke(true.B)\n", + " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", + "\n", + " // Select lower index only\n", + " c.io.in_sels(0).poke(true.B)\n", + " c.io.in_sels(1).poke(false.B)\n", + " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", "}" ] }, @@ -403,44 +412,42 @@ "outputs": [], "source": [ "simulate(new Module {\n", - " // Example circuit using Mux1H\n", - " val io = IO(new Bundle {\n", - " val in_sels = Input(Vec(2, Bool()))\n", - " val in_bits = Input(Vec(2, UInt(8.W)))\n", - " val out = Output(UInt(8.W))\n", - " })\n", - " io.out := Mux1H(io.in_sels, io.in_bits)\n", - " }) { c =>\n", - " c.io.in_bits(0).poke(10.U)\n", - " c.io.in_bits(1).poke(20.U)\n", - "\n", - " // Select index 1\n", - " c.io.in_sels(0).poke(false.B)\n", - " c.io.in_sels(1).poke(true.B)\n", - " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", - "\n", - " // Select index 0\n", - " c.io.in_sels(0).poke(true.B)\n", - " c.io.in_sels(1).poke(false.B)\n", - " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", - "\n", - " // Select none (invalid)\n", - " c.io.in_sels(0).poke(false.B)\n", - " c.io.in_sels(1).poke(false.B)\n", - " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", - "\n", - " // Select both (invalid)\n", - " c.io.in_sels(0).poke(true.B)\n", - " c.io.in_sels(1).poke(true.B)\n", - " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", + " // Example circuit using Mux1H\n", + " val io = IO(new Bundle {\n", + " val in_sels = Input(Vec(2, Bool()))\n", + " val in_bits = Input(Vec(2, UInt(8.W)))\n", + " val out = Output(UInt(8.W))\n", + " })\n", + " io.out := Mux1H(io.in_sels, io.in_bits)\n", + "}) { c =>\n", + " c.io.in_bits(0).poke(10.U)\n", + " c.io.in_bits(1).poke(20.U)\n", + "\n", + " // Select index 1\n", + " c.io.in_sels(0).poke(false.B)\n", + " c.io.in_sels(1).poke(true.B)\n", + " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", + "\n", + " // Select index 0\n", + " c.io.in_sels(0).poke(true.B)\n", + " c.io.in_sels(1).poke(false.B)\n", + " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", + "\n", + " // Select none (invalid)\n", + " c.io.in_sels(0).poke(false.B)\n", + " c.io.in_sels(1).poke(false.B)\n", + " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", + "\n", + " // Select both (invalid)\n", + " c.io.in_sels(0).poke(true.B)\n", + " c.io.in_sels(1).poke(true.B)\n", + " println(s\"in_sels=${c.io.in_sels(0).peek().litValue}, out=${c.io.out.peek().litValue}\")\n", "}" ] }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "## Counter\n", "`Counter` is a counter that can be incremented once every cycle, up to some specified limit, at which point it overflows. Note that it is **not** a Module, and its value is accessible." @@ -453,33 +460,33 @@ "outputs": [], "source": [ "simulate(new Module {\n", - " // Example circuit using Mux1H\n", - " val io = IO(new Bundle {\n", - " val count = Input(Bool())\n", - " val out = Output(UInt(2.W))\n", - " })\n", - " val counter = Counter(3) // 3-count Counter (outputs range [0...2])\n", - " when(io.count) {\n", - " counter.inc()\n", - " }\n", - " io.out := counter.value\n", - " }) { c =>\n", - " c.io.count.poke(true.B)\n", - " println(s\"start: counter value=${c.io.out.peek().litValue}\")\n", - "\n", - " c.clock.step(1)\n", - " println(s\"step 1: counter value=${c.io.out.peek().litValue}\")\n", - "\n", - " c.clock.step(1)\n", - " println(s\"step 2: counter value=${c.io.out.peek().litValue}\")\n", - "\n", - " c.io.count.poke(false.B)\n", - " c.clock.step(1)\n", - " println(s\"step without increment: counter value=${c.io.out.peek().litValue}\")\n", - "\n", - " c.io.count.poke(true.B)\n", - " c.clock.step(1)\n", - " println(s\"step again: counter value=${c.io.out.peek().litValue}\")\n", + " // Example circuit using Mux1H\n", + " val io = IO(new Bundle {\n", + " val count = Input(Bool())\n", + " val out = Output(UInt(2.W))\n", + " })\n", + " val counter = Counter(3) // 3-count Counter (outputs range [0...2])\n", + " when(io.count) {\n", + " counter.inc()\n", + " }\n", + " io.out := counter.value\n", + "}) { c =>\n", + " c.io.count.poke(true.B)\n", + " println(s\"start: counter value=${c.io.out.peek().litValue}\")\n", + "\n", + " c.clock.step(1)\n", + " println(s\"step 1: counter value=${c.io.out.peek().litValue}\")\n", + "\n", + " c.clock.step(1)\n", + " println(s\"step 2: counter value=${c.io.out.peek().litValue}\")\n", + "\n", + " c.io.count.poke(false.B)\n", + " c.clock.step(1)\n", + " println(s\"step without increment: counter value=${c.io.out.peek().litValue}\")\n", + "\n", + " c.io.count.poke(true.B)\n", + " c.clock.step(1)\n", + " println(s\"step again: counter value=${c.io.out.peek().litValue}\")\n", "}" ] }, diff --git a/3.3_higher-order_functions.ipynb b/3.3_higher-order_functions.ipynb index 1d2f61d..4e36e80 100644 --- a/3.3_higher-order_functions.ipynb +++ b/3.3_higher-order_functions.ipynb @@ -18,7 +18,8 @@ "## Motivation\n", "Those pesky `for` loops in the previous module are verbose and defeat the purpose of functional programming! In this module, your generators will get funct-ky.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -113,15 +114,17 @@ "metadata": {}, "outputs": [], "source": [ - "println(List(1, 2, 3, 4).map(x => x + 1)) // explicit argument list in function\n", - "println(List(1, 2, 3, 4).map(_ + 1)) // equivalent to the above, but implicit arguments\n", - "println(List(1, 2, 3, 4).map(_.toString + \"a\")) // the output element type can be different from the input element type\n", + "println(List(1, 2, 3, 4).map(x => x + 1)) // explicit argument list in function\n", + "println(List(1, 2, 3, 4).map(_ + 1)) // equivalent to the above, but implicit arguments\n", + "println(List(1, 2, 3, 4).map(_.toString + \"a\")) // the output element type can be different from the input element type\n", "\n", - "println(List((1, 5), (2, 6), (3, 7), (4, 8)).map { case (x, y) => x*y }) // this unpacks a tuple, note use of curly braces\n", + "println(List((1, 5), (2, 6), (3, 7), (4, 8)).map { case (x, y) =>\n", + " x * y\n", + "}) // this unpacks a tuple, note use of curly braces\n", "\n", "// Related: Scala has a syntax for constructing lists of sequential numbers\n", - "println(0 to 10) // to is inclusive , the end point is part of the result\n", - "println(0 until 10) // until is exclusive at the end, the end point is not part of the result\n", + "println(0 to 10) // to is inclusive , the end point is part of the result\n", + "println(0 until 10) // until is exclusive at the end, the end point is not part of the result\n", "\n", "// Those largely behave like lists, and can be useful for generating indices:\n", "val myList = List(\"a\", \"b\", \"c\", \"d\")\n", @@ -141,7 +144,7 @@ "metadata": {}, "outputs": [], "source": [ - "// Now you try: \n", + "// Now you try:\n", "// Fill in the blanks (the ???) such that this doubles the elements of the input list.\n", "// This should return: List(2, 4, 6, 8)\n", "println(List(1, 2, 3, 4).map(???))" @@ -168,9 +171,9 @@ "metadata": {}, "outputs": [], "source": [ - "println(List(1, 2, 3, 4).zipWithIndex) // note indices start at zero\n", + "println(List(1, 2, 3, 4).zipWithIndex) // note indices start at zero\n", "println(List(\"a\", \"b\", \"c\", \"d\").zipWithIndex)\n", - "println(List((\"a\", \"b\"), (\"c\", \"d\"), (\"e\", \"f\"), (\"g\", \"h\")).zipWithIndex) // tuples nest" + "println(List((\"a\", \"b\"), (\"c\", \"d\"), (\"e\", \"f\"), (\"g\", \"h\")).zipWithIndex) // tuples nest" ] }, { @@ -190,8 +193,8 @@ "outputs": [], "source": [ "println(List(1, 2, 3, 4).reduce((a, b) => a + b)) // returns the sum of all the elements\n", - "println(List(1, 2, 3, 4).reduce(_ * _)) // returns the product of all the elements\n", - "println(List(1, 2, 3, 4).map(_ + 1).reduce(_ + _)) // you can chain reduce onto the result of a map" + "println(List(1, 2, 3, 4).reduce(_ * _)) // returns the product of all the elements\n", + "println(List(1, 2, 3, 4).map(_ + 1).reduce(_ + _)) // you can chain reduce onto the result of a map" ] }, { @@ -217,7 +220,7 @@ "metadata": {}, "outputs": [], "source": [ - "// Now you try: \n", + "// Now you try:\n", "// Fill in the blanks (the ???) such that this returns the product of the double of the elements of the input list.\n", "// This should return: (1*2)*(2*2)*(3*2)*(4*2) = 384\n", "println(List(1, 2, 3, 4).map(???).reduce(???))" @@ -243,9 +246,9 @@ "metadata": {}, "outputs": [], "source": [ - "println(List(1, 2, 3, 4).fold(0)(_ + _)) // equivalent to the sum using reduce\n", - "println(List(1, 2, 3, 4).fold(1)(_ + _)) // like above, but accumulation starts at 1\n", - "println(List().fold(1)(_ + _)) // unlike reduce, does not fail on an empty input" + "println(List(1, 2, 3, 4).fold(0)(_ + _)) // equivalent to the sum using reduce\n", + "println(List(1, 2, 3, 4).fold(1)(_ + _)) // like above, but accumulation starts at 1\n", + "println(List().fold(1)(_ + _)) // unlike reduce, does not fail on an empty input" ] }, { @@ -261,7 +264,7 @@ "metadata": {}, "outputs": [], "source": [ - "// Now you try: \n", + "// Now you try:\n", "// Fill in the blanks (the ???) such that this returns the double the product of the elements of the input list.\n", "// This should return: 2*(1*2*3*4) = 48\n", "// Note: unless empty list tolerance is needed, reduce is a much better fit here.\n", @@ -297,47 +300,47 @@ "source": [ "class MyRoutingArbiter(numChannels: Int) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Vec(numChannels, Flipped(Decoupled(UInt(8.W))))\n", + " val in = Vec(numChannels, Flipped(Decoupled(UInt(8.W))))\n", " val out = Decoupled(UInt(8.W))\n", - " } )\n", + " })\n", "\n", " // YOUR CODE BELOW\n", " ???\n", "}\n", "\n", "simulate(new MyRoutingArbiter(4)) { c =>\n", - " // verify that the computation is correct\n", - " // Set input defaults\n", - " for(i <- 0 until 4) {\n", - " c.io.in(i).valid.poke(false.B)\n", - " c.io.in(i).bits.poke(i.U)\n", - " c.io.out.ready.poke(true.B)\n", - " }\n", - "\n", - " c.io.out.valid.expect(false.B)\n", - "\n", - " // Check single input valid behavior with backpressure\n", - " for (i <- 0 until 4) {\n", - " c.io.in(i).valid.poke(true.B)\n", - " c.io.out.valid.expect(true.B)\n", - " c.io.out.bits.expect(i.U)\n", - "\n", - " c.io.out.ready.poke(false.B)\n", - " c.io.in(i).ready.expect(false.B)\n", - "\n", - " c.io.out.ready.poke(true.B)\n", - " c.io.in(i).valid.poke(false.B)\n", - " }\n", - "\n", - " // Basic check of multiple input ready behavior with backpressure\n", - " c.io.in(1).valid.poke(true.B)\n", - " c.io.in(2).valid.poke(true.B)\n", - " c.io.out.bits.expect(1.U)\n", - " c.io.in(1).ready.expect(true.B)\n", - " c.io.in(0).ready.expect(false.B)\n", + " // verify that the computation is correct\n", + " // Set input defaults\n", + " for (i <- 0 until 4) {\n", + " c.io.in(i).valid.poke(false.B)\n", + " c.io.in(i).bits.poke(i.U)\n", + " c.io.out.ready.poke(true.B)\n", + " }\n", + "\n", + " c.io.out.valid.expect(false.B)\n", + "\n", + " // Check single input valid behavior with backpressure\n", + " for (i <- 0 until 4) {\n", + " c.io.in(i).valid.poke(true.B)\n", + " c.io.out.valid.expect(true.B)\n", + " c.io.out.bits.expect(i.U)\n", "\n", " c.io.out.ready.poke(false.B)\n", - " c.io.in(1).ready.expect(false.B)\n", + " c.io.in(i).ready.expect(false.B)\n", + "\n", + " c.io.out.ready.poke(true.B)\n", + " c.io.in(i).valid.poke(false.B)\n", + " }\n", + "\n", + " // Basic check of multiple input ready behavior with backpressure\n", + " c.io.in(1).valid.poke(true.B)\n", + " c.io.in(2).valid.poke(true.B)\n", + " c.io.out.bits.expect(1.U)\n", + " c.io.in(1).ready.expect(true.B)\n", + " c.io.in(0).ready.expect(false.B)\n", + "\n", + " c.io.out.ready.poke(false.B)\n", + " c.io.in(1).ready.expect(false.B)\n", "}\n", "\n", "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!" diff --git a/3.4_functional_programming.ipynb b/3.4_functional_programming.ipynb index 80d0c2d..7a1649f 100644 --- a/3.4_functional_programming.ipynb +++ b/3.4_functional_programming.ipynb @@ -18,7 +18,8 @@ "## Motivation\n", "You saw functions in many previous modules, but now it's time to make our own and use them effectively.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -70,7 +71,7 @@ "source": [ "// No inputs or outputs (two versions).\n", "def hello1(): Unit = print(\"Hello!\")\n", - "def hello2 = print(\"Hello again!\")\n", + "def hello2 = print(\"Hello again!\")\n", "\n", "// Math operation: one input and one output.\n", "def times2(x: Int): Int = 2 * x\n", @@ -83,9 +84,9 @@ "hello1()\n", "hello2\n", "times2(4)\n", - "timesN(4) // no need to specify n to use the default value\n", - "timesN(4, 3) // argument order is the same as the order where the function was defined\n", - "timesN(n=7, x=2) // arguments may be reordered and assigned to explicitly" + "timesN(4) // no need to specify n to use the default value\n", + "timesN(4, 3) // argument order is the same as the order where the function was defined\n", + "timesN(n = 7, x = 2) // arguments may be reordered and assigned to explicitly" ] }, { @@ -106,18 +107,18 @@ "outputs": [], "source": [ "// These are normal functions.\n", - "def plus1funct(x: Int): Int = x + 1\n", + "def plus1funct(x: Int): Int = x + 1\n", "def times2funct(x: Int): Int = x * 2\n", "\n", "// These are functions as vals.\n", "// The first one explicitly specifies the return type.\n", "val plus1val: Int => Int = x => x + 1\n", - "val times2val = (x: Int) => x * 2\n", + "val times2val = (x: Int) => x * 2\n", "\n", "// Calling both looks the same.\n", "plus1funct(4)\n", "plus1val(4)\n", - "plus1funct(x=4)\n", + "plus1funct(x = 4)\n", "//plus1val(x=4) // this doesn't work" ] }, @@ -138,18 +139,18 @@ "outputs": [], "source": [ "// create our function\n", - "val plus1 = (x: Int) => x + 1\n", + "val plus1 = (x: Int) => x + 1\n", "val times2 = (x: Int) => x * 2\n", "\n", "// pass it to map, a list function\n", - "val myList = List(1, 2, 5, 9)\n", - "val myListPlus = myList.map(plus1)\n", + "val myList = List(1, 2, 5, 9)\n", + "val myListPlus = myList.map(plus1)\n", "val myListTimes = myList.map(times2)\n", "\n", "// create a custom function, which performs an operation on X N times using recursion\n", "def opN(x: Int, n: Int, op: Int => Int): Int = {\n", " if (n <= 0) { x }\n", - " else { opN(op(x), n-1, op) }\n", + " else { opN(op(x), n - 1, op) }\n", "}\n", "\n", "opN(7, 3, plus1)\n", @@ -205,15 +206,15 @@ "// add one to every item in the list using an anonymous function\n", "// arguments get passed to the underscore variable\n", "// these all do the same thing\n", - "myList.map( (x:Int) => x + 1 )\n", + "myList.map((x: Int) => x + 1)\n", "myList.map(_ + 1)\n", "\n", "// a common situation is to use case statements within an anonymous function\n", "val myAnyList = List(1, 2, \"3\", 4L, myList)\n", "myAnyList.map {\n", - " case (_:Int|_:Long) => \"Number\"\n", - " case _:String => \"String\"\n", - " case _ => \"error\"\n", + " case (_: Int | _: Long) => \"Number\"\n", + " case _: String => \"String\"\n", + " case _ => \"error\"\n", "}" ] }, @@ -235,14 +236,14 @@ "\n", "// write a custom function to add two numbers, then use reduce to find the sum of all values in exList\n", "def add(a: Int, b: Int): Int = ???\n", - "val sum = ???\n", + "val sum = ???\n", "\n", "// find the sum of exList using an anonymous function (hint: you've seen this before!)\n", "val anon_sum = ???\n", "\n", "// find the moving average of exList from right to left using scan; make the result (ma2) a list of doubles\n", "def avg(a: Int, b: Double): Double = ???\n", - "val ma2 = ???" + "val ma2 = ???" ] }, { @@ -307,15 +308,15 @@ "\n", "// simple triangular window\n", "val TriangularWindow: (Int, Int) => Seq[Int] = (length, bitwidth) => {\n", - " val raw_coeffs = (0 until length).map( (x:Int) => 1-abs((x.toDouble-(length-1)/2.0)/((length-1)/2.0)) )\n", - " val scaled_coeffs = raw_coeffs.map( (x: Double) => round(x * pow(2, bitwidth)).toInt)\n", + " val raw_coeffs = (0 until length).map((x: Int) => 1 - abs((x.toDouble - (length - 1) / 2.0) / ((length - 1) / 2.0)))\n", + " val scaled_coeffs = raw_coeffs.map((x: Double) => round(x * pow(2, bitwidth)).toInt)\n", " scaled_coeffs\n", "}\n", "\n", "// Hamming window\n", "val HammingWindow: (Int, Int) => Seq[Int] = (length, bitwidth) => {\n", - " val raw_coeffs = (0 until length).map( (x: Int) => 0.54 - 0.46*cos(2*Pi*x/(length-1)))\n", - " val scaled_coeffs = raw_coeffs.map( (x: Double) => round(x * pow(2, bitwidth)).toInt)\n", + " val raw_coeffs = (0 until length).map((x: Int) => 0.54 - 0.46 * cos(2 * Pi * x / (length - 1)))\n", + " val scaled_coeffs = raw_coeffs.map((x: Double) => round(x * pow(2, bitwidth)).toInt)\n", " scaled_coeffs\n", "}\n", "\n", @@ -340,25 +341,27 @@ "// our FIR has parameterized window length, IO bitwidth, and windowing function\n", "class MyFir(length: Int, bitwidth: Int, window: (Int, Int) => Seq[Int]) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(UInt(bitwidth.W))\n", - " val out = Output(UInt((bitwidth*2+length-1).W)) // expect bit growth, conservative but lazy\n", + " val in = Input(UInt(bitwidth.W))\n", + " val out = Output(UInt((bitwidth * 2 + length - 1).W)) // expect bit growth, conservative but lazy\n", " })\n", "\n", " // calculate the coefficients using the provided window function, mapping to UInts\n", " val coeffs = window(length, bitwidth).map(_.U)\n", - " \n", + "\n", " // create an array holding the output of the delays\n", " // note: we avoid using a Vec here since we don't need dynamic indexing\n", - " val delays = Seq.fill(length)(Wire(UInt(bitwidth.W))).scan(io.in)( (prev: UInt, next: UInt) => {\n", - " next := RegNext(prev)\n", - " next\n", - " })\n", - " \n", + " val delays = Seq\n", + " .fill(length)(Wire(UInt(bitwidth.W)))\n", + " .scan(io.in)((prev: UInt, next: UInt) => {\n", + " next := RegNext(prev)\n", + " next\n", + " })\n", + "\n", " // multiply, putting result in \"mults\"\n", - " val mults = delays.zip(coeffs).map{ case(delay: UInt, coeff: UInt) => delay * coeff }\n", - " \n", + " val mults = delays.zip(coeffs).map { case (delay: UInt, coeff: UInt) => delay * coeff }\n", + "\n", " // add up multiplier outputs with bit growth\n", - " val result = mults.reduce(_+&_)\n", + " val result = mults.reduce(_ +& _)\n", "\n", " // connect output\n", " io.out := result\n", @@ -396,43 +399,42 @@ "}\n", "\n", "// test parameters\n", - "val length = 7\n", + "val length = 7\n", "val bitwidth = 12 // must be less than 15, otherwise Int can't represent the data, need BigInt\n", - "val window = TriangularWindow\n", + "val window = TriangularWindow\n", "\n", "// test our FIR\n", "simulate(new MyFir(length, bitwidth, window)) { c =>\n", - " \n", - " // test data\n", - " val n = 100 // input length\n", - " val sine_freq = 10\n", - " val samp_freq = 100\n", - "\n", - " // sample data, scale to between 0 and 2^bitwidth\n", - " val max_value = pow(2, bitwidth)-1\n", - " val sine = (0 until n).map(i => (max_value/2 + max_value/2*sin(2*Pi*sine_freq/samp_freq*i)).toInt)\n", - " //println(s\"input = ${sine.mkString(\", \")}\")\n", - "\n", - " // coefficients\n", - " val coeffs = window(length, bitwidth)\n", - " //println(s\"coeffs = ${coeffs.mkString(\", \")}\")\n", - "\n", - " // use the plain Scala convolution as golden model\n", - " val expected = goldenFir(sine, coeffs)\n", - " //println(s\"exp_out = ${expected.mkString(\", \")}\")\n", - "\n", - " // push data through our FIR and check the result\n", - " c.reset.poke(true.B)\n", - " c.clock.step(5)\n", - " c.reset.poke(false.B)\n", - " for (i <- 0 until n) {\n", - " c.io.in.poke(sine(i).U)\n", - " if (i >= length-1) { // wait for all registers to be initialized since we didn't zero-pad the data\n", - " c.io.out.expect(expected(i).U)\n", - " //println(s\"cycle $i, got ${c.io.out.peek()}, expect ${expected(i)}\")\n", - " }\n", - " c.clock.step(1)\n", + " // test data\n", + " val n = 100 // input length\n", + " val sine_freq = 10\n", + " val samp_freq = 100\n", + "\n", + " // sample data, scale to between 0 and 2^bitwidth\n", + " val max_value = pow(2, bitwidth) - 1\n", + " val sine = (0 until n).map(i => (max_value / 2 + max_value / 2 * sin(2 * Pi * sine_freq / samp_freq * i)).toInt)\n", + " // println(s\"input = ${sine.mkString(\", \")}\")\n", + "\n", + " // coefficients\n", + " val coeffs = window(length, bitwidth)\n", + " // println(s\"coeffs = ${coeffs.mkString(\", \")}\")\n", + "\n", + " // use the plain Scala convolution as golden model\n", + " val expected = goldenFir(sine, coeffs)\n", + " // println(s\"exp_out = ${expected.mkString(\", \")}\")\n", + "\n", + " // push data through our FIR and check the result\n", + " c.reset.poke(true.B)\n", + " c.clock.step(5)\n", + " c.reset.poke(false.B)\n", + " for (i <- 0 until n) {\n", + " c.io.in.poke(sine(i).U)\n", + " if (i >= length - 1) { // wait for all registers to be initialized since we didn't zero-pad the data\n", + " c.io.out.expect(expected(i).U)\n", + " // println(s\"cycle $i, got ${c.io.out.peek()}, expect ${expected(i)}\")\n", " }\n", + " c.clock.step(1)\n", + " }\n", "}" ] }, @@ -447,7 +449,7 @@ "**Exercise: Neural Network Neuron**
\n", "Our first example will have you build a neuron, the building block of fully-connected layers in artificial neural networks. Neurons take inputs and a set of weights, one per input, and produce one output. The weights and inputs are multiplied and added, and the result is fed through an activation function. In this exercise, you will implement different activation functions and pass them as an argument to your neuron generator.\n", "\n", - "![Neuron](https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/ArtificialNeuronModel_english.png/600px-ArtificialNeuronModel_english.png)\n", + "![Neuron](https://upload.wikimedia.org/wikipedia/commons/6/60/ArtificialNeuronModel_english.png)\n", "\n", "First, complete the following code to create a neuron generator. The parameter `inputs` gives the number of inputs. The parameter `act` is a function that implements the logic of the activation function. We'll make the inputs and outputs 16-bit fixed point values with 8 fractional bits.\n", "\n", @@ -475,11 +477,11 @@ "source": [ "class Neuron(inputs: Int, act: SInt => SInt) extends Module {\n", " val io = IO(new Bundle {\n", - " val in = Input(Vec(inputs, SInt(16.W))) // 8 fractional bits\n", - " val weights = Input(Vec(inputs, SInt(16.W))) // 8 fractional bits\n", - " val out = Output(SInt(16.W)) // 8 fractional bits\n", + " val in = Input(Vec(inputs, SInt(16.W))) // 8 fractional bits\n", + " val weights = Input(Vec(inputs, SInt(16.W))) // 8 fractional bits\n", + " val out = Output(SInt(16.W)) // 8 fractional bits\n", " })\n", - " \n", + "\n", " ???\n", "}" ] @@ -565,26 +567,26 @@ "metadata": {}, "outputs": [], "source": [ - "// test our Neuron \n", + "// test our Neuron\n", "simulate(new Neuron(2, Step)) { c =>\n", - " val inputs = Seq(Seq(-1, -1), Seq(-1, 1), Seq(1, -1), Seq(1, 1))\n", - "\n", - " // make this a sequence of two values\n", - " val weights = ???\n", - "\n", - " // push data through our Neuron and check the result (AND gate)\n", - " c.reset.poke(true.B)\n", - " c.clock.step(5)\n", - " c.reset.poke(false.B)\n", - " for (i <- inputs) {\n", - " c.io.in(0).poke(toFixed(i(0)))\n", - " c.io.in(1).poke(toFixed(i(1)))\n", - " c.io.weights(0).poke(toFixed(weights(0)))\n", - " c.io.weights(1).poke(toFixed(weights(1)))\n", - " c.io.out.expect(toFixed(if (i(0) + i(1) > 0) 1.0 else 0.0))\n", - " c.clock.step(1)\n", - " }\n", - " \n", + " val inputs = Seq(Seq(-1, -1), Seq(-1, 1), Seq(1, -1), Seq(1, 1))\n", + "\n", + " // make this a sequence of two values\n", + " val weights = ???\n", + "\n", + " // push data through our Neuron and check the result (AND gate)\n", + " c.reset.poke(true.B)\n", + " c.clock.step(5)\n", + " c.reset.poke(false.B)\n", + " for (i <- inputs) {\n", + " c.io.in(0).poke(toFixed(i(0)))\n", + " c.io.in(1).poke(toFixed(i(1)))\n", + " c.io.weights(0).poke(toFixed(weights(0)))\n", + " c.io.weights(1).poke(toFixed(weights(1)))\n", + " c.io.out.expect(toFixed(if (i(0) + i(1) > 0) 1.0 else 0.0))\n", + " c.clock.step(1)\n", + " }\n", + "\n", "}" ] }, diff --git a/3.5_object_oriented_programming.ipynb b/3.5_object_oriented_programming.ipynb index 8b6bbd7..a25c9f6 100644 --- a/3.5_object_oriented_programming.ipynb +++ b/3.5_object_oriented_programming.ipynb @@ -21,7 +21,8 @@ "However, as we'll see below, there are some differences.\n", "Chisel's hardware modules are similar to Verilog's modules, in that they can be instantiated and wired up as single or multiple instances.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -76,11 +77,11 @@ "}\n", "class ConcreteClass extends MyAbstractClass {\n", " def myFunction(i: Int): Int = i + 1\n", - " val myValue = \"Hello World!\"\n", + " val myValue = \"Hello World!\"\n", "}\n", "// Uncomment below to test!\n", "// val abstractClass = new MyAbstractClass() // Illegal! Cannot instantiate an abstract class\n", - "val concreteClass = new ConcreteClass() // Legal!\n" + "val concreteClass = new ConcreteClass() // Legal!" ] }, { @@ -111,12 +112,12 @@ "}\n", "class MyClass extends HasFunction with HasValue {\n", " override def myFunction(i: Int): Int = i + 1\n", - " val myValue = \"Hello World!\"\n", + " val myValue = \"Hello World!\"\n", "}\n", "// Uncomment below to test!\n", "// val myTraitFunction = new HasFunction() // Illegal! Cannot instantiate a trait\n", "// val myTraitValue = new HasValue() // Illegal! Cannot instantiate a trait\n", - "val myClass = new MyClass() // Legal!" + "val myClass = new MyClass() // Legal!" ] }, { @@ -143,7 +144,7 @@ "outputs": [], "source": [ "object MyObject {\n", - " def hi: String = \"Hello World!\"\n", + " def hi: String = \"Hello World!\"\n", " def apply(msg: String) = msg\n", "}\n", "println(MyObject.hi)\n", @@ -168,10 +169,10 @@ "outputs": [], "source": [ "object Lion {\n", - " def roar(): Unit = println(\"I'M AN OBJECT!\")\n", + " def roar(): Unit = println(\"I'M AN OBJECT!\")\n", "}\n", "class Lion {\n", - " def roar(): Unit = println(\"I'M A CLASS!\")\n", + " def roar(): Unit = println(\"I'M A CLASS!\")\n", "}\n", "new Lion().roar()\n", "Lion.roar()" @@ -196,13 +197,13 @@ "outputs": [], "source": [ "object Animal {\n", - " val defaultName = \"Bigfoot\"\n", - " private var numberOfAnimals = 0\n", - " def apply(name: String): Animal = {\n", - " numberOfAnimals += 1\n", - " new Animal(name, numberOfAnimals)\n", - " }\n", - " def apply(): Animal = apply(defaultName)\n", + " val defaultName = \"Bigfoot\"\n", + " private var numberOfAnimals = 0\n", + " def apply(name: String): Animal = {\n", + " numberOfAnimals += 1\n", + " new Animal(name, numberOfAnimals)\n", + " }\n", + " def apply(): Animal = apply(defaultName)\n", "}\n", "class Animal(name: String, order: Int) {\n", " def info: String = s\"Hi my name is $name, and I'm $order in line!\"\n", @@ -210,10 +211,10 @@ "\n", "val bunny = Animal.apply(\"Hopper\") // Calls the Animal factory method\n", "println(bunny.info)\n", - "val cat = Animal(\"Whiskers\") // Calls the Animal factory method\n", + "val cat = Animal(\"Whiskers\") // Calls the Animal factory method\n", "println(cat.info)\n", - "val yeti = Animal() // Calls the Animal factory method\n", - "println(yeti.info)\n" + "val yeti = Animal() // Calls the Animal factory method\n", + "println(yeti.info)" ] }, { @@ -284,11 +285,11 @@ "// println(nail.length) // Illegal! Class constructor parameters are not by default externally visible\n", "\n", "class Screw(val threadSpace: Int) // By using the `val` keyword, threadSpace is now externally visible\n", - "val screw = new Screw(2) // Requires the `new` keyword\n", + "val screw = new Screw(2) // Requires the `new` keyword\n", "println(screw.threadSpace)\n", "\n", "case class Staple(isClosed: Boolean) // Case class constructor parameters are, by default, externally visible\n", - "val staple = Staple(false) // No `new` keyword required\n", + "val staple = Staple(false) // No `new` keyword required\n", "println(staple.isClosed)" ] }, @@ -314,14 +315,10 @@ "metadata": {}, "outputs": [], "source": [ - "case class SomeGeneratorParameters(\n", - " someWidth: Int,\n", - " someOtherWidth: Int = 10,\n", - " pipelineMe: Boolean = false\n", - ") {\n", - " require(someWidth >= 0)\n", - " require(someOtherWidth >= 0)\n", - " val totalWidth = someWidth + someOtherWidth\n", + "case class SomeGeneratorParameters(someWidth: Int, someOtherWidth: Int = 10, pipelineMe: Boolean = false) {\n", + " require(someWidth >= 0)\n", + " require(someOtherWidth >= 0)\n", + " val totalWidth = someWidth + someOtherWidth\n", "}" ] }, @@ -361,23 +358,27 @@ "\n", "// create a module\n", "class GrayCoder(bitwidth: Int) extends Module {\n", - " val io = IO(new Bundle{\n", - " val in = Input(UInt(bitwidth.W))\n", - " val out = Output(UInt(bitwidth.W))\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(bitwidth.W))\n", + " val out = Output(UInt(bitwidth.W))\n", " val encode = Input(Bool()) // decode on false\n", " })\n", - " \n", - " when (io.encode) { //encode\n", + "\n", + " when(io.encode) { // encode\n", " io.out := io.in ^ (io.in >> 1.U)\n", - " } .otherwise { // decode, much more complicated\n", - " io.out := Seq.fill(log2Ceil(bitwidth))(Wire(UInt(bitwidth.W))).zipWithIndex.fold((io.in, 0)){\n", - " case ((w1: UInt, i1: Int), (w2: UInt, i2: Int)) => {\n", - " w2 := w1 ^ (w1 >> pow(2, log2Ceil(bitwidth)-i2-1).toInt.U)\n", - " (w2, i1)\n", + " }.otherwise { // decode, much more complicated\n", + " io.out := Seq\n", + " .fill(log2Ceil(bitwidth))(Wire(UInt(bitwidth.W)))\n", + " .zipWithIndex\n", + " .fold((io.in, 0)) {\n", + " case ((w1: UInt, i1: Int), (w2: UInt, i2: Int)) => {\n", + " w2 := w1 ^ (w1 >> pow(2, log2Ceil(bitwidth) - i2 - 1).toInt.U)\n", + " (w2, i1)\n", + " }\n", " }\n", - " }._1\n", + " ._1\n", " }\n", - "}\n" + "}" ] }, { @@ -396,24 +397,24 @@ "// test our gray coder\n", "val bitwidth = 4\n", "simulate(new GrayCoder(bitwidth)) { c =>\n", - " def toBinary(i: Int, digits: Int = 8) = {\n", - " String.format(\"%\" + digits + \"s\", i.toBinaryString).replace(' ', '0')\n", - " }\n", - " println(\"Encoding:\")\n", - " for (i <- 0 until pow(2, bitwidth).toInt) {\n", - " c.io.in.poke(i.U)\n", - " c.io.encode.poke(true.B)\n", - " c.clock.step(1)\n", - " println(s\"In = ${toBinary(i, bitwidth)}, Out = ${toBinary(c.io.out.peek().litValue.toInt, bitwidth)}\")\n", - " }\n", - "\n", - " println(\"Decoding:\")\n", - " for (i <- 0 until pow(2, bitwidth).toInt) {\n", - " c.io.in.poke(i.U)\n", - " c.io.encode.poke(false.B)\n", - " c.clock.step(1)\n", - " println(s\"In = ${toBinary(i, bitwidth)}, Out = ${toBinary(c.io.out.peek().litValue.toInt, bitwidth)}\")\n", - " }\n", + " def toBinary(i: Int, digits: Int = 8) = {\n", + " String.format(\"%\" + digits + \"s\", i.toBinaryString).replace(' ', '0')\n", + " }\n", + " println(\"Encoding:\")\n", + " for (i <- 0 until pow(2, bitwidth).toInt) {\n", + " c.io.in.poke(i.U)\n", + " c.io.encode.poke(true.B)\n", + " c.clock.step(1)\n", + " println(s\"In = ${toBinary(i, bitwidth)}, Out = ${toBinary(c.io.out.peek().litValue.toInt, bitwidth)}\")\n", + " }\n", + "\n", + " println(\"Decoding:\")\n", + " for (i <- 0 until pow(2, bitwidth).toInt) {\n", + " c.io.in.poke(i.U)\n", + " c.io.encode.poke(false.B)\n", + " c.clock.step(1)\n", + " println(s\"In = ${toBinary(i, bitwidth)}, Out = ${toBinary(c.io.out.peek().litValue.toInt, bitwidth)}\")\n", + " }\n", "\n", "}" ] @@ -432,42 +433,42 @@ "outputs": [], "source": [ "class AsyncFIFO(depth: Int = 16) extends Module {\n", - " val io = IO(new Bundle{\n", + " val io = IO(new Bundle {\n", " // write inputs\n", - " val write_clock = Input(Clock())\n", + " val write_clock = Input(Clock())\n", " val write_enable = Input(Bool())\n", - " val write_data = Input(UInt(32.W))\n", - " \n", + " val write_data = Input(UInt(32.W))\n", + "\n", " // read inputs/outputs\n", - " val read_clock = Input(Clock())\n", + " val read_clock = Input(Clock())\n", " val read_enable = Input(Bool())\n", - " val read_data = Output(UInt(32.W))\n", - " \n", + " val read_data = Output(UInt(32.W))\n", + "\n", " // FIFO status\n", - " val full = Output(Bool())\n", + " val full = Output(Bool())\n", " val empty = Output(Bool())\n", " })\n", - " \n", + "\n", " // add extra bit to counter to check for fully/empty status\n", " assert(isPow2(depth), \"AsyncFIFO needs a power-of-two depth!\")\n", - " val write_counter = withClock(io.write_clock) { Counter(io.write_enable && !io.full, depth*2)._1 }\n", - " val read_counter = withClock(io.read_clock) { Counter(io.read_enable && !io.empty, depth*2)._1 }\n", - " \n", + " val write_counter = withClock(io.write_clock) { Counter(io.write_enable && !io.full, depth * 2)._1 }\n", + " val read_counter = withClock(io.read_clock) { Counter(io.read_enable && !io.empty, depth * 2)._1 }\n", + "\n", " // encode\n", " val encoder = Module(new GrayCoder(write_counter.getWidth))\n", - " encoder.io.in := write_counter\n", + " encoder.io.in := write_counter\n", " encoder.io.encode := true.B\n", - " \n", + "\n", " // synchronize\n", " val sync = withClock(io.read_clock) { ShiftRegister(encoder.io.out, 2) }\n", - " \n", + "\n", " // decode\n", " val decoder = Module(new GrayCoder(read_counter.getWidth))\n", - " decoder.io.in := sync\n", + " decoder.io.in := sync\n", " decoder.io.encode := false.B\n", - " \n", + "\n", " // status logic goes here\n", - " \n", + "\n", "}" ] }, diff --git a/3.6_types.ipynb b/3.6_types.ipynb index 96ddd7b..90d8939 100644 --- a/3.6_types.ipynb +++ b/3.6_types.ipynb @@ -26,7 +26,8 @@ "While initially you may feel you have limited productivity, you will soon learn to understand compile-time error messages and how to architect your programs with the type system in mind to catch more errors for you. \n", "\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -90,7 +91,7 @@ "outputs": [], "source": [ "class MyClass {\n", - " def myMethod = ???\n", + " def myMethod = ???\n", "}\n", "println(new MyClass().getClass)" ] @@ -131,9 +132,9 @@ "metadata": {}, "outputs": [], "source": [ - "var counter = 0\n", + "var counter = 0\n", "def increment(): Unit = {\n", - " counter += 1\n", + " counter += 1\n", "}\n", "increment()" ] @@ -188,9 +189,7 @@ { "attachments": {}, "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "### asInstanceOf\n", "\n", @@ -242,18 +241,18 @@ "outputs": [], "source": [ "class TypeConvertDemo extends Module {\n", - " val io = IO(new Bundle {\n", - " val in = Input(UInt(4.W))\n", - " val out = Output(SInt(4.W))\n", - " })\n", - " io.out := io.in//.asTypeOf(io.out)\n", + " val io = IO(new Bundle {\n", + " val in = Input(UInt(4.W))\n", + " val out = Output(SInt(4.W))\n", + " })\n", + " io.out := io.in // .asTypeOf(io.out)\n", "}\n", "\n", "simulate(new TypeConvertDemo) { c =>\n", - " c.io.in.poke(3.U)\n", - " c.io.out.expect(3.S)\n", - " c.io.in.poke(15.U)\n", - " c.io.out.expect(-1.S)\n", + " c.io.in.poke(3.U)\n", + " c.io.out.expect(3.S)\n", + " c.io.in.poke(15.U)\n", + " c.io.out.expect(-1.S)\n", "}" ] }, @@ -283,18 +282,18 @@ "outputs": [], "source": [ "class ConstantSum(in1: Data, in2: Data) extends Module {\n", - " val io = IO(new Bundle {\n", - " val out = Output(chiselTypeOf(in1)) // in case in1 is literal then just get its type\n", - " })\n", - " (in1, in2) match {\n", - " case (x: UInt, y: UInt) => io.out := x + y\n", - " case (x: SInt, y: SInt) => io.out := x + y\n", - " case _ => throw new Exception(\"I give up!\")\n", - " }\n", + " val io = IO(new Bundle {\n", + " val out = Output(chiselTypeOf(in1)) // in case in1 is literal then just get its type\n", + " })\n", + " (in1, in2) match {\n", + " case (x: UInt, y: UInt) => io.out := x + y\n", + " case (x: SInt, y: SInt) => io.out := x + y\n", + " case _ => throw new Exception(\"I give up!\")\n", + " }\n", "}\n", "println(getVerilog(dut = new ConstantSum(3.U, 4.U)))\n", "println(getVerilog(dut = new ConstantSum(-3.S, 4.S)))\n", - "println(getVerilog(dut = new ConstantSum(3.U, 4.S)))\n" + "println(getVerilog(dut = new ConstantSum(3.U, 4.S)))" ] }, { @@ -360,19 +359,15 @@ "metadata": {}, "outputs": [], "source": [ - "case class SomeGeneratorParameters(\n", - " someWidth: Int,\n", - " someOtherWidth: Int = 10,\n", - " pipelineMe: Boolean = false\n", - ") {\n", - " require(someWidth >= 0)\n", - " require(someOtherWidth >= 0)\n", - " val totalWidth = someWidth + someOtherWidth\n", + "case class SomeGeneratorParameters(someWidth: Int, someOtherWidth: Int = 10, pipelineMe: Boolean = false) {\n", + " require(someWidth >= 0)\n", + " require(someOtherWidth >= 0)\n", + " val totalWidth = someWidth + someOtherWidth\n", "}\n", "\n", "def delay(p: SomeGeneratorParameters): Int = p match {\n", - " case SomeGeneratorParameters(_, sw, false) => sw * 2\n", - " case sg @SomeGeneratorParameters(_, _, true) => sg.totalWidth * 3\n", + " case SomeGeneratorParameters(_, sw, false) => sw * 2\n", + " case sg @ SomeGeneratorParameters(_, _, true) => sg.totalWidth * 3\n", "}\n", "\n", "println(delay(SomeGeneratorParameters(10, 10)))\n", @@ -418,15 +413,15 @@ "source": [ "class Boat(val name: String, val length: Int)\n", "object Boat {\n", - " def unapply(b: Boat): Option[(String, Int)] = Some((b.name, b.length))\n", - " def apply(name: String, length: Int): Boat = new Boat(name, length)\n", + " def unapply(b: Boat): Option[(String, Int)] = Some((b.name, b.length))\n", + " def apply(name: String, length: Int): Boat = new Boat(name, length)\n", "}\n", "\n", "def getSmallBoats(seq: Seq[Boat]): Seq[Boat] = seq.filter { b =>\n", - " b match {\n", - " case Boat(_, length) if length < 60 => true\n", - " case Boat(_, _) => false\n", - " }\n", + " b match {\n", + " case Boat(_, length) if length < 60 => true\n", + " case Boat(_, _) => false\n", + " }\n", "}\n", "\n", "val boats = Seq(Boat(\"Santa Maria\", 62), Boat(\"Pinta\", 56), Boat(\"Nina\", 50))\n", @@ -533,15 +528,15 @@ "\n", "class BadTypeModule extends Module {\n", " val io = IO(new Bundle {\n", - " val c = Input(Clock())\n", - " val in = Input(UInt(2.W))\n", + " val c = Input(Clock())\n", + " val in = Input(UInt(2.W))\n", " val out = Output(Bool())\n", "\n", - " val bundleIn = Input(new Bundle2)\n", + " val bundleIn = Input(new Bundle2)\n", " val bundleOut = Output(new Bundle1)\n", " })\n", - " \n", - " //io.out := io.c // won't work due to different types\n", + "\n", + " // io.out := io.c // won't work due to different types\n", "\n", " // Okay, but Chisel will truncate the input width to 1 to match the output.\n", " io.out := io.in\n", @@ -594,11 +589,11 @@ "source": [ "//val default = Seq() // Error!\n", "val default = Seq[String]() // User must tell compiler that default is of type Seq[String]\n", - "Seq(1, \"2\", true).foldLeft(default){ (strings, next) =>\n", - " next match {\n", - " case s: String => strings ++ Seq(s)\n", - " case _ => strings\n", - " }\n", + "Seq(1, \"2\", true).foldLeft(default) { (strings, next) =>\n", + " next match {\n", + " case s: String => strings ++ Seq(s)\n", + " case _ => strings\n", + " }\n", "}" ] }, @@ -617,12 +612,12 @@ "outputs": [], "source": [ "def time[T](block: => T): T = {\n", - " val t0 = System.nanoTime()\n", - " val result = block\n", - " val t1 = System.nanoTime()\n", - " val timeMillis = (t1 - t0) / 1000000.0\n", - " println(s\"Block took $timeMillis milliseconds!\")\n", - " result\n", + " val t0 = System.nanoTime()\n", + " val result = block\n", + " val t1 = System.nanoTime()\n", + " val timeMillis = (t1 - t0) / 1000000.0\n", + " println(s\"Block took $timeMillis milliseconds!\")\n", + " result\n", "}\n", "\n", "// Adds 1 through a million\n", @@ -631,7 +626,7 @@ "\n", "// Finds the largest number under a million that, in hex, contains \"beef\"\n", "val string = time {\n", - " (1 to 1000000).map(_.toHexString).filter(_.contains(\"beef\")).last\n", + " (1 to 1000000).map(_.toHexString).filter(_.contains(\"beef\")).last\n", "}\n", "println(s\"The largest number under a million that has beef: $string\")" ] @@ -682,29 +677,30 @@ "outputs": [], "source": [ "class ShiftRegisterIO[T <: Data](gen: T, n: Int) extends Bundle {\n", - " require (n >= 0, \"Shift register must have non-negative shift\")\n", - " \n", - " val in = Input(gen)\n", - " val out = Output(Vec(n + 1, gen)) // + 1 because in is included in out\n", + " require(n >= 0, \"Shift register must have non-negative shift\")\n", + "\n", + " val in = Input(gen)\n", + " val out = Output(Vec(n + 1, gen)) // + 1 because in is included in out\n", "}\n", "\n", "class ShiftRegister[T <: Data](gen: T, n: Int) extends Module {\n", - " val io = IO(new ShiftRegisterIO(gen, n))\n", - " \n", - " io.out.foldLeft(io.in) { case (in, out) =>\n", - " out := in\n", - " RegNext(in, 0.U.asTypeOf(gen)) // registers reset to zero\n", - " }\n", + " val io = IO(new ShiftRegisterIO(gen, n))\n", + "\n", + " io.out.foldLeft(io.in) { case (in, out) =>\n", + " out := in\n", + " RegNext(in, 0.U.asTypeOf(gen)) // registers reset to zero\n", + " }\n", "}\n", "\n", "visualize(() => new ShiftRegister(SInt(6.W), 3))\n", - "simulate(new ShiftRegister(SInt(6.W), 3)) { c => \n", - " println(s\"Testing ShiftRegister of type ${c.io.in} and depth ${c.io.out.length}\")\n", - " for (i <- 0 until 10) {\n", - " c.io.in.poke(i.S) // magic literal creation\n", - " println(s\"$i: ${c.io.out.indices.map { index => c.io.out(index).peek().litValue} }\")\n", - " c.clock.step(1)\n", - " }}" + "simulate(new ShiftRegister(SInt(6.W), 3)) { c =>\n", + " println(s\"Testing ShiftRegister of type ${c.io.in} and depth ${c.io.out.length}\")\n", + " for (i <- 0 until 10) {\n", + " c.io.in.poke(i.S) // magic literal creation\n", + " println(s\"$i: ${c.io.out.indices.map { index => c.io.out(index).peek().litValue }}\")\n", + " c.clock.step(1)\n", + " }\n", + "}" ] }, { @@ -727,7 +723,6 @@ "\n", "The example above was limited to simple operations that could be performed on any instance of `Data` such as `:=` or `RegNext()`.\n", "When generating DSP circuits, we would like to do mathematical operations like addition and multiplication.\n", - "Libraries such as `dsptools` (which is not used in this bootcamp) provide tools for writing type parameterized DSP generators; here we build a tiny version of the same idea ourselves.\n", "\n", "The key tool is a *typeclass*.\n", "A typeclass is a trait (here `Ring[T]`) that describes operations on some type `T` without `T` having to inherit from it.\n", @@ -744,7 +739,9 @@ }, { "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ "// A typeclass describing \"number-like\" hardware types: they have 0, 1, +, - and *.\n", "trait Ring[T <: Data] {\n", @@ -761,16 +758,16 @@ "\n", " // instances for the built-in types; living in the companion object, the compiler finds them automatically\n", " implicit object UIntRing extends Ring[UInt] {\n", - " def zero: UInt = 0.U\n", - " def one: UInt = 1.U\n", - " def plus(a: UInt, b: UInt): UInt = a + b\n", + " def zero: UInt = 0.U\n", + " def one: UInt = 1.U\n", + " def plus(a: UInt, b: UInt): UInt = a + b\n", " def minus(a: UInt, b: UInt): UInt = a - b\n", " def times(a: UInt, b: UInt): UInt = a * b\n", " }\n", " implicit object SIntRing extends Ring[SInt] {\n", - " def zero: SInt = 0.S\n", - " def one: SInt = 1.S\n", - " def plus(a: SInt, b: SInt): SInt = a + b\n", + " def zero: SInt = 0.S\n", + " def one: SInt = 1.S\n", + " def plus(a: SInt, b: SInt): SInt = a + b\n", " def minus(a: SInt, b: SInt): SInt = a - b\n", " def times(a: SInt, b: SInt): SInt = a * b\n", " }\n", @@ -782,9 +779,7 @@ " def -(rhs: T): T = ring.minus(lhs, rhs)\n", " def *(rhs: T): T = ring.times(lhs, rhs)\n", "}" - ], - "execution_count": null, - "outputs": [] + ] }, { "cell_type": "code", @@ -792,18 +787,18 @@ "metadata": {}, "outputs": [], "source": [ - "class Mac[T <: Data : Ring](genIn : T, genOut: T) extends Module {\n", - " val io = IO(new Bundle {\n", - " val a = Input(genIn)\n", - " val b = Input(genIn)\n", - " val c = Input(genIn)\n", - " val out = Output(genOut)\n", - " })\n", - " io.out := io.a * io.b + io.c\n", + "class Mac[T <: Data: Ring](genIn: T, genOut: T) extends Module {\n", + " val io = IO(new Bundle {\n", + " val a = Input(genIn)\n", + " val b = Input(genIn)\n", + " val c = Input(genIn)\n", + " val out = Output(genOut)\n", + " })\n", + " io.out := io.a * io.b + io.c\n", "}\n", "\n", - "println(getVerilog(new Mac(UInt(4.W), UInt(6.W)) ))\n", - "println(getVerilog(new Mac(SInt(4.W), SInt(6.W)) ))" + "println(getVerilog(new Mac(UInt(4.W), UInt(6.W))))\n", + "println(getVerilog(new Mac(SInt(4.W), SInt(6.W))))" ] }, { @@ -829,21 +824,21 @@ "outputs": [], "source": [ "object Mac {\n", - " def apply[T <: Data : Ring](a: T, b: T, c: T): T = {\n", - " ??? // your code\n", - " }\n", + " def apply[T <: Data: Ring](a: T, b: T, c: T): T = {\n", + " ??? // your code\n", + " }\n", "}\n", "\n", "class MacTestModule extends Module {\n", - " val io = IO(new Bundle {\n", - " val uin = Input(UInt(4.W))\n", - " val uout = Output(UInt(16.W))\n", - " val sin = Input(SInt(4.W))\n", - " val sout = Output(SInt(16.W))\n", - " })\n", - " // for each IO pair, do out = in * in + in\n", - " io.uout := Mac(io.uin, io.uin, io.uin)\n", - " io.sout := Mac(io.sin, io.sin, io.sin)\n", + " val io = IO(new Bundle {\n", + " val uin = Input(UInt(4.W))\n", + " val uout = Output(UInt(16.W))\n", + " val sin = Input(SInt(4.W))\n", + " val sout = Output(SInt(16.W))\n", + " })\n", + " // for each IO pair, do out = in * in + in\n", + " io.uout := Mac(io.uin, io.uin, io.uin)\n", + " io.sout := Mac(io.sin, io.sin, io.sin)\n", "}\n", "println(getVerilog(new MacTestModule))" ] @@ -883,26 +878,26 @@ "metadata": {}, "outputs": [], "source": [ - "class Integrator[T <: Data : Ring](genIn: T, genReg: T) extends Module {\n", - " val io = IO(new Bundle {\n", - " val in = Input(genIn)\n", - " val out = Output(genReg)\n", - " })\n", - " \n", - " ??? // your code\n", + "class Integrator[T <: Data: Ring](genIn: T, genReg: T) extends Module {\n", + " val io = IO(new Bundle {\n", + " val in = Input(genIn)\n", + " val out = Output(genReg)\n", + " })\n", + "\n", + " ??? // your code\n", "}\n", "\n", "simulate(new Integrator(SInt(4.W), SInt(8.W))) { c =>\n", - " c.io.in.poke(3.S)\n", - " c.io.out.expect(0.S)\n", - " c.clock.step(1)\n", - " c.io.in.poke(-4.S)\n", - " c.io.out.expect(3.S)\n", - " c.clock.step(1)\n", - " c.io.in.poke(6.S)\n", - " c.io.out.expect(-1.S)\n", - " c.clock.step(1)\n", - " c.io.out.expect(5.S)\n", + " c.io.in.poke(3.S)\n", + " c.io.out.expect(0.S)\n", + " c.clock.step(1)\n", + " c.io.in.poke(-4.S)\n", + " c.io.out.expect(3.S)\n", + " c.clock.step(1)\n", + " c.io.in.poke(6.S)\n", + " c.io.out.expect(-1.S)\n", + " c.clock.step(1)\n", + " c.io.out.expect(5.S)\n", "}" ] }, @@ -950,8 +945,7 @@ "metadata": {}, "source": [ "**Example: Complex Numbers**
\n", - "Complex numbers are a classic example of a custom data type.\n", - "The `dsptools` library has a `DspComplex` type; we write a minimal version of our own.\n", + "Complex numbers are a classic example of a custom data type; we write a minimal one.\n", "The key line to understand is this:\n", "```scala\n", "class Complex[T <: Data : Ring](val real: T, val imag: T) extends Bundle\n", @@ -976,19 +970,19 @@ "outputs": [], "source": [ "// A complex number whose real and imaginary parts can be any type T\n", - "class Complex[T <: Data : Ring](val real: T, val imag: T) extends Bundle\n", + "class Complex[T <: Data: Ring](val real: T, val imag: T) extends Bundle\n", "\n", "// Complex numbers form a Ring as well, as long as their parts do\n", - "implicit def complexRing[T <: Data : Ring]: Ring[Complex[T]] = new Ring[Complex[T]] {\n", + "implicit def complexRing[T <: Data: Ring]: Ring[Complex[T]] = new Ring[Complex[T]] {\n", " private def make(re: T, im: T): Complex[T] = {\n", " val result = Wire(new Complex(chiselTypeOf(re), chiselTypeOf(im)))\n", " result.real := re\n", " result.imag := im\n", " result\n", " }\n", - " def zero: Complex[T] = make(Ring[T].zero, Ring[T].zero)\n", - " def one: Complex[T] = make(Ring[T].one, Ring[T].zero)\n", - " def plus(a: Complex[T], b: Complex[T]): Complex[T] = make(a.real + b.real, a.imag + b.imag)\n", + " def zero: Complex[T] = make(Ring[T].zero, Ring[T].zero)\n", + " def one: Complex[T] = make(Ring[T].one, Ring[T].zero)\n", + " def plus(a: Complex[T], b: Complex[T]): Complex[T] = make(a.real + b.real, a.imag + b.imag)\n", " def minus(a: Complex[T], b: Complex[T]): Complex[T] = make(a.real - b.real, a.imag - b.imag)\n", " // (a + bi)(c + di) = (ac - bd) + (ad + bc)i\n", " def times(a: Complex[T], b: Complex[T]): Complex[T] =\n", @@ -1020,49 +1014,49 @@ "outputs": [], "source": [ "class SignMagnitude(val magnitudeWidth: Option[Int] = None) extends Bundle {\n", - " val sign = Bool()\n", - " val magnitude = magnitudeWidth match {\n", - " case Some(w) => UInt(w.W)\n", - " case None => UInt()\n", - " }\n", - " def +(that: SignMagnitude): SignMagnitude = {\n", - " // Implement this!\n", - " }\n", - " def -(that: SignMagnitude): SignMagnitude = {\n", - " this.+(-that)\n", - " }\n", - " def unary_-(): SignMagnitude = {\n", - " val result = Wire(new SignMagnitude())\n", - " result.sign := !this.sign\n", - " result.magnitude := this.magnitude\n", - " result\n", - " }\n", - " def *(that: SignMagnitude): SignMagnitude = {\n", - " // Implement this!\n", - " }\n", + " val sign = Bool()\n", + " val magnitude = magnitudeWidth match {\n", + " case Some(w) => UInt(w.W)\n", + " case None => UInt()\n", + " }\n", + " def +(that: SignMagnitude): SignMagnitude = {\n", + " // Implement this!\n", + " }\n", + " def -(that: SignMagnitude): SignMagnitude = {\n", + " this.+(-that)\n", + " }\n", + " def unary_-(): SignMagnitude = {\n", + " val result = Wire(new SignMagnitude())\n", + " result.sign := !this.sign\n", + " result.magnitude := this.magnitude\n", + " result\n", + " }\n", + " def *(that: SignMagnitude): SignMagnitude = {\n", + " // Implement this!\n", + " }\n", "}\n", "implicit object SignMagnitudeRing extends Ring[SignMagnitude] {\n", - " def plus(f: SignMagnitude, g: SignMagnitude): SignMagnitude = {\n", - " f + g\n", - " }\n", - " def minus(f: SignMagnitude, g: SignMagnitude): SignMagnitude = {\n", - " f - g\n", - " }\n", - " def times(f: SignMagnitude, g: SignMagnitude): SignMagnitude = {\n", - " f * g\n", - " }\n", - " def one: SignMagnitude = {\n", - " val one = Wire(new SignMagnitude(Some(1)))\n", - " one.sign := false.B\n", - " one.magnitude := 1.U\n", - " one\n", - " }\n", - " def zero: SignMagnitude = {\n", - " val zero = Wire(new SignMagnitude(Some(1)))\n", - " zero.sign := false.B\n", - " zero.magnitude := 0.U\n", - " zero\n", - " }\n", + " def plus(f: SignMagnitude, g: SignMagnitude): SignMagnitude = {\n", + " f + g\n", + " }\n", + " def minus(f: SignMagnitude, g: SignMagnitude): SignMagnitude = {\n", + " f - g\n", + " }\n", + " def times(f: SignMagnitude, g: SignMagnitude): SignMagnitude = {\n", + " f * g\n", + " }\n", + " def one: SignMagnitude = {\n", + " val one = Wire(new SignMagnitude(Some(1)))\n", + " one.sign := false.B\n", + " one.magnitude := 1.U\n", + " one\n", + " }\n", + " def zero: SignMagnitude = {\n", + " val zero = Wire(new SignMagnitude(Some(1)))\n", + " zero.sign := false.B\n", + " zero.magnitude := 0.U\n", + " zero\n", + " }\n", "}" ] }, @@ -1075,16 +1069,16 @@ "import chisel3.experimental.BundleLiterals._\n", "\n", "simulate(new Mac(new SignMagnitude(Some(4)), new SignMagnitude(Some(5)))) { c =>\n", - " c.io.a.poke(chiselTypeOf(c.io.a).Lit(_.sign -> false.B, _.magnitude -> 3.U))\n", - " c.io.b.poke(chiselTypeOf(c.io.b).Lit(_.sign -> false.B, _.magnitude -> 3.U))\n", - " c.io.c.poke(chiselTypeOf(c.io.c).Lit(_.sign -> false.B, _.magnitude -> 2.U))\n", - " c.io.out.expect(chiselTypeOf(c.io.out).Lit(_.sign -> false.B, _.magnitude -> 11.U))\n", + " c.io.a.poke(chiselTypeOf(c.io.a).Lit(_.sign -> false.B, _.magnitude -> 3.U))\n", + " c.io.b.poke(chiselTypeOf(c.io.b).Lit(_.sign -> false.B, _.magnitude -> 3.U))\n", + " c.io.c.poke(chiselTypeOf(c.io.c).Lit(_.sign -> false.B, _.magnitude -> 2.U))\n", + " c.io.out.expect(chiselTypeOf(c.io.out).Lit(_.sign -> false.B, _.magnitude -> 11.U))\n", "\n", - " c.io.c.sign.poke(true.B)\n", - " c.io.out.expect(chiselTypeOf(c.io.out).Lit(_.sign -> false.B, _.magnitude -> 7.U))\n", + " c.io.c.sign.poke(true.B)\n", + " c.io.out.expect(chiselTypeOf(c.io.out).Lit(_.sign -> false.B, _.magnitude -> 7.U))\n", "\n", - " c.io.b.sign.poke(true.B)\n", - " c.io.out.expect(chiselTypeOf(c.io.out).Lit(_.sign -> true.B, _.magnitude -> 11.U))\n", + " c.io.b.sign.poke(true.B)\n", + " c.io.out.expect(chiselTypeOf(c.io.out).Lit(_.sign -> true.B, _.magnitude -> 11.U))\n", "}\n", "println(\"SUCCESS!!\") // Scala Code: if we get here, our tests passed!" ] @@ -1120,7 +1114,14 @@ "metadata": {}, "outputs": [], "source": [ - "println(getVerilog(new Mac(new Complex(new SignMagnitude(Some(4)), new SignMagnitude(Some(4))), new Complex(new SignMagnitude(Some(5)), new SignMagnitude(Some(5))))))" + "println(\n", + " getVerilog(\n", + " new Mac(\n", + " new Complex(new SignMagnitude(Some(4)), new SignMagnitude(Some(4))),\n", + " new Complex(new SignMagnitude(Some(5)), new SignMagnitude(Some(5)))\n", + " )\n", + " )\n", + ")" ] }, { diff --git a/4.1_firrtl_ast.ipynb b/4.1_firrtl_ast.ipynb index 112e4c0..7bde7e4 100644 --- a/4.1_firrtl_ast.ipynb +++ b/4.1_firrtl_ast.ipynb @@ -26,7 +26,8 @@ "\n", "In this module we will learn to read FIRRTL, and then write small Scala programs that parse, analyze and rewrite it.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -151,7 +152,9 @@ "outputs": [], "source": [ "val firrtlDialect = _root_.circt.stage.ChiselStage.emitFIRRTLDialect(new DelayBy2(4))\n", - "println(firrtlDialect.linesIterator.dropWhile(!_.contains(\"firrtl.module\")).takeWhile(!_.startsWith(\" }\")).mkString(\"\\n\"))" + "println(\n", + " firrtlDialect.linesIterator.dropWhile(!_.contains(\"firrtl.module\")).takeWhile(!_.startsWith(\" }\")).mkString(\"\\n\")\n", + ")" ] }, { @@ -232,8 +235,8 @@ " m1.io.in(0) := io.a\n", " m1.io.in(1) := io.b\n", " m1.io.in(2) := m0.io.out\n", - " io.y := m0.io.out\n", - " io.z := m1.io.out\n", + " io.y := m0.io.out\n", + " io.z := m1.io.out\n", "}" ] }, @@ -271,8 +274,8 @@ "source": [ "class Parent extends Module {\n", " val io = IO(new Bundle { val in = Input(UInt(4.W)); val out = Output(UInt(5.W)) })\n", - " val r = RegInit(0.U(3.W))\n", - " val w = Wire(UInt(3.W))\n", + " val r = RegInit(0.U(3.W))\n", + " val w = Wire(UInt(3.W))\n", " w := r\n", " println(s\"r: isReg=${DataMirror.isReg(r)} isWire=${DataMirror.isWire(r)}\")\n", " println(s\"w: isReg=${DataMirror.isReg(w)} isWire=${DataMirror.isWire(w)}\")\n", @@ -283,7 +286,7 @@ " }\n", " child.io.in(0) := io.in\n", " child.io.in(1) := io.in\n", - " io.out := child.io.out\n", + " io.out := child.io.out\n", "}\n", "val parentFirrtl = getFirrtl(new Parent)" ] @@ -371,8 +374,8 @@ " val q = Output(UInt(8.W))\n", " })\n", "\n", - " val r = ??? // a register with an 8-bit width and reset value 0\n", - " ??? // when `en` is true, load `d` into r\n", + " val r = ??? // a register with an 8-bit width and reset value 0\n", + " ??? // when `en` is true, load `d` into r\n", " io.q := r\n", "}\n", "\n", diff --git a/4.2_firrtl_ast_traversal.ipynb b/4.2_firrtl_ast_traversal.ipynb index 8546a62..a0c5bdc 100644 --- a/4.2_firrtl_ast_traversal.ipynb +++ b/4.2_firrtl_ast_traversal.ipynb @@ -22,7 +22,8 @@ "\n", "Our AST covers the subset of FIRRTL that Chisel emits for ordinary designs: modules, ports, registers, wires, nodes, instances, connects, `when`/`else` and all expressions. Anything else (printf, memories, ...) is kept as raw text in an `OtherStmt`.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -83,9 +84,10 @@ " case leaf => leaf\n", " }\n", "}\n", - "case class Reference(name: String) extends Expression // x, io.in[0], m0.io.out\n", - "case class Literal(tpe: String, value: String) extends Expression // UInt<3>(0h5)\n", - "case class DoPrim(op: String, args: Seq[Expression], consts: Seq[Int]) extends Expression // add(a, b), bits(a, 3, 0), mux(c, a, b)\n", + "case class Reference(name: String) extends Expression // x, io.in[0], m0.io.out\n", + "case class Literal(tpe: String, value: String) extends Expression // UInt<3>(0h5)\n", + "case class DoPrim(op: String, args: Seq[Expression], consts: Seq[Int])\n", + " extends Expression // add(a, b), bits(a, 3, 0), mux(c, a, b)\n", "\n", "// ---- Statements ----\n", "sealed trait Statement {\n", @@ -109,12 +111,18 @@ "}\n", "sealed trait IsRegister extends Statement { def name: String; def tpe: String }\n", "case class DefRegister(info: String, name: String, tpe: String, clock: Expression) extends IsRegister\n", - "case class DefRegisterReset(info: String, name: String, tpe: String, clock: Expression,\n", - " reset: Expression, init: Expression) extends IsRegister\n", - "case class DefWire(info: String, name: String, tpe: String) extends Statement\n", - "case class DefNode(info: String, name: String, value: Expression) extends Statement\n", - "case class DefInstance(info: String, name: String, module: String) extends Statement\n", - "case class Connect(info: String, loc: Expression, expr: Expression) extends Statement\n", + "case class DefRegisterReset(\n", + " info: String,\n", + " name: String,\n", + " tpe: String,\n", + " clock: Expression,\n", + " reset: Expression,\n", + " init: Expression\n", + ") extends IsRegister\n", + "case class DefWire(info: String, name: String, tpe: String) extends Statement\n", + "case class DefNode(info: String, name: String, value: Expression) extends Statement\n", + "case class DefInstance(info: String, name: String, module: String) extends Statement\n", + "case class Connect(info: String, loc: Expression, expr: Expression) extends Statement\n", "case class Conditionally(info: String, pred: Expression, conseq: Seq[Statement], alt: Seq[Statement]) extends Statement\n", "// Everything we do not model in detail (printf, assert, mem, ...). Keeps the raw text.\n", "case class OtherStmt(info: String, text: String, children: Seq[Statement]) extends Statement\n", @@ -146,14 +154,14 @@ "source": [ "// Pretty-prints any of our case classes as an indented tree: one node per line.\n", "def showTree(x: Any, depth: Int = 0, label: String = \"\"): String = {\n", - " val pad = \" \" * depth + (if (label.isEmpty) \"\" else label + \": \")\n", + " val pad = \" \" * depth + (if (label.isEmpty) \"\" else label + \": \")\n", " def isNode(v: Any): Boolean = v match {\n", " case _: Expression | _: Statement | _: Port | _: DefModule | _: Circuit => true\n", - " case _ => false\n", + " case _ => false\n", " }\n", " x match {\n", " case p: Product if isNode(p) =>\n", - " val fields = p.productElementNames.toList.zip(p.productIterator.toList)\n", + " val fields = p.productElementNames.toList.zip(p.productIterator.toList)\n", " val (kids, atoms) = fields.partition {\n", " case (_, v: Seq[_]) => v.nonEmpty && v.forall(isNode)\n", " case (_, v) => isNode(v)\n", @@ -167,9 +175,13 @@ " }\n", "}\n", "\n", - "val addOne = DefModule(\"\", \"AddOne\", true,\n", + "val addOne = DefModule(\n", + " \"\",\n", + " \"AddOne\",\n", + " true,\n", " Seq(Port(\"\", \"input\", \"in\", \"UInt<4>\"), Port(\"\", \"output\", \"out\", \"UInt<5>\")),\n", - " Seq(Connect(\"\", Reference(\"out\"), DoPrim(\"add\", Seq(Reference(\"in\"), Literal(\"UInt<1>\", \"0h1\")), Nil))))\n", + " Seq(Connect(\"\", Reference(\"out\"), DoPrim(\"add\", Seq(Reference(\"in\"), Literal(\"UInt<1>\", \"0h1\")), Nil)))\n", + ")\n", "\n", "println(showTree(addOne))" ] @@ -204,20 +216,23 @@ "val infoRegex = \"\"\"^(.*?)\\s*@\\[(.*)\\]\\s*$\"\"\".r\n", "\n", "def toLines(text: String): List[Line] =\n", - " text.linesIterator.filter(_.trim.nonEmpty).map { raw =>\n", - " val indent = raw.length - raw.dropWhile(_ == ' ').length\n", - " raw.trim match {\n", - " case infoRegex(code, info) => Line(indent, code, info)\n", - " case code => Line(indent, code, \"\")\n", + " text.linesIterator\n", + " .filter(_.trim.nonEmpty)\n", + " .map { raw =>\n", + " val indent = raw.length - raw.dropWhile(_ == ' ').length\n", + " raw.trim match {\n", + " case infoRegex(code, info) => Line(indent, code, info)\n", + " case code => Line(indent, code, \"\")\n", + " }\n", " }\n", - " }.toList\n", + " .toList\n", "\n", "// Parses the sibling lines at `indent`; a more indented line starts the children of the line before it.\n", "def toTree(lines: List[Line], indent: Int): (Vector[Node], List[Line]) = {\n", - " var rest = lines\n", + " var rest = lines\n", " val siblings = Vector.newBuilder[Node]\n", " while (rest.nonEmpty && rest.head.indent == indent) {\n", - " val line = rest.head\n", + " val line = rest.head\n", " val (kids, remaining) =\n", " if (rest.tail.nonEmpty && rest.tail.head.indent > indent) toTree(rest.tail, rest.tail.head.indent)\n", " else (Vector.empty[Node], rest.tail)\n", @@ -254,7 +269,7 @@ "def splitTop(s: String): List[String] = {\n", " var depth = 0\n", " val parts = scala.collection.mutable.ListBuffer[String]()\n", - " val cur = new StringBuilder\n", + " val cur = new StringBuilder\n", " for (c <- s) c match {\n", " case '(' | '[' | '{' | '<' => depth += 1; cur += c\n", " case ')' | ']' | '}' | '>' => depth -= 1; cur += c\n", @@ -271,7 +286,7 @@ "\n", "def parseExpr(text: String): Expression = text.trim match {\n", " case literalRegex(tpe, value) => Literal(tpe, value)\n", - " case primRegex(op, args) =>\n", + " case primRegex(op, args) =>\n", " val (consts, exprs) = splitTop(args).partition(a => intRegex.matches(a))\n", " DoPrim(op, exprs.map(parseExpr), consts.map(_.toInt))\n", " case ref => Reference(ref)\n", @@ -327,19 +342,19 @@ " case wireRegex(name, tpe) => DefWire(info, name, tpe)\n", " case nodeRegex(name, value) => DefNode(info, name, parseExpr(value))\n", " case instRegex(name, module) => DefInstance(info, name, module)\n", - " case connectRegex(args) =>\n", + " case connectRegex(args) =>\n", " val Seq(loc, expr) = splitTop(args)\n", " Connect(info, parseExpr(loc), parseExpr(expr))\n", - " case whenRegex(pred) => Conditionally(info, parseExpr(pred), toStatements(kids), Nil)\n", - " case other => OtherStmt(info, other, toStatements(kids))\n", + " case whenRegex(pred) => Conditionally(info, parseExpr(pred), toStatements(kids), Nil)\n", + " case other => OtherStmt(info, other, toStatements(kids))\n", " }\n", "}\n", "\n", "def toModule(node: Node): DefModule = {\n", " val Node(Line(_, text, info), kids) = node\n", - " val moduleRegex(pub, name) = text\n", - " val (portNodes, bodyNodes) = kids.partition(k => portRegex.matches(k.line.text))\n", - " val ports = portNodes.map { k =>\n", + " val moduleRegex(pub, name) = text\n", + " val (portNodes, bodyNodes) = kids.partition(k => portRegex.matches(k.line.text))\n", + " val ports = portNodes.map { k =>\n", " val portRegex(dir, pname, tpe) = k.line.text\n", " Port(k.line.info, dir, pname, tpe)\n", " }\n", @@ -363,14 +378,16 @@ "source": [ "def parseCircuit(firrtl: String): Circuit = {\n", " // Skip the \"FIRRTL version\" line and the multi-line annotation block `circuit Top :%[[ ... ]]`.\n", - " val lines = firrtl.linesIterator.dropWhile(!_.startsWith(\"circuit \")).toList\n", - " val header = lines.head\n", - " val afterAnnos = if (header.endsWith(\"%[[\")) lines.tail.dropWhile(_.trim != \"]]\").tail else lines.tail\n", - " val main = header.stripPrefix(\"circuit \").takeWhile(c => c != ' ' && c != ':')\n", + " val lines = firrtl.linesIterator.dropWhile(!_.startsWith(\"circuit \")).toList\n", + " val header = lines.head\n", + " val afterAnnos = if (header.endsWith(\"%[[\")) lines.tail.dropWhile(_.trim != \"]]\").tail else lines.tail\n", + " val main = header.stripPrefix(\"circuit \").takeWhile(c => c != ' ' && c != ':')\n", " val (children, _) = toTree(toLines(afterAnnos.mkString(\"\\n\")), 2)\n", " // `layer` and `extmodule` declarations are not analyzed: we keep their text to serialize it back.\n", " def rawLines(n: Node, depth: Int): Seq[String] =\n", - " ((\" \" * depth) + n.line.text + (if (n.line.info.isEmpty) \"\" else s\" @[${n.line.info}]\")) +: n.kids.flatMap(rawLines(_, depth + 1))\n", + " ((\" \" * depth) + n.line.text + (if (n.line.info.isEmpty) \"\" else s\" @[${n.line.info}]\")) +: n.kids.flatMap(\n", + " rawLines(_, depth + 1)\n", + " )\n", " val (modules, others) = children.partition(n => moduleRegex.matches(n.line.text))\n", " Circuit(main, modules.map(toModule), others.flatMap(rawLines(_, 1)))\n", "}" @@ -421,8 +438,8 @@ "outputs": [], "source": [ "def serialize(e: Expression): String = e match {\n", - " case Reference(name) => name\n", - " case Literal(tpe, value) => s\"$tpe($value)\"\n", + " case Reference(name) => name\n", + " case Literal(tpe, value) => s\"$tpe($value)\"\n", " case DoPrim(op, args, consts) => (args.map(serialize) ++ consts).mkString(s\"$op(\", \", \", \")\")\n", "}\n", "\n", @@ -430,16 +447,17 @@ " val pad = \" \" * indent\n", " val loc = (i: String) => if (i.isEmpty) \"\" else s\" @[$i]\"\n", " s match {\n", - " case DefRegister(i, n, t, c) => Seq(s\"${pad}reg $n : $t, ${serialize(c)}${loc(i)}\")\n", - " case DefRegisterReset(i, n, t, c, r, v) => Seq(s\"${pad}regreset $n : $t, ${serialize(c)}, ${serialize(r)}, ${serialize(v)}${loc(i)}\")\n", - " case DefWire(i, n, t) => Seq(s\"${pad}wire $n : $t${loc(i)}\")\n", - " case DefNode(i, n, v) => Seq(s\"${pad}node $n = ${serialize(v)}${loc(i)}\")\n", - " case DefInstance(i, n, m) => Seq(s\"${pad}inst $n of $m${loc(i)}\")\n", - " case Connect(i, l, r) => Seq(s\"${pad}connect ${serialize(l)}, ${serialize(r)}${loc(i)}\")\n", - " case Conditionally(i, p, c, a) =>\n", + " case DefRegister(i, n, t, c) => Seq(s\"${pad}reg $n : $t, ${serialize(c)}${loc(i)}\")\n", + " case DefRegisterReset(i, n, t, c, r, v) =>\n", + " Seq(s\"${pad}regreset $n : $t, ${serialize(c)}, ${serialize(r)}, ${serialize(v)}${loc(i)}\")\n", + " case DefWire(i, n, t) => Seq(s\"${pad}wire $n : $t${loc(i)}\")\n", + " case DefNode(i, n, v) => Seq(s\"${pad}node $n = ${serialize(v)}${loc(i)}\")\n", + " case DefInstance(i, n, m) => Seq(s\"${pad}inst $n of $m${loc(i)}\")\n", + " case Connect(i, l, r) => Seq(s\"${pad}connect ${serialize(l)}, ${serialize(r)}${loc(i)}\")\n", + " case Conditionally(i, p, c, a) =>\n", " Seq(s\"${pad}when ${serialize(p)} :${loc(i)}\") ++ c.flatMap(serialize(_, indent + 1)) ++\n", " (if (a.isEmpty) Nil else Seq(s\"${pad}else :\") ++ a.flatMap(serialize(_, indent + 1)))\n", - " case OtherStmt(i, t, kids) => Seq(s\"$pad$t${loc(i)}\") ++ kids.flatMap(serialize(_, indent + 1))\n", + " case OtherStmt(i, t, kids) => Seq(s\"$pad$t${loc(i)}\") ++ kids.flatMap(serialize(_, indent + 1))\n", " }\n", "}\n", "\n", @@ -564,16 +582,16 @@ "// A module with a register inside a `when`, to make it interesting\n", "class WhenReg extends Module {\n", " val io = IO(new Bundle { val en = Input(Bool()); val d = Input(UInt(4.W)); val q = Output(UInt(4.W)) })\n", - " val a = Reg(UInt(4.W))\n", + " val a = Reg(UInt(4.W))\n", " io.q := a\n", - " when (io.en) {\n", + " when(io.en) {\n", " val b = RegNext(io.d)\n", " a := b + 1.U\n", " }\n", "}\n", "\n", "lazy val whenRegAST = parseCircuit(getFirrtl(new WhenReg))\n", - "val regNames = mutable.LinkedHashSet[String]()\n", + "val regNames = mutable.LinkedHashSet[String]()\n", "whenRegAST.modules.foreach(m => m.mapStmt(collectRegs(regNames)))\n", "println(regNames)" ] diff --git a/4.3_firrtl_common_idioms.ipynb b/4.3_firrtl_common_idioms.ipynb index d7c0cdd..807f5b0 100644 --- a/4.3_firrtl_common_idioms.ipynb +++ b/4.3_firrtl_common_idioms.ipynb @@ -19,7 +19,8 @@ "\n", "In this section we look at the typical tasks that programs working on a FIRRTL AST perform: *collecting* information, *adding* statements and *deleting* statements. We will use the AST from the previous section.\n", "\n", - "## Setup" + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -67,9 +68,10 @@ " case leaf => leaf\n", " }\n", "}\n", - "case class Reference(name: String) extends Expression // x, io.in[0], m0.io.out\n", - "case class Literal(tpe: String, value: String) extends Expression // UInt<3>(0h5)\n", - "case class DoPrim(op: String, args: Seq[Expression], consts: Seq[Int]) extends Expression // add(a, b), bits(a, 3, 0), mux(c, a, b)\n", + "case class Reference(name: String) extends Expression // x, io.in[0], m0.io.out\n", + "case class Literal(tpe: String, value: String) extends Expression // UInt<3>(0h5)\n", + "case class DoPrim(op: String, args: Seq[Expression], consts: Seq[Int])\n", + " extends Expression // add(a, b), bits(a, 3, 0), mux(c, a, b)\n", "\n", "// ---- Statements ----\n", "sealed trait Statement {\n", @@ -93,12 +95,18 @@ "}\n", "sealed trait IsRegister extends Statement { def name: String; def tpe: String }\n", "case class DefRegister(info: String, name: String, tpe: String, clock: Expression) extends IsRegister\n", - "case class DefRegisterReset(info: String, name: String, tpe: String, clock: Expression,\n", - " reset: Expression, init: Expression) extends IsRegister\n", - "case class DefWire(info: String, name: String, tpe: String) extends Statement\n", - "case class DefNode(info: String, name: String, value: Expression) extends Statement\n", - "case class DefInstance(info: String, name: String, module: String) extends Statement\n", - "case class Connect(info: String, loc: Expression, expr: Expression) extends Statement\n", + "case class DefRegisterReset(\n", + " info: String,\n", + " name: String,\n", + " tpe: String,\n", + " clock: Expression,\n", + " reset: Expression,\n", + " init: Expression\n", + ") extends IsRegister\n", + "case class DefWire(info: String, name: String, tpe: String) extends Statement\n", + "case class DefNode(info: String, name: String, value: Expression) extends Statement\n", + "case class DefInstance(info: String, name: String, module: String) extends Statement\n", + "case class Connect(info: String, loc: Expression, expr: Expression) extends Statement\n", "case class Conditionally(info: String, pred: Expression, conseq: Seq[Statement], alt: Seq[Statement]) extends Statement\n", "// Everything we do not model in detail (printf, assert, mem, ...). Keeps the raw text.\n", "case class OtherStmt(info: String, text: String, children: Seq[Statement]) extends Statement\n", @@ -119,20 +127,23 @@ "val infoRegex = \"\"\"^(.*?)\\s*@\\[(.*)\\]\\s*$\"\"\".r\n", "\n", "def toLines(text: String): List[Line] =\n", - " text.linesIterator.filter(_.trim.nonEmpty).map { raw =>\n", - " val indent = raw.length - raw.dropWhile(_ == ' ').length\n", - " raw.trim match {\n", - " case infoRegex(code, info) => Line(indent, code, info)\n", - " case code => Line(indent, code, \"\")\n", + " text.linesIterator\n", + " .filter(_.trim.nonEmpty)\n", + " .map { raw =>\n", + " val indent = raw.length - raw.dropWhile(_ == ' ').length\n", + " raw.trim match {\n", + " case infoRegex(code, info) => Line(indent, code, info)\n", + " case code => Line(indent, code, \"\")\n", + " }\n", " }\n", - " }.toList\n", + " .toList\n", "\n", "// Parses the sibling lines at `indent`; a more indented line starts the children of the line before it.\n", "def toTree(lines: List[Line], indent: Int): (Vector[Node], List[Line]) = {\n", - " var rest = lines\n", + " var rest = lines\n", " val siblings = Vector.newBuilder[Node]\n", " while (rest.nonEmpty && rest.head.indent == indent) {\n", - " val line = rest.head\n", + " val line = rest.head\n", " val (kids, remaining) =\n", " if (rest.tail.nonEmpty && rest.tail.head.indent > indent) toTree(rest.tail, rest.tail.head.indent)\n", " else (Vector.empty[Node], rest.tail)\n", @@ -147,7 +158,7 @@ "def splitTop(s: String): List[String] = {\n", " var depth = 0\n", " val parts = scala.collection.mutable.ListBuffer[String]()\n", - " val cur = new StringBuilder\n", + " val cur = new StringBuilder\n", " for (c <- s) c match {\n", " case '(' | '[' | '{' | '<' => depth += 1; cur += c\n", " case ')' | ']' | '}' | '>' => depth -= 1; cur += c\n", @@ -164,22 +175,22 @@ "\n", "def parseExpr(text: String): Expression = text.trim match {\n", " case literalRegex(tpe, value) => Literal(tpe, value)\n", - " case primRegex(op, args) =>\n", + " case primRegex(op, args) =>\n", " val (consts, exprs) = splitTop(args).partition(a => intRegex.matches(a))\n", " DoPrim(op, exprs.map(parseExpr), consts.map(_.toInt))\n", " case ref => Reference(ref)\n", "}\n", "\n", "// ---- Step 3: statements, ports, modules ----\n", - "val portRegex = \"\"\"^(input|output) (\\S+) : (.*)$\"\"\".r\n", - "val regRegex = \"\"\"^reg (\\S+) : (.*)$\"\"\".r\n", + "val portRegex = \"\"\"^(input|output) (\\S+) : (.*)$\"\"\".r\n", + "val regRegex = \"\"\"^reg (\\S+) : (.*)$\"\"\".r\n", "val regResetRegex = \"\"\"^regreset (\\S+) : (.*)$\"\"\".r\n", - "val wireRegex = \"\"\"^wire (\\S+) : (.*)$\"\"\".r\n", - "val nodeRegex = \"\"\"^node (\\S+) = (.*)$\"\"\".r\n", - "val instRegex = \"\"\"^inst (\\S+) of (\\S+)$\"\"\".r\n", - "val connectRegex = \"\"\"^connect (.*)$\"\"\".r\n", - "val whenRegex = \"\"\"^when (.*) :$\"\"\".r\n", - "val moduleRegex = \"\"\"^(public )?module (\\S+) :$\"\"\".r\n", + "val wireRegex = \"\"\"^wire (\\S+) : (.*)$\"\"\".r\n", + "val nodeRegex = \"\"\"^node (\\S+) = (.*)$\"\"\".r\n", + "val instRegex = \"\"\"^inst (\\S+) of (\\S+)$\"\"\".r\n", + "val connectRegex = \"\"\"^connect (.*)$\"\"\".r\n", + "val whenRegex = \"\"\"^when (.*) :$\"\"\".r\n", + "val moduleRegex = \"\"\"^(public )?module (\\S+) :$\"\"\".r\n", "\n", "// An `else :` node belongs to the `when` right before it, so we convert siblings together.\n", "def toStatements(nodes: Seq[Node]): Seq[Statement] =\n", @@ -201,22 +212,22 @@ " case regRegex(name, rest) =>\n", " val Seq(tpe, clock) = splitTop(rest)\n", " DefRegister(info, name, tpe, parseExpr(clock))\n", - " case wireRegex(name, tpe) => DefWire(info, name, tpe)\n", - " case nodeRegex(name, value) => DefNode(info, name, parseExpr(value))\n", - " case instRegex(name, module) => DefInstance(info, name, module)\n", - " case connectRegex(args) =>\n", + " case wireRegex(name, tpe) => DefWire(info, name, tpe)\n", + " case nodeRegex(name, value) => DefNode(info, name, parseExpr(value))\n", + " case instRegex(name, module) => DefInstance(info, name, module)\n", + " case connectRegex(args) =>\n", " val Seq(loc, expr) = splitTop(args)\n", " Connect(info, parseExpr(loc), parseExpr(expr))\n", - " case whenRegex(pred) => Conditionally(info, parseExpr(pred), toStatements(kids), Nil)\n", - " case other => OtherStmt(info, other, toStatements(kids))\n", + " case whenRegex(pred) => Conditionally(info, parseExpr(pred), toStatements(kids), Nil)\n", + " case other => OtherStmt(info, other, toStatements(kids))\n", " }\n", "}\n", "\n", "def toModule(node: Node): DefModule = {\n", " val Node(Line(_, text, info), kids) = node\n", - " val moduleRegex(pub, name) = text\n", - " val (portNodes, bodyNodes) = kids.partition(k => portRegex.matches(k.line.text))\n", - " val ports = portNodes.map { k =>\n", + " val moduleRegex(pub, name) = text\n", + " val (portNodes, bodyNodes) = kids.partition(k => portRegex.matches(k.line.text))\n", + " val ports = portNodes.map { k =>\n", " val portRegex(dir, pname, tpe) = k.line.text\n", " Port(k.line.info, dir, pname, tpe)\n", " }\n", @@ -226,21 +237,23 @@ "// ---- Step 4: the whole file ----\n", "def parseCircuit(firrtl: String): Circuit = {\n", " // Skip the \"FIRRTL version\" line and the multi-line annotation block `circuit Top :%[[ ... ]]`.\n", - " val lines = firrtl.linesIterator.dropWhile(!_.startsWith(\"circuit \")).toList\n", - " val header = lines.head\n", - " val afterAnnos = if (header.endsWith(\"%[[\")) lines.tail.dropWhile(_.trim != \"]]\").tail else lines.tail\n", - " val main = header.stripPrefix(\"circuit \").takeWhile(c => c != ' ' && c != ':')\n", + " val lines = firrtl.linesIterator.dropWhile(!_.startsWith(\"circuit \")).toList\n", + " val header = lines.head\n", + " val afterAnnos = if (header.endsWith(\"%[[\")) lines.tail.dropWhile(_.trim != \"]]\").tail else lines.tail\n", + " val main = header.stripPrefix(\"circuit \").takeWhile(c => c != ' ' && c != ':')\n", " val (children, _) = toTree(toLines(afterAnnos.mkString(\"\\n\")), 2)\n", " // `layer` and `extmodule` declarations are not analyzed: we keep their text to serialize it back.\n", " def rawLines(n: Node, depth: Int): Seq[String] =\n", - " ((\" \" * depth) + n.line.text + (if (n.line.info.isEmpty) \"\" else s\" @[${n.line.info}]\")) +: n.kids.flatMap(rawLines(_, depth + 1))\n", + " ((\" \" * depth) + n.line.text + (if (n.line.info.isEmpty) \"\" else s\" @[${n.line.info}]\")) +: n.kids.flatMap(\n", + " rawLines(_, depth + 1)\n", + " )\n", " val (modules, others) = children.partition(n => moduleRegex.matches(n.line.text))\n", " Circuit(main, modules.map(toModule), others.flatMap(rawLines(_, 1)))\n", "}\n", "\n", "def serialize(e: Expression): String = e match {\n", - " case Reference(name) => name\n", - " case Literal(tpe, value) => s\"$tpe($value)\"\n", + " case Reference(name) => name\n", + " case Literal(tpe, value) => s\"$tpe($value)\"\n", " case DoPrim(op, args, consts) => (args.map(serialize) ++ consts).mkString(s\"$op(\", \", \", \")\")\n", "}\n", "\n", @@ -248,16 +261,17 @@ " val pad = \" \" * indent\n", " val loc = (i: String) => if (i.isEmpty) \"\" else s\" @[$i]\"\n", " s match {\n", - " case DefRegister(i, n, t, c) => Seq(s\"${pad}reg $n : $t, ${serialize(c)}${loc(i)}\")\n", - " case DefRegisterReset(i, n, t, c, r, v) => Seq(s\"${pad}regreset $n : $t, ${serialize(c)}, ${serialize(r)}, ${serialize(v)}${loc(i)}\")\n", - " case DefWire(i, n, t) => Seq(s\"${pad}wire $n : $t${loc(i)}\")\n", - " case DefNode(i, n, v) => Seq(s\"${pad}node $n = ${serialize(v)}${loc(i)}\")\n", - " case DefInstance(i, n, m) => Seq(s\"${pad}inst $n of $m${loc(i)}\")\n", - " case Connect(i, l, r) => Seq(s\"${pad}connect ${serialize(l)}, ${serialize(r)}${loc(i)}\")\n", - " case Conditionally(i, p, c, a) =>\n", + " case DefRegister(i, n, t, c) => Seq(s\"${pad}reg $n : $t, ${serialize(c)}${loc(i)}\")\n", + " case DefRegisterReset(i, n, t, c, r, v) =>\n", + " Seq(s\"${pad}regreset $n : $t, ${serialize(c)}, ${serialize(r)}, ${serialize(v)}${loc(i)}\")\n", + " case DefWire(i, n, t) => Seq(s\"${pad}wire $n : $t${loc(i)}\")\n", + " case DefNode(i, n, v) => Seq(s\"${pad}node $n = ${serialize(v)}${loc(i)}\")\n", + " case DefInstance(i, n, m) => Seq(s\"${pad}inst $n of $m${loc(i)}\")\n", + " case Connect(i, l, r) => Seq(s\"${pad}connect ${serialize(l)}, ${serialize(r)}${loc(i)}\")\n", + " case Conditionally(i, p, c, a) =>\n", " Seq(s\"${pad}when ${serialize(p)} :${loc(i)}\") ++ c.flatMap(serialize(_, indent + 1)) ++\n", " (if (a.isEmpty) Nil else Seq(s\"${pad}else :\") ++ a.flatMap(serialize(_, indent + 1)))\n", - " case OtherStmt(i, t, kids) => Seq(s\"$pad$t${loc(i)}\") ++ kids.flatMap(serialize(_, indent + 1))\n", + " case OtherStmt(i, t, kids) => Seq(s\"$pad$t${loc(i)}\") ++ kids.flatMap(serialize(_, indent + 1))\n", " }\n", "}\n", "\n", @@ -273,14 +287,14 @@ "\n", "// Pretty-prints any of our case classes as an indented tree: one node per line.\n", "def showTree(x: Any, depth: Int = 0, label: String = \"\"): String = {\n", - " val pad = \" \" * depth + (if (label.isEmpty) \"\" else label + \": \")\n", + " val pad = \" \" * depth + (if (label.isEmpty) \"\" else label + \": \")\n", " def isNode(v: Any): Boolean = v match {\n", " case _: Expression | _: Statement | _: Port | _: DefModule | _: Circuit => true\n", - " case _ => false\n", + " case _ => false\n", " }\n", " x match {\n", " case p: Product if isNode(p) =>\n", - " val fields = p.productElementNames.toList.zip(p.productIterator.toList)\n", + " val fields = p.productElementNames.toList.zip(p.productIterator.toList)\n", " val (kids, atoms) = fields.partition {\n", " case (_, v: Seq[_]) => v.nonEmpty && v.forall(isNode)\n", " case (_, v) => isNode(v)\n", @@ -338,7 +352,7 @@ " val count = Output(UInt(width.W))\n", " })\n", " val c = RegInit(0.U(width.W))\n", - " when (io.en) { c := c + 1.U }\n", + " when(io.en) { c := c + 1.U }\n", " io.count := c\n", "}\n", "\n", @@ -351,9 +365,9 @@ " val slow = Module(new Counter(4))\n", " val last = Reg(Bool())\n", " fast.io.en := io.en\n", - " last := fast.io.count(7)\n", + " last := fast.io.count(7)\n", " slow.io.en := last\n", - " io.out := fast.io.count + slow.io.count\n", + " io.out := fast.io.count + slow.io.count\n", "}\n", "\n", "lazy val topAST = parseCircuit(getFirrtl(new Top))\n", @@ -403,8 +417,9 @@ "source": [ "def readsOf(m: DefModule, signal: String): Seq[String] =\n", " allStatements(m.body).flatMap {\n", - " case Connect(_, _, rhs) => allExprs(rhs).collect { case Reference(`signal`) => serialize(rhs) }\n", - " case DefNode(_, name, value) => allExprs(value).collect { case Reference(`signal`) => s\"node $name = ${serialize(value)}\" }\n", + " case Connect(_, _, rhs) => allExprs(rhs).collect { case Reference(`signal`) => serialize(rhs) }\n", + " case DefNode(_, name, value) =>\n", + " allExprs(value).collect { case Reference(`signal`) => s\"node $name = ${serialize(value)}\" }\n", " // clocks, resets, `when` predicates...\n", " case s => directExprs(s).flatMap(e => allExprs(e).collect { case Reference(`signal`) => serialize(e) })\n", " }\n", @@ -498,10 +513,10 @@ "outputs": [], "source": [ "class CheckedTop extends Module {\n", - " val io = IO(new Bundle { val out = Output(UInt(8.W)) })\n", + " val io = IO(new Bundle { val out = Output(UInt(8.W)) })\n", " val child = Module(new Counter(8))\n", " child.io.en := true.B\n", - " io.out := child.io.count\n", + " io.out := child.io.count\n", " // Which ports of `child` have a width of exactly 8 bits?\n", " val wide = DataMirror.fullModulePorts(child).filter { case (_, d) => d.widthOption.contains(8) }\n", " println(\"8-bit ports of child: \" + wide.map(_._1))\n", @@ -574,6 +589,7 @@ "outputs": [], "source": [ "object Splitter {\n", + "\n", " /** Run splitM on every module */\n", " def run(c: Circuit): Circuit = c.mapModule(splitM)\n", "\n", @@ -581,7 +597,7 @@ " def splitM(m: DefModule): DefModule = {\n", " var counter = 0\n", " // Skip the names that the module already uses\n", - " val used = serialize(m).flatMap(\"[A-Za-z_][A-Za-z0-9_]*\".r.findAllIn(_)).toSet\n", + " val used = serialize(m).flatMap(\"[A-Za-z_][A-Za-z0-9_]*\".r.findAllIn(_)).toSet\n", " def newName(): String = {\n", " while (used.contains(s\"_GEN_$counter\")) counter += 1\n", " val n = s\"_GEN_$counter\"; counter += 1; n\n", @@ -602,7 +618,9 @@ " }\n", "\n", " /** Post-order: split the children first. If e is a DoPrim, add a new DefNode and return a reference to it. */\n", - " def splitE(nodes: scala.collection.mutable.ArrayBuffer[Statement], newName: () => String, info: String)(e: Expression): Expression =\n", + " def splitE(nodes: scala.collection.mutable.ArrayBuffer[Statement], newName: () => String, info: String)(\n", + " e: Expression\n", + " ): Expression =\n", " e.mapExpr(splitE(nodes, newName, info)) match {\n", " case p: DoPrim =>\n", " val name = newName()\n", @@ -640,6 +658,7 @@ "outputs": [], "source": [ "object Inliner {\n", + "\n", " /** Run inlineM on every module */\n", " def run(c: Circuit): Circuit = c.mapModule(inlineM)\n", "\n", @@ -647,15 +666,20 @@ " val values = scala.collection.mutable.HashMap[String, Expression]()\n", " // We do not rewrite the text of the statements we did not parse (printf, assert...), so a node\n", " // that they mention must stay\n", - " val mentioned = allStatements(m.body).collect { case o: OtherStmt => o.text }\n", - " .flatMap(\"[A-Za-z_][A-Za-z0-9_]*\".r.findAllIn(_)).toSet\n", + " val mentioned = allStatements(m.body)\n", + " .collect { case o: OtherStmt => o.text }\n", + " .flatMap(\"[A-Za-z_][A-Za-z0-9_]*\".r.findAllIn(_))\n", + " .toSet\n", " m.copy(body = inlineBody(m.body, values, mentioned))\n", " }\n", "\n", " /** Statements are processed in order, so a node is known before the statements that use it. A DefNode\n", " * containing a literal is recorded and dropped (returned as an empty Seq), the others are kept. */\n", - " def inlineBody(body: Seq[Statement], values: scala.collection.mutable.HashMap[String, Expression],\n", - " mentioned: Set[String]): Seq[Statement] =\n", + " def inlineBody(\n", + " body: Seq[Statement],\n", + " values: scala.collection.mutable.HashMap[String, Expression],\n", + " mentioned: Set[String]\n", + " ): Seq[Statement] =\n", " body.flatMap { s =>\n", " s.mapExpr(inlineE(values)) match {\n", " case DefNode(_, name, l: Literal) if !mentioned(name) =>\n", diff --git a/4.4_firrtl_add_ops_per_module.ipynb b/4.4_firrtl_add_ops_per_module.ipynb index 956311b..f5350a5 100644 --- a/4.4_firrtl_add_ops_per_module.ipynb +++ b/4.4_firrtl_add_ops_per_module.ipynb @@ -15,12 +15,14 @@ "source": [ "# Module 4.4: A FIRRTL Transform Example\n", "**Prev: [Common Pass Idioms](4.3_firrtl_common_idioms.ipynb)**
\n", + "**Next: [The RV32I Instruction Set](5.1_riscv_isa.ipynb)**
\n", "\n", "This AnalyzeCircuit transform walks a `Circuit` (our AST from Modules 4.2 and 4.3), and records the number of add ops it finds, per module. Then we extend it to count the adders of a whole hierarchy.\n", "\n", "## Setup\n", + "Please run the following. The second cell contains the IR, the parser, `serialize` and the traversal helpers that we wrote in Modules 4.2 and 4.3, once more, since notebooks do not share definitions. Nothing is new there.\n", "\n", - "Please run the following. The second cell contains the IR, the parser, `serialize` and the traversal helpers that we wrote in Modules 4.2 and 4.3, once more, since notebooks do not share definitions. Nothing is new there." + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." ] }, { @@ -48,9 +50,10 @@ " case leaf => leaf\n", " }\n", "}\n", - "case class Reference(name: String) extends Expression // x, io.in[0], m0.io.out\n", - "case class Literal(tpe: String, value: String) extends Expression // UInt<3>(0h5)\n", - "case class DoPrim(op: String, args: Seq[Expression], consts: Seq[Int]) extends Expression // add(a, b), bits(a, 3, 0), mux(c, a, b)\n", + "case class Reference(name: String) extends Expression // x, io.in[0], m0.io.out\n", + "case class Literal(tpe: String, value: String) extends Expression // UInt<3>(0h5)\n", + "case class DoPrim(op: String, args: Seq[Expression], consts: Seq[Int])\n", + " extends Expression // add(a, b), bits(a, 3, 0), mux(c, a, b)\n", "\n", "// ---- Statements ----\n", "sealed trait Statement {\n", @@ -74,12 +77,18 @@ "}\n", "sealed trait IsRegister extends Statement { def name: String; def tpe: String }\n", "case class DefRegister(info: String, name: String, tpe: String, clock: Expression) extends IsRegister\n", - "case class DefRegisterReset(info: String, name: String, tpe: String, clock: Expression,\n", - " reset: Expression, init: Expression) extends IsRegister\n", - "case class DefWire(info: String, name: String, tpe: String) extends Statement\n", - "case class DefNode(info: String, name: String, value: Expression) extends Statement\n", - "case class DefInstance(info: String, name: String, module: String) extends Statement\n", - "case class Connect(info: String, loc: Expression, expr: Expression) extends Statement\n", + "case class DefRegisterReset(\n", + " info: String,\n", + " name: String,\n", + " tpe: String,\n", + " clock: Expression,\n", + " reset: Expression,\n", + " init: Expression\n", + ") extends IsRegister\n", + "case class DefWire(info: String, name: String, tpe: String) extends Statement\n", + "case class DefNode(info: String, name: String, value: Expression) extends Statement\n", + "case class DefInstance(info: String, name: String, module: String) extends Statement\n", + "case class Connect(info: String, loc: Expression, expr: Expression) extends Statement\n", "case class Conditionally(info: String, pred: Expression, conseq: Seq[Statement], alt: Seq[Statement]) extends Statement\n", "// Everything we do not model in detail (printf, assert, mem, ...). Keeps the raw text.\n", "case class OtherStmt(info: String, text: String, children: Seq[Statement]) extends Statement\n", @@ -100,20 +109,23 @@ "val infoRegex = \"\"\"^(.*?)\\s*@\\[(.*)\\]\\s*$\"\"\".r\n", "\n", "def toLines(text: String): List[Line] =\n", - " text.linesIterator.filter(_.trim.nonEmpty).map { raw =>\n", - " val indent = raw.length - raw.dropWhile(_ == ' ').length\n", - " raw.trim match {\n", - " case infoRegex(code, info) => Line(indent, code, info)\n", - " case code => Line(indent, code, \"\")\n", + " text.linesIterator\n", + " .filter(_.trim.nonEmpty)\n", + " .map { raw =>\n", + " val indent = raw.length - raw.dropWhile(_ == ' ').length\n", + " raw.trim match {\n", + " case infoRegex(code, info) => Line(indent, code, info)\n", + " case code => Line(indent, code, \"\")\n", + " }\n", " }\n", - " }.toList\n", + " .toList\n", "\n", "// Parses the sibling lines at `indent`; a more indented line starts the children of the line before it.\n", "def toTree(lines: List[Line], indent: Int): (Vector[Node], List[Line]) = {\n", - " var rest = lines\n", + " var rest = lines\n", " val siblings = Vector.newBuilder[Node]\n", " while (rest.nonEmpty && rest.head.indent == indent) {\n", - " val line = rest.head\n", + " val line = rest.head\n", " val (kids, remaining) =\n", " if (rest.tail.nonEmpty && rest.tail.head.indent > indent) toTree(rest.tail, rest.tail.head.indent)\n", " else (Vector.empty[Node], rest.tail)\n", @@ -128,7 +140,7 @@ "def splitTop(s: String): List[String] = {\n", " var depth = 0\n", " val parts = scala.collection.mutable.ListBuffer[String]()\n", - " val cur = new StringBuilder\n", + " val cur = new StringBuilder\n", " for (c <- s) c match {\n", " case '(' | '[' | '{' | '<' => depth += 1; cur += c\n", " case ')' | ']' | '}' | '>' => depth -= 1; cur += c\n", @@ -145,22 +157,22 @@ "\n", "def parseExpr(text: String): Expression = text.trim match {\n", " case literalRegex(tpe, value) => Literal(tpe, value)\n", - " case primRegex(op, args) =>\n", + " case primRegex(op, args) =>\n", " val (consts, exprs) = splitTop(args).partition(a => intRegex.matches(a))\n", " DoPrim(op, exprs.map(parseExpr), consts.map(_.toInt))\n", " case ref => Reference(ref)\n", "}\n", "\n", "// ---- Step 3: statements, ports, modules ----\n", - "val portRegex = \"\"\"^(input|output) (\\S+) : (.*)$\"\"\".r\n", - "val regRegex = \"\"\"^reg (\\S+) : (.*)$\"\"\".r\n", + "val portRegex = \"\"\"^(input|output) (\\S+) : (.*)$\"\"\".r\n", + "val regRegex = \"\"\"^reg (\\S+) : (.*)$\"\"\".r\n", "val regResetRegex = \"\"\"^regreset (\\S+) : (.*)$\"\"\".r\n", - "val wireRegex = \"\"\"^wire (\\S+) : (.*)$\"\"\".r\n", - "val nodeRegex = \"\"\"^node (\\S+) = (.*)$\"\"\".r\n", - "val instRegex = \"\"\"^inst (\\S+) of (\\S+)$\"\"\".r\n", - "val connectRegex = \"\"\"^connect (.*)$\"\"\".r\n", - "val whenRegex = \"\"\"^when (.*) :$\"\"\".r\n", - "val moduleRegex = \"\"\"^(public )?module (\\S+) :$\"\"\".r\n", + "val wireRegex = \"\"\"^wire (\\S+) : (.*)$\"\"\".r\n", + "val nodeRegex = \"\"\"^node (\\S+) = (.*)$\"\"\".r\n", + "val instRegex = \"\"\"^inst (\\S+) of (\\S+)$\"\"\".r\n", + "val connectRegex = \"\"\"^connect (.*)$\"\"\".r\n", + "val whenRegex = \"\"\"^when (.*) :$\"\"\".r\n", + "val moduleRegex = \"\"\"^(public )?module (\\S+) :$\"\"\".r\n", "\n", "// An `else :` node belongs to the `when` right before it, so we convert siblings together.\n", "def toStatements(nodes: Seq[Node]): Seq[Statement] =\n", @@ -182,22 +194,22 @@ " case regRegex(name, rest) =>\n", " val Seq(tpe, clock) = splitTop(rest)\n", " DefRegister(info, name, tpe, parseExpr(clock))\n", - " case wireRegex(name, tpe) => DefWire(info, name, tpe)\n", - " case nodeRegex(name, value) => DefNode(info, name, parseExpr(value))\n", - " case instRegex(name, module) => DefInstance(info, name, module)\n", - " case connectRegex(args) =>\n", + " case wireRegex(name, tpe) => DefWire(info, name, tpe)\n", + " case nodeRegex(name, value) => DefNode(info, name, parseExpr(value))\n", + " case instRegex(name, module) => DefInstance(info, name, module)\n", + " case connectRegex(args) =>\n", " val Seq(loc, expr) = splitTop(args)\n", " Connect(info, parseExpr(loc), parseExpr(expr))\n", - " case whenRegex(pred) => Conditionally(info, parseExpr(pred), toStatements(kids), Nil)\n", - " case other => OtherStmt(info, other, toStatements(kids))\n", + " case whenRegex(pred) => Conditionally(info, parseExpr(pred), toStatements(kids), Nil)\n", + " case other => OtherStmt(info, other, toStatements(kids))\n", " }\n", "}\n", "\n", "def toModule(node: Node): DefModule = {\n", " val Node(Line(_, text, info), kids) = node\n", - " val moduleRegex(pub, name) = text\n", - " val (portNodes, bodyNodes) = kids.partition(k => portRegex.matches(k.line.text))\n", - " val ports = portNodes.map { k =>\n", + " val moduleRegex(pub, name) = text\n", + " val (portNodes, bodyNodes) = kids.partition(k => portRegex.matches(k.line.text))\n", + " val ports = portNodes.map { k =>\n", " val portRegex(dir, pname, tpe) = k.line.text\n", " Port(k.line.info, dir, pname, tpe)\n", " }\n", @@ -207,21 +219,23 @@ "// ---- Step 4: the whole file ----\n", "def parseCircuit(firrtl: String): Circuit = {\n", " // Skip the \"FIRRTL version\" line and the multi-line annotation block `circuit Top :%[[ ... ]]`.\n", - " val lines = firrtl.linesIterator.dropWhile(!_.startsWith(\"circuit \")).toList\n", - " val header = lines.head\n", - " val afterAnnos = if (header.endsWith(\"%[[\")) lines.tail.dropWhile(_.trim != \"]]\").tail else lines.tail\n", - " val main = header.stripPrefix(\"circuit \").takeWhile(c => c != ' ' && c != ':')\n", + " val lines = firrtl.linesIterator.dropWhile(!_.startsWith(\"circuit \")).toList\n", + " val header = lines.head\n", + " val afterAnnos = if (header.endsWith(\"%[[\")) lines.tail.dropWhile(_.trim != \"]]\").tail else lines.tail\n", + " val main = header.stripPrefix(\"circuit \").takeWhile(c => c != ' ' && c != ':')\n", " val (children, _) = toTree(toLines(afterAnnos.mkString(\"\\n\")), 2)\n", " // `layer` and `extmodule` declarations are not analyzed: we keep their text to serialize it back.\n", " def rawLines(n: Node, depth: Int): Seq[String] =\n", - " ((\" \" * depth) + n.line.text + (if (n.line.info.isEmpty) \"\" else s\" @[${n.line.info}]\")) +: n.kids.flatMap(rawLines(_, depth + 1))\n", + " ((\" \" * depth) + n.line.text + (if (n.line.info.isEmpty) \"\" else s\" @[${n.line.info}]\")) +: n.kids.flatMap(\n", + " rawLines(_, depth + 1)\n", + " )\n", " val (modules, others) = children.partition(n => moduleRegex.matches(n.line.text))\n", " Circuit(main, modules.map(toModule), others.flatMap(rawLines(_, 1)))\n", "}\n", "\n", "def serialize(e: Expression): String = e match {\n", - " case Reference(name) => name\n", - " case Literal(tpe, value) => s\"$tpe($value)\"\n", + " case Reference(name) => name\n", + " case Literal(tpe, value) => s\"$tpe($value)\"\n", " case DoPrim(op, args, consts) => (args.map(serialize) ++ consts).mkString(s\"$op(\", \", \", \")\")\n", "}\n", "\n", @@ -229,16 +243,17 @@ " val pad = \" \" * indent\n", " val loc = (i: String) => if (i.isEmpty) \"\" else s\" @[$i]\"\n", " s match {\n", - " case DefRegister(i, n, t, c) => Seq(s\"${pad}reg $n : $t, ${serialize(c)}${loc(i)}\")\n", - " case DefRegisterReset(i, n, t, c, r, v) => Seq(s\"${pad}regreset $n : $t, ${serialize(c)}, ${serialize(r)}, ${serialize(v)}${loc(i)}\")\n", - " case DefWire(i, n, t) => Seq(s\"${pad}wire $n : $t${loc(i)}\")\n", - " case DefNode(i, n, v) => Seq(s\"${pad}node $n = ${serialize(v)}${loc(i)}\")\n", - " case DefInstance(i, n, m) => Seq(s\"${pad}inst $n of $m${loc(i)}\")\n", - " case Connect(i, l, r) => Seq(s\"${pad}connect ${serialize(l)}, ${serialize(r)}${loc(i)}\")\n", - " case Conditionally(i, p, c, a) =>\n", + " case DefRegister(i, n, t, c) => Seq(s\"${pad}reg $n : $t, ${serialize(c)}${loc(i)}\")\n", + " case DefRegisterReset(i, n, t, c, r, v) =>\n", + " Seq(s\"${pad}regreset $n : $t, ${serialize(c)}, ${serialize(r)}, ${serialize(v)}${loc(i)}\")\n", + " case DefWire(i, n, t) => Seq(s\"${pad}wire $n : $t${loc(i)}\")\n", + " case DefNode(i, n, v) => Seq(s\"${pad}node $n = ${serialize(v)}${loc(i)}\")\n", + " case DefInstance(i, n, m) => Seq(s\"${pad}inst $n of $m${loc(i)}\")\n", + " case Connect(i, l, r) => Seq(s\"${pad}connect ${serialize(l)}, ${serialize(r)}${loc(i)}\")\n", + " case Conditionally(i, p, c, a) =>\n", " Seq(s\"${pad}when ${serialize(p)} :${loc(i)}\") ++ c.flatMap(serialize(_, indent + 1)) ++\n", " (if (a.isEmpty) Nil else Seq(s\"${pad}else :\") ++ a.flatMap(serialize(_, indent + 1)))\n", - " case OtherStmt(i, t, kids) => Seq(s\"$pad$t${loc(i)}\") ++ kids.flatMap(serialize(_, indent + 1))\n", + " case OtherStmt(i, t, kids) => Seq(s\"$pad$t${loc(i)}\") ++ kids.flatMap(serialize(_, indent + 1))\n", " }\n", "}\n", "\n", @@ -254,14 +269,14 @@ "\n", "// Pretty-prints any of our case classes as an indented tree: one node per line.\n", "def showTree(x: Any, depth: Int = 0, label: String = \"\"): String = {\n", - " val pad = \" \" * depth + (if (label.isEmpty) \"\" else label + \": \")\n", + " val pad = \" \" * depth + (if (label.isEmpty) \"\" else label + \": \")\n", " def isNode(v: Any): Boolean = v match {\n", " case _: Expression | _: Statement | _: Port | _: DefModule | _: Circuit => true\n", - " case _ => false\n", + " case _ => false\n", " }\n", " x match {\n", " case p: Product if isNode(p) =>\n", - " val fields = p.productElementNames.toList.zip(p.productIterator.toList)\n", + " val fields = p.productElementNames.toList.zip(p.productIterator.toList)\n", " val (kids, atoms) = fields.partition {\n", " case (_, v: Seq[_]) => v.nonEmpty && v.forall(isNode)\n", " case (_, v) => isNode(v)\n", @@ -333,14 +348,14 @@ "source": [ "class Ledger {\n", " private var moduleName: Option[String] = None\n", - " private val modules = mutable.LinkedHashSet[String]()\n", - " private val moduleAddMap = mutable.Map[String, Int]()\n", - " def foundAdd(): Unit = moduleName match {\n", - " case None => sys.error(\"Module name not defined in Ledger!\")\n", + " private val modules = mutable.LinkedHashSet[String]()\n", + " private val moduleAddMap = mutable.Map[String, Int]()\n", + " def foundAdd(): Unit = moduleName match {\n", + " case None => sys.error(\"Module name not defined in Ledger!\")\n", " case Some(name) => moduleAddMap(name) = moduleAddMap.getOrElse(name, 0) + 1\n", " }\n", " def getModuleName: String = moduleName match {\n", - " case None => sys.error(\"Module name not defined in Ledger!\")\n", + " case None => sys.error(\"Module name not defined in Ledger!\")\n", " case Some(name) => name\n", " }\n", " def setModuleName(myName: String): Unit = {\n", @@ -348,7 +363,7 @@ " moduleName = Some(myName)\n", " }\n", " def addCount(name: String): Int = moduleAddMap.getOrElse(name, 0)\n", - " def serialize: String = {\n", + " def serialize: String = {\n", " modules map { myName =>\n", " s\"$myName => ${addCount(myName)} add ops!\"\n", " } mkString \"\\n\"\n", @@ -564,8 +579,8 @@ " m1.io.in(0) := io.a\n", " m1.io.in(1) := io.b\n", " m1.io.in(2) := m0.io.out\n", - " io.y := m0.io.out\n", - " io.z := m1.io.out\n", + " io.y := m0.io.out\n", + " io.z := m1.io.out\n", "}\n", "\n", "lazy val topFirrtl = getFirrtl(new Top)\n", @@ -590,8 +605,12 @@ "outputs": [], "source": [ "def opCounts(m: DefModule): Map[String, Int] =\n", - " allStatements(m.body).flatMap(directExprs).flatMap(allExprs).collect { case DoPrim(op, _, _) => op }\n", - " .groupBy(identity).map { case (op, l) => op -> l.size }\n", + " allStatements(m.body)\n", + " .flatMap(directExprs)\n", + " .flatMap(allExprs)\n", + " .collect { case DoPrim(op, _, _) => op }\n", + " .groupBy(identity)\n", + " .map { case (op, l) => op -> l.size }\n", "\n", "lazy val topCircuit = parseCircuit(topFirrtl)\n", "for (m <- topCircuit.modules) println(s\"${m.name}: ${opCounts(m)}\")" @@ -621,11 +640,11 @@ "// Two instances of the same module count twice\n", "class Twice extends Module {\n", " val io = IO(new Bundle { val in = Input(UInt(4.W)); val out = Output(UInt(5.W)) })\n", - " val a = Module(new AddMe(2, 4))\n", - " val b = Module(new AddMe(2, 4))\n", - " a.io.in(0) := io.in; a.io.in(1) := io.in\n", + " val a = Module(new AddMe(2, 4))\n", + " val b = Module(new AddMe(2, 4))\n", + " a.io.in(0) := io.in; a.io.in(1) := io.in\n", " b.io.in(0) := a.io.out; b.io.in(1) := io.in\n", - " io.out := b.io.out\n", + " io.out := b.io.out\n", "}\n", "lazy val twiceCircuit = parseCircuit(getFirrtl(new Twice))\n", "println(twiceCircuit.modules.map(_.name))\n", diff --git a/5.10_to_silicon.ipynb b/5.10_to_silicon.ipynb new file mode 100644 index 0000000..d889283 --- /dev/null +++ b/5.10_to_silicon.ipynb @@ -0,0 +1,340 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.10: From Chisel to an FPGA\n", + "**Prev: [Debugging and Verification](5.9_debug_and_verify.ipynb)**
\n", + "\n", + "## Motivation\n", + "So far the processor has only run in simulation. To become hardware, its description goes through\n", + "a chain of tools:\n", + "\n", + "1. **SystemVerilog**: Chisel elaborates the design and `firtool` writes it as SystemVerilog, the\n", + " language every hardware tool reads.\n", + "2. **Lint**: a checker (here Verilator's) reports suspicious constructs, such as unused signals.\n", + "3. **Synthesis**: a tool (here Yosys) turns the description into the cells of a chip: for an FPGA,\n", + " look-up tables, flip-flops, carry chains and memories.\n", + "4. **Place and route**: a tool (for the FPGAs here, nextpnr) places the cells on the chip, wires\n", + " them, and computes how fast the clock can run.\n", + "5. **Bitstream**: the configuration that is loaded into the FPGA.\n", + "\n", + "The bootcamp's image has the tools for steps 1-3. This notebook runs them on the decoders and the\n", + "cores of Module 5, and prepares the system of Module 5.8 for a real board, a ULX3S; steps 4 and 5\n", + "need tools you install on your own machine (`riscv/fpga/`).\n", + "\n", + "The cells that build a design stop with a `NotImplementedError` until the exercises of 5.2-5.8 are\n", + "done; the synthesis cells also need Yosys (the image has it; `Install.md` says how to install it).\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.simulator.PeekPokeAPI._\n", + "import riscv._\n", + "\n", + "// The tools of this notebook, through load-ivy.sc's scrub: Almond cannot show an error raised while\n", + "// Chisel builds a module (such as an unfinished exercise) without it\n", + "def verilog(gen: => RawModule): String = scrub(Yosys.verilog(gen))\n", + "def lint(gen: => RawModule): Seq[String] = scrub(Synth.lint(gen))\n", + "def cells(gen: => RawModule, family: String): Cells = scrub(Synth.cells(gen, family))\n", + "def report(designs: Seq[(String, () => RawModule)]) = scrub(Synth.report(designs))\n", + "\n", + "val hello = Asm(Programs.source(\"programs/src\", \"hello\")) // for the board, below" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# SystemVerilog, for Yosys\n", + "\n", + "`riscv.Yosys.verilog` is `getVerilog` with options that Yosys's reader needs: no assertion layers,\n", + "no random initial values, no packed arrays and no variables declared inside `always` blocks (Yosys\n", + "reads most of SystemVerilog, but not those). The forwarding core, as SystemVerilog:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val sv = verilog(new ForwardingCore)\n", + "println(\n", + " s\"${sv.linesIterator.size} lines, modules: \" +\n", + " sv.linesIterator.filter(_.startsWith(\"module \")).map(_.split(\"[ (]\")(1)).mkString(\", \")\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Lint\n", + "\n", + "`verilator --lint-only -Wall` reads a design as a simulator would, and warns about what is legal\n", + "but often a mistake. On the forwarding core it only finds signals, or bits of signals, that are not\n", + "used (`UNUSEDSIGNAL`); none is a bug here, but in a design of your own an unused signal is often a\n", + "wire you forgot to connect:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "lint(new ForwardingCore).foreach(println)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Synthesis\n", + "\n", + "Yosys maps a design to the cells of an FPGA family. Two families, both supported by the open\n", + "place-and-route tool nextpnr:\n", + "\n", + "- **Lattice iCE40** (for example the UP5K of the iCEBreaker board: 5280 LUTs): 4-input look-up\n", + " tables (`SB_LUT4`), flip-flops (`SB_DFF*`), carry cells, and block RAMs that are read\n", + " *synchronously*, one cycle after the address.\n", + "- **Lattice ECP5** (the ULX3S board: 12K to 85K LUTs): the same kinds of cells, and LUTs that can\n", + " also be used as small RAMs read *combinationally* (`TRELLIS_DPR16X4`, 16 words of 4 bits).\n", + "\n", + "`riscv.Synth.cells` runs `synth_ice40` or `synth_ecp5` and counts the cells. First the two decoders\n", + "of [Module 5.3](5.3_decoder.ipynb), which compared them as lines of SystemVerilog (the\n", + "table-driven one several times longer than the `switch`). The first run of Yosys in a container\n", + "compiles it, which takes about a minute." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val table = scrub(Synth.cells(new Decoder, Synth.families)) // one Yosys run for both families\n", + "val hand = scrub(Synth.cells(new SwitchDecoder, Synth.families))\n", + "for (family <- Synth.families) {\n", + " val (t, h) = (table(family), hand(family))\n", + " println(f\"$family%-6s table-driven: ${t.luts}%4d LUTs, switch: ${h.luts}%4d LUTs (${t.luts.toDouble / h.luts}%.1fx)\")\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As gates, the table-driven decoder is under twice the size of the hand-written one: synthesis optimizes the sum of products again, and shares logic across the output bits\n", + "that the text keeps apart. Both are a few percent of a core.\n", + "\n", + "Now the three cores. `SynthReport` prints the same table for all the designs of Module 5, outside\n", + "a notebook: `cd riscv && sbt \"runMain riscv.SynthReport\"`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(report(Synth.all.filter(_._1.endsWith(\"Core\")))) // the three cores of Synth.all" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What the numbers say:\n", + "\n", + "- **The register file decides the iCE40 numbers.** It is read combinationally (in the cycle of\n", + " the address), and an iCE40's block RAMs are read a cycle later, so Yosys builds it from\n", + " flip-flops (992: x0 is constant) and the multiplexers that select a register: most of the FFs\n", + " and of the 4000 to 4500 LUTs of each core. On an ECP5 it fits in 48 LUT RAM cells (16 per read port:\n", + " two for the operands, one for the debug port), and the cores need a half to a third of the LUTs.\n", + " A core meant for an iCE40 would read its registers a cycle early, in the stage before.\n", + "- **The pipeline registers** are the 600 or so flip-flops that the pipelined cores have on top of\n", + " the single-cycle core.\n", + "- **Forwarding** adds multiplexers on the operands, and the stall logic: 400 to 750 LUTs.\n", + "- **Not every difference has a story.** On the ECP5 the pipelined core comes out smaller than the\n", + " single-cycle one, and on the iCE40 it does not: synthesis is a search, and its result moves by\n", + " hundreds of LUTs with the shape of the logic. Compare designs by large differences, and on the\n", + " same tool and version.\n", + "\n", + "Cells are area. What the pipeline buys is speed: a shorter path between registers, so a faster\n", + "clock. That number comes from place and route, which computes the delays of the cells and of the\n", + "wires between them; nextpnr does it, outside the image." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# A board: the ULX3S\n", + "\n", + "`riscv.Ulx3sTop` puts the system of Module 5.8 on a ULX3S board: a 25 MHz clock, a button, eight\n", + "LEDs, and a USB serial port the UART can send to. A program has to get into the RAM without a\n", + "debugger or a `CoSim.load`, so the top copies it from a ROM (a `VecInit` of the program's words)\n", + "through the RAM's load port, holding the system in reset meanwhile:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val board = os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"Board.scala\")\n", + "println(board.slice(board.indexOf(\"class Ulx3sTop\"), board.indexOf(\"/** Writes the SystemVerilog\")))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The names of its ports are those of the board's constraint file, which gives each one a pin of\n", + "the FPGA (and a voltage, a pull-up or -down, a drive strength):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "os.read.lines(os.pwd / \"riscv\" / \"fpga\" / \"ulx3s.lpf\").filter(_.startsWith(\"LOCATE\")).foreach(println)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Before synthesis, the top runs in simulation: with a clock of 400 Hz and a UART at 100 baud (the\n", + "same 4 cycles per bit as in 5.8), it boots `hello.S` and the UART's output says hello:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new Ulx3sTop(hello, clockHz = 400, baud = 100)) { c =>\n", + " // Soc.run's loop (5.8), on the board's serial line; LED 1 says the program has halted\n", + " val out = Soc.listen(c.clock, c.ftdi_rxd, (c.led.peek().litValue & 2) != 0, divider = 4)\n", + " print(out)\n", + " assert(out == \"Hello, world!\\n\")\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And synthesized for the ECP5, at the real clock and baud rate (25 MHz, 115200 baud). The smallest\n", + "ULX3S has an LFE5U-12F, with 12K LUTs and 32 block RAMs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val top = cells(new Ulx3sTop(hello), \"ecp5\")\n", + "println(s\"Ulx3sTop: ${top.luts} LUTs, ${top.flipFlops} FFs, ${top.lutRams} LUT RAMs, ${top.blockRams} block RAMs\")\n", + "println(top.byType.toSeq.sorted.map { case (t, n) => s\" $t: $n\" }.mkString(\"\\n\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The whole system takes fewer LUTs than the forwarding core alone did: the board does not use the\n", + "core's retire port, so synthesis removes the logic that only feeds it, and its debug port only\n", + "reads the 6 bits of a0 that the LEDs show (34 LUT RAM cells instead of 48: 16 for each operand's\n", + "read port, and 2 for those 6 bits). `PFUMX` and `L6MUX21`\n", + "are the multiplexers in each slice of the ECP5 that combine LUTs into functions of more inputs. The 4 KB RAM went into 4\n", + "block RAMs (`DP16KD`), although they are read a cycle after the address: the addresses of both of\n", + "its ports come straight from registers (the pc, and the bus's registered request), and Yosys moves\n", + "those registers into the block RAMs. The design fits the smallest ULX3S with room to spare.\n", + "\n", + "To go on to a bitstream, on a machine with the tools (`riscv/fpga/README.md` says which), from\n", + "`riscv/`:\n", + "\n", + "```\n", + "fpga/ulx3s.sh hello 12k\n", + "openFPGALoader -b ulx3s fpga/build/Ulx3sTop.bit\n", + "```\n", + "\n", + "When this was written, nextpnr-ecp5 placed and routed `Ulx3sTop` on an LFE5U-12F and reported a\n", + "maximum clock of about 48 MHz, above the board's 25 MHz.\n", + "\n", + "---\n", + "# You're done!\n", + "\n", + "This is the last notebook of the processor. From here: run your own programs on the board (they\n", + "must fit in its 4 KB RAM, stack included; LEDs 2-7 show the low bits of a0), or make the core\n", + "read its registers a cycle early so that an iCE40 fits it.\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/5.1_riscv_isa.ipynb b/5.1_riscv_isa.ipynb new file mode 100644 index 0000000..b9c545d --- /dev/null +++ b/5.1_riscv_isa.ipynb @@ -0,0 +1,464 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.1: The RV32I Instruction Set\n", + "**Prev: [A FIRRTL Transform Example](4.4_firrtl_add_ops_per_module.ipynb)**
\n", + "**Next: [The ALU, the Immediates and the Registers](5.2_alu_and_regfile.ipynb)**
\n", + "\n", + "## Motivation\n", + "Module 5 builds a RISC-V processor in Chisel, one piece per notebook, in the sbt project under\n", + "`riscv/` (its design decisions are in [riscv/DESIGN.md](https://github.com/sysprog21/chisel-bootcamp/blob/dev/riscv/DESIGN.md)). Before writing hardware, this\n", + "notebook looks at what the processor must execute: the 40 instructions of RV32I, the base integer\n", + "instruction set of 32-bit RISC-V. You will see\n", + "\n", + "- the 32 registers and their ABI names;\n", + "- the six instruction formats, and why the immediates are split up the way they are;\n", + "- a decoder that turns a 32-bit word into a Scala case class;\n", + "- a small assembler, which the next notebooks use to write test programs;\n", + "\n", + "and then write a disassembler yourself.\n", + "\n", + "Everything here is plain Scala from `riscv/src/main/scala/riscv/` (`Asm.scala` and `Isa.scala`): it\n", + "is the reference that the hardware decoder of the processor is checked against.\n", + "\n", + "## Setup\n", + "The second cell compiles the `riscv/` project with sbt the first time it runs (about half a minute)\n", + "and adds its classes to this notebook.\n", + "\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.util.BitPat\n", + "import riscv._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Registers\n", + "\n", + "RV32I has 32 registers of 32 bits, `x0` to `x31`, and the program counter `pc`. `x0` always reads\n", + "0, and writes to it are ignored: this gives a constant zero and a place to throw results away. The\n", + "other 31 are the same for the hardware; the *calling convention* (the ABI) gives each one a name\n", + "and a role, which assembly programs use:\n", + "\n", + "| Register | ABI name | Role |\n", + "|---|---|---|\n", + "| `x0` | `zero` | always 0 |\n", + "| `x1` | `ra` | return address |\n", + "| `x2` | `sp` | stack pointer |\n", + "| `x3`, `x4` | `gp`, `tp` | global and thread pointer (unused here) |\n", + "| `x5`-`x7`, `x28`-`x31` | `t0`-`t6` | temporaries (a call may change them) |\n", + "| `x8`, `x9`, `x18`-`x27` | `s0`-`s11` | saved by the callee (`s0` is also `fp`) |\n", + "| `x10`-`x17` | `a0`-`a7` | arguments; `a0` and `a1` also return values (a call may change them) |\n", + "\n", + "`Reg` turns either kind of name into a register number:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(Reg.names.zipWithIndex.map { case (n, i) => s\"x$i=$n\" }.mkString(\" \"))\n", + "println(s\"a0 is x${Reg(\"a0\")}, x10 is x${Reg(\"x10\")}, fp is x${Reg(\"fp\")}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The six instruction formats\n", + "\n", + "Every RV32I instruction is one 32-bit word. The low 7 bits are the *opcode*, which selects the\n", + "format; the other fields are always in the same place when a format has them, so the hardware can\n", + "read the registers before it knows what the instruction is:\n", + "\n", + "```\n", + " 31 25 24 20 19 15 14 12 11 7 6 0\n", + "R | funct7 | rs2 | rs1 |funct3| rd | opcode | register-register ALU ops\n", + "I | imm[11:0] | rs1 |funct3| rd | opcode | ALU ops with a constant, loads, jalr\n", + "S | imm[11:5] | rs2 | rs1 |funct3| imm[4:0] | opcode | stores\n", + "B |imm[12|10:5]| rs2 | rs1 |funct3|imm[4:1|11]| opcode | conditional branches\n", + "U | imm[31:12] | rd | opcode | lui, auipc\n", + "J | imm[20|10:1|11|19:12] | rd | opcode | jal\n", + "```\n", + "\n", + "`rd` is the destination register, `rs1` and `rs2` the sources; `funct3` and `funct7` select the\n", + "operation within an opcode (for example `add` and `sub` differ only in `funct7`).\n", + "`Rv32i.encodings` lists the format, opcode, funct3 and funct7 of each instruction:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for ((format, insts) <- Rv32i.encodings.groupBy(_._2.format).toSeq.sortBy(_._1.toString))\n", + " println(s\"$format: ${insts.keys.toSeq.sorted.mkString(\" \")}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Immediates\n", + "\n", + "The immediate is always sign-extended from its top bit, and that bit is always instruction bit 31,\n", + "so the hardware can sign-extend before it decodes the format. The rest of the immediate is placed\n", + "so that each immediate bit comes from as few instruction bits as possible across the formats; the\n", + "cost is the strange order of the B and J fields:\n", + "\n", + "- **I**: `imm[11:0] = inst[31:20]`, from -2048 to 2047.\n", + " The shifts by an immediate (`slli`, `srli`, `srai`) are the exception: `inst[24:20]` is an\n", + " unsigned shift amount, 0 to 31, and `inst[31:25]` is a `funct7` (`0100000` for `srai`).\n", + "- **S**: the same 12 bits, but split around `rd`'s position (a store has no `rd`):\n", + " `imm[11:5] = inst[31:25]`, `imm[4:0] = inst[11:7]`.\n", + "- **B**: a branch offset is a multiple of 2, so `imm[0]` is not stored and the 12 stored bits reach\n", + " from -4096 to 4094. The sign bit (`inst[31]`, here `imm[12]`) and `imm[10:1]` are where the S\n", + " format has them (`imm[10:5]` and `imm[4:1]`), and the place of the S format's `imm[0]`\n", + " (`inst[7]`) holds `imm[11]`.\n", + "- **U**: `inst[31:12]` are the upper 20 bits, the low 12 are zero: `lui a0, 0x12345` puts\n", + " `0x12345000` in `a0`, and an `addi` adds the low 12 bits. As `addi` sign-extends them, a value\n", + " whose bit 11 is set needs the upper part rounded up: `0x12345800` is `lui 0x12346` plus\n", + " `addi -2048` (the assembler's `li` and `%hi` do this).\n", + "- **J**: like B, `imm[0]` is not stored; the 20 stored bits reach ±1 MiB.\n", + "\n", + "Here is the B-type immediate taken apart by hand, for `beq a0, a1, -8`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val word = Rv32i.encode(Inst(\"beq\", rs1 = Reg(\"a0\"), rs2 = Reg(\"a1\"), imm = -8))\n", + "def bits(x: Long, hi: Int, lo: Int): Long = (x >> lo) & ((1L << (hi - lo + 1)) - 1)\n", + "println(f\"word: 0x$word%08x = ${word.toBinaryString.reverse.padTo(32, '0').reverse}\")\n", + "val imm13 = bits(word, 31, 31) << 12 | bits(word, 7, 7) << 11 | bits(word, 30, 25) << 5 | bits(word, 11, 8) << 1\n", + "println(s\"imm[12:0] = ${imm13.toBinaryString}, sign-extended: ${(imm13.toInt << 19) >> 19}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Decoding into a case class\n", + "\n", + "`Rv32i.decode` turns a word into an `Inst`: the instruction's name, its register numbers and its\n", + "sign-extended immediate (fields that the format does not have are 0). It returns `None` for a word\n", + "that is not an RV32I instruction, and `Rv32i.encode` does the opposite:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for (w <- Seq(0x00a00293L, 0x40208233L, 0xffc12503L, 0x00b42423L, 0x12345537L, 0x00000073L, 0x34011073L))\n", + " println(f\"0x$w%08x -> ${Rv32i.decode(w)}\")\n", + "println(f\"0x${Rv32i.encode(Inst(\"addi\", rd = 5, imm = 10))}%08x\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The hardware decoder of the processor will use the bit patterns of `riscv.Instructions` instead\n", + "(the `BitPat`s of [Module 2.7](2.7_enums_and_bundles.ipynb)). The two descriptions are written\n", + "independently, and a test in `riscv/` checks that they agree: for each of the 40 instructions, 100\n", + "random instructions are encoded, matched against every `BitPat` (only their own one may match) and\n", + "decoded back to the same `Inst`. A similar check runs here the other way round: starting from\n", + "each `BitPat`, it fills the bits the pattern leaves free (`mask` has a 1 where the pattern fixes the\n", + "bit, `value` holds the fixed bits) with random ones, then decodes and re-encodes the word:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val rnd = new scala.util.Random(0)\n", + "for ((name, pattern) <- Instructions.all; _ <- 1 to 100) {\n", + " val word = (rnd.nextLong() & ~pattern.mask.toLong | pattern.value.toLong) & 0xffffffffL\n", + " val decoded = Rv32i.decode(word)\n", + " assert(decoded.map(_.name).contains(name.toLowerCase), f\"$name: 0x$word%08x decodes to $decoded\")\n", + " assert(Rv32i.encode(decoded.get) == word, f\"$name: 0x$word%08x\")\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What this course does with the 40 instructions\n", + "\n", + "There are no CSRs (see [riscv/DESIGN.md](https://github.com/sysprog21/chisel-bootcamp/blob/dev/riscv/DESIGN.md)), so there are no traps either:\n", + "\n", + "- `fence` orders memory accesses between harts and devices; with one in-order core it is a no-op.\n", + "- `ecall` and `ebreak` would trap to an operating system or a debugger. Here they **halt** the\n", + " core, which reports why on its retire port; so do an illegal instruction, a misaligned load or\n", + " store, and a branch or jump to an address that is not a multiple of 4.\n", + " The test programs end with `ecall`, leaving their result in `a0`.\n", + "- The other 37 do what the specification says." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The assembler\n", + "\n", + "Writing words by hand is error-prone, and the course has no RISC-V compiler: like the\n", + "[Ripes](https://github.com/mortbopet/Ripes) simulator, it brings its own assembler, `riscv.Asm`,\n", + "written in Scala in `riscv/src/main/scala/riscv/Asm.scala` (read it: it is a two-pass assembler in\n", + "a few hundred lines). It reads the GNU syntax:\n", + "\n", + "- one statement per line, `#` comments, labels (`loop:`) and numeric labels (`1:`, used as `1b`\n", + " backwards or `1f` forwards);\n", + "- the sections `.text` and `.data` (and `.bss`), and data directives such as `.word`, `.byte`,\n", + " `.string` and `.align`;\n", + "- the RV32I pseudo-instructions, which stand for one or two real instructions: `nop`, `li` (any\n", + " 32-bit value), `la` (the address of a label), `mv`, `not`, `neg`, `j`, `call`, `ret`, branches\n", + " against zero (`beqz`, `bnez`, ...) and the reversed comparisons (`bgt`, `ble`, ...).\n", + "\n", + "A branch or jump target is a label, and the assembler computes the offset (a plain number is\n", + "taken as the offset itself). `Asm(source)` returns the memory image, one word per element, for a\n", + "program that starts at `0x8000_0000`: the instructions of `.text`, then the `.data` words.\n", + "\n", + "This is the Fibonacci program of `riscv/programs/src/fib.S`; its words are those of\n", + "`riscv/programs/hex/fib.hex`, which the processors of the next notebooks load:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val fib = Asm(\"\"\"\n", + " li t0, 10 # how many steps\n", + " li a0, 0 # fib(0)\n", + " li a1, 1 # fib(1)\n", + "loop:\n", + " beqz t0, done\n", + " add t1, a0, a1\n", + " mv a0, a1\n", + " mv a1, t1\n", + " addi t0, t0, -1\n", + " j loop\n", + "done:\n", + " ecall\n", + "halt: j halt\n", + "\"\"\")\n", + "val hex = os.read.lines(os.pwd / \"riscv\" / \"programs\" / \"hex\" / \"fib.hex\").map(java.lang.Long.parseLong(_, 16))\n", + "for ((w, i) <- fib.zipWithIndex) println(f\"${0x80000000L + 4 * i}%08x: $w%08x ${Rv32i.decode(w).get}\")\n", + "assert(fib == hex)\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A program with data: `la` loads the address of `table` (an `auipc` and an `addi`, so it works\n", + "wherever the program is), and `Asm.assemble` also returns the address of every label:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val sum = Asm.assemble(\"\"\"\n", + " la t0, table # t0 = the address of table\n", + " li t1, 4 # four words\n", + " li a0, 0\n", + "1: lw t2, 0(t0)\n", + " add a0, a0, t2\n", + " addi t0, t0, 4\n", + " addi t1, t1, -1\n", + " bnez t1, 1b\n", + " ecall\n", + " .data\n", + "table: .word 1, 2, 3, 0x12345678\n", + "\"\"\")\n", + "println(sum.symbols)\n", + "for ((w, i) <- sum.words.zipWithIndex) {\n", + " val address = sum.base + 4 * i\n", + " val what = if (address < sum.symbols(\"table\")) Rv32i.decode(w).get.toString else \"data\"\n", + " println(f\"$address%08x: $w%08x $what\")\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Exercise: a disassembler\n", + "\n", + "`Inst` prints as a case class; a disassembler prints it as assembly. Write\n", + "`disassemble(inst: Long): String`, which returns the assembly of `inst` in the syntax that `Asm`\n", + "reads, with ABI register names, one space after the name and `\", \"` between operands:\n", + "\n", + "| Kind | Example |\n", + "|---|---|\n", + "| R | `add t1, a0, a1` |\n", + "| loads and `jalr` | `lw a0, -4(sp)` |\n", + "| other I (shifts too) | `addi t0, t0, -1` |\n", + "| S | `sw a1, 8(s0)` |\n", + "| B (the offset, in bytes) | `beq t0, zero, 24` |\n", + "| U (the 20 upper bits, in hex) | `lui a0, 0x12345` |\n", + "| J (the offset) | `jal zero, -20` |\n", + "| `ecall`, `ebreak`, `fence` | just the name |\n", + "| not RV32I | `unknown` |\n", + "\n", + "Use `Rv32i.decode`, `Rv32i.encodings(name).format`, `Rv32i.isLoad` and `Reg.names`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def disassemble(inst: Long): String = {\n", + " ??? // your code here\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val expected = Seq(\n", + " 0x00b50333L -> \"add t1, a0, a1\",\n", + " 0xffc12503L -> \"lw a0, -4(sp)\",\n", + " 0x000300e7L -> \"jalr ra, 0(t1)\",\n", + " 0xfff28293L -> \"addi t0, t0, -1\",\n", + " 0x41f55513L -> \"srai a0, a0, 31\",\n", + " 0x00b42423L -> \"sw a1, 8(s0)\",\n", + " 0x00028c63L -> \"beq t0, zero, 24\",\n", + " 0x12345537L -> \"lui a0, 0x12345\",\n", + " 0xfedff06fL -> \"jal zero, -20\",\n", + " 0x00000073L -> \"ecall\",\n", + " 0x0ff0000fL -> \"fence\",\n", + " 0x00000000L -> \"unknown\"\n", + ")\n", + "for ((word, text) <- expected) assert(disassemble(word) == text, f\"0x$word%08x: got '${disassemble(word)}'\")\n", + "// and the assembler reads the result back: every word of the program above survives the round trip\n", + "for (w <- fib) assert(Asm(disassemble(w), base = 0) == Seq(w), disassemble(w))\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "def disassemble(inst: Long): String = Rv32i.decode(inst) match {\n",
+    "  case None => \"unknown\"\n",
+    "  case Some(i) =>\n",
+    "    def r(n: Int) = Reg.names(n)\n",
+    "    Rv32i.encodings(i.name).format match {\n",
+    "      case _ if Set(\"ecall\", \"ebreak\", \"fence\")(i.name) => i.name\n",
+    "      case Format.R                                       => s\"${i.name} ${r(i.rd)}, ${r(i.rs1)}, ${r(i.rs2)}\"\n",
+    "      case Format.I if Rv32i.isLoad(i.name) || i.name == \"jalr\" =>\n",
+    "        s\"${i.name} ${r(i.rd)}, ${i.imm}(${r(i.rs1)})\"\n",
+    "      case Format.I => s\"${i.name} ${r(i.rd)}, ${r(i.rs1)}, ${i.imm}\"\n",
+    "      case Format.S => s\"${i.name} ${r(i.rs2)}, ${i.imm}(${r(i.rs1)})\"\n",
+    "      case Format.B => s\"${i.name} ${r(i.rs1)}, ${r(i.rs2)}, ${i.imm}\"\n",
+    "      case Format.U => f\"${i.name} ${r(i.rd)}, 0x${i.imm >>> 12}%x\"\n",
+    "      case Format.J => s\"${i.name} ${r(i.rd)}, ${i.imm}\"\n",
+    "    }\n",
+    "}\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# You're done!\n", + "\n", + "The [next notebook](5.2_alu_and_regfile.ipynb) builds the first pieces of hardware: the ALU, the\n", + "immediate generator and the register file.\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/5.2_alu_and_regfile.ipynb b/5.2_alu_and_regfile.ipynb new file mode 100644 index 0000000..47c30ea --- /dev/null +++ b/5.2_alu_and_regfile.ipynb @@ -0,0 +1,355 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.2: The ALU, the Immediates and the Registers\n", + "**Prev: [The RV32I Instruction Set](5.1_riscv_isa.ipynb)**
\n", + "**Next: [The Decoder](5.3_decoder.ipynb)**
\n", + "\n", + "## Motivation\n", + "A processor's datapath is built from a few blocks that every instruction passes through. This\n", + "notebook builds three of them, as modules of the `riscv/` project that the processors of the\n", + "next notebooks instantiate:\n", + "\n", + "- the **ALU**, which does the arithmetic and logic of RV32I (your exercise);\n", + "- the **immediate generator**, which takes the immediate out of an instruction, whatever its format;\n", + "- the **register file**, the 32 registers, from [Module 2.8](2.8_memories.ipynb).\n", + "\n", + "Each is checked against a model written in Scala: the ALU against the golden model of the course,\n", + "`riscv.IsaSim` (an RV32I interpreter), and the immediate generator against the software decoder of\n", + "[Module 5.1](5.1_riscv_isa.ipynb).\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.util._\n", + "import chisel3.simulator.PeekPokeAPI._\n", + "import riscv._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The ALU\n", + "\n", + "The ALU computes `a op b` for the ten operations of the RV32I arithmetic instructions. They are a\n", + "`ChiselEnum` ([Module 2.7](2.7_enums_and_bundles.ipynb)), `riscv.AluOp`; the register-register\n", + "instruction of each is its `mnemonic`, and `IsaSim.alu` is the golden model's version of it:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for (op <- AluOp.all)\n", + " println(f\"${AluOp.mnemonic(op)}%-5s 7 op 3 = ${IsaSim.alu(AluOp.mnemonic(op), 7, 3)}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The I-type instructions (`addi`, `slti`, ...) use the same operations with the immediate as `b`,\n", + "which is why there is no `AluOp` for them. Other instructions need an addition too: loads, stores\n", + "and `jalr` compute register + immediate, and `auipc` adds the immediate to the pc.\n", + "\n", + "The ALU is parameterized by its `width`: `Alu(32)` is the one of RV32I, but nothing in it is\n", + "specific to 32 bits. Its interface:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"Alu.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise: complete the ALU\n", + "\n", + "Open `riscv/src/main/scala/riscv/Alu.scala` (in Jupyter Lab: the file browser on the left) and\n", + "replace the `???` with the logic of every `AluOp`. Some hints:\n", + "\n", + "- a shift uses only the low `log2Ceil(width)` bits of `b` (5 bits for 32), as RV32I says;\n", + "- `Slt` compares as signed numbers (`asSInt`), `Sltu` as unsigned ones; both give 1 or 0;\n", + "- `Sra` shifts in copies of the sign bit: shift the `SInt`, then turn it back into a `UInt`;\n", + "- `MuxLookup` ([Module 2.7](2.7_enums_and_bundles.ipynb)) selects by the operation.\n", + "\n", + "Until then, the next two cells stop with a `NotImplementedError` when they build the ALU: that is\n", + "the `???`, not a broken setup. When your ALU is written, **restart the kernel** (the running kernel keeps the classes it loaded) and run the notebook\n", + "again from the top: `load-riscv.sc` recompiles the project. The test below compares your ALU with\n", + "`IsaSim.alu` on random operands and on the corner cases random numbers rarely hit, in one\n", + "simulation: building it (elaborating, then compiling with Verilator) takes most of the time, the\n", + "5000 checks a small part of it, so one simulation with many pokes is much faster than many small\n", + "ones." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new Alu) { c =>\n", + " val rnd = new scala.util.Random(1)\n", + " def unsigned(x: Int) = BigInt(Integer.toUnsignedLong(x))\n", + " val corners = Seq(0, 1, -1, 31, 32, Int.MaxValue, Int.MinValue)\n", + " def operand() = if (rnd.nextInt(4) == 0) corners(rnd.nextInt(corners.size)) else rnd.nextInt()\n", + " for (op <- AluOp.all; _ <- 0 until 500) {\n", + " val (a, b) = (operand(), operand())\n", + " c.io.op.poke(op)\n", + " c.io.a.poke(unsigned(a).U)\n", + " c.io.b.poke(unsigned(b).U)\n", + " c.io.out.expect(unsigned(IsaSim.alu(AluOp.mnemonic(op), a, b)).U, s\"${AluOp.mnemonic(op)}($a, $b)\")\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And the parameterization: an 8-bit ALU wraps around at 256, and shifts by the low 3 bits of `b`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new Alu(8)) { c =>\n", + " def check(op: AluOp.Type, a: Int, b: Int, expected: Int) = {\n", + " c.io.op.poke(op)\n", + " c.io.a.poke(a.U)\n", + " c.io.b.poke(b.U)\n", + " c.io.out.expect(expected.U, s\"${AluOp.mnemonic(op)}($a, $b)\")\n", + " }\n", + " check(AluOp.Add, 200, 100, 44) // 300 - 256\n", + " check(AluOp.Sub, 0, 1, 255)\n", + " check(AluOp.Sll, 1, 9, 2) // 9 = 0b1001: shift by 1\n", + " check(AluOp.Sra, 0x80, 1, 0xc0) // the sign bit is bit 7\n", + " check(AluOp.Slt, 0xff, 1, 1) // -1 < 1\n", + " check(AluOp.Sltu, 0xff, 1, 0)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  val shamt = io.b(log2Ceil(width) - 1, 0)\n",
+    "  io.out := MuxLookup(io.op, 0.U)(\n",
+    "    Seq(\n",
+    "      AluOp.Add  -> (io.a + io.b),\n",
+    "      AluOp.Sub  -> (io.a - io.b),\n",
+    "      AluOp.Sll  -> (io.a << shamt)(width - 1, 0),\n",
+    "      AluOp.Slt  -> (io.a.asSInt < io.b.asSInt),\n",
+    "      AluOp.Sltu -> (io.a < io.b),\n",
+    "      AluOp.Xor  -> (io.a ^ io.b),\n",
+    "      AluOp.Srl  -> (io.a >> shamt),\n",
+    "      AluOp.Sra  -> (io.a.asSInt >> shamt).asUInt,\n",
+    "      AluOp.Or   -> (io.a | io.b),\n",
+    "      AluOp.And  -> (io.a & io.b)\n",
+    "    )\n",
+    "  )\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The immediate generator\n", + "\n", + "[Module 5.1](5.1_riscv_isa.ipynb) showed how each format scatters its immediate over the\n", + "instruction. In hardware, that is only wiring: every immediate bit comes from a fixed instruction\n", + "bit (or is a copy of the sign, bit 31, or a zero), and a multiplexer picks the format. The decoder\n", + "of the next notebook tells it the format:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"ImmGen.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`Fill(n, sign)` is `n` copies of the sign bit and `Cat` concatenates, most significant first, so\n", + "each line can be read against the format table of 5.1. The test compares it with the software\n", + "decoder, `Rv32i.decode`, on random instructions of every format:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// random instructions as in 5.1: the pattern's fixed bits, random bits elsewhere (the immediate)\n", + "val formats = Seq(\n", + " ImmFormat.I -> Seq(\"ADDI\", \"LW\", \"JALR\"),\n", + " ImmFormat.S -> Seq(\"SW\"),\n", + " ImmFormat.B -> Seq(\"BEQ\"),\n", + " ImmFormat.U -> Seq(\"LUI\", \"AUIPC\"),\n", + " ImmFormat.J -> Seq(\"JAL\")\n", + ")\n", + "simulate(new ImmGen) { c =>\n", + " val rnd = new scala.util.Random(1)\n", + " for ((format, names) <- formats; name <- names; _ <- 0 until 100) {\n", + " val word = Instructions.random(name, rnd)\n", + " c.io.inst.poke(word.U)\n", + " c.io.format.poke(format)\n", + " c.io.imm.expect(BigInt(Integer.toUnsignedLong(Rv32i.decode(word).get.imm)).U, f\"$name 0x$word%08x\")\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The register file\n", + "\n", + "`riscv.RegFile` is the same register file as the one of [Module 2.8](2.8_memories.ipynb): two\n", + "combinational read ports (an instruction reads `rs1` and `rs2` in the same cycle), one write port\n", + "that writes at the clock edge, `x0` hard-wired to 0, and a debug port that lets a test read any\n", + "register without disturbing the processor. The processors read their results through it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"RegFile.scala\"))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new RegFile) { c =>\n", + " // write x1..x31, and x0 (which must ignore it)\n", + " c.io.wen.poke(true.B)\n", + " for (r <- 0 until 32) {\n", + " c.io.rd.poke(r.U)\n", + " c.io.wdata.poke((100 + r).U)\n", + " c.clock.step()\n", + " }\n", + " c.io.wen.poke(false.B)\n", + " for (r <- 0 until 32) {\n", + " c.io.dbgAddr.poke(r.U)\n", + " c.io.dbgData.expect((if (r == 0) 0 else 100 + r).U, s\"x$r\")\n", + " }\n", + " // a read in the same cycle as a write to the same register sees the old value\n", + " c.io.rs1.poke(5.U)\n", + " c.io.rd.poke(5.U)\n", + " c.io.wdata.poke(7.U)\n", + " c.io.wen.poke(true.B)\n", + " c.io.rs1Data.expect(105.U)\n", + " c.clock.step()\n", + " c.io.rs1Data.expect(7.U)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That last check matters for pipelines: an instruction that reads a register in the same cycle as\n", + "an older instruction writes it gets the old value: the new one is written a cycle too late. A\n", + "pipelined processor has to deal with it, by forwarding the new value or by waiting.\n", + "\n", + "---\n", + "# You're done!\n", + "\n", + "The [next notebook](5.3_decoder.ipynb) builds the decoder, which turns an instruction into the control signals of these\n", + "blocks (`AluOp`, `ImmFormat`, register write, ...).\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/5.3_decoder.ipynb b/5.3_decoder.ipynb new file mode 100644 index 0000000..3f46cd7 --- /dev/null +++ b/5.3_decoder.ipynb @@ -0,0 +1,410 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.3: The Decoder\n", + "**Prev: [The ALU, the Immediates and the Registers](5.2_alu_and_regfile.ipynb)**
\n", + "**Next: [A Single-Cycle RV32I Processor](5.4_single_cycle.ipynb)**
\n", + "\n", + "## Motivation\n", + "The decoder turns an instruction into the control signals of the datapath: which ALU operation,\n", + "which immediate format, where the ALU's operands come from, and what kind of instruction it is.\n", + "It is also where an instruction that is not RV32I is caught.\n", + "\n", + "A decoder can be written by hand, as nested `switch` statements on the opcode and `funct3`, but\n", + "then the knowledge \"what does `sltiu` do\" is spread over many lines. This notebook writes it as a\n", + "*table*, one row per instruction, and lets Chisel generate and minimize the logic, with\n", + "`chisel3.util.experimental.decode` and the `BitPat`s of [Module 2.7](2.7_enums_and_bundles.ipynb).\n", + "At the end, the two styles are compared.\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.util._\n", + "import chisel3.simulator.PeekPokeAPI._\n", + "import riscv._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The control signals\n", + "\n", + "`riscv.Control` holds what the decoder decides; three new `ChiselEnum`s name the choices:\n", + "\n", + "- `kind` (`Kind`): `Alu`, `Load`, `Store`, `Branch`, `Jal`, `Jalr`, `Fence`, `Ecall` or `Ebreak`.\n", + " The datapath derives everything else from it: whether `rd` is written and with what (the ALU\n", + " result, the loaded value, or pc + 4), whether memory is read or written, how the next pc is\n", + " computed. The size of a load or store and the condition of a branch are in `funct3`, so the\n", + " datapath takes them from the instruction directly (a branch compares its registers in a\n", + " comparator of its own: the ALU is busy computing the target);\n", + "- `aluOp` (`AluOp`, from 5.2) and `immFormat` (`ImmFormat`, from 5.2);\n", + "- `aSel` (`ASel`: `Rs1`, `Pc` or `Zero`) and `bSel` (`BSel`: `Rs2` or `Imm`), the ALU's operands:\n", + " `auipc` and the jump and branch targets add to the pc, `lui` adds to zero;\n", + "- `legal`: false for a word that is not an RV32I instruction (the other fields then mean nothing)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The table\n", + "\n", + "`riscv/src/main/scala/riscv/DecodeRows.scala` has one `Row` per instruction. A field that an\n", + "instruction does not use is `None`: a *don't care*, which the logic minimizer may set to whatever\n", + "makes the logic smallest (`fence`, for example, uses nothing)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"DecodeRows.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise: complete the table\n", + "\n", + "Three rows are missing (`???`): `BGEU`, `SLTIU` and `SRA`. Fill them in in\n", + "`riscv/src/main/scala/riscv/DecodeRows.scala`, using the helpers at the top of the table and the\n", + "rows of similar instructions. Then **restart the kernel** and run the notebook again. Until then,\n", + "the cells that use the table stop with a `NotImplementedError` (the `???`).\n", + "\n", + "The first check compares the table with a second description of the same decoder, worked out\n", + "from each instruction's opcode in the encodings of [Module 5.1](5.1_riscv_isa.ipynb): the opcode\n", + "gives the kind and the operands, the format gives the immediate, and an arithmetic instruction\n", + "asks the ALU for its own operation (`sltiu` for `Sltu`). A wrong or missing field fails it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// the row an instruction must have, worked out from its opcode and name alone\n", + "def expectedRow(name: String): Row = {\n", + " val e = Rv32i.encodings(name.toLowerCase)\n", + " val alu = AluOp.all.find(AluOp.mnemonic(_) == name.toLowerCase.filterNot(_ == 'i')) // addi -> add\n", + " def row(kind: Kind.Type, a: ASel.Type, b: BSel.Type, op: Option[AluOp.Type] = Some(AluOp.Add)) =\n", + " Row(kind, op, ImmFormat.of(e.format), Some(a), Some(b))\n", + " e.opcode match {\n", + " case 0x37 => row(Kind.Alu, ASel.Zero, BSel.Imm) // lui: 0 + imm\n", + " case 0x17 => row(Kind.Alu, ASel.Pc, BSel.Imm) // auipc: pc + imm\n", + " case 0x6f => row(Kind.Jal, ASel.Pc, BSel.Imm) // the target\n", + " case 0x67 => row(Kind.Jalr, ASel.Rs1, BSel.Imm)\n", + " case 0x63 => row(Kind.Branch, ASel.Pc, BSel.Imm)\n", + " case 0x03 => row(Kind.Load, ASel.Rs1, BSel.Imm) // the address\n", + " case 0x23 => row(Kind.Store, ASel.Rs1, BSel.Imm)\n", + " case 0x13 => row(Kind.Alu, ASel.Rs1, BSel.Imm, alu)\n", + " case 0x33 => row(Kind.Alu, ASel.Rs1, BSel.Rs2, alu)\n", + " case 0x0f => Row(Kind.Fence)\n", + " case 0x73 => Row(if (name == \"ECALL\") Kind.Ecall else Kind.Ebreak)\n", + " }\n", + "}\n", + "// rows as plain values: enum values compare by their encoding\n", + "def values(r: Row) =\n", + " (r.kind.litValue, r.aluOp.map(_.litValue), r.imm.map(_.litValue), r.a.map(_.litValue), r.b.map(_.litValue))\n", + "\n", + "val rows = DecodeRows.table\n", + "assert(rows.keySet == Instructions.all.map(_._1).toSet, \"a row for every instruction\")\n", + "for ((name, row) <- rows) assert(values(row) == values(expectedRow(name)), s\"the row of $name\")\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "    \"BGEU\"  -> branch,\n",
+    "    \"SLTIU\" -> imm(Sltu),\n",
+    "    \"SRA\"    -> reg(Sra),\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# From the table to logic\n", + "\n", + "`chisel3.util.experimental.decode` turns the table into hardware in three steps (see the\n", + "`Decoder` object in `riscv/src/main/scala/riscv/Decoder.scala`):\n", + "\n", + "1. each instruction is a `DecodePattern`, here `InstPattern(name, bitPat)` with the `BitPat` of\n", + " `Instructions.all`;\n", + "2. each control signal is a `DecodeField`, whose `genTable(pattern)` gives the signal's value for\n", + " that instruction as a `BitPat`: `BitPat(AluOp.Add)` for a value, `dc` (don't care) for `None`.\n", + " The `legal` field is `y` for every instruction, and its `default` (for a word that matches no\n", + " pattern) is `n`;\n", + "3. `DecodeTable(patterns, fields)` concatenates the fields into one output word per pattern: a\n", + " *truth table*, with the defaults for every other input.\n", + "\n", + "A logic minimizer then turns the truth table into a sum of products. `decoder.qmc` uses\n", + "Quine-McCluskey, built into Chisel; `DecodeTable.decode` would first try the external `espresso`\n", + "program, which is not installed here (it would fall back to Quine-McCluskey with a warning), so\n", + "the module calls `decoder.qmc` directly.\n", + "\n", + "The truth table has one line per instruction, the input pattern then the output bits:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val truth = Decoder.table.table\n", + "println(s\"${truth.table.size} rows, ${truth.table.head._1.getWidth} input bits, ${truth.default.getWidth} output bits\")\n", + "truth.table.take(3).foreach { case (in, out) => println(s\"$in -> $out\") }" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Testing the decoder\n", + "\n", + "Two tests in one simulation: 50 random instances of every RV32I instruction must give the\n", + "signals of their row (where the row cares), and words that are not RV32I must be flagged as\n", + "illegal. The illegal words include *near misses*, instructions with one fixed bit flipped, which\n", + "random words would hardly ever produce; the software decoder of 5.1 says which words are not RV32I." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new Decoder) { c =>\n", + " val rows = DecodeRows.table // each cell stands alone: an earlier one may have failed\n", + " val rnd = new scala.util.Random(1)\n", + " for ((name, _) <- Instructions.all; _ <- 0 until 50) {\n", + " val word = Instructions.random(name, rnd)\n", + " val row = rows(name)\n", + " val what = f\"$name 0x$word%08x\"\n", + " c.io.inst.poke(word.U)\n", + " c.io.ctrl.legal.expect(true.B, what)\n", + " c.io.ctrl.kind.expect(row.kind, what)\n", + " row.aluOp.foreach(c.io.ctrl.aluOp.expect(_, what))\n", + " row.imm.foreach(c.io.ctrl.immFormat.expect(_, what))\n", + " row.a.foreach(c.io.ctrl.aSel.expect(_, what))\n", + " row.b.foreach(c.io.ctrl.bSel.expect(_, what))\n", + " }\n", + " val nearMisses = Instructions.all.flatMap { case (n, _) => Seq.fill(20)(Instructions.nearMiss(n, rnd)) }\n", + " val illegal = (nearMisses ++ Seq.fill(2000)(rnd.nextLong() & 0xffffffffL)).filter(Rv32i.decode(_).isEmpty)\n", + " for (word <- illegal) {\n", + " c.io.inst.poke(word.U)\n", + " c.io.ctrl.legal.expect(false.B, f\"0x$word%08x\")\n", + " }\n", + " println(s\"${Instructions.all.size * 50} instructions and ${illegal.size} illegal words checked\")\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A table is only correct if no word matches two rows. The patterns of `Instructions.all` must not\n", + "overlap: `BitPat.overlap` tells whether some word matches both (this does not need the table, so\n", + "it runs before the exercise is done too)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val overlaps = for {\n", + " (a, i) <- Instructions.all.zipWithIndex\n", + " b <- Instructions.all.drop(i + 1)\n", + " if a._2.overlap(b._2)\n", + "} yield s\"${a._1} and ${b._1}\"\n", + "assert(overlaps.isEmpty, overlaps.mkString(\", \"))\n", + "println(s\"no two of the ${Instructions.all.size} patterns overlap\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Table or `switch`?\n", + "\n", + "Here is the same decoder written by hand: a `switch` on the opcode, with `funct3` and `funct7`\n", + "inside. It is shorter to type than the table, but each instruction's behavior is spread over\n", + "several lines, and the legality conditions (which `funct3` values exist for loads, which `funct7`\n", + "for shifts) are easy to get wrong. It is `riscv.SwitchDecoder` (Module 5.10 synthesizes it too):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"SwitchDecoder.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The two decoders must agree wherever the table cares, and on legality. Their size, measured\n", + "roughly as lines of FIRRTL and of SystemVerilog after `firtool`'s optimizations (a fairer\n", + "measure, the number of logic cells after synthesis, needs Yosys, which comes in Module 5.10):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// both decoders on the same instruction; one output per signal says whether they agree\n", + "class Compare extends Module {\n", + " val inst = IO(Input(UInt(32.W)))\n", + " val same = IO(Output(new Bundle {\n", + " val legal, kind, aluOp, immFormat, aSel, bSel = Bool()\n", + " }))\n", + " val table = Module(new Decoder)\n", + " val hand = Module(new SwitchDecoder)\n", + " table.io.inst := inst\n", + " hand.io.inst := inst\n", + " val (t, h) = (table.io.ctrl, hand.io.ctrl)\n", + " same.legal := t.legal === h.legal\n", + " same.kind := t.kind === h.kind\n", + " same.aluOp := t.aluOp === h.aluOp\n", + " same.immFormat := t.immFormat === h.immFormat\n", + " same.aSel := t.aSel === h.aSel\n", + " same.bSel := t.bSel === h.bSel\n", + "}\n", + "simulate(new Compare) { c =>\n", + " val rows = DecodeRows.table\n", + " val rnd = new scala.util.Random(3)\n", + " val words = Instructions.all.flatMap { case (n, _) =>\n", + " Seq.fill(20)(Instructions.random(n, rnd)) ++ Seq.fill(20)(Instructions.nearMiss(n, rnd))\n", + " } ++ Seq.fill(2000)(rnd.nextLong() & 0xffffffffL)\n", + " for (word <- words) {\n", + " c.inst.poke(word.U)\n", + " val what = f\"0x$word%08x\"\n", + " c.same.legal.expect(true.B, what)\n", + " for (i <- Rv32i.decode(word); row = rows(i.name.toUpperCase)) { // where the row cares\n", + " c.same.kind.expect(true.B, what)\n", + " if (row.aluOp.isDefined) c.same.aluOp.expect(true.B, what)\n", + " if (row.imm.isDefined) c.same.immFormat.expect(true.B, what)\n", + " if (row.a.isDefined) c.same.aSel.expect(true.B, what)\n", + " if (row.b.isDefined) c.same.bSel.expect(true.B, what)\n", + " }\n", + " }\n", + "}\n", + "def size(gen: => RawModule): (Int, Int) = (\n", + " _root_.circt.stage.ChiselStage.emitCHIRRTL(gen).linesIterator.size,\n", + " _root_.circt.stage.ChiselStage\n", + " .emitSystemVerilog(gen, firtoolOpts = Array(\"-disable-all-randomization\", \"-strip-debug-info\"))\n", + " .linesIterator\n", + " .size\n", + ")\n", + "val (tableFir, tableSv) = size(new Decoder)\n", + "val (handFir, handSv) = size(new SwitchDecoder)\n", + "println(s\"table-driven: $tableFir lines of FIRRTL, $tableSv lines of SystemVerilog\")\n", + "println(s\"switch: $handFir lines of FIRRTL, $handSv lines of SystemVerilog\")\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `switch` comes out several times smaller as text. The minimizer turns each of the 15 output\n", + "bits into a sum of products of the instruction bits on its own, using every don't care; products\n", + "that come out identical are shared, but there is nothing like the `switch`'s structure, where one\n", + "comparison of the opcode serves all the signals of an instruction class. Lines of text are not gates, though: a synthesis tool optimizes both\n", + "descriptions again. Yosys (Module 5.10) maps them to about 100 and 60 look-up tables for a Lattice\n", + "iCE40 FPGA (about 140 and 75 for an ECP5): as gates, the table-driven decoder is under twice the size.\n", + "\n", + "The table's advantage is elsewhere: adding an instruction is adding a row, and the tests above\n", + "check every row against an independent description of the ISA. The processors of this course\n", + "use the table-driven `Decoder`.\n", + "\n", + "---\n", + "# You're done!\n", + "\n", + "The [next notebook](5.4_single_cycle.ipynb) puts the ALU, the immediate generator, the register file and the decoder\n", + "together into a single-cycle RV32I processor.\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/5.4_single_cycle.ipynb b/5.4_single_cycle.ipynb new file mode 100644 index 0000000..1d40705 --- /dev/null +++ b/5.4_single_cycle.ipynb @@ -0,0 +1,382 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.4: A Single-Cycle RV32I Processor\n", + "**Prev: [The Decoder](5.3_decoder.ipynb)**
\n", + "**Next: [The Official RISC-V Tests](5.5_compliance.ipynb)**
\n", + "\n", + "## Motivation\n", + "Everything is in place: the ALU and the register file ([5.2](5.2_alu_and_regfile.ipynb)), the\n", + "immediate generator, and the decoder ([5.3](5.3_decoder.ipynb)). This notebook connects them into\n", + "a processor that runs RV32I programs: a **single-cycle** one, which fetches, decodes, executes\n", + "and retires one instruction in each clock cycle. It is the simplest correct design, and the\n", + "reference for the faster ones that follow.\n", + "\n", + "The processor uses your ALU and decode table: if you have not completed the exercises of 5.2 and\n", + "5.3 yet, do that first (the cells below stop with a `NotImplementedError` until then). This\n", + "notebook adds two more exercises: the branch comparator and the load extension.\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.util._\n", + "import chisel3.simulator.PeekPokeAPI._\n", + "import riscv._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Memory\n", + "\n", + "The core talks to memory through two ports, one for instructions and one for data, of the same\n", + "type, `riscv.MemPort`: a request (`Decoupled`: address, write data, byte strobes) and a response\n", + "(`Valid`: the word read, or an error for an address outside the memory). The RAM of this notebook\n", + "answers in the same cycle, because it is a `Mem` (combinational read, [Module 2.8](2.8_memories.ipynb)):\n", + "a single-cycle core must fetch and load within one cycle. This core relies on that: it retires an\n", + "instruction only in a cycle where both answers are there, and ignores `ready`. A memory that\n", + "answers later, such as a bus, needs a core that keeps track of its requests ([Module 5.8](5.8_bus_and_mmio.ipynb)).\n", + "\n", + "Memory is byte-addressed, but the RAM stores words: a store of a byte or a half-word sends the\n", + "word with the bytes in place, and *strobes* that say which bytes to write. The RAM has one more\n", + "port, `load`, through which a testbench writes the program before the core starts." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"Memory.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note the comment about the write port: `firtool` drops the write masks of a memory that also has\n", + "a write port without a mask (see the end of the write-mask section of\n", + "[Module 2.8](2.8_memories.ipynb)), so the RAM has one write port, which the load port and the\n", + "stores share." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The datapath\n", + "\n", + "`riscv.SingleCycleCore` follows an instruction through the cycle:\n", + "\n", + "1. **fetch** the word at `pc` from the instruction port;\n", + "2. **decode** it (`Decoder`), read `rs1` and `rs2` (`RegFile`), and build the immediate (`ImmGen`);\n", + "3. **execute**: the ALU computes the result, a memory address or a jump target, with the operands\n", + " that `aSel` and `bSel` choose; the **branch unit** compares `rs1` and `rs2`;\n", + "4. **memory**: a load or a store goes to the data port; a load's byte or half-word is extracted\n", + " and extended (`LoadExtend`);\n", + "5. **write back** the result (the ALU's, the loaded value, or pc + 4 for `jal`/`jalr`) to `rd`, and\n", + " move to the next pc (pc + 4, or the target of a jump or a taken branch).\n", + "\n", + "The core also checks what halts it (an illegal instruction, `ecall`, `ebreak`, a misaligned\n", + "access or target, an address outside the RAM) and reports every retired instruction on its\n", + "**retire port**, with the same fields as the golden model's `Retire` records: tests compare the\n", + "two streams instruction by instruction." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"SingleCycleCore.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Exercise 1: the branch comparator\n", + "\n", + "A branch is taken if its two registers compare as its `funct3` says: `beq` (0), `bne` (1), `blt`\n", + "(4), `bge` (5), `bltu` (6), `bgeu` (7). Complete `riscv/src/main/scala/riscv/BranchUnit.scala`.\n", + "A hint: the low bit of `funct3` negates the condition (`bne` is not `beq`, `bge` is not `blt`)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new BranchUnit) { c =>\n", + " val rnd = new scala.util.Random(1)\n", + " def unsigned(x: Int) = BigInt(Integer.toUnsignedLong(x))\n", + " val corners = Seq(0, 1, -1, Int.MaxValue, Int.MinValue)\n", + " def operand = if (rnd.nextInt(3) == 0) corners(rnd.nextInt(corners.size)) else rnd.nextInt()\n", + " for ((f3, name) <- Seq(0 -> \"beq\", 1 -> \"bne\", 4 -> \"blt\", 5 -> \"bge\", 6 -> \"bltu\", 7 -> \"bgeu\"); _ <- 0 until 300) {\n", + " val (a, b) = if (rnd.nextInt(5) == 0) { val x = operand; (x, x) }\n", + " else (operand, operand)\n", + " c.io.funct3.poke(f3.U)\n", + " c.io.a.poke(unsigned(a).U)\n", + " c.io.b.poke(unsigned(b).U)\n", + " c.io.taken.expect(IsaSim.taken(name, a, b).B, s\"$name $a, $b\") // the golden model's decision\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  // funct3 bit 0 negates the condition: bne, bge and bgeu are the opposites of beq, blt and bltu\n",
+    "  val condition = MuxLookup(io.funct3(2, 1), false.B)(\n",
+    "    Seq(\n",
+    "      0.U -> (io.a === io.b),\n",
+    "      2.U -> (io.a.asSInt < io.b.asSInt),\n",
+    "      3.U -> (io.a < io.b)\n",
+    "    )\n",
+    "  )\n",
+    "  io.taken := condition =/= io.funct3(0)\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Exercise 2: the load extension\n", + "\n", + "The data port returns the whole word at the (word-aligned) address. For `lb`, `lbu`, `lh` and\n", + "`lhu`, the byte or half-word starts at byte `offset` of the word (the address's low two bits;\n", + "RISC-V is little-endian, so byte 0 is bits 7 to 0), and must be sign-extended (`lb`, `lh`) or\n", + "zero-extended (`lbu`, `lhu`) to 32 bits. Complete `riscv/src/main/scala/riscv/LoadExtend.scala`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new LoadExtend) { c =>\n", + " val rnd = new scala.util.Random(2)\n", + " def unsigned(x: Int) = BigInt(Integer.toUnsignedLong(x))\n", + " for (_ <- 0 until 300; (f3, name) <- Seq(0 -> \"lb\", 1 -> \"lh\", 2 -> \"lw\", 4 -> \"lbu\", 5 -> \"lhu\")) {\n", + " val bytes = IsaSim.width(name)\n", + " val word = rnd.nextInt()\n", + " val offset = rnd.nextInt(4 / bytes) * bytes\n", + " // the bytes the load reads, and what the golden model makes of them\n", + " val raw = (Integer.toUnsignedLong(word) >>> (8 * offset)) & ((1L << (8 * bytes)) - 1)\n", + " c.io.funct3.poke(f3.U)\n", + " c.io.offset.poke(offset.U)\n", + " c.io.rdata.poke(unsigned(word).U)\n", + " c.io.value.expect(unsigned(IsaSim.loadValue(name, raw)).U, f\"$name offset $offset word 0x$word%08x\")\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  val shifted  = io.rdata >> (io.offset ## 0.U(3.W)) // offset * 8\n",
+    "  val unsigned = io.funct3(2)\n",
+    "  val byte     = shifted(7, 0)\n",
+    "  val half     = shifted(15, 0)\n",
+    "  io.value := MuxLookup(io.funct3(1, 0), shifted)(\n",
+    "    Seq(\n",
+    "      0.U -> Cat(Fill(24, byte(7) && !unsigned), byte),\n",
+    "      1.U -> Cat(Fill(16, half(15) && !unsigned), half)\n",
+    "    )\n",
+    "  )\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Running a program\n", + "\n", + "`riscv.SingleCycleSystem` is the core with its RAM. `CoSim.load` writes a program (assembled by\n", + "`riscv.Asm`, [Module 5.1](5.1_riscv_isa.ipynb)) through the load port, `CoSim.run` clocks the\n", + "core until it halts and collects what it retires, and `CoSim.reg` reads a register through the\n", + "debug port. Here is the Fibonacci program, instruction by instruction:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val fib = Asm(Programs.source(\"programs/src\", \"fib\"))\n", + "simulate(new SingleCycleSystem) { c =>\n", + " CoSim.load(c, fib)\n", + " val trace = CoSim.run(c)\n", + " for (r <- trace.take(12)) {\n", + " val write = if (r.rd != 0) f\"x${r.rd}%-2d = ${r.rdValue}\" else \"\"\n", + " println(f\"${r.pc}%08x ${Rv32i.decode(r.inst).map(_.toString).getOrElse(\"?\")}%-28s $write\")\n", + " }\n", + " println(s\"... ${trace.size} instructions in ${trace.size} cycles, halted by ${trace.last.halt.get}\")\n", + " assert(CoSim.reg(c, riscv.Reg(\"a0\")) == 55)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Comparing with the golden model\n", + "\n", + "A program that ends with the right result can still have taken a wrong turn on the way. The\n", + "strong test compares every retired instruction with the golden model, `IsaSim`:\n", + "`CoSim.compare` runs a program on both and returns the first difference. Here: the factorial\n", + "program (calls, the stack, and a multiplication by shifts and adds) and random programs\n", + "(`RandomProgram`, which are written so that they always end with `ecall`)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new SingleCycleSystem) { c =>\n", + " val fact = Asm(Programs.source(\"programs/src\", \"fact\"))\n", + " CoSim.compare(c, fact).foreach(d => sys.error(s\"factorial: $d\"))\n", + " for (seed <- 1L to 5L)\n", + " CoSim.compare(c, Asm(RandomProgram(seed))).foreach(d => sys.error(s\"RandomProgram($seed): $d\"))\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Halting\n", + "\n", + "Without CSRs there is no trap handler: the instructions that would trap halt the core instead,\n", + "which reports why. An instruction that halts the core changes nothing (here, `ra` is not written\n", + "by the jump to a misaligned address):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val programs = Seq(\n", + " \"ecall\" -> Halt.Ecall,\n", + " \"ebreak\" -> Halt.Ebreak,\n", + " \".word 0x30200073 # mret\" -> Halt.Illegal,\n", + " \"la ra, x\\njalr ra, 2(ra)\\nx: nop\" -> Halt.Misaligned,\n", + " \"li t0, 4\\nlw a0, 0(t0)\" -> Halt.BadAddress\n", + ")\n", + "simulate(new SingleCycleSystem) { c =>\n", + " for ((source, cause) <- programs) {\n", + " CoSim.load(c, Asm(source))\n", + " val last = CoSim.run(c).last\n", + " println(f\"${source.replace(\"\\n\", \"; \")}%-40s halts: ${last.halt.get}\")\n", + " assert(last.halt.contains(cause) && last.rd == 0)\n", + " if (cause == Halt.Misaligned) assert(CoSim.reg(c, 1) == 0x8000000cL, \"ra still points to x\") // not written\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# You're done!\n", + "\n", + "The core runs one instruction per cycle, so its clock can only be as fast as the slowest\n", + "instruction's path (a load: fetch, decode, register read, ALU, memory, extension, write back).\n", + "The [next notebook](5.5_compliance.ipynb) runs the official RISC-V tests on it; later notebooks split the path into a\n", + "pipeline.\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/5.5_compliance.ipynb b/5.5_compliance.ipynb new file mode 100644 index 0000000..a644fe2 --- /dev/null +++ b/5.5_compliance.ipynb @@ -0,0 +1,225 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.5: The Official RISC-V Tests\n", + "**Prev: [A Single-Cycle RV32I Processor](5.4_single_cycle.ipynb)**
\n", + "**Next: [A Five-Stage Pipeline](5.6_pipeline.ipynb)**
\n", + "\n", + "## Motivation\n", + "The core of [Module 5.4](5.4_single_cycle.ipynb) passes the tests we wrote, and retires the same\n", + "instructions as our golden model. But both were written by the same people, from the same reading\n", + "of the specification: if we misread an instruction, the model and the core agree, and are both\n", + "wrong. The [riscv-tests](https://github.com/riscv-software-src/riscv-tests) of RISC-V\n", + "International are an independent check: for each instruction, a program that runs it on chosen\n", + "operands (corner cases included) and compares the results with values computed elsewhere.\n", + "\n", + "This notebook runs the `rv32ui` tests (the unprivileged RV32I instructions) on the golden model and\n", + "on the single-cycle core.\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.simulator.PeekPokeAPI._\n", + "import riscv._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# How the tests got here\n", + "\n", + "A riscv-test is an assembly file written with C preprocessor macros: `TEST_RR_OP(2, add, 3, 1, 2)`\n", + "expands to \"load 1 and 2, add them, compare with 3, jump to `fail` if different\", numbered so that a\n", + "failure says which case it was. The tests normally run in an *environment* (`riscv_test.h`) that\n", + "sets up trap handlers with CSRs, and they report through a memory location the simulator watches.\n", + "\n", + "This course has neither CSRs nor a C compiler, so `tools/import-riscv-tests.py` (run on a\n", + "development machine, with git and `cpp`) did two things once: it replaced the environment with a\n", + "small CSR-free one, where a test starts at the first instruction and ends with `ecall`, leaving 0\n", + "in `a0` if it passed (or the failing case's number, shifted left by one, plus one); and it expanded\n", + "the macros with `cpp`. The expanded files are in `riscv/programs/riscv-tests/rv32ui/`, and `riscv.Asm`\n", + "assembles them here (they come out word for word as GNU `as` assembles them). Two tests are left\n", + "out: `fence_i` (`FENCE.I` belongs to the Zifencei extension) and `ma_data` (misaligned accesses,\n", + "which halt this course's cores).\n", + "\n", + "The environment:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val tests = os.pwd / \"riscv\" / \"programs\" / \"riscv-tests\"\n", + "println(os.read(tests / \"riscv_test.h\"))\n", + "println(os.read(tests / \"EXCLUDED\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And the first cases of `add` after expansion (`;` separates instructions on a line; `0xffff...`\n", + "values are written for 64-bit registers and masked to 32 bits by the expression around them):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "os.read.lines(tests / \"rv32ui\" / \"add.S\").filter(_.contains(\"test_\")).take(3).foreach(println)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# On the golden model\n", + "\n", + "`IsaSim` first: it needs no hardware, so this runs even before the exercises of 5.2-5.4 are done.\n", + "A test that the model fails would mean a misreading of the specification in the model itself." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val all = Programs.images(\"programs/riscv-tests/rv32ui\") // each test, by name, assembled once\n", + "val names = all.map(_._1)\n", + "val images = all.toMap\n", + "def outcome(halt: Option[Halt], a0: Long) =\n", + " if (halt.contains(Halt.Ecall) && a0 == 0) \"pass\"\n", + " else if (halt.contains(Halt.Ecall)) s\"FAIL (case ${a0 >> 1})\"\n", + " else s\"FAIL (stopped: ${halt.getOrElse(\"no halt\")})\"\n", + "\n", + "val model = names.map { name =>\n", + " val sim = new IsaSim(images(name))\n", + " val trace = sim.run(100000)\n", + " name -> (outcome(sim.halted, sim.reg(riscv.Reg(\"a0\"))), trace.size)\n", + "}.toMap\n", + "for (row <- names.grouped(4)) println(row.map(n => f\"$n%-7s ${model(n)._1}%-5s\").mkString(\" \"))\n", + "assert(model.values.forall(_._1 == \"pass\"))\n", + "println(s\"${names.size} tests, ${model.values.map(_._2).sum} instructions: all pass on the golden model\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# On the single-cycle core\n", + "\n", + "Now the core, in one simulation (the core is compiled once; `CoSim.load` writes each test into\n", + "the RAM and resets the core). For each test, `CoSim.compare` also checks every retired instruction\n", + "against the golden model, so a test passes here only if the core gets the right answer *the same\n", + "way*." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val start = System.nanoTime\n", + "val core = scala.collection.mutable.Map[String, String]()\n", + "simulate(new SingleCycleSystem) { c =>\n", + " for (name <- names) {\n", + " val difference = CoSim.compare(c, images(name))\n", + " // no difference: the core halted as the golden model did, with ECALL, so a0 holds the result\n", + " core(name) = difference.map(_ => \"DIFFERS\").getOrElse(outcome(Some(Halt.Ecall), CoSim.reg(c, riscv.Reg(\"a0\"))))\n", + " difference.foreach(d => println(s\"$name: $d\"))\n", + " }\n", + "}\n", + "val seconds = (System.nanoTime - start) / 1e9\n", + "val excluded = os.read.lines(tests / \"EXCLUDED\").map(_.takeWhile(_ != ':'))\n", + "println(f\"${\"test\"}%-8s ${\"golden model\"}%-14s ${\"core\"}%-8s instructions\")\n", + "for (name <- names) println(f\"$name%-8s ${model(name)._1}%-14s ${core(name)}%-8s ${model(name)._2}\")\n", + "for (name <- excluded) println(f\"$name%-8s ${\"unsupported\"}%-14s ${\"unsupported\"}%-8s\")\n", + "println(f\"${names.count(core(_) == \"pass\")} of ${names.size} pass on the core, in $seconds%.0f s (simulation included)\")\n", + "assert(names.forall(core(_) == \"pass\"))\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Each core instruction takes one clock cycle, so the number of instructions is also the number of\n", + "cycles. Most of the time goes into compiling the simulation and into the testbench, which\n", + "peeks the retire port every cycle.\n", + "\n", + "---\n", + "# You're done!\n", + "\n", + "The single-cycle core passes the official tests. It is slow in another sense, though: its clock\n", + "period must cover the longest instruction, a load, from fetch to write back. The next notebooks\n", + "split that path into stages and run several instructions at once: a\n", + "[pipeline](5.6_pipeline.ipynb).\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/5.6_pipeline.ipynb b/5.6_pipeline.ipynb new file mode 100644 index 0000000..5ed5bc2 --- /dev/null +++ b/5.6_pipeline.ipynb @@ -0,0 +1,307 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.6: A Five-Stage Pipeline\n", + "**Prev: [The Official RISC-V Tests](5.5_compliance.ipynb)**
\n", + "**Next: [Hazards](5.7_hazards.ipynb)**
\n", + "\n", + "## Motivation\n", + "The single-cycle processor of [Module 5.4](5.4_single_cycle.ipynb) does all the work of an\n", + "instruction in one clock cycle, so the clock period must cover the slowest instruction from start\n", + "to end: fetch, decode, register read, ALU, memory, write back. A **pipeline** cuts that path into\n", + "stages with registers between them, and works on several instructions at once, one per stage, like\n", + "an assembly line: the clock period only has to cover the slowest stage, and an instruction still\n", + "finishes every cycle.\n", + "\n", + "This notebook builds the classic five-stage pipeline: fetch (IF), decode and register read (ID),\n", + "execute (EX), memory (MEM) and write back (WB). It also meets the price of overlapping\n", + "instructions: *hazards*. An instruction may need a result that an older one has not written yet\n", + "(a data hazard), and the instructions fetched after a jump may not be the ones that run next (a\n", + "control hazard). This notebook handles control hazards and halts; data hazards it avoids with\n", + "nops, and the next one handles them in hardware.\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.util._\n", + "import chisel3.simulator.PeekPokeAPI._\n", + "import riscv._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Stages and stage registers\n", + "\n", + "Each stage passes its instruction to the next through a register: IF/ID, ID/EX, EX/MEM and MEM/WB,\n", + "each a `Bundle` of what the later stages need, wrapped in `Valid` (a stage may hold no instruction:\n", + "a *bubble*). `Stage` builds such a register: it takes the next stage's input at each clock edge,\n", + "or a bubble when it is *flushed*, and has an enable for the stalls of the next notebook (Chisel's\n", + "`RegEnable` does the same without the flush). The datapath blocks are the ones of 5.2-5.4.\n", + "\n", + "The interesting part is what happens between the stages:\n", + "\n", + "- **EX** resolves jumps and branches. The pipeline has fetched two more instructions by then (at\n", + " pc + 4 and pc + 8, a guess that the branch is not taken); if the branch is taken, they are on\n", + " the wrong path and must be *flushed*, and fetch restarts at the target.\n", + "- **MEM** is the last stage that can find a reason to halt (a misaligned or out-of-range access).\n", + " An instruction that halts the core must not let any younger instruction change memory (in MEM)\n", + " or registers (in WB), so it flushes them all and fetching stops.\n", + "- **WB** writes the register file and reports the instruction on the retire port, which the\n", + " golden model compares as for the single-cycle core." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"PipelinedCore.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Exercise: the flushes\n", + "\n", + "`riscv.PipelineFlush` decides which stage registers take a bubble: `redirect` is a jump or taken\n", + "branch in EX, `halt` a halting instruction in MEM. Complete\n", + "`riscv/src/main/scala/riscv/PipelineFlush.scala`, restart the kernel and run the notebook again\n", + "(until then, the cells that build the core stop with a `NotImplementedError`, as do those of 5.2-5.4\n", + "if their exercises are not done). Think about which instructions are younger than the one in EX,\n", + "and than the one in MEM, and where each of them is." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new PipelineFlush) { c =>\n", + " for (redirect <- Seq(false, true); halt <- Seq(false, true)) {\n", + " c.io.redirect.poke(redirect.B)\n", + " c.io.halt.poke(halt.B)\n", + " c.io.flushIfId.expect((redirect || halt).B, s\"redirect $redirect, halt $halt\")\n", + " c.io.flushIdEx.expect((redirect || halt).B, s\"redirect $redirect, halt $halt\")\n", + " c.io.flushExMem.expect(halt.B, s\"redirect $redirect, halt $halt: the jump itself goes on\")\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  io.flushIfId  := io.redirect || io.halt\n",
+    "  io.flushIdEx  := io.redirect || io.halt\n",
+    "  io.flushExMem := io.halt // the jump or branch in EX itself goes on\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Data hazards, and nops\n", + "\n", + "An instruction reads its registers in ID and its result is written in WB, three stages later. If\n", + "the next instruction uses that result, it reads the register too early and gets the old value:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val program = \"\"\"\n", + " li a0, 5\n", + " addi a1, a0, 1 # needs a0 = 5\n", + " ecall\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new PipelinedSystem) { c =>\n", + " println(CoSim.compare(c, Asm(program)).getOrElse(\"no difference\"))\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`addi` read `a0` while `li` was still in EX. The register file is written in the first half of a\n", + "cycle and read in the second, so a result can be read in the cycle its instruction is in WB: an\n", + "instruction that uses it must come three instructions later, with two others between. Until the\n", + "hardware handles it, the program can make room with `nop`s. `Asm.padded(source, 2)` assembles a\n", + "program with two nops after every instruction (inside pseudo-instructions too), which is enough for\n", + "any program:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new PipelinedSystem) { c =>\n", + " println(CoSim.compare(c, Asm.padded(program, 2)).getOrElse(\"no difference\"))\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Running programs\n", + "\n", + "The Fibonacci and factorial programs, padded, retire exactly as on the golden model, and so do\n", + "random programs. The cycle count shows the cost: the nops are instructions too, each taken branch\n", + "or jump wastes two cycles on flushed instructions, and filling the pipeline takes four." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def cycles(c: PipelinedSystem, image: Seq[Long]): (Int, Int) = {\n", + " CoSim.load(c, image)\n", + " var n = 0\n", + " while (!c.io.halted.peek().litToBoolean) { c.clock.step(); n += 1 }\n", + " (n, new IsaSim(image).run().size) // cycles, instructions\n", + "}\n", + "simulate(new PipelinedSystem) { c =>\n", + " for (name <- Seq(\"fib\", \"fact\")) {\n", + " val source = Programs.source(\"programs/src\", name)\n", + " CoSim.compare(c, Asm.padded(source, 2)).foreach(d => sys.error(s\"$name: $d\"))\n", + " val useful = new IsaSim(Asm(source)).run().size\n", + " val (n, retired) = cycles(c, Asm.padded(source, 2))\n", + " println(f\"$name%-5s $useful%4d instructions, $retired%4d with the nops, $n%4d cycles\")\n", + " }\n", + " for (seed <- 1L to 5L)\n", + " CoSim.compare(c, Asm.padded(RandomProgram(seed), 2)).foreach(d => sys.error(s\"RandomProgram($seed): $d\"))\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Halting\n", + "\n", + "A halting instruction flushes everything behind it, so nothing younger takes effect. In this\n", + "program (not padded: the two nops give `auipc`'s result time to reach the `sw`), the first store\n", + "is in EX and the second in ID when `ecall` reaches MEM. Both are flushed before they reach MEM,\n", + "and nothing retires after `ecall`: `CoSim.compare` checks that too, a few cycles past the halt." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new PipelinedSystem) { c =>\n", + " val source = \"auipc t0, 0\\nnop\\nnop\\necall\\nsw t0, 0(t0)\\nsw t0, 4(t0)\"\n", + " println(CoSim.compare(c, Asm(source)).getOrElse(\"no difference: the stores never happened\"))\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# And the official tests?\n", + "\n", + "The riscv-tests of [Module 5.5](5.5_compliance.ipynb) are full of back-to-back dependent\n", + "instructions, so they fail on this pipeline as they are; padded with nops they grow so much that\n", + "their branches to `fail` no longer reach (a branch reaches 4 KB). The [next notebook](5.7_hazards.ipynb) removes the\n", + "need for nops: it forwards results from the later stages to EX and stalls when it must, and then\n", + "the official tests run unchanged.\n", + "\n", + "---\n", + "# You're done!\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/5.7_hazards.ipynb b/5.7_hazards.ipynb new file mode 100644 index 0000000..25eca72 --- /dev/null +++ b/5.7_hazards.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.7: Hazards\n", + "**Prev: [A Five-Stage Pipeline](5.6_pipeline.ipynb)**
\n", + "**Next: [A Bus and a UART](5.8_bus_and_mmio.ipynb)**
\n", + "\n", + "## Motivation\n", + "The pipeline of [Module 5.6](5.6_pipeline.ipynb) needs two nops between an instruction and the\n", + "next one that uses its result. That costs cycles, and it is not something to ask of a compiler\n", + "or of the official tests. This notebook makes the pipeline handle its hazards in hardware:\n", + "\n", + "- it **forwards** a result to the instruction that needs it as soon as the result exists, instead\n", + " of waiting until it is written to the register file;\n", + "- it **stalls** for one cycle when even forwarding is too late (a value loaded from memory, used\n", + " right away), and while the memory has not answered;\n", + "- and it keeps flushing the wrong path after a jump or taken branch, as in 5.6.\n", + "\n", + "The result runs any RV32I program as it is: the official tests of [Module 5.5](5.5_compliance.ipynb)\n", + "pass on it.\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.util._\n", + "import chisel3.simulator.PeekPokeAPI._\n", + "import riscv._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Every hazard, and what resolves it\n", + "\n", + "| Hazard | Example | Resolved by | Signal in `ForwardingCore` |\n", + "|---|---|---|---|\n", + "| A result is needed one instruction later | `li a0, 5` then `addi a1, a0, 1` | forwarding from EX/MEM to EX | `fromExMem` into `Forward` |\n", + "| A result is needed two instructions later | `li a0, 5`, any, `addi a1, a0, 1` | forwarding from MEM/WB to EX | `fromMemWb` into `Forward` |\n", + "| A result is needed three instructions later | the same, two between | a bypass in ID, as if the register file were written before it is read | `wbRd`, `wbValue` (5.6) |\n", + "| A loaded value is needed right away | `lw a0, 0(t0)` then `addi a1, a0, 1` | one-cycle stall: IF and ID hold, EX gets a bubble; then MEM/WB forwards | `loadUse` |\n", + "| A jump or taken branch | `beq` resolved in EX | predict not taken; flush IF/ID and ID/EX, fetch the target | `redirect`, `PipelineFlush` (5.6) |\n", + "| An instruction halts the core | `ecall` in MEM | flush IF/ID, ID/EX and EX/MEM; fetch no more | `haltInMem`, `PipelineFlush` (5.6) |\n", + "| The data memory answers late | a slow bus | everything holds (WB gets bubbles); EX keeps its forwarded operands | `memWait` |\n", + "\n", + "The instruction memory must still answer in the same cycle: a slow fetch needs a core that keeps\n", + "its fetch request while a jump redirects it, which [Module 5.8](5.8_bus_and_mmio.ipynb) discusses with the bus. One more\n", + "detail: a store that needs a just-loaded value only as the data to store also waits a cycle,\n", + "although that value could be forwarded from MEM to MEM; the simpler rule costs a cycle, not\n", + "correctness.\n", + "\n", + "Forwarding takes the *newest* result: when the instructions in both MEM and WB write the\n", + "register, the one in MEM is younger, and its value is the one the program means. And it never\n", + "forwards for `x0`, which stays 0 whatever an instruction writes to it." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Exercise: forwarding\n", + "\n", + "`riscv.Forward` chooses the value of one source register for the instruction in EX: from the\n", + "instruction one ahead (EX/MEM), from the one two ahead (MEM/WB), or the value read in ID.\n", + "Complete `riscv/src/main/scala/riscv/Forward.scala`, restart the kernel and run the notebook again\n", + "(the cells that build the core stop with a `NotImplementedError` until then, and also until the\n", + "exercises of 5.2-5.4 and 5.6 are done: the core uses them all)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new Forward) { c =>\n", + " def check(rs: Int, ex: Option[(Int, Int)], wb: Option[(Int, Int)], expected: Int) = {\n", + " c.io.rs.poke(rs.U)\n", + " c.io.regValue.poke(1.U)\n", + " for ((port, r) <- Seq(c.io.exMem -> ex, c.io.memWb -> wb)) {\n", + " port.valid.poke(r.isDefined.B)\n", + " port.bits.rd.poke(r.map(_._1).getOrElse(0).U)\n", + " port.bits.value.poke(r.map(_._2).getOrElse(0).U)\n", + " }\n", + " c.io.value.expect(expected.U, s\"rs $rs, EX/MEM $ex, MEM/WB $wb\")\n", + " }\n", + " check(5, None, None, 1) // nothing to forward: the register file's value\n", + " check(5, Some(5 -> 2), None, 2)\n", + " check(5, None, Some(5 -> 3), 3)\n", + " check(5, Some(5 -> 2), Some(5 -> 3), 2) // the newest\n", + " check(5, Some(6 -> 2), Some(5 -> 3), 3)\n", + " check(5, Some(6 -> 2), Some(7 -> 3), 1) // neither is for rs\n", + " check(0, Some(0 -> 2), Some(0 -> 3), 1) // never x0\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  def has(r: Valid[Result]) = r.valid && r.bits.rd =/= 0.U && r.bits.rd === io.rs\n",
+    "  io.value := MuxCase(io.regValue, Seq(has(io.exMem) -> io.exMem.bits.value, has(io.memWb) -> io.memWb.bits.value))\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The core\n", + "\n", + "`riscv.ForwardingCore` is the pipeline of 5.6 with these changes: EX takes its operands through two\n", + "`Forward`s; `loadUse` holds IF/ID and the pc and sends a bubble into EX; `memWait` holds every\n", + "stage, sends bubbles into WB, and keeps EX's forwarded operands; and a redirect waits while the\n", + "pipeline holds (a flush would remove the instruction that is waiting in EX)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"ForwardingCore.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Testing the hazards\n", + "\n", + "One short program per hazard of the table, without nops, each compared instruction by instruction\n", + "with the golden model. They include a store on the wrong path of a jump and a store behind a halt,\n", + "which must have no effect." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val hazards = Seq(\n", + " \"EX/MEM to EX\" -> \"li a0, 5\\naddi a1, a0, 1\\necall\",\n", + " \"MEM/WB to EX\" -> \"li a0, 5\\nnop\\naddi a1, a0, 1\\necall\",\n", + " \"the newest result wins\" -> \"li a0, 1\\nli a0, 2\\nadd a1, a0, a0\\necall\",\n", + " \"x0 is not forwarded\" -> \"addi zero, zero, 7\\nadd a0, zero, zero\\necall\",\n", + " \"load-use\" -> \"la t0, d\\nlw a0, 0(t0)\\naddi a1, a0, 1\\necall\\n.data\\nd: .word 41\",\n", + " \"load then store\" -> \"la t0, d\\nlw a0, 0(t0)\\nsw a0, 4(t0)\\nlw a1, 4(t0)\\necall\\n.data\\nd: .word 41, 0\",\n", + " \"branch on a loaded value\" -> \"la t0, d\\nlw a0, 0(t0)\\nbnez a0, 1f\\nebreak\\n1: ecall\\n.data\\nd: .word 1\",\n", + " \"jal link used at once\" -> \"jal ra, 1f\\nebreak\\n1: addi a0, ra, 0\\necall\",\n", + " \"wrong-path stores\" -> \"la t0, d\\nj 1f\\nsw t0, 0(t0)\\n1: lw a0, 0(t0)\\necall\\n.data\\nd: .word 7\",\n", + " \"a store behind a halt\" -> \"la t0, d\\nebreak\\nsw t0, 0(t0)\\n.data\\nd: .word 7\"\n", + ")\n", + "simulate(new ForwardingSystem) { c =>\n", + " for ((name, source) <- hazards) {\n", + " CoSim.compare(c, Asm(source)).foreach(d => sys.error(s\"$name: $d\"))\n", + " println(s\"ok: $name\")\n", + " }\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The official tests, on the pipeline\n", + "\n", + "The rv32ui tests, as they are (no nops), on the pipelined core, again compared instruction by\n", + "instruction with the golden model:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val tests = Programs.images(\"programs/riscv-tests/rv32ui\") // each test, by name, assembled\n", + "val start = System.nanoTime\n", + "simulate(new ForwardingSystem) { c =>\n", + " val failed = tests.filter { case (name, image) =>\n", + " val bad = CoSim.compare(c, image).isDefined || CoSim.reg(c, riscv.Reg(\"a0\")) != 0\n", + " if (bad) println(s\"FAIL: $name\")\n", + " bad\n", + " }\n", + " println(\n", + " f\"${tests.size - failed.size} of ${tests.size} pass on the pipeline, in ${(System.nanoTime - start) / 1e9}%.0f s\"\n", + " )\n", + " assert(failed.isEmpty)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# How much faster?\n", + "\n", + "A **cycle counter** (`CoSim.timed`) gives the cycles a program takes; divided by the instructions\n", + "it retires, that is its CPI, cycles per instruction. The single-cycle core takes exactly one\n", + "cycle per instruction, but a long clock period; the pipeline has a short one, and a CPI above 1:\n", + "it loses four cycles filling the pipeline, one per load-use stall, and two for the instructions\n", + "flushed after each jump or taken branch. Without forwarding (5.6), the nops are instructions too,\n", + "and the CPI per useful instruction is far worse:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val programs = Seq(\"fib\", \"fact\").map(n => n -> Programs.source(\"programs/src\", n))\n", + "// the cycles each program takes on one core (one simulation for all the programs)\n", + "def measure(system: => RiscvSystem, images: Seq[Seq[Long]]): Seq[Int] = {\n", + " var cycles = Seq.empty[Int]\n", + " simulate(system) { c =>\n", + " cycles = images.map { image =>\n", + " CoSim.load(c, image)\n", + " val (trace, n) = CoSim.timed(c)\n", + " assert(trace.lastOption.exists(_.halt.isDefined), \"the program did not halt\")\n", + " n\n", + " }\n", + " }\n", + " cycles\n", + "}\n", + "val padded = measure(new PipelinedSystem, programs.map(p => Asm.padded(p._2, 2)))\n", + "val forward = measure(new ForwardingSystem, programs.map(p => Asm(p._2)))\n", + "for ((((name, source), p), f) <- programs.zip(padded).zip(forward)) {\n", + " val useful = new IsaSim(Asm(source)).run().size // also the single-cycle core's cycles\n", + " println(\n", + " f\"$name%-5s $useful%4d instructions: single-cycle $useful%4d cycles, \" +\n", + " f\"5.6 with nops $p%4d (CPI ${p.toDouble / useful}%.2f), 5.7 $f%4d (CPI ${f.toDouble / useful}%.2f)\"\n", + " )\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The pipeline needs more cycles than the single-cycle core, but each of its cycles is shorter: one\n", + "stage instead of the whole path, so ideally up to five times shorter, and less in practice (the\n", + "stages are not equally long, the stage registers add delay, and forwarding lengthens EX). Whether\n", + "it runs a program in less time depends on those delays, which a synthesis tool reports (Module\n", + "5.10).\n", + "\n", + "---\n", + "# You're done!\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/5.8_bus_and_mmio.ipynb b/5.8_bus_and_mmio.ipynb new file mode 100644 index 0000000..94423e6 --- /dev/null +++ b/5.8_bus_and_mmio.ipynb @@ -0,0 +1,292 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.8: A Bus and a UART\n", + "**Prev: [Hazards](5.7_hazards.ipynb)**
\n", + "**Next: [Debugging and Verification](5.9_debug_and_verify.ipynb)**
\n", + "\n", + "## Motivation\n", + "So far the processor's memory has been ideal: a RAM next to the core that answers in the same\n", + "cycle. In a real system, the core reaches memory and devices through a **bus**: it sends a\n", + "request, the bus routes it by address, and the answer may take cycles. Devices sit on the same bus\n", + "as memory, at their own addresses, and programs control them with ordinary loads and stores:\n", + "**memory-mapped I/O**.\n", + "\n", + "This notebook puts the pipelined core of [Module 5.7](5.7_hazards.ipynb) on a bus with the RAM\n", + "and a **UART**, the serial port of every microcontroller, and makes it print \"Hello, world!\".\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.util._\n", + "import chisel3.simulator.PeekPokeAPI._\n", + "import riscv._" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The bus\n", + "\n", + "The core's data port is a `MemPort`: a request (`Decoupled`: address, data, byte strobes) and an\n", + "answer (`Valid`: data, or an error). The rules of this bus:\n", + "\n", + "- **Handshake.** A request is taken when `valid` and `ready` are both high in a cycle (`fire`).\n", + " The core then waits for the answer; it sends each request once (`ForwardingCore` remembers that\n", + " it has sent it).\n", + "- **One request at a time, in order.** The bus is busy from a request until its answer, so\n", + " answers come back in the order of the requests.\n", + "- **Backpressure.** A device answers when it can. Until then the core waits, the whole pipeline\n", + " holding (the `memWait` of 5.7).\n", + "- **Errors.** An address that no device holds is answered with an error, which halts the core with\n", + " `BadAddress`, as an address outside the RAM did before.\n", + "\n", + "The bus registers each request, so every load and store now takes a cycle more. Instruction fetch\n", + "stays on the RAM's own port, which answers in the same cycle (a fetch through the bus would need a\n", + "core that keeps its fetch request when a jump redirects it).\n", + "\n", + "| Address | Device | Register |\n", + "|---|---|---|\n", + "| `0x8000_0000` - `0x8000_ffff` | RAM (64 KB) | code, data, stack |\n", + "| `0x1000_0000` | UART | data: write a byte to send it |\n", + "| `0x1000_0004` | UART | status: 1 while a byte is being sent |" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"Bus.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The UART\n", + "\n", + "A UART sends a byte over one wire, `txd`, one bit at a time, at a rate both sides agree on (the\n", + "baud rate; here a bit lasts `divider` clock cycles). The line is 1 when idle. A byte goes as a\n", + "*frame* of 10 bits: a **start bit** (0), which tells the receiver a byte is coming, the 8 **data\n", + "bits**, least significant first, and a **stop bit** (1), which returns the line to idle.\n", + "\n", + "The UART on the bus has a data register and a status register. A write to the data register while\n", + "the previous byte is still being sent is not answered until the transmitter is free: the store\n", + "waits, so a program can write bytes one after the other without checking the status.\n", + "\n", + "## Exercise: the transmitter\n", + "\n", + "Complete the two `???` of `riscv/src/main/scala/riscv/UartTx.scala`: the frame to load (stop bit,\n", + "data, start bit: the start bit must be in bit 0, as it goes first) and how the frame moves on after\n", + "each bit. Restart the kernel and run the notebook again (the cells that build the transmitter or\n", + "the system stop with a `NotImplementedError` until then, as do the exercises of 5.2-5.7).\n", + "\n", + "`UartReceiver` is a receiver in software: fed `txd` once per cycle, it returns each byte." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new UartTx(divider = 4)) { c =>\n", + " val receiver = new UartReceiver(4)\n", + " val text = \"Hi!\"\n", + " val out = new StringBuilder\n", + " var pending = text.toList\n", + " var line = new StringBuilder // txd, one character per bit\n", + " for (cycle <- 0 until 150) {\n", + " val busy = c.io.busy.peek().litToBoolean\n", + " c.io.send.valid.poke((!busy && pending.nonEmpty).B)\n", + " c.io.send.bits.poke(pending.headOption.getOrElse(' ').toInt.U)\n", + " if (!busy && pending.nonEmpty) pending = pending.tail\n", + " val txd = c.io.txd.peek().litToBoolean\n", + " if (cycle % 4 == 0 && cycle < 4 * 12) line += (if (txd) '1' else '0')\n", + " out ++= receiver.sample(txd)\n", + " c.clock.step()\n", + " }\n", + " println(s\"txd, one sample per bit: $line\")\n", + " println(\"idle 1, then 'H' (0x48 = 01001000): start 0, data 00010010 (least significant first), stop 1,\")\n", + " println(\"then the start bit of 'i' (each sample of 'H' is taken in the last cycle of its bit)\")\n", + " assert(out.toString == text, out.toString)\n", + "}\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "  val frame = RegInit(1.U(10.W))                    // the bits still to send, the next one in bit 0\n",
+    "  val left  = RegInit(0.U(4.W))                     // how many\n",
+    "  val count = RegInit(0.U(log2Ceil(divider + 1).W)) // cycles left of the current bit\n",
+    "  io.busy := left =/= 0.U\n",
+    "  io.txd  := Mux(io.busy, frame(0), true.B)\n",
+    "\n",
+    "  when(!io.busy && io.send.valid) {\n",
+    "    frame := 1.U(1.W) ## io.send.bits ## 0.U(1.W)\n",
+    "    left  := 10.U\n",
+    "    count := (divider - 1).U\n",
+    "  }.elsewhen(io.busy) {\n",
+    "    when(count === 0.U) {\n",
+    "      frame := frame >> 1\n",
+    "      left  := left - 1.U\n",
+    "      count := (divider - 1).U\n",
+    "    }.otherwise(count := count - 1.U)\n",
+    "  }\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Hello, world\n", + "\n", + "`riscv.SocSystem` is the system on a chip: the forwarding core, the bus, the RAM and the UART.\n", + "The program stores each byte of the string to the UART's data register:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val hello = Programs.source(\"programs/src\", \"hello\")\n", + "println(hello)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`Soc.run` runs it and decodes what the UART sends. The golden model has a UART too (`UartModel`,\n", + "which sends at once; `SocSystem.model` gives it), so `CoSim.compare` can check every instruction the\n", + "core retires, the stores to the UART included:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(new SocSystem) { c =>\n", + " val image = Asm(hello)\n", + " CoSim.compare(c, image).foreach(d => sys.error(d)) // SocSystem's golden model has the UART\n", + " CoSim.load(c, image)\n", + " print(Soc.run(c))\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# What the bus costs\n", + "\n", + "The bus registers each request, so every load and store takes a cycle more than with the RAM next\n", + "to the core, and a store to the UART waits for the whole previous frame. In cycles:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val fact = Asm(Programs.source(\"programs/src\", \"fact\"))\n", + "def cycles(c: RiscvSystem, image: Seq[Long]): Int = { CoSim.load(c, image); CoSim.timed(c)._2 }\n", + "var near = 0\n", + "simulate(new ForwardingSystem) { c => near = cycles(c, fact) }\n", + "simulate(new SocSystem) { c =>\n", + " println(s\"fact: $near cycles with the RAM next to the core, ${cycles(c, fact)} through the bus\")\n", + " println(s\"hello: ${cycles(c, Asm(hello))} cycles to the ecall (the UART sends 10 bits of 4 cycles per byte)\")\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# You're done!\n", + "\n", + "Without CSRs there are no interrupts, so the UART cannot tell the core when it is done: the core\n", + "waits on the bus instead. A program could also read the status register in a loop, but its\n", + "instructions would then depend on timing (the golden model's UART is never busy), so\n", + "`CoSim.compare` could no longer check it instruction by instruction. Waiting on the bus is enough\n", + "for a program that only prints.\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/5.9_debug_and_verify.ipynb b/5.9_debug_and_verify.ipynb new file mode 100644 index 0000000..27e67fe --- /dev/null +++ b/5.9_debug_and_verify.ipynb @@ -0,0 +1,424 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"Chisel" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Module 5.9: Debugging and Verification\n", + "**Prev: [A Bus and a UART](5.8_bus_and_mmio.ipynb)**
\n", + "**Next: [From Chisel to an FPGA](5.10_to_silicon.ipynb)**
\n", + "\n", + "## Motivation\n", + "Every core of this module has been checked the same way: run a program on the core and on the\n", + "golden model, and compare what they retire. This notebook looks at that method, and at two more,\n", + "on a bug planted in the forwarding unit of [Module 5.7](5.7_hazards.ipynb):\n", + "\n", + "- the **retire trace**, which says *which* instruction went wrong;\n", + "- **waveforms**, which say *why*, signal by signal and cycle by cycle;\n", + "- a **formal check**, which proves a unit right for *every* input, or finds an input that breaks\n", + " it, without a test program.\n", + "\n", + "The cells that build a core stop with a `NotImplementedError` until the exercises of 5.2-5.7 are\n", + "done (the forwarding core uses them all, `Forward` of 5.7 included).\n", + "\n", + "## Setup\n", + "If a cell fails or hangs, see [Troubleshooting](docs/troubleshooting.md)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-ivy.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "interp.load.module(os.pwd / \"source\" / \"load-riscv.sc\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import chisel3._\n", + "import chisel3.util._\n", + "import chisel3.simulator.PeekPokeAPI._\n", + "import riscv._\n", + "\n", + "// Formal.prove (below), through load-ivy.sc's scrub: Almond cannot show an error raised while Chisel\n", + "// builds a module (such as an unfinished exercise) without it\n", + "def prove(check: => RawModule): Option[String] = scrub(Formal.prove(check))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# The retire trace\n", + "\n", + "Each core has a **retire port** (`io.retire`): in each cycle in which an instruction completes, it\n", + "reports the instruction and everything it did. It follows RVFI, the RISC-V Formal Interface that\n", + "riscv-formal and many verification tools use, in a smaller form:\n", + "\n", + "| `RetireInfo` | RVFI | Meaning |\n", + "|---|---|---|\n", + "| `valid` (of the `Valid` around `RetireInfo`) | `rvfi_valid` | an instruction retires in this cycle |\n", + "| `pc`, `inst` | `rvfi_pc_rdata`, `rvfi_insn` | its address and its word |\n", + "| `nextPc` | `rvfi_pc_wdata` | the address of the next instruction |\n", + "| `rd`, `rdValue` | `rvfi_rd_addr`, `rvfi_rd_wdata` | the register it writes (0: none) and the value |\n", + "| `mem` | `rvfi_mem_addr`, `rvfi_mem_rdata`/`wdata`, masks | its load or store |\n", + "| `halt` | `rvfi_halt`; `rvfi_trap` for `Illegal`, `Misaligned`, `BadAddress` | it stops the core, and why |\n", + "\n", + "`CoSim.run` collects the retired instructions, and each prints as a line of a trace, disassembled\n", + "(`Rv32i.disassemble`). The golden model reports the same records, so the two traces can be\n", + "compared line by line: that is all `CoSim.compare` does." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val fib = Asm(Programs.source(\"programs/src\", \"fib\"))\n", + "simulate(new ForwardingSystem) { c =>\n", + " CoSim.load(c, fib)\n", + " CoSim.run(c).take(12).foreach(println)\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# A planted bug\n", + "\n", + "`OldestFirst` is a forwarding unit with a plausible mistake: when the instructions in both EX/MEM\n", + "and MEM/WB write the register, it forwards the one in MEM/WB, the *older* result. `ForwardingCore`\n", + "takes the unit to build as a parameter, so the bug goes into an otherwise correct core:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class OldestFirst extends Forward {\n", + " def writes(r: Valid[Result]) = r.valid && r.bits.rd =/= 0.U && r.bits.rd === io.rs\n", + " io.value := MuxCase(\n", + " io.regValue,\n", + " Seq(writes(io.memWb) -> io.memWb.bits.value, writes(io.exMem) -> io.exMem.bits.value)\n", + " )\n", + "}\n", + "def buggy = new CoreSystem(new ForwardingCore(forwardUnit = new OldestFirst))\n", + "val twice = \"li a0, 1\\nli a0, 2\\nadd a1, a0, a0\\necall\" // the smallest program that shows it" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Would the tests find it? `Programs.corpus` is every program of the course (but `hello`, which\n", + "needs the UART of 5.8), random programs (20 here) and the official tests; each is compared with the golden model:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val corpus = Programs.corpus(seeds = 1L to 20L)\n", + "simulate(buggy) { c =>\n", + " val found = corpus.filter { case (_, image) => CoSim.compare(c, image).isDefined }.map(_._1)\n", + " println(s\"${found.size} of ${corpus.size} programs find the bug: ${found.mkString(\", \")}\")\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A program finds the bug only if it writes a register in two instructions in a row and reads it in\n", + "the next: most of the official tests do (they compute a value, then check it), `fact` does, some of the\n", + "random programs do, and `fib` and `sum` do not. A test suite finds a bug only if some\n", + "program happens to exercise it, which is why programs written by others, for other reasons, and\n", + "random ones are worth running.\n", + "\n", + "`twice`, defined above, is the smallest program that shows it:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(buggy) { c =>\n", + " println(CoSim.compare(c, Asm(twice)).getOrElse(\"no difference\"))\n", + " CoSim.load(c, Asm(twice))\n", + " println(\"\\nthe core's trace:\")\n", + " CoSim.run(c).foreach(println)\n", + "}\n", + "println(\"\\nthe golden model's trace:\")\n", + "new IsaSim(Asm(twice)).run().foreach(println)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`instruction 2` counts from 0: it is the third. The trace says which instruction is wrong (`add a1, a0, a0` wrote 2, not 4), and what it computed:\n", + "1 + 1, the first `li`'s value. It does not say why. For that, look inside." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# Waveforms\n", + "\n", + "`simulate(..., waves = \"name\")` dumps every signal of the design in every cycle into a VCD file\n", + "(Module 2.6), which a waveform viewer (GTKWave, Surfer) shows. `riscv.Vcd` reads one in Scala, so\n", + "this notebook can print the signals that matter as a table: one row per cycle, read just before\n", + "the clock edge (what the registers take at that edge).\n", + "\n", + "The units' instances are `rs1Data_f` and `rs2Data_f` (one per source register), and the pipeline\n", + "registers keep their names (`idEx_bits_inst` is the instruction in EX). `vcd(name)` gives a\n", + "signal as a function of time. The table samples each cycle just before its clock edge, from the\n", + "first instruction in EX to the `ecall` (the instructions fetched behind it are flushed), and shows\n", + "what the unit for `rs1` gets and forwards:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "simulate(buggy, waves = \"oldest-first\") { c =>\n", + " CoSim.load(c, Asm(twice))\n", + " CoSim.run(c)\n", + "}\n", + "val vcd = Vcd.read(wavesFile(\"oldest-first\").get)\n", + "\n", + "def signal(name: String) = vcd(s\"core.$name\")\n", + "def unit(port: String) = signal(s\"rs1Data_f.io_$port\") // the forwarding unit of rs1\n", + "def result(stage: String) = { // what the unit gets from a stage ahead: \"x10 = 2\", or dashes\n", + " val (valid, rd, value) = (unit(s\"${stage}_valid\"), unit(s\"${stage}_bits_rd\"), unit(s\"${stage}_bits_value\"))\n", + " (t: Long) => if (valid(t) == 1) f\"x${rd(t)}%-2s = ${value(t)}%-6s\" else \"-\" * 13\n", + "}\n", + "val (inEx, inst, pc) = (signal(\"idEx_valid\"), signal(\"idEx_bits_inst\"), signal(\"idEx_bits_pc\"))\n", + "val (rs, forwarded) = (unit(\"rs\"), unit(\"value\"))\n", + "val (exMem, memWb) = (result(\"exMem\"), result(\"memWb\"))\n", + "def isEcall(t: Long) = Rv32i.decode(inst(t).toLong).exists(_.name == \"ecall\")\n", + "val cycles = vcd.risingEdges(\"core.clock\").map(_ - 1).zipWithIndex.filter { case (t, _) => inEx(t) == 1 }\n", + "assert(cycles.exists(c => isEcall(c._1)), \"the ecall never reached EX\")\n", + "println(\"cycle in EX rs EX/MEM rd = value MEM/WB rd = value forwarded\")\n", + "for ((t, cycle) <- cycles.take(cycles.indexWhere(c => isEcall(c._1)) + 1)) {\n", + " val text = Rv32i.disassemble(inst(t).toLong, pc(t).toLong)\n", + " println(f\"$cycle%5d $text%-24s x${rs(t)}%-2s ${exMem(t)}%19s ${memWb(t)}%19s ${forwarded(t)}\")\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the cycle in which `add a1, a0, a0` is in EX, both stages ahead hold a result for `x10` (`a0`):\n", + "2 from the second `li`, one stage ahead, and 1 from the first. The unit forwards 1. With a bug in\n", + "hand, a waveform is the place to confirm the cause; it is a poor place to search for one, as a\n", + "long program has thousands of cycles and hundreds of signals. The trace narrows the search to one\n", + "instruction, and so to a few cycles." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# A formal check\n", + "\n", + "Co-simulation tries programs; a **formal** tool reasons about all inputs at once. `ForwardCheck`\n", + "puts a forwarding unit next to its specification (the newest valid result for `rs`, never for\n", + "`x0`, else the register file's value), written another way: with `when`s, the older result\n", + "connected first and the newer one after it, so that Chisel's last-connect rule makes the newer one\n", + "win. It has an output `ok` that is 1 when the two agree:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "println(os.read(os.pwd / \"riscv\" / \"src\" / \"main\" / \"scala\" / \"riscv\" / \"ForwardCheck.scala\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`Formal.prove` emits the SystemVerilog of the check, and asks **Yosys** to prove that `ok` is 1\n", + "for every value of the inputs, with Yosys's own SAT solver (the `sat -prove` command). It takes a\n", + "combinational module: the check has no registers. The image\n", + "installs YoWASP's Yosys, compiled to WebAssembly; its first run in a container compiles it, which\n", + "takes about a minute.\n", + "\n", + "`prove` (defined in the Setup) returns None when the proof succeeds, or the counterexample: input\n", + "values for which `ok` is 0. `check` prints either:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def check(name: String, unit: => Forward): Unit =\n", + " if (!Yosys.available) println(s\"$name: no formal check (Yosys is not installed)\")\n", + " else\n", + " println(\n", + " prove(new ForwardCheck(unit)).fold(s\"$name: proved for every input\")(cex => s\"$name, a counterexample:\\n$cex\")\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "check(\"Forward\", new Forward)\n", + "check(\"OldestFirst\", new OldestFirst)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The solver found the situation on its own: both stages valid and writing `rs`, with different\n", + "values. No program was needed, and the check covers all 2^113 combinations of its 113 input bits.\n", + "\n", + "What it does not cover: the proof is about one unit against a specification someone wrote, so a\n", + "mistake in both is not found, nor is a bug in how the core wires the unit. And `sat -prove` checks\n", + "combinational logic: a property over several cycles (say, that a request is answered within 10 cycles) needs\n", + "a bounded model check over a number of steps, or induction, for which SymbiYosys is the usual\n", + "front end; it is not in the image. Co-simulation checks the whole core, but only for the programs\n", + "it runs. The two complement each other.\n", + "\n", + "---\n", + "# Exercise: find the second bug\n", + "\n", + "`ForwardsX0` makes another mistake: it forgets that `x0` is always 0, and forwards a result\n", + "\"written\" to it. Write a program (as assembly in `program`) that the correct core runs as the golden\n", + "model does, and on which the core with `ForwardsX0` differs from it. Then ask the formal check." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class ForwardsX0 extends Forward {\n", + " def writes(r: Valid[Result]) = r.valid && r.bits.rd === io.rs // no check for x0\n", + " io.value := MuxCase(\n", + " io.regValue,\n", + " Seq(writes(io.exMem) -> io.exMem.bits.value, writes(io.memWb) -> io.memWb.bits.value)\n", + " )\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def program: String = ??? // the assembly of your program, ending with ecall" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "val image = Asm(program)\n", + "simulate(new ForwardingSystem) { c => assert(CoSim.compare(c, image).isEmpty, \"the correct core should run it\") }\n", + "simulate(new CoreSystem(new ForwardingCore(forwardUnit = new ForwardsX0))) { c =>\n", + " val difference = CoSim.compare(c, image)\n", + " assert(difference.isDefined, \"the core with ForwardsX0 runs it as the model does: try again\")\n", + " println(difference.get)\n", + "}\n", + "check(\"ForwardsX0\", new ForwardsX0)\n", + "println(\"SUCCESS!!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "\n", + "
\n", + "
\n",
+    "def program: String = \"addi zero, zero, 7\\nadd a0, zero, zero\\necall\"\n",
+    "\n",
+    "// addi writes 7 \"to\" x0 (and changes nothing); the next instruction reads x0 while that addi is\n",
+    "// one stage ahead, so ForwardsX0 forwards 7: a0 = 14 instead of 0. The formal check's\n",
+    "// counterexample has rs = 0.\n",
+    "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "# You're done!\n", + "\n", + "[Return to the top.](#top)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Scala", + "language": "scala", + "name": "scala" + }, + "language_info": { + "codemirror_mode": "text/x-scala", + "file_extension": ".scala", + "mimetype": "text/x-scala", + "name": "scala", + "nbconvert_exporter": "script", + "version": "2.13.18" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c14a005 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,88 @@ +# Contributing + +## Notebooks are committed without outputs + +Commit notebooks without cell outputs, execution counts or editor metadata (such as +`collapsed` or `scrolled`), so that diffs show only real changes. A pre-commit hook strips +them for you: + +```bash +pip install pre-commit +pre-commit install # once per clone: the hook then runs on every `git commit` +pre-commit run --all-files # check (and fix) every file now +``` + +CI runs the same hook and fails if it would change a notebook. + +## Code style + +- **Python:** [black](https://black.readthedocs.io/) with the settings in `pyproject.toml`. +- **Shell:** [shfmt](https://github.com/mvdan/sh) with 4-space indentation (`shfmt -i 4`). +- **Scala:** [scalafmt](https://scalameta.org/scalafmt/) with `.scalafmt.conf`, for + `source/*.sc`, the `riscv/` project and the code cells of the notebooks. + +The pre-commit hooks above run black and shfmt. scalafmt needs a separate binary (download the +version named in `.scalafmt.conf` from its releases, or `cs install scalafmt`); then + +```bash +python3 tools/format-scala.py # formats source/*.sc, riscv/ and every notebook's Scala cells +python3 tools/format-scala.py --check # what CI runs +``` + +`tools/format-scala.py` leaves alone the cells that scalafmt cannot parse, such as a deliberate +syntax error (see its docstring). CI checks all three styles. + +Out of scope: the shell commands inside the `Dockerfile` and the workflow `run:` steps. The formatter versions are pinned in `.pre-commit-config.yaml` +and `.scalafmt.conf`; bump them by hand (`pre-commit autoupdate` for the hooks; a new scalafmt +version also needs its checksum in `.github/workflows/checks.yml`). + +## Checks you can run without a kernel + +```bash +python3 tools/check-versions.py # pinned versions agree across the repository +python3 tests/test_notebooks.py --self-test # links, images, alt text, removed APIs, runtest.py +``` + +`tools/check-versions.py` compares every pinned version with the `Dockerfile` (the files and +patterns are in its `CHECKS` table) and checks that `FIRTOOL_VERSION` is the firtool version +Chisel was published against. To upgrade a version, change it everywhere the script reports. + +`tests/test_notebooks.py` rejects mentions of removed Chisel 3 APIs (its `REMOVED_APIS`). A +deliberate mention, such as a migration note, is +allowed by adding ` ` to `tests/lint-allowlist.txt`; code cells are never allowed. + +## Running the notebooks + +`runtest.py` runs notebooks in the Scala kernel and compares the errors they raise with the +expected ones (exercises with `???` and cells that fail on purpose raise errors by design). +In the Docker image, without network access: + +```bash +docker build -t chisel-bootcamp . +docker run --rm --network none chisel-bootcamp python3 runtest.py 2.1_first_module.ipynb +docker run --rm --network none chisel-bootcamp python3 runtest.py # every notebook +``` + +Locally (see `Install.md`), run `python3 runtest.py ` from the repository root. +`BOOTCAMP_CELL_TIMEOUT` sets the per-cell timeout in seconds (default 600). `runtest.py` treats +every deprecation warning as an unexpected error. The warning names the deprecated call, except +for code in `source/load-ivy.sc`, which only gets a count: compile the suspect definitions in a +cell of their own to see the details. + +## The riscv/ project + +Exercises in `riscv/src/` contain `???`; their reference solutions are in `riscv/solutions/` at the +same paths (see `riscv/DESIGN.md`). `tools/check-solutions.sh` checks that the scaffold compiles +and that the solutions pass every test; run it after changing either. + +## Adding a notebook + +1. Add an entry to the `notebooks` dict in `runtest.py` with the errors it is expected to + raise, in order. CI runs every registered notebook on pushes to `dev` and nightly; a pull + request runs a smoke subset plus the notebooks it changes, or every notebook when it changes + shared files such as `source/` or the Dockerfile (see `tools/ci-notebooks.py`). +2. Link it from the previous notebook's Prev/Next links (and link back to the previous one + from the new notebook), and add it to the outline in `README.md`. +3. Give every image non-empty alt text. +4. Format its Scala cells (`tools/format-scala.py`), then run the checks above and + `runtest.py` on the new notebook. diff --git a/Dockerfile b/Dockerfile index a068584..04c5035 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,20 +1,49 @@ -# First stage : setup the system and environment +# A Java 17 runtime cut down to the modules the course uses (the Scala compiler, Almond, coursier +# and sbt): 92 MB instead of the 172 MB of Alpine's JRE, with a class-data sharing archive so that +# the JVM starts as fast. Its window-system, sound, font and image libraries go (nothing here +# draws, plays or reads images); its cacerts is replaced by the system's (java-cacerts, in the base stage). +FROM alpine:3.22 AS jre +ARG TARGETARCH +ARG BUILDARCH +RUN \ + apk add --no-cache openjdk17-jdk binutils && \ + # Under qemu (an Arm64 image cross-built on x86-64) the JVM crashes while probing SVE + if [ "$TARGETARCH" = "arm64" ] && [ "$BUILDARCH" != "arm64" ]; then export JAVA_TOOL_OPTIONS="-XX:UseSVE=0"; fi && \ + jlink --add-modules java.se,jdk.unsupported,jdk.zipfs,jdk.crypto.ec,jdk.charsets,jdk.management \ + --strip-debug --no-header-files --no-man-pages --generate-cds-archive \ + --output /opt/java && \ + rm /opt/java/lib/libawt_xawt.so /opt/java/lib/libjsound.so /opt/java/lib/libsplashscreen.so \ + /opt/java/lib/libjawt.so /opt/java/lib/liblcms.so /opt/java/lib/libfontmanager.so \ + /opt/java/lib/libjavajpeg.so \ + /opt/java/lib/server/classes_nocoops.jsa # (for heaps over 32 GB) + +# Then set up the system and environment FROM alpine:3.22 AS base ARG TARGETARCH -# Install OpenJDK 17 and runtime dependencies. +# Install the Java runtime above, and the runtime dependencies. # Chisel 7 simulates with ChiselSim, which drives Verilator, so a C++ toolchain -# (g++, make, musl-dev) and Perl (Verilator is a Perl script) are runtime dependencies. +# (g++, make, musl-dev) is a runtime dependency. Verilator's `verilator` command is a Perl wrapper +# around verilator_bin; a shell script below takes its place, so that the image has no Perl. # Stable Alpine ships Verilator for x86-64 only, so both architectures take it from the # edge/community repository; the @edge tag keeps every other package on 3.22. Later apk # calls need --no-cache (or a fresh index) so that the @edge tag still resolves. # On Arm64, firtool (an x86-64 executable, see the intermediate-builder stage) runs -# through qemu-user. +# through qemu-user. ChiselSim needs Verilator 5.026 or newer (older ones abort now and then). +# Yosys (for the formal check of 5.10) is not packaged for stable Alpine; YoWASP's build is Yosys +# compiled to WebAssembly, run by wasmtime (wheels for musl on x86-64 and Arm64), and installed as +# `yosys`. It adds about 115 MB; its first run in a container compiles it (about a minute). +# The course needs only JupyterLab and the Scala kernel: the Python kernel that JupyterLab pulls in +# (ipykernel, IPython, jedi, debugpy) is uninstalled, about 80 MB. The image has no RISC-V +# toolchain (riscv.Asm assembles programs); the host GCC is there for Verilator, which compiles +# C++ only, so its C compiler, link-time optimizer, plugin headers, gcov and static C libraries go +# (about 140 MB), as do Verilator's debug binaries. RUN \ echo "@edge https://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories && \ apk add --no-cache \ - openjdk17-jre-headless \ + zlib \ + java-cacerts \ graphviz \ python3 \ py3-pip \ @@ -25,7 +54,6 @@ RUN \ g++ \ make \ musl-dev \ - perl \ && \ if [ "$TARGETARCH" = "arm64" ]; then apk add --no-cache qemu-x86_64; fi && \ apk add --no-cache --virtual .build-deps \ @@ -33,27 +61,118 @@ RUN \ linux-headers \ python3-dev \ && \ - pip3 install --no-cache-dir --break-system-packages jupyter jupyterlab && \ - find /usr/lib/python3.12 -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true && \ + pip3 install --no-cache-dir --break-system-packages jupyterlab \ + yowasp-yosys==0.71.0.0.post1285 yowasp-runtime==1.96 wasmtime==47.0.1 && \ + pip3 uninstall -y --break-system-packages ipykernel ipython ipython-pygments-lexers jedi parso \ + debugpy prompt-toolkit wcwidth stack-data executing asttokens pure-eval matplotlib-inline \ + comm nest-asyncio nest-asyncio2 psutil pexpect && \ + ln -s "$(command -v yowasp-yosys)" /usr/local/bin/yosys && \ + { find /usr/lib/python3.12 -type d -name __pycache__ -exec rm -rf {} + || true; } 2>/dev/null && \ find /usr/lib/python3.12 -type f -name '*.pyc' -delete && \ find /usr/lib/python3.12 -type f -name '*.pyo' -delete && \ - find /usr/lib/python3.12/site-packages/babel/locale-data -mindepth 1 ! -name 'en_*' -a ! -name 'root.dat' -delete 2>/dev/null || true && \ - find /usr/lib/python3.12/site-packages -type d -name tests -exec rm -rf {} + 2>/dev/null || true && \ - find /usr/lib/python3.12/site-packages -type d -name testing -exec rm -rf {} + 2>/dev/null || true && \ - rm -rf /usr/lib/python3.12/site-packages/pip /usr/lib/python3.12/site-packages/setuptools && \ - apk del --no-cache .build-deps + { find /usr/lib/python3.12/site-packages/babel/locale-data -mindepth 1 ! -name 'en_*' -a ! -name 'root.dat' -delete || true; } 2>/dev/null && \ + { find /usr/lib/python3.12/site-packages -type d -name tests -exec rm -rf {} + || true; } 2>/dev/null && \ + { find /usr/lib/python3.12/site-packages -type d -name testing -exec rm -rf {} + || true; } 2>/dev/null && \ + rm -rf /usr/lib/python3.12/site-packages/pip /usr/lib/python3.12/site-packages/setuptools \ + /usr/lib/python3.12/ensurepip /usr/lib/python3.12/lib2to3 /usr/lib/python3.12/pydoc_data \ + /usr/lib/python3.12/idlelib /usr/lib/python3.12/tkinter /usr/lib/python3.12/turtledemo \ + /usr/lib/python3.12/test /usr/lib/python3.12/site-packages/jupyterlab/galata && \ + find /usr/lib/python3.12/site-packages -name '*.map' -delete && \ + # Yosys's techmap libraries: 5.10 synthesizes for iCE40 and ECP5 only + cd /usr/lib/python3.12/site-packages/yowasp_yosys/share && \ + for d in */; do case "$d" in ice40/|ecp5/|lattice/|include/|python3/|choices/|sdc/) ;; *) rm -r "$d" ;; esac; done && \ + cd / && \ + # (the server must still start without the packages uninstalled above) + python3 -B -c 'import jupyter_server.serverapp, jupyterlab.labapp' && \ + apk del --no-cache .build-deps && \ + # (gcc prints a bare name for what it cannot find: check both paths before deleting) + cc1plus=$(gcc -print-prog-name=cc1plus) && plugin=$(gcc -print-file-name=plugin) && \ + test -x "$cc1plus" && test -d "$plugin" && \ + rm -r "$(dirname "$cc1plus")/cc1" "$(dirname "$cc1plus")/lto1" "$plugin" && \ + rm -f /usr/bin/lto-dump /usr/bin/gcov /usr/bin/gcov-dump /usr/bin/gcov-tool /usr/bin/dwp \ + /usr/lib/libc.a /usr/lib/libstdc++.a /usr/bin/verilator_bin_dbg /usr/bin/verilator_coverage_bin_dbg && \ + # Graphviz: only dot's SVG output is used (its core and dot-layout plugins); the image-format and + # window-system plugins go, with the libraries that only they load (about 25 MB) + cd /usr/lib/graphviz && \ + rm -f libgvplugin_gd.so* libgvplugin_kitty.so* libgvplugin_neato_layout.so* libgvplugin_pango.so* \ + libgvplugin_vt.so* libgvplugin_webp.so* libgvplugin_xlib.so* config6 && \ + dot -c && cd / && \ + libs="aom-libs libdav1d libyuv libavif libheif libwebp libsharpyuv libgd libtiff libjpeg-turbo \ + cairo pango harfbuzz libx11 libxcb libxext libxrender libxft libxpm libxau libxdmcp pixman \ + graphite2 fontconfig freetype libpng glib libbsd libmd libxml2 libjxl libde265 x265-libs lerc \ + libdeflate gdk-pixbuf" && \ + for p in $libs; do \ + apk info -L "$p" 2>/dev/null | grep '^usr/lib/.*\.so' | sed 's|^|/|' | xargs -r rm -f; \ + done && \ + # (what the course runs must still find every library, and dot must not warn) + for f in /usr/bin/dot /usr/lib/graphviz/*.so.6 $(find /usr/lib/python3.12 -name '*.so') \ + /usr/bin/verilator_bin "$cc1plus" /usr/bin/as /usr/bin/ld /usr/bin/make; do \ + if ldd "$f" 2>&1 | grep -q 'Error loading'; then ldd "$f"; exit 1; fi; \ + done && \ + test -z "$(echo 'digraph { a -> b }' | dot -Tsvg 2>&1 >/dev/null)" && \ + # The `verilator` wrapper, without Perl: for a normal run, the Perl one sets VERILATOR_ROOT, + # counts its re-entries, lifts the stack limit and runs verilator_bin with the same arguments. + # (Lost: its --help text, --gdb, --valgrind and verilator_coverage, which the course does not + # use.) Then Perl goes (about 40 MB), with the Perl trampolines in Verilator's own bin/. + printf '%s\n' '#!/bin/sh' \ + '# Stands in for Verilator'"'"'s Perl wrapper (see the Dockerfile)' \ + 'if [ "$1" = --help ]; then echo "See https://verilator.org/guide/latest/exe_verilator.html"; exit 0; fi' \ + 'export VERILATOR_ROOT="${VERILATOR_ROOT:-/usr/share/verilator}"' \ + 'export VERILATOR_RUNNING=$(( ${VERILATOR_RUNNING:-0} + 1 ))' \ + 'ulimit -s unlimited 2>/dev/null' \ + 'exec /usr/bin/verilator_bin "$@"' > /usr/bin/verilator && \ + cd /usr/share/verilator/bin && \ + rm verilator verilator_bin verilator_bin_dbg verilator_coverage verilator_coverage_bin_dbg \ + verilator_gantt verilator_profcfunc /usr/bin/verilator_coverage && \ + ln -s /usr/bin/verilator verilator && ln -s /usr/bin/verilator_bin verilator_bin && \ + ln -s /usr/bin/verilator_gantt verilator_gantt && ln -s /usr/bin/verilator_profcfunc verilator_profcfunc && \ + apk info -L perl | grep '^usr/' | sed 's|^|/|' | xargs rm -rf && \ + rm -rf /usr/lib/perl5 /usr/share/perl5 && \ + cd / && \ + # On amd64, the C++ compiler and Verilator compressed with UPX: 35 MB less, and they unpack in a + # fraction of a second. Not on Arm64, where UPX 5.0 packs programs that fail to start in a large + # environment (upx/upx#952, fixed in 5.1). + if [ "$TARGETARCH" = "amd64" ]; then \ + apk add --no-cache --virtual .pack upx && upx -q "$cc1plus" /usr/bin/verilator_bin && \ + apk del --no-cache .pack && \ + echo 'int main() {}' | g++ -x c++ - -o /tmp/a.out && /tmp/a.out && rm /tmp/a.out && \ + verilator --version; \ + fi && \ + # apk still lists the packages that lost files above as installed; an image built on this one + # that adds packages restores them first: apk fix --no-cache $(cat /etc/bootcamp-pruned) + # (apk info -e prints those installed, and exits with the number of the others) + { apk info -e perl verilator graphviz gcc g++ musl-dev libstdc++-dev python3 $libs || true; } \ + > /etc/bootcamp-pruned && \ + grep -qx perl /etc/bootcamp-pruned +COPY --from=jre /opt/java /usr/lib/jvm/java-17-openjdk ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk ENV PATH=$JAVA_HOME/bin:$PATH -RUN adduser -D -s /bin/bash bootcamp +RUN for f in "$JAVA_HOME"/lib/*.so "$JAVA_HOME"/lib/server/*.so; do \ + if LD_LIBRARY_PATH="$JAVA_HOME/lib:$JAVA_HOME/lib/server" ldd "$f" 2>&1 | grep -q 'Error loading'; then \ + ldd "$f"; exit 1; \ + fi; \ + done && \ + ln -s "$JAVA_HOME/bin/java" /usr/bin/java && \ + ln -sf /etc/ssl/certs/java/cacerts "$JAVA_HOME/lib/security/cacerts" && \ + adduser -D -s /bin/bash bootcamp ENV SCALA_VERSION=2.13.18 ENV ALMOND_VERSION=0.14.5 ENV COURSIER_VERSION=2.1.24 +# sha256 of the coursier launcher of its GitHub release; update together with COURSIER_VERSION +ENV COURSIER_SHA256=7aa975f12469726d6bb87852107afe0b8d6f3c82b12a49ef43cc6647c4e057ca +ENV SBT_VERSION=1.13.1 +# sha256 of sbt-$SBT_VERSION.tgz (from its GitHub release); update together with SBT_VERSION +ENV SBT_SHA256=4a20e36c1642b6d5be34ef641d2ed6c8c0d464e6145283730d5566716e4083be ENV CHISEL_VERSION=7.16.0 -# Must be the firtool version that Chisel $CHISEL_VERSION was published against +# Must be the firtool version that Chisel $CHISEL_VERSION was published against (checked by +# tools/check-versions.py, which also makes you revisit what 2.8_memories.ipynb says about how +# this firtool builds a SyncReadMem). ENV FIRTOOL_VERSION=1.160.0 +# sha256 of llvm-firtool-$FIRTOOL_VERSION-linux-x64.jar (Maven Central); update together +ENV FIRTOOL_JAR_SHA256=8f66a76dd7e48dd3b5134bafa091e467d90d4aef2f85b0ebcf3659435f9b22e6 ENV JUPYTER_CONFIG_DIR=/jupyter/config ENV JUPYTER_DATA_DIR=/jupyter/data @@ -68,22 +187,26 @@ RUN mkdir -p $JUPYTER_CONFIG_DIR/custom && \ cp source/jupyter_server_config.py $JUPYTER_CONFIG_DIR/ && \ cp source/overrides.json $JUPYTER_CONFIG_DIR/lab/user-settings/@jupyterlab/apputils-extension/notification.jupyterlab-settings -# Ammonite and the build stage use this preloaded cache -ENV COURSIER_CACHE=/coursier_cache +# Ammonite, sbt and the build stage use this preloaded cache (coursier/), beside sbt's own files +# (sbt/): one directory, so that the jars both hold are stored once (see the last stage) +ENV COURSIER_CACHE=/opt/cache/coursier +ENV PATH=/opt/sbt/bin:$PATH # Second stage - download Scala requirements and the Scala kernel FROM base AS intermediate-builder ARG TARGETARCH +ARG BUILDARCH # Download everything into the cache that the final image uses at runtime -RUN mkdir /coursier_cache +RUN mkdir -p /opt/cache/coursier # The JVM launcher of coursier works on every architecture. RUN \ apk add --no-cache curl unzip && \ curl -fL --retry 3 -o coursier \ "https://github.com/coursier/coursier/releases/download/v${COURSIER_VERSION}/coursier" && \ + echo "$COURSIER_SHA256 coursier" | sha256sum -c - && \ chmod +x coursier && \ ./coursier \ bootstrap \ @@ -112,9 +235,17 @@ RUN \ mkdir -p /opt/firtool/bin && \ curl -fL --retry 3 -o firtool.jar \ "https://repo1.maven.org/maven2/org/chipsalliance/llvm-firtool/${FIRTOOL_VERSION}/llvm-firtool-${FIRTOOL_VERSION}-linux-x64.jar" && \ + echo "$FIRTOOL_JAR_SHA256 firtool.jar" | sha256sum -c - && \ unzip -p firtool.jar org.chipsalliance/llvm-firtool/linux-x64/bin/firtool > /opt/firtool/bin/firtool.x86_64 && \ rm firtool.jar && \ chmod +x /opt/firtool/bin/firtool.x86_64 && \ + # Dropping its symbols and compressing it with UPX take it from 53 to 10 MB, for about 0.2 s more + # per run; on Arm64, where firtool runs under qemu, neither (Arm64's binutils cannot read an + # x86-64 executable, and unpacking under emulation would be slow) + if [ "$TARGETARCH" = "amd64" ]; then \ + apk add --no-cache --virtual .pack upx && strip /opt/firtool/bin/firtool.x86_64 && \ + upx -q /opt/firtool/bin/firtool.x86_64 && apk del --no-cache .pack; \ + fi && \ if [ "$TARGETARCH" = "arm64" ]; then \ printf '#!/bin/sh\nexec qemu-x86_64 /opt/firtool/bin/firtool.x86_64 "$@"\n' > /opt/firtool/bin/firtool && \ chmod +x /opt/firtool/bin/firtool; \ @@ -122,6 +253,35 @@ RUN \ mv /opt/firtool/bin/firtool.x86_64 /opt/firtool/bin/firtool; \ fi +# sbt for the riscv/ project (Module 5). sbt runs on the JRE: the project has no Java sources. +# Its own files go to /opt/cache/sbt (set in sbt's configuration file, so every user gets it). +RUN \ + curl -fL --retry 3 -o sbt.tgz "https://github.com/sbt/sbt/releases/download/v${SBT_VERSION}/sbt-${SBT_VERSION}.tgz" && \ + echo "$SBT_SHA256 sbt.tgz" | sha256sum -c - && \ + tar -xzf sbt.tgz -C /opt && \ + rm sbt.tgz /opt/sbt/bin/sbtn-* /opt/sbt/bin/sbt.bat && \ + printf '%s\n' -Dsbt.global.base=/opt/cache/sbt/global -Dsbt.boot.directory=/opt/cache/sbt/boot \ + -Dsbt.ivy.home=/opt/cache/sbt/ivy -Dsbt.server.forcestart=false >> /opt/sbt/conf/sbtopts + +# Preload what `sbt test` needs offline: the sbt runtime and the Scala 2.12 bridge that compiles +# build.sbt (/opt/cache/sbt), and the project's dependencies (/opt/cache/coursier). Only the build +# definition and two placeholder sources are used, so editing riscv/src does not redo this step. +COPY riscv/build.sbt /tmp/riscv/ +COPY riscv/project/build.properties /tmp/riscv/project/ +RUN \ + mkdir -p /tmp/riscv/src/main/scala /tmp/riscv/src/test/scala && \ + echo 'class Warmup extends chisel3.Module' > /tmp/riscv/src/main/scala/Warmup.scala && \ + echo 'class WarmupSpec extends org.scalatest.flatspec.AnyFlatSpec with chisel3.simulator.scalatest.ChiselSim' \ + > /tmp/riscv/src/test/scala/WarmupSpec.scala && \ + cd /tmp/riscv && \ + # Under qemu (an Arm64 image cross-built on x86-64) the JVM crashes while probing SVE + if [ "$TARGETARCH" = "arm64" ] && [ "$BUILDARCH" != "arm64" ]; then export JAVA_TOOL_OPTIONS="-XX:UseSVE=0"; fi && \ + sbt -batch update Test/compile && \ + # (sbt regenerates java9-rt-ext, 59 MB, offline in a few seconds on first use) + cd / && rm -rf /tmp/riscv /opt/cache/sbt/global/server /opt/cache/sbt/global/java9-rt-ext-* && \ + # sbt and coursier hold many of the same jars (75 MB): hard links store each once + apk add --no-cache util-linux-misc && hardlink -q -t /opt/cache # (-t: whatever their times) + # Last stage FROM base AS final @@ -129,9 +289,10 @@ FROM base AS final ENV CHISEL_FIRTOOL_PATH=/opt/firtool/bin # copy the Scala requirements and kernel into the image -COPY --from=intermediate-builder --chown=bootcamp:bootcamp /coursier_cache/ /coursier_cache/ +COPY --from=intermediate-builder --chown=bootcamp:bootcamp /opt/cache/ /opt/cache/ COPY --from=intermediate-builder --chown=bootcamp:bootcamp /usr/local/share/jupyter/kernels/scala/ /usr/local/share/jupyter/kernels/scala/ COPY --from=intermediate-builder /opt/firtool/ /opt/firtool/ +COPY --from=intermediate-builder /opt/sbt/ /opt/sbt/ COPY --chown=bootcamp:bootcamp . /chisel-bootcamp/ diff --git a/Install.md b/Install.md index 0889880..916e2a6 100644 --- a/Install.md +++ b/Install.md @@ -1,6 +1,7 @@ ## Local Setup Instructions -If you want to run the bootcamp locally, follow the instructions below for your platform. +If you want to run the bootcamp locally, follow the instructions below for your platform. If something +fails, [docs/troubleshooting.md](docs/troubleshooting.md) has the errors seen so far and their fixes. Note: Java 17 or later is recommended (Java 11 also works). If you have multiple Java versions installed, select the appropriate version before running `jupyter notebook`: @@ -18,6 +19,7 @@ The `sysprog21/chisel-bootcamp` image supports both x86-64 and Arm64 architectur - Scala 2.13.18 with Almond 0.14.5 kernel - Chisel 7.16.0 and CIRCT firtool 1.160.0 (preinstalled, so the image also works offline) - Verilator and a C++ toolchain, used by ChiselSim to simulate designs +- sbt 1.13.1 with the dependencies of the `riscv/` project preloaded (see below) - Jupyter Lab - Graphviz for circuit visualization @@ -51,28 +53,27 @@ Jupyter notebooks allow you to interactively run code in your browser. It supports multiple programming languages. For this bootcamp, we'll install jupyter first and then the Scala-specific jupyter backend (now called almond). +On Ubuntu 24.04 or newer, `tools/install.sh` (run from a clone of the repository) does every step of +this section; the rest describes them by hand, for other systems. + #### Jupyter First install Jupyter. -Dependencies: curl, openssh-client, openjdk-17-jre (-headless OK), ca-certificates-java, Verilator 5 or newer, a C++ compiler (g++ or clang++) and make +Dependencies: curl, openssh-client, openjdk-17-jre (-headless OK), ca-certificates-java, Verilator 5.026 or newer, a C++ compiler (g++ or clang++) and make -Install Jupyter using pip3 (see [Jupyter installation docs](https://jupyter.org/install)): +Install Jupyter with pip (see [Jupyter installation docs](https://jupyter.org/install)), in a Python +virtual environment where the system's Python refuses packages installed with pip (as on Ubuntu 24.04): ``` -pip3 install --upgrade pip -pip3 install jupyter --ignore-installed +python3 -m venv ~/.local/share/chisel-bootcamp/venv && source ~/.local/share/chisel-bootcamp/venv/bin/activate +pip install --upgrade pip +pip install jupyter ``` -If pip3 isn't working out of the box (possibly because your Python3 version is out of date), you can try `python3 -m pip` in lieu of `pip3`. - (To reinstall jupyter later for whatever reason, you can use `--no-deps` to avoid re-installing all the dependencies.) -You may want to try out Jupyter lab, the newer interface developed by Project Jupyter. -It is especially useful if you want to be able to run a terminal emulator in your browser. -It can be installed with `pip3`: -``` -pip3 install jupyterlab -``` +The `jupyter` package includes JupyterLab, the newer interface developed by Project Jupyter, which +can also run a terminal emulator in your browser. #### Jupyter Backend for Scala @@ -80,7 +81,9 @@ If you experience errors or issues with this section, try running `rm -rf ~/.loc Download coursier and use it to install Almond (see [Almond installation docs](https://almond.sh/docs/quick-start-install) for details): ```bash -curl -L -o coursier https://github.com/coursier/coursier/releases/latest/download/coursier +curl -L -o coursier https://github.com/coursier/coursier/releases/download/v2.1.24/coursier +echo "7aa975f12469726d6bb87852107afe0b8d6f3c82b12a49ef43cc6647c4e057ca coursier" | sha256sum -c - +# without sha256sum (as on macOS), end the line above with `| shasum -a 256 -c -` instead chmod +x coursier ``` @@ -93,13 +96,25 @@ You can delete the `coursier` and `almond` files afterward if desired. #### Verilator -Chisel simulates designs with ChiselSim ([documentation](https://www.chisel-lang.org)), which runs [Verilator](https://verilator.org) (version 5 or newer) and compiles the result with a C++ compiler. -For example, on Debian/Ubuntu: `sudo apt install verilator g++ make` (Ubuntu 24.04 or newer provides Verilator 5), on macOS: `brew install verilator`. +Chisel simulates designs with ChiselSim ([documentation](https://www.chisel-lang.org)), which runs [Verilator](https://verilator.org) and compiles the result with a C++ compiler. +Use Verilator 5.026 or newer: older 5.x releases intermittently abort with "attempted to destroy locked Thread Pool" while ChiselSim compiles a design. On macOS, `brew install verilator` is new enough; Ubuntu 24.04's package (5.020) is not, and `tools/install.sh` builds a newer one there. Check with `verilator --version`. Chisel also needs CIRCT's `firtool` to generate SystemVerilog. You don't have to install it: Chisel downloads the matching version on first use (this needs Internet access once). You can also point the `CHISEL_FIRTOOL_PATH` environment variable at a directory that contains `firtool` 1.160.0. +On Linux/Arm64 (outside Docker) there is no firtool for Chisel to download: Maven Central has firtool +for Linux x86-64, macOS and Windows only. `tools/install.sh` sets up the x86-64 one under qemu-user, +as the Docker image does (firtool is slower there), and points `CHISEL_FIRTOOL_PATH` at it. + +#### Yosys + +Module 5.9 proves a property with [Yosys](https://yosyshq.net/yosys/), run as `yosys`. The Docker +image installs YoWASP's build (Yosys compiled to WebAssembly); locally, install either your +system's `yosys` (for example `sudo apt install yosys` or `brew install yosys`) or the same build +with `pip install yowasp-yosys` (`riscv.Formal` runs `yosys`, or else `yowasp-yosys`). Without +it, the formal-check cells of 5.9 print that Yosys is not installed, and its other cells still run. + #### Visualizations [Graphviz](https://graphviz.org/download/) is required to show visualizations of Chisel modules, such as in the demo page. However, visualizations are optional as the other Chisel and Scala features will work without it. @@ -143,7 +158,7 @@ If you did not elect to add Jupyter to the PATH, start a prompt using the #### Install Scala components -Download the latest Coursier from [GitHub releases](https://github.com/coursier/coursier/releases/latest/download/coursier). +Download Coursier from [GitHub releases](https://github.com/coursier/coursier/releases/download/v2.1.24/coursier). Navigate to your download folder and run: ```bash @@ -183,6 +198,30 @@ a browser window. ##### Proxy usage If you require a proxy, try uncommenting and changing the relevant lines at the start of `source/load-ivy.sc`. -Good Luck! +### The `riscv/` sbt project +Module 5 builds a RISC-V processor in an sbt project under `riscv/`. In the Docker image, sbt and +everything the project needs are preinstalled, so it works offline. Open a terminal in Jupyter Lab +(or `docker exec -it bash`) and run: +```bash +cd riscv +sbt test # compile and run every test (ChiselSim tests need Verilator) +sbt "testOnly riscv.IsaSpec" +sbt "testOnly riscv.MemorySpec -- -DemitVcd=1" # also dump each simulation's waveform (VCD) under build/ +# assemble a test program into the memory image that the processors load +sbt "runMain riscv.Asm programs/src/fib.S programs/hex/fib.hex" +``` + +The programs are RV32I assembly, assembled by the project's own assembler (`riscv.Asm`); no RISC-V +compiler is needed (see `riscv/DESIGN.md`). + +Outside Docker, install [sbt](https://www.scala-sbt.org/download/) (any 1.x launcher; the project +pins its sbt version in `riscv/project/build.properties`), Java 17 or later (a runtime is enough: the project has no Java sources, and the image has only +the Java 17 runtime), +and Verilator 5.026 or newer as described above (`tools/install.sh` installs all of them on Ubuntu, in its Python environment: activate it before running `sbt`); the first `sbt` run downloads the dependencies. + +The image has no network access to fetch more: changing `scalaVersion` or adding a dependency to +`riscv/build.sbt` makes the offline `sbt` fail. Run such builds with network access. + +Good Luck! diff --git a/README.md b/README.md index 4a73c87..3728acc 100644 --- a/README.md +++ b/README.md @@ -38,23 +38,87 @@ nerdctl run -it --rm -p 8888:8888 sysprog21/chisel-bootcamp Then open the provided URL (starting with http://127.0.0.1:8888) in your browser. +Image tags: `latest` follows the `dev` branch, `chisel-` (for example `chisel-7.16.0`) +is the newest image built for that Chisel release, and `sha-` (the first 7 hex digits +of a `dev` commit; a commit superseded by a newer push while its build was queued has none) +pins one exact build. + ### Alternative Options - Try it online [HERE](https://mybinder.org/v2/gh/sysprog21/chisel-bootcamp/HEAD)! No local installation required! + Binder covers Modules 1-4 only: it lacks sbt and Yosys (Module 5), and its memory may be too + small for a JVM beside a Verilator build. Use the Docker image for the whole course. - For local installation without Docker, [look at installation instructions here](Install.md). +- Teaching a course? See the [instructor guide](docs/instructors.md). ## Outline -The bootcamp is divided into modules, which are further subdivided. -This README serves as *Module 0*, an introduction and motivation to learning the material contained within. -*Module 1* gives a quick introduction to Scala. -It teaches you enough to start writing Chisel, but many more Scala concepts are taught along the way. -Chisel is introduced in *Module 2*, starting with a hardware example and breaking it down. -The rest of *Module 2* covers combinational and sequential logic, as well as software and hardware control flow. -*Module 3* teaches you how to write hardware generators in Chisel that take advantage of Scala's high-level programming language features. -*Module 4* looks under the hood: the FIRRTL that Chisel emits, how CIRCT's `firtool` turns it into SystemVerilog, and how to write small programs that analyze and transform FIRRTL. -By the end, you will be able to read and understand most of the [Chisel code base](https://github.com/chipsalliance/chisel) and begin using [Rocket Chip](https://github.com/chipsalliance/rocket-chip). -This tutorial *does not* yet cover SBT, build systems, backend flows for FPGA or ASIC processes, or analog circuits. +The bootcamp is divided into modules, which are further subdivided. This README serves as +*Module 0*, an introduction and motivation. The times are rough estimates for a first pass, +exercises included, from the length of each notebook; they vary a lot with your background. + +| Notebook | Topic | Time | +|---|---|---| +| [0_demo](0_demo.ipynb) | A preview of what you will learn (not part of the course) | 15 min | +| **Module 1: Scala** | | | +| [1_intro_to_scala](1_intro_to_scala.ipynb) | Enough Scala to start writing Chisel; more comes along the way | 45 min | +| **Module 2: Chisel** | | | +| [2.1_first_module](2.1_first_module.ipynb) | A hardware example, broken down | 35 min | +| [2.2_comb_logic](2.2_comb_logic.ipynb) | Combinational logic | 55 min | +| [2.3_control_flow](2.3_control_flow.ipynb) | Software and hardware control flow | 75 min | +| [2.4_sequential_logic](2.4_sequential_logic.ipynb) | Registers, and the kinds of reset | 55 min | +| [2.5_exercise](2.5_exercise.ipynb) | Putting it together: an FIR filter | 25 min | +| [2.6_chiselsim](2.6_chiselsim.ipynb) | Testing with ChiselSim and Verilator, waveforms | 50 min | +| [2.7_enums_and_bundles](2.7_enums_and_bundles.ipynb) | Enums, bit-pattern decoders, bundles and vectors | 65 min | +| [2.8_memories](2.8_memories.ipynb) | Memories, write masks, a register file | 45 min | +| **Module 3: generators** | | | +| [3.1_parameters](3.1_parameters.ipynb) | Parameters | 45 min | +| [3.2_collections](3.2_collections.ipynb) | Collections | 40 min | +| [3.2_interlude](3.2_interlude.ipynb) | The Chisel standard library | 20 min | +| [3.3_higher-order_functions](3.3_higher-order_functions.ipynb) | Higher-order functions | 35 min | +| [3.4_functional_programming](3.4_functional_programming.ipynb) | Functional programming | 75 min | +| [3.5_object_oriented_programming](3.5_object_oriented_programming.ipynb) | Object-oriented programming | 25 min | +| [3.6_types](3.6_types.ipynb) | Types | 90 min | +| **Module 4: under the hood** | | | +| [4.1_firrtl_ast](4.1_firrtl_ast.ipynb) | FIRRTL, and how `firtool` turns it into SystemVerilog | 40 min | +| [4.2_firrtl_ast_traversal](4.2_firrtl_ast_traversal.ipynb) | Walking a FIRRTL circuit | 45 min | +| [4.3_firrtl_common_idioms](4.3_firrtl_common_idioms.ipynb) | Common idioms of passes: collecting, adding, deleting | 40 min | +| [4.4_firrtl_add_ops_per_module](4.4_firrtl_add_ops_per_module.ipynb) | A worked example: counting adders per module | 35 min | +| **Module 5: a RISC-V processor** | | | +| [5.1_riscv_isa](5.1_riscv_isa.ipynb) | The RV32I instruction set, a decoder and an assembler in Scala | 55 min | +| [5.2_alu_and_regfile](5.2_alu_and_regfile.ipynb) | The ALU, the immediate generator and the register file | 45 min | +| [5.3_decoder](5.3_decoder.ipynb) | A table-driven decoder | 45 min | +| [5.4_single_cycle](5.4_single_cycle.ipynb) | A single-cycle RV32I processor, checked against a golden model | 70 min | +| [5.5_compliance](5.5_compliance.ipynb) | The official RISC-V tests on the processor | 15 min | +| [5.6_pipeline](5.6_pipeline.ipynb) | A five-stage pipeline: stages, flushes, data hazards | 45 min | +| [5.7_hazards](5.7_hazards.ipynb) | Hazards: forwarding, stalls, the official tests on the pipeline | 40 min | +| [5.8_bus_and_mmio](5.8_bus_and_mmio.ipynb) | A bus, memory-mapped I/O and a UART: Hello, world | 45 min | +| [5.9_debug_and_verify](5.9_debug_and_verify.ipynb) | Debugging a core: retire traces, waveforms, a formal check | 40 min | +| [5.10_to_silicon](5.10_to_silicon.ipynb) | From Chisel to an FPGA: lint, synthesis, a board | 30 min | + +Module 5 builds the processor in an sbt project under `riscv/` (see +[Install.md](Install.md#the-riscv-sbt-project)): you write parts of it in Scala files there, and the +notebooks load the project. + +By the end, you will be able to read and understand most of the +[Chisel code base](https://github.com/chipsalliance/chisel), begin using +[Rocket Chip](https://github.com/chipsalliance/rocket-chip), and build and test a processor of your +own, and synthesize it for an FPGA board (Module 5.10). It does not cover ASIC flows or analog +circuits. + +### Which path should I take? + +- **New to Scala:** take Module 1 in full, then Modules 2 and 3 in order. Module 4 is optional. +- **Verilog or VHDL designer:** read the sections of Module 1 tagged *Required* (enough to read + Scala), take Module 2 (2.6 on testing and 2.7-2.8 differ most from what you know), then Module 3 + for what Verilog cannot do: generators. +- **Here for the RISC-V processor:** Module 1 (at least its *Required* sections), what Module 5 + assumes (below), then Module 5 in order. Module 4 and the rest of Module 3 are optional for it. + +Module 5 assumes Module 2 (2.6-2.8 especially: testing, decoders and enums, memories), 3.1 +(`match`, `Option`, case classes), 3.2_interlude (`Decoupled`) and 3.3 (the collection methods), +and knowing what a processor's datapath is (a computer architecture course, or a book such as +Patterson and Hennessy's *Computer Organization and Design*); it explains RV32I itself. ## Motivation All hardware description languages support writing single instances. @@ -80,6 +144,12 @@ But if you take the time to learn how to write generators, then the power of Chi Learning to write generators is difficult, but we hope this tutorial will pave the way for you to become a better hardware designer, programmer, and thinker! ## Contributors + +The bootcamp was written at UC Berkeley by the people below. This fork, +[sysprog21/chisel-bootcamp](https://github.com/sysprog21/chisel-bootcamp), moved it to Chisel 7, +ChiselSim and CIRCT's `firtool`, rewrote the testing notebook for ChiselSim, added the notebooks on +enums, decoders and memories, and Module 5 with its RISC-V project. + - Stevo Bailey ([stevo@berkeley.edu](mailto:stevo@berkeley.edu)) - Adam Izraelevitz ([adamiz@berkeley.edu](mailto:azidar@berkeley.edu)) - Richard Lin ([richard.lin@berkeley.edu](mailto:edwardw@berkeley.edu)) diff --git a/binder/environment.yml b/binder/environment.yml index 1f2b5e3..e20ef79 100644 --- a/binder/environment.yml +++ b/binder/environment.yml @@ -3,4 +3,4 @@ channels: - conda-forge dependencies: # Ubuntu 22.04's apt package is Verilator 4, but ChiselSim requires 5. - - verilator >=5,<6 + - verilator >=5.026,<6 diff --git a/binder/postBuild b/binder/postBuild old mode 100644 new mode 100755 index a78ef14..15f3e48 --- a/binder/postBuild +++ b/binder/postBuild @@ -4,15 +4,24 @@ set -e SCALA_VERSION=2.13.18 ALMOND_VERSION=0.14.5 COURSIER_VERSION=2.1.24 +COURSIER_SHA256=7aa975f12469726d6bb87852107afe0b8d6f3c82b12a49ef43cc6647c4e057ca -# Chisel 7 simulates with ChiselSim, which needs Verilator 5 or newer -command -v verilator >/dev/null || { echo "ERROR: verilator not found" >&2; exit 1; } -VERILATOR=$(verilator --version) -echo "$VERILATOR" -[ "$(echo "$VERILATOR" | sed -E 's/^Verilator ([0-9]+).*/\1/')" -ge 5 ] || { echo "ERROR: Verilator 5 or newer is required" >&2; exit 1; } +# Chisel 7 simulates with ChiselSim, which needs a recent Verilator (older ones abort now and then) +VERILATOR_MIN=5.026 +command -v verilator >/dev/null || { + echo "ERROR: verilator not found" >&2 + exit 1 +} +VERILATOR=$(verilator --version | awk '{print $2}') +echo "Verilator $VERILATOR" +[ "$(printf '%s\n%s\n' "$VERILATOR_MIN" "$VERILATOR" | sort -V | head -1)" = "$VERILATOR_MIN" ] || { + echo "ERROR: Verilator $VERILATOR_MIN or newer is required" >&2 + exit 1 +} # Install coursier (the JVM launcher works on every platform) curl -fLo coursier "https://github.com/coursier/coursier/releases/download/v${COURSIER_VERSION}/coursier" +echo "$COURSIER_SHA256 coursier" | sha256sum -c - chmod +x coursier # Install almond diff --git a/docs/chisel7-audit.md b/docs/chisel7-audit.md new file mode 100644 index 0000000..3e546b1 --- /dev/null +++ b/docs/chisel7-audit.md @@ -0,0 +1,40 @@ +# Chisel 7 deprecation audit + +Run on 2026-11-13 against Chisel 7.16.0, Scala 2.13.18 and Almond 0.14.5, in the +Docker image with `--network none`. + +## Method + +Every notebook was run in a fresh kernel with a copy of `source/load-ivy.sc` whose compiler +options add `-deprecation` and `-feature` to `-language:reflectiveCalls -Ytasty-reader`. Every +line of cell output containing `warn`, `deprecat` or `[W0` (Chisel's elaboration warnings) was +collected. Cells that contain `???` were marked as exercises so that their errors are not counted; +no exercise cell produced a warning. + +`load-ivy.sc` itself is compiled before its own `configureCompiler` call takes effect, so its +warnings only show up as a summary ("1 deprecation ... re-run enabling -deprecation"). To find +the culprit, its definitions were compiled one per cell after the options were set. + +With every warning fixed, `-Werror` adds nothing: the run reports no warnings at all. + +## Findings + +| Notebook | Cell | Warning | Fix | +| :--- | :--- | :--- | :--- | +| every notebook | load cell (`source/load-ivy.sc`, `visualize`) | `1 deprecation (since 0.4.1)`: `almond.api.helpers.Display.html` is deprecated | fix: `almond.display.Html(html).display()` | +| `1_intro_to_scala.ipynb` | 17 | `procedure syntax is deprecated: instead, add ': Unit =' to explicitly declare 'asciiTriangle''s return type` | fix: `def asciiTriangle(rows: Int): Unit = {` | +| `1_intro_to_scala.ipynb` | 21, 23, 25 | `method + in class Int is deprecated (since 2.13.0): Adding a number and a String is deprecated. Use the string interpolation` | fix: `print(s"$i ")` | + +## Not deprecated + +No compiler or Chisel message was reported for these, so they stay as they are: `Module(new ...)`, +`FlatIO`, `suggestName`, and `chisel3.util.experimental.*` (`decode` is the supported route for +table-driven decoders). `decoder(input, table)` tries the external `espresso` tool first and prints +a warning when it is missing, so notebooks should call `decoder.qmc` (the built-in minimizer) directly. + +## Keeping it clean + +The kernel names each deprecated call in a cell even without `-deprecation` (checked with a seeded +cell), and `runtest.py` reports each line of output that mentions a deprecation as an error, so CI +fails when a deprecated API comes back. The warnings of `load-ivy.sc` itself appear only as the +"re-run enabling -deprecation" summary line, which contains the same word and is caught too. diff --git a/docs/instructors.md b/docs/instructors.md new file mode 100644 index 0000000..171a7b5 --- /dev/null +++ b/docs/instructors.md @@ -0,0 +1,94 @@ +# Instructor guide + +How to run the bootcamp as a course: a schedule, how the exercises are checked, the errors students +meet most, and how to host it for a class. It has not yet been reviewed by an instructor who ran +the course; corrections are welcome. + +## The course in 14 weeks + +The notebooks add up to about 23 hours (the README's outline times each). With a two-hour lab a +week they fill 14 weeks; weeks 3, 7, 8 and 11 run over two hours, week 14 leaves time for review, +and Module 5, the processor, takes the last five. + +| Week | Notebooks | Topic | +|---|---|---| +| 1 | 0_demo, 1_intro_to_scala | Setup, enough Scala to start | +| 2 | 2.1, 2.2 | A first module, combinational logic | +| 3 | 2.3, 2.4 | Control flow, registers and reset | +| 4 | 2.5, 2.6 | An FIR filter; testing with ChiselSim, waveforms, assertions | +| 5 | 2.7, 2.8 | Enums, decoders, bundles; memories | +| 6 | 3.1, 3.2, 3.2_interlude | Parameters, collections, the standard library | +| 7 | 3.3, 3.4, 3.5 | Functional and object-oriented generators | +| 8 | 3.6, 4.1 | Types; FIRRTL and `firtool` | +| 9 | 4.2, 4.3, 4.4 | Passes over FIRRTL | +| 10 | 5.1, 5.2 | The RV32I ISA, the assembler; the ALU and registers | +| 11 | 5.3, 5.4, 5.5 | The decoder, a single-cycle core, the official tests | +| 12 | 5.6, 5.7 | The pipeline and its hazards | +| 13 | 5.8, 5.9 | A bus and a UART; debugging and a formal check | +| 14 | 5.10 | Lint, synthesis, an FPGA board; review | + +Module 4 is the part to shorten for a hardware-only course (it is about the compiler, not the +hardware); Modules 2 and 5 are the core. Module 5's notebooks build on each other's exercises: a +student who skips one cannot run the next. + +## Checking the exercises + +- **Modules 2-4:** each exercise is a cell with `???` to fill in, followed by a cell that tests it: + it errors until the answer is right; most then print `SUCCESS!!`. The hidden "Solution" block under each exercise gives an answer. A + submission is the notebook; rerunning it from the top (Kernel, Restart Kernel and Run All Cells) + checks it. +- **Module 5:** the exercises are Scala files under `riscv/src/main/scala/riscv/` with `???` to + fill in, and the tests of the project check them: from a terminal in `riscv/`, + `sbt "testOnly riscv.AluSpec"` for one part, `sbt test` for all. The notebooks also run the + checks of their module. A submission is the `riscv/src/` directory. +- **Reference solutions** are in `riscv/solutions/` of the repository, which the Docker image leaves + out. `tools/check-solutions.sh` (from a clone) checks that they pass every test, and that the + student scaffold compiles; `runtest.py` runs every notebook as a student gets it. + +## Errors students meet + +[Troubleshooting](troubleshooting.md) has each error with its text and fix; mention these in the +first lab: + +- [A cell that never finishes](troubleshooting.md#a-cell-runs-forever-with-no-output) after + building a module with a `???` in it. +- [`Killed`, or a kernel that dies](troubleshooting.md#killed-or-the-kernel-dies-while-simulating): + too little memory. +- **`NotImplementedError: an implementation is missing`**: an exercise, or an earlier one it + depends on, is not done yet. In Module 5 the cells stop with it until the exercises of the + earlier notebooks are done. +- **Cells run out of order**: a later cell uses a definition from a cell that was not run; run the + notebook from the top. + +## Hosting a class + +Each student needs one container of the image (`sysprog21/chisel-bootcamp`, or a `chisel-` +tag to keep a term on one release; the README lists the tags). + +- **Memory: 4 GB per student**, for a JVM beside Verilator's C++ compiler (the + [troubleshooting entry](troubleshooting.md#killed-or-the-kernel-dies-while-simulating) has the + measurements). +- **CPU: 2 cores per student.** Verilator builds in parallel, so more cores speed up Module 5; one + core works but is slower. The first Yosys cell in a container (5.9, 5.10) takes about a minute. +- **Disk:** the image is about 0.65 GB (amd64; Arm64 about 0.75 GB); each container writes little + (`build/` holds simulation output). +- **An image of your own on top of it:** to keep it small, the image deletes files of some Alpine + packages it keeps installed (Perl, Graphviz's image plugins and libraries, parts of GCC), so run + `apk fix --no-cache $(cat /etc/bootcamp-pruned)` before `apk add` in your Dockerfile. +- **Arm64 machines** run the image too, with `firtool` under emulation (slower to build + SystemVerilog). + +Two ways to host it: + +- **Per-student containers** on students' own machines: `docker run -it --rm -p 8888:8888 + sysprog21/chisel-bootcamp` (README). The notebooks and `riscv/src` live in `/chisel-bootcamp`, so + to keep work between sessions, run it with a named volume there: + `docker run -it --rm -p 8888:8888 -v bootcamp-work:/chisel-bootcamp sysprog21/chisel-bootcamp` + (Docker fills the volume from the image the first time; a newer image's notebooks then do not + replace the ones in the volume). Or have students download their notebooks and `riscv/src`. +- **JupyterHub** with DockerSpawner: [`docs/jupyterhub/`](jupyterhub/) has a `Dockerfile` that adds + the hub's single-user server to the image (`docker build --build-arg JUPYTERHUB_VERSION= -t bootcamp-hub docs/jupyterhub`), the settings it adds to the server + configuration (the image's own is for one person on a laptop: no cross-site request check, any + origin), and the spawner settings to add to `jupyterhub_config.py`: the image, 4 GB and 2 CPUs + per user, and a named volume per user on `/chisel-bootcamp`. diff --git a/docs/jupyterhub/Dockerfile b/docs/jupyterhub/Dockerfile new file mode 100644 index 0000000..8746bee --- /dev/null +++ b/docs/jupyterhub/Dockerfile @@ -0,0 +1,16 @@ +# The bootcamp image for a JupyterHub (DockerSpawner): adds the single-user server, and turns back +# on the checks that the image's server configuration (one person on a laptop) turns off. +# Build: docker build --build-arg JUPYTERHUB_VERSION= -t bootcamp-hub docs/jupyterhub +ARG BOOTCAMP_IMAGE=sysprog21/chisel-bootcamp:chisel-7.16.0 +FROM ${BOOTCAMP_IMAGE} +ARG JUPYTERHUB_VERSION +USER root +# the image deletes pip after its own installs: restore Alpine's py3-pip, then install the hub's +# single-user server +RUN test -n "$JUPYTERHUB_VERSION" && \ + apk fix --no-cache py3-pip && \ + pip3 install --no-cache-dir --break-system-packages "jupyterhub==${JUPYTERHUB_VERSION}" +COPY hub_server_config.py /tmp/hub_server_config.py +RUN cat /tmp/hub_server_config.py >> /jupyter/config/jupyter_server_config.py && rm /tmp/hub_server_config.py +USER bootcamp +CMD ["jupyterhub-singleuser"] diff --git a/docs/jupyterhub/hub_server_config.py b/docs/jupyterhub/hub_server_config.py new file mode 100644 index 0000000..065b05a --- /dev/null +++ b/docs/jupyterhub/hub_server_config.py @@ -0,0 +1,8 @@ +# Appended to the image's Jupyter Server configuration (/jupyter/config/jupyter_server_config.py) +# by docs/jupyterhub/Dockerfile: on a hub, which authenticates users, these settings, which come +# later, turn the checks back on that the image's configuration turns off for one person on a +# laptop. The rest of that configuration (hidden files, log filters) still applies. + +c.ServerApp.disable_check_xsrf = False +c.ServerApp.allow_origin = "" +c.ServerApp.allow_credentials = False diff --git a/docs/jupyterhub/jupyterhub_config.py b/docs/jupyterhub/jupyterhub_config.py new file mode 100644 index 0000000..9741489 --- /dev/null +++ b/docs/jupyterhub/jupyterhub_config.py @@ -0,0 +1,13 @@ +# The parts of a jupyterhub_config.py that the bootcamp needs (DockerSpawner); add the hub's +# authenticator and network settings. + +c = get_config() # noqa + +c.JupyterHub.spawner_class = "dockerspawner.DockerSpawner" +c.DockerSpawner.image = "bootcamp-hub" # built from docs/jupyterhub/Dockerfile +c.DockerSpawner.notebook_dir = "/chisel-bootcamp" +# one named volume per user: Docker fills it from the image the first time +c.DockerSpawner.volumes = {"bootcamp-{username}": "/chisel-bootcamp"} +c.DockerSpawner.mem_limit = "4G" # a JVM beside Verilator's C++ compiler (docs/troubleshooting.md) +c.DockerSpawner.cpu_limit = 2 +c.Spawner.default_url = "/lab" # JupyterLab (the image has no classic Notebook) diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..b163415 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,118 @@ +# Troubleshooting + +Failures seen while building and running the bootcamp, with the text they print and the fix. Most of +them happen outside the Docker image, whose setup avoids them. + +## A cell runs forever, with no output + +**What you see:** the cell stays busy (`[*]`) and prints nothing, after code that builds a module, +for example `ChiselStage.emitSystemVerilog(new MyModule)` while `MyModule` still has a `???` exercise +in it. Interrupting does not help, and every later cell stays busy too. The kernel's own log (the +terminal that runs `jupyter lab`, or `docker logs` of the bootcamp's container) has: + +``` +Exception in thread "main" scala.MatchError: ArraySeq() (of class scala.collection.immutable.ArraySeq$ofRef) + at almond.interpreter.ExecuteError$.highlightFrame(ExecuteError.scala:21) +``` + +**Why:** Chisel shortens the stack trace of an error raised while it builds a module, with frames +named `...`, and Almond 0.14.5 fails on those frames while it formats the error. + +**Fix:** restart the kernel (Kernel, Restart Kernel) and run the Setup cells again. `getVerilog`, +`getFirrtl` and `simulate` (from `source/load-ivy.sc`) already show such errors; wrap anything else +that builds a module in `scrub`, e.g. `scrub(ChiselStage.emitSystemVerilog(new MyModule))`. + +## The first Yosys cell takes a minute + +**What you see:** in Modules 5.9 and 5.10, before the cell's own output: + +``` +Preparing to run yowasp-yosys. This might take a while... +``` + +This is not a failure: the image's Yosys is WebAssembly, compiled for your machine on its first run +in a container. Unlike the hang above, the cell finishes, and later runs are fast. + +## `Missing dependency 'Add -Ytasty-reader to scalac options ...'` + +**What you see:** for example on `import scala.util.Random`: + +``` +error while loading FromDigits, Missing dependency 'Add -Ytasty-reader to scalac options to parse the TASTy in .../scala3-library_3-3.3.6.jar(scala/util/FromDigits.tasty)', required by ... +``` + +**Why:** Chisel 7's dependencies put Scala 3 classes on the classpath, which the kernel's Scala 2.13 +compiler reads only with `-Ytasty-reader`. + +**Fix:** run the first Setup cell, `interp.load.module(os.pwd / "source" / "load-ivy.sc")`, which +sets the option; in a notebook of your own, make it the first cell. + +## `reference to Input is ambiguous` + +**What you see:** + +``` +reference to Input is ambiguous; +it is imported twice in the same scope by +import chisel3._ +and import _root_.almond.input.Input +``` + +**Why:** the kernel imports Almond's own `Input`, which clashes with Chisel's. + +**Fix:** import Chisel's by name after `import chisel3._`, as the notebooks' Setup cells do: +`import chisel3.Input // avoid a name clash with almond.input.Input`. + +## `%Error: -j accepts positive integer, but '0' is passed` + +**What you see:** a simulation fails while ChiselSim compiles it, and the compilation log has: + +``` +%Error: -j accepts positive integer, but '0' is passed +%Error: Exiting due to 1 error(s) +``` + +**Why:** the Verilator on the `PATH` is older than version 5 (this text is from 4.210), and ChiselSim +passes it options of Verilator 5. + +**Fix:** install Verilator 5.026 or newer, as [Install.md](../Install.md#verilator) describes, or use +the Docker image. + +## `%Error: Internal Error: attempted to destroy locked Thread Pool` + +**What you see:** a simulation fails while ChiselSim compiles it, now and then (running it again may +work), and the compilation log has: + +``` +%Error: Internal Error: attempted to destroy locked Thread Pool +%Error: Verilator aborted. Suggest trying --debug --gdbbt +``` + +**Why:** a bug of Verilator before 5.026 (reported on 5.020, which Ubuntu 24.04 ships). + +**Fix:** use Verilator 5.026 or newer; on Ubuntu, `tools/install.sh` builds one when the system's is +older. + +## `Killed`, or the kernel dies, while simulating + +**What you see:** `sbt` prints `Killed` and stops, or JupyterLab says that the kernel appears to +have died and will restart automatically, in a cell that compiles a simulation. + +**Why:** the container ran out of memory: Verilator runs a C++ compiler beside the JVM of the kernel +or of sbt, and Module 5's tests need more than 3 GB. + +**Fix:** give the container at least 4 GB (Docker Desktop on macOS or Windows: Settings, Resources, +Memory; on Linux, Docker sets no limit unless you pass `--memory`), and close the kernels of +notebooks you no longer use (Kernel, Shut Down Kernel). + +## A memory loaded from a file reads random values + +**What you see:** no error while the module is built, but a `Mem` or `SyncReadMem` initialized with +`loadMemoryFromFileInline` reads values that are not in the file, so an `expect` on them fails. + +**Why and fix:** ChiselSim randomizes memories after `$readmemh` loads the file; turn that off for +the simulation, as [Module 2.8](../2.8_memories.ipynb) explains and does: + +```scala +simulate(new MyModule, randomization = chisel3.simulator.Randomization.random.copy(memories = false)) { c => ... } +``` diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..d6fa7c7 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,3 @@ +# Python style: black (run by pre-commit and CI, see CONTRIBUTING.md) +[tool.black] +line-length = 120 diff --git a/riscv/DESIGN.md b/riscv/DESIGN.md new file mode 100644 index 0000000..1e2c68c --- /dev/null +++ b/riscv/DESIGN.md @@ -0,0 +1,226 @@ +# Design of the Module 5 RISC-V project + +Decisions for the processor built in Module 5 and for this sbt project. The notebooks of Module 5 +refer to this file. + +## Build tool: sbt + +The project is built with [sbt](https://www.scala-sbt.org/) 1.x (pinned in +`project/build.properties`), not Mill, because: + +- it is the build tool most Chisel material for learners uses (the chisel-template project, + Chipyard, Rocket Chip's users), so what students learn here carries over; +- its dependencies resolve through coursier into the same `COURSIER_CACHE` the notebooks use, so + the Docker image shares one preloaded cache, and sbt runs on the image's JRE; +- sbt 1.x keeps the build definition in Scala 2.12, independent of the project's Scala 2.13; + sbt 2.0 (Scala 3 build definitions) can follow once the course material settles. + +Cost in the Docker image (measured with sbt 1.13.1 and Chisel 7.16.0, before the image was cut +down to its present 0.65 GB): +140 MB (961 MB to 1.1 GB): the sbt launcher (4 MB, without the +`sbtn` native clients), sbt's runtime and Scala 2.12 in +`/opt/cache/sbt` (73 MB), and the project's extra dependencies in `/opt/cache/coursier` (58 MB); +the image stores the jars that both hold once. +The warm-up `sbt update Test/compile` adds about a minute to a native image build; a complete +Arm64 cross-build under qemu took 310 s (see the Dockerfile for the qemu workaround). + +## ISA: RV32I only, no CSRs + +RV32I, pinned to "The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture", +version 20240411. `Instructions.all` lists its 40 instructions (FENCE.I belongs to Zifencei). +Nothing else: no CSRs (Zicsr), hence no privileged architecture, traps or interrupts, and no +extensions (M, A, C, F, ...). The CSR instructions (SYSTEM opcode, funct3 != 0) are illegal. + +Without CSRs there is no trap handler, so `ECALL`, `EBREAK`, an illegal instruction and a +misaligned access (load/store, or a branch/jump target that is not 4-byte aligned) halt the +core, which reports the cause on its retire port. So does an access (or a fetch) outside the RAM, +until the bus and its memory-mapped devices arrive (Module 5.8). `FENCE` is a no-op. An +instruction that halts the core retires without changing any state: a jump to a misaligned target +does not write its link register. An access that is both misaligned and outside the RAM halts as +misaligned, and a fetch outside the RAM retires with instruction word 0; the cores must report the +same, since their retire records are compared with the golden model's. + +## Exercises and solutions + +Students work in `src/`: a module that is an exercise compiles but contains `???` where the +student's code goes, so its test fails with `NotImplementedError` until the exercise is done. +The reference solutions live in `solutions/`, with the same paths as `src/` (for example +`solutions/main/scala/riscv/Alu.scala`); a solution file replaces the scaffold file of the same +name. Both are in this repository, so contributors keep them in sync, but `.dockerignore` keeps +`solutions/` out of the Docker image that students use. The Module 5 notebooks are to show the +solutions in hidden "Solution" boxes (`source/custom.js`), as the other modules do. + +`tools/check-solutions.sh` checks both: the scaffold compiles, and with `solutions/` copied over +`src/` every test passes. CI runs it in the image with `solutions/` mounted. A course that wants +the solutions private can move `solutions/` to a private repository and run the same script with +`SOLUTIONS=/path/to/solutions`. + +## Using the project from notebooks + +`source/load-riscv.sc` compiles the project with sbt when `build.sbt`, `project/` or `src/main/` +changed since the last compilation (it compares a list of paths, sizes and times, so deleted files +count too) and adds `target/scala-2.13/classes` to the notebook's classpath, so a notebook can +`import riscv._` and use the modules in `src/` (as written by the student). A running kernel keeps +the classes it has loaded, so after editing `src/`, restart the kernel. There is one source +tree; the notebooks do not copy code. Ammonite's `import $file` was not used: the sources have +`package` declarations and need the Chisel compiler plugin, which sbt already handles. + +## Test programs and the assembler + +The programs the cores run are RV32I assembly, assembled by `riscv.Asm` (`src/main/scala/riscv/Asm.scala`), +an assembler written in Scala as part of the project, in the spirit of the one built into the +[Ripes](https://github.com/mortbopet/Ripes) simulator. There is no RISC-V compiler in the Docker +image: a bare-metal GCC with binutils, cut down to RV32I, added about 80 MB, and the course only needs +assembly. The notebooks call the assembler directly (`Asm("...")` returns the words), and it is +small enough for students to read. + +`Asm` reads the GNU syntax: the `.text`, `.data` and `.bss` sections, labels and numeric local labels +(`1b`, `1f`), the data and alignment directives, `.equ`, `%hi`/`%lo`/`%pcrel_hi`/`%pcrel_lo`, and +the RV32I pseudo-instructions (`li` of any 32-bit value, `la`, `call`, `tail`, `ret`, branches +against zero, ...); its scaladoc has the full list. It lays a program out the way the cores see +memory: `.text` from `0x8000_0000`, where the core starts (and where riscv-tests start too), then +`.data` from the next word (or the next multiple of its largest `.align`), then `.bss`, which is +not in the image and which nothing clears. +A program sets up its own stack pointer if it needs one (the RAM is 64 KB, so `li sp, 0x80010000`) +and ends with `ECALL`, leaving its result in `a0`. + +`programs/src/*.S` are the course's programs and `programs/hex/.hex` their memory images, one +little-endian 32-bit word per line for `$readmemh`. After editing a program, regenerate its image: + +``` +sbt "runMain riscv.Asm programs/src/fact.S programs/hex/fact.hex" +``` + +`AsmSpec` fails if an image does not match its source. The committed images were produced by GNU as +and ld (2.44, `-march=rv32i -mno-relax`, with the same layout), so the test also checks `Asm` against +GNU on whole programs; it compares single instructions and every directive and pseudo-instruction +with GNU output too, and assembles each of the 40 instructions. + +Without a C compiler the course has no C programs. A student who wants one can install a bare-metal +RISC-V GCC (`-march=rv32i -mabi=ilp32 -nostdlib`, linked at `0x8000_0000` with `.text` first) and +convert its output with `objcopy -O binary` and `hexdump -v -e '1/4 "%08x\n"'`. + +## The golden model + +`riscv.IsaSim` (`src/main/scala/riscv/IsaSim.scala`) interprets RV32I one instruction at a time and +reports each as a `Retire` record: PC, instruction, next PC, register write, memory access and halt +cause, the fields of the cores' RVFI-style retire port. Tests compare a core's retire stream with +it, not only the final state. It is a teaching oracle written together with the course (it uses +`Rv32i.decode`), not an independent reference; the riscv-tests suite (Module 5.5) is the +independent check. + +`riscv.RandomProgram(seed)` writes a random RV32I program in assembly that halts by construction: +branches and jumps only go forward, loads and stores stay in a 1 KB data area based on `s11`. A +program that exposes a difference can be saved as a `.S` file and kept as a regression test. + +## Memory interface and the single-cycle core + +The cores reach memory through `MemPort` (`src/main/scala/riscv/Memory.scala`): a `Decoupled` +request (word address, write data, byte strobes) and a `Valid` response (data, error for an +address outside the memory). The RAM (`Ram`, 64 KB at `0x8000_0000`, constants in `object Ram` +that `IsaSim` shares) answers in the same cycle on an instruction and a data port, and has a load +port through which testbenches write programs while reset is held. It has a single write port: +firtool drops the write masks of a memory that also has a write port without a mask (a constant +all-ones mask counts as none), so a masked write would write every byte (see 2.8). + +`SingleCycleCore` retires one instruction per cycle and depends on that same-cycle answer (it +ignores `ready`); a bus that answers later needs a core that tracks its requests. It reports each +retired instruction on a `Valid(RetireInfo)` port with the fields of `IsaSim`'s `Retire`, and +`CoSim` runs a program on a core with its RAM (any `RiscvSystem`: the load, retire, halted and +debug ports of `SystemIO`) and on `IsaSim`, and returns the first difference. The tests run +directed programs (each feature, every halt cause), the committed programs, random programs, and +`programs/regress/*.S`, programs that once exposed a bug (`RegressSpec`), through `CoSim`. Reset +does not clear the RAM or the registers, so a program may read only what it wrote, or its image. + +## The official tests + +`programs/riscv-tests/rv32ui/` holds the rv32ui tests of +[riscv-tests](https://github.com/riscv-software-src/riscv-tests) (BSD license, in +`programs/riscv-tests/LICENSE`) at a pinned revision, already expanded: they are written with C +preprocessor macros, and the image has no compiler. `tools/import-riscv-tests.py` (run where git and +`cpp` are available; CI runs it with `--check`) expands them against `programs/riscv-tests/riscv_test.h`, +a test environment without CSRs: a test starts at `_start`, the first word of `.text`, and ends with +`ECALL`, leaving `a0` = 0 if it passed, or (failing case << 1) | 1. `riscv.Asm` assembles the +expanded files; for all of them its output is identical to GNU as and ld 2.44 with the same layout. +`fence_i` (Zifencei) and `ma_data` (misaligned accesses, which halt the cores) are left out +(`programs/riscv-tests/EXCLUDED`). `ComplianceSpec` runs the others on `IsaSim` and on the +single-cycle core (through `CoSim`, so each retired instruction is compared too). + +## The five-stage pipeline + +`PipelinedCore` (`src/main/scala/riscv/PipelinedCore.scala`) runs IF, ID, EX, MEM and WB, with +stage registers made by `Stage` (a `Valid` register with an enable and a flush). Jumps and branches +are resolved in EX, and the two younger instructions are flushed when one is taken; an instruction +that halts the core flushes all younger ones when it is in MEM, the last stage that finds a halt +cause, so none of them changes memory or registers. Its register reads see a register that WB +writes in the same cycle (written first, read second), but it handles no other data hazard: +programs for it are assembled with `Asm.padded(source, 2)`, two nops after every instruction. +`PipelineFlush` (which stage registers to flush) is the exercise. It shares `Core`, `CoreSystem` +and `CoSim` with the single-cycle core; padded riscv-tests no longer fit their branch range, so +the official tests run on the pipeline once it handles hazards (Module 5.7). + +## Hazards + +`ForwardingCore` (`src/main/scala/riscv/ForwardingCore.scala`) is the pipeline with its hazards +handled, so programs need no nops: EX takes its operands through `Forward` (EX/MEM first, then +MEM/WB, never for x0; the exercise), a load followed by a use of its value stalls one cycle +(`loadUse`), and while the data memory has not answered the whole pipeline holds (`memWait`; EX +keeps its forwarded operands, and redirects wait; the instruction memory must still answer in the +same cycle). It passes the rv32ui tests unchanged. `CoSim.timed` counts cycles: ForwardingSpec +prints the CPI of the Fibonacci and factorial programs and checks that it beats the padded 5.6 +pipeline. The memory-wait path is tested with a data memory that answers two cycles late. + +## A bus and memory-mapped I/O + +`SocSystem` (`src/main/scala/riscv/Soc.scala`) puts `ForwardingCore`'s data port on a `Bus` +(`Bus.scala`): one request at a time, registered (a cycle of latency), routed by address to a +device that answers when it can; an unmapped address is answered with an error (a `BadAddress` +halt). The devices are the RAM (`0x8000_0000`, 64 KB) and a `Uart` (`0x1000_0000`: a data register, +and a status register at +4 that reads 1 while a byte is being sent). A write to the data register +is not answered while the transmitter (`UartTx`, the exercise: start bit, 8 data bits LSB first, +stop bit, `divider` cycles each) is busy, so programs need no status loop and their instruction +streams stay deterministic. `ForwardingCore` sends each data request once (`req.fire`), then waits. +Instructions still come from the RAM's own port, which answers in the same cycle. The golden model +takes memory-mapped `Device`s (`UartModel` sends at once; each `RiscvSystem` gives its golden +model, `SocSystem` with the UART), so `CoSim.compare` checks `programs/src/hello.S` instruction by +instruction, and `UartReceiver` decodes `txd` in software. A program that reads the UART's status +cannot be compared that way: the model's UART is never busy. + +## Debugging and verification + +Module 5.9 plants bugs in the forwarding unit (`ForwardingCore(forwardUnit = ...)` builds the core +with another `Forward`) and finds them three ways. Each `Retire` prints as a line of a trace, +disassembled by `Rv32i.disassemble` (as `objdump -M no-aliases` does, near enough; its output `Asm` +assembles back to the same word, tested on every instruction of the programs but `fence`, which it +shows without operands), so `CoSim.compare`'s messages name the instruction that differs and what it +did. `Vcd` reads the VCD file (binary search per signal, so long tables stay fast) of `simulate(..., +waves = ...)`, so a notebook can print signals per cycle without a waveform viewer. `Formal.prove` +emits a check module (`ForwardCheck.scala`: a unit next to its specification, written with +last-connect `when`s rather than a `MuxCase`, with an output `ok`) and runs Yosys's `sat -prove` on +it: a proof for every input of a combinational module, or a counterexample (a module with registers +would need `sat -seq`, and a different table parser). The formal flow was chosen after a spike: +stable Alpine has no Yosys (edge's needs edge's Python), firtool's jar ships no `circt-bmc`, and +building Yosys in the image would take hours under QEMU for Arm64, while YoWASP's Yosys +(WebAssembly, run by wasmtime, with musl wheels for x86-64 and Arm64) installs with pip (pinned with +its runtime and wasmtime) and adds about 115 MB. Its first run in a container compiles the +WebAssembly (about a minute); the compiled cache (220 MB) is not baked into the image. SymbiYosys +(multi-cycle BMC and induction) is not installed. + +## Synthesis and a board + +Module 5.10 takes the designs through Verilator's lint and Yosys's synthesis (`Synth.lint`, +`Synth.cells`; `sbt "runMain riscv.SynthReport"` prints the table for the decoders and cores). +`Yosys.verilog` emits SystemVerilog that Yosys's reader takes: firtool's +`disallowLocalVariables,disallowPackedArrays` lowering options, no layers, no randomization +(without them, Yosys rejects the `switch` decoder's packed-array table and the pipelined cores' +`automatic` variables). Families: iCE40 and ECP5, two that nextpnr supports. The +combinational register file decides the iCE40 numbers (992 flip-flops, x0 being constant, as iCE40 block RAMs read +synchronously; the forwarding core alone is about 4500 of an UP5K's 5280 LUTs), so the board is a +ULX3S (ECP5: LUT RAM reads combinationally). `Ulx3sTop` (`Board.scala`) boots a program from a ROM +through the RAM's load port with the system held in reset (rather than initializing the RAM with +`$readmemh`: a reset then restores the program's data too), and runs `SocSystem` with a 4 KB RAM +(`ramWords`); `fpga/ulx3s.lpf` gives its pins (from the board's published `ulx3s_v20.lpf`) and +`fpga/ulx3s.sh` runs synthesis, nextpnr-ecp5 and ecppack. Place and route is not in the image +(YoWASP's nextpnr-ice40 wheel alone is 72 MB): the script was checked with YoWASP's nextpnr-ecp5 in +a scratch container (LFE5U-12F, about 48 MHz against the board's 25 MHz), not on a board. Yosys's +`ltp` was tried as a stand-in for timing and dropped: it follows paths through LUT RAM across +cycles, so its lengths mean nothing here. diff --git a/riscv/build.sbt b/riscv/build.sbt new file mode 100644 index 0000000..85e9e02 --- /dev/null +++ b/riscv/build.sbt @@ -0,0 +1,14 @@ +// The RISC-V processor of Module 5. Versions must agree with the Dockerfile and +// source/load-ivy.sc (tools/check-versions.py checks them). +scalaVersion := "2.13.18" + +val chiselVersion = "7.16.0" + +libraryDependencies ++= Seq( + "org.chipsalliance" %% "chisel" % chiselVersion, + "org.scalatest" %% "scalatest" % "3.2.19" % Test +) +addCompilerPlugin("org.chipsalliance" % "chisel-plugin" % chiselVersion cross CrossVersion.full) +scalacOptions ++= Seq("-deprecation", "-feature", "-language:reflectiveCalls") +// ChiselSim tests build Verilator models; run them one at a time +Test / parallelExecution := false diff --git a/riscv/fpga/README.md b/riscv/fpga/README.md new file mode 100644 index 0000000..46db868 --- /dev/null +++ b/riscv/fpga/README.md @@ -0,0 +1,39 @@ +# The processor on an FPGA board + +`Ulx3sTop` (`src/main/scala/riscv/Board.scala`) runs the system of Module 5.8 (the forwarding core, +the bus, a 4 KB RAM and the UART) on a [ULX3S](https://github.com/emard/ulx3s) board, whose Lattice +ECP5 FPGA the open tools support from synthesis to bitstream. It copies a program into the RAM when +the FPGA starts (and on button F1), runs it, and sends what it prints to the board's USB serial +port at 115200 baud; LED 0 lights when the program is loaded, LED 1 when it has halted. + +From `riscv/`: + +``` +fpga/ulx3s.sh hello 12k # SystemVerilog, synthesis, place and route, bitstream +openFPGALoader -b ulx3s fpga/build/Ulx3sTop.bit +screen /dev/ttyUSB0 115200 # or any serial terminal: "Hello, world!" +``` + +The second argument is the size of the board's FPGA (`12k`, `25k`, `45k` or `85k`). The script +needs sbt, Yosys, nextpnr-ecp5 and ecppack (Project Trellis), for example from the +[OSS CAD Suite](https://github.com/YosysHQ/oss-cad-suite-build), or YoWASP's builds: +`pip install yowasp-yosys yowasp-nextpnr-ecp5`. The bootcamp's Docker image has Yosys only (and +no USB access to a board), so there the script stops at once, saying that nextpnr-ecp5 is missing: +run it on your machine. In the image, `sbt "runMain riscv.Ulx3s"` and Yosys go as far as +synthesis, as Module 5.10 does. + +`ulx3s.lpf` gives the pins of `Ulx3sTop`'s ports, taken from the board's published constraints. +A program must fit in the 4 KB RAM and keep its stack there. `hello.S` does; `fact.S` does not run +on the board: its stack is at the top of the 64 KB of the simulations, outside the board's RAM, so +its first store halts the core with a bad address. LEDs 2-7 show the 6 low bits of a0, so a +program that does not print shows its result there. + +With the hello program on the board's LFE5U-12F (`12k`), nextpnr-ecp5 0.11 placed and routed the +design with room to spare (4 of the 12F's 32 block RAMs) and reported a maximum clock of about +48 MHz, above the board's 25 MHz. The 12F is a 25F die sold with a smaller rated capacity: +`--12k` places on that die, so nextpnr reports 56 block RAMs and its 48 MHz is a timing estimate +for the chip on the board; ecppack writes the 12F's IDCODE, which the chip checks before it accepts +a bitstream. nextpnr does not keep a design within the 12F's rated resources, so compare its +"Device utilisation" lines with them, such as TRELLIS_COMB (LUTs) with 12K and DP16KD (block RAMs) +with 32. These results come from YoWASP's builds of the tools; the bitstream has not been run on a +board for this course. diff --git a/riscv/fpga/ulx3s.lpf b/riscv/fpga/ulx3s.lpf new file mode 100644 index 0000000..751a9db --- /dev/null +++ b/riscv/fpga/ulx3s.lpf @@ -0,0 +1,36 @@ +# Pins of Ulx3sTop on a ULX3S board (v2.x), from the board's published constraints +# (ulx3s_v20.lpf in https://github.com/emard/ulx3s). The names are Ulx3sTop's ports. +BLOCK RESETPATHS; +BLOCK ASYNCPATHS; +SYSCONFIG CONFIG_IOVOLTAGE=3.3 COMPRESS_CONFIG=ON MCCLK_FREQ=62 SLAVE_SPI_PORT=DISABLE MASTER_SPI_PORT=ENABLE SLAVE_PARALLEL_PORT=DISABLE; + +# the 25 MHz oscillator +LOCATE COMP "clock" SITE "G2"; +IOBUF PORT "clock" PULLMODE=NONE IO_TYPE=LVCMOS33; +FREQUENCY PORT "clock" 25 MHZ; + +# button F1 (high while pressed): reset +LOCATE COMP "reset" SITE "R1"; +IOBUF PORT "reset" PULLMODE=DOWN IO_TYPE=LVCMOS33; + +# the UART: the FPGA sends to the FTDI chip, the board's USB serial port +LOCATE COMP "ftdi_rxd" SITE "L4"; +IOBUF PORT "ftdi_rxd" PULLMODE=UP IO_TYPE=LVCMOS33 DRIVE=4; + +# the 8 LEDs +LOCATE COMP "led[0]" SITE "B2"; +LOCATE COMP "led[1]" SITE "C2"; +LOCATE COMP "led[2]" SITE "C1"; +LOCATE COMP "led[3]" SITE "D2"; +LOCATE COMP "led[4]" SITE "D1"; +LOCATE COMP "led[5]" SITE "E2"; +LOCATE COMP "led[6]" SITE "E1"; +LOCATE COMP "led[7]" SITE "H3"; +IOBUF PORT "led[0]" PULLMODE=NONE IO_TYPE=LVCMOS33 DRIVE=4; +IOBUF PORT "led[1]" PULLMODE=NONE IO_TYPE=LVCMOS33 DRIVE=4; +IOBUF PORT "led[2]" PULLMODE=NONE IO_TYPE=LVCMOS33 DRIVE=4; +IOBUF PORT "led[3]" PULLMODE=NONE IO_TYPE=LVCMOS33 DRIVE=4; +IOBUF PORT "led[4]" PULLMODE=NONE IO_TYPE=LVCMOS33 DRIVE=4; +IOBUF PORT "led[5]" PULLMODE=NONE IO_TYPE=LVCMOS33 DRIVE=4; +IOBUF PORT "led[6]" PULLMODE=NONE IO_TYPE=LVCMOS33 DRIVE=4; +IOBUF PORT "led[7]" PULLMODE=NONE IO_TYPE=LVCMOS33 DRIVE=4; diff --git a/riscv/fpga/ulx3s.sh b/riscv/fpga/ulx3s.sh new file mode 100755 index 0000000..e13a724 --- /dev/null +++ b/riscv/fpga/ulx3s.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Build a bitstream of Ulx3sTop (the system of Module 5.8, running programs/src/.S) for a +# ULX3S board: SystemVerilog (sbt), synthesis (Yosys), place and route (nextpnr-ecp5) and the +# bitstream (ecppack), all in fpga/build/. Each tool is taken as `tool` or, else, as YoWASP's +# `yowasp-tool` (pip install yowasp-yosys yowasp-nextpnr-ecp5). The bootcamp image has Yosys only. +# +# Usage: fpga/ulx3s.sh [program] [12k|25k|45k|85k] (from riscv/; default: hello on a 12k board) +# Then: openFPGALoader -b ulx3s fpga/build/Ulx3sTop.bit +set -euo pipefail + +program=${1:-hello} +device=${2:-12k} +[[ $program =~ ^[A-Za-z0-9_-]+$ ]] || { + echo "fpga/ulx3s.sh: the program is the name of a file of programs/src, without .S" >&2 + exit 1 +} +[[ $device =~ ^(12k|25k|45k|85k)$ ]] || { + echo "fpga/ulx3s.sh: the device is 12k, 25k, 45k or 85k" >&2 + exit 1 +} +cd "$(dirname "$0")/.." + +tool() { # the command for a tool, or its YoWASP build + for cmd in "$1" "yowasp-$1"; do + if command -v "$cmd" >/dev/null; then + echo "$cmd" + return + fi + done + echo "fpga/ulx3s.sh: neither $1 nor yowasp-$1 is installed" >&2 + exit 1 +} +yosys=$(tool yosys) +nextpnr=$(tool nextpnr-ecp5) +ecppack=$(tool ecppack) + +rm -f fpga/build/Ulx3sTop.bit # a failed build must not leave an old bitstream to flash +sbt -batch "runMain riscv.Ulx3s $program" +"$yosys" -q -p "read_verilog -sv fpga/build/Ulx3sTop.sv; synth_ecp5 -top Ulx3sTop; delete t:\$scopeinfo; write_json fpga/build/Ulx3sTop.json" +"$nextpnr" "--$device" --package CABGA381 --json fpga/build/Ulx3sTop.json --lpf fpga/ulx3s.lpf \ + --textcfg fpga/build/Ulx3sTop.config +"$ecppack" --compress fpga/build/Ulx3sTop.config fpga/build/Ulx3sTop.bit +echo "fpga/build/Ulx3sTop.bit: program it with openFPGALoader -b ulx3s fpga/build/Ulx3sTop.bit" diff --git a/riscv/programs/hex/fact.hex b/riscv/programs/hex/fact.hex new file mode 100644 index 0000000..0db0266 --- /dev/null +++ b/riscv/programs/hex/fact.hex @@ -0,0 +1,36 @@ +80010137 +00500513 +00000097 +01c080e7 +00000297 +07c28293 +00a2a023 +00000073 +0000006f +00100293 +02a2da63 +ff810113 +00112223 +00a12023 +fff50513 +00000097 +fe8080e7 +00012583 +00000097 +01c080e7 +00412083 +00810113 +00008067 +00100513 +00008067 +00050293 +00000513 +00058e63 +0015f313 +00030463 +00550533 +00129293 +0015d593 +fe9ff06f +00008067 +00000000 diff --git a/riscv/programs/hex/fib.hex b/riscv/programs/hex/fib.hex new file mode 100644 index 0000000..2992e1d --- /dev/null +++ b/riscv/programs/hex/fib.hex @@ -0,0 +1,11 @@ +00a00293 +00000513 +00100593 +00028c63 +00b50333 +00058513 +00030593 +fff28293 +fedff06f +00000073 +0000006f diff --git a/riscv/programs/hex/hello.hex b/riscv/programs/hex/hello.hex new file mode 100644 index 0000000..774005b --- /dev/null +++ b/riscv/programs/hex/hello.hex @@ -0,0 +1,13 @@ +100002b7 +00000317 +02030313 +00034383 +00038863 +00728023 +00130313 +ff1ff06f +00000073 +6c6c6548 +77202c6f +646c726f +00000a21 diff --git a/riscv/programs/hex/sum.hex b/riscv/programs/hex/sum.hex new file mode 100644 index 0000000..34cb93c --- /dev/null +++ b/riscv/programs/hex/sum.hex @@ -0,0 +1,77 @@ +00000513 +00200393 +00000297 +02c28293 +04000313 +0002ae03 +01c50533 +00428293 +fff30313 +fe0318e3 +fff38393 +fc039ee3 +00000073 +00000000 +00000001 +00000002 +00000003 +00000004 +00000005 +00000006 +00000007 +00000008 +00000009 +0000000a +0000000b +0000000c +0000000d +0000000e +0000000f +00000010 +00000011 +00000012 +00000013 +00000014 +00000015 +00000016 +00000017 +00000018 +00000019 +0000001a +0000001b +0000001c +0000001d +0000001e +0000001f +00000020 +00000021 +00000022 +00000023 +00000024 +00000025 +00000026 +00000027 +00000028 +00000029 +0000002a +0000002b +0000002c +0000002d +0000002e +0000002f +00000030 +00000031 +00000032 +00000033 +00000034 +00000035 +00000036 +00000037 +00000038 +00000039 +0000003a +0000003b +0000003c +0000003d +0000003e +0000003f diff --git a/riscv/programs/regress/README.md b/riscv/programs/regress/README.md new file mode 100644 index 0000000..eedfe32 --- /dev/null +++ b/riscv/programs/regress/README.md @@ -0,0 +1,11 @@ +# Regression programs + +Programs that once exposed a difference between a core and the golden model (`riscv.IsaSim`). +`RegressSpec` runs each `.S` file here (today on the single-cycle core; later cores join it) and +compares what the core retires with the golden model, one test per program. + +When `CoSim.compare` or a random program finds a bug, save the program here with a comment that +says what went wrong: `RandomProgram(seed)` returns the program's source text, starting with a +`# RandomProgram(seed = ...)` line. Reset clears neither the RAM nor the registers (nor does a fresh +simulation promise their values), so a program must not read a register or a memory word it has not +written (or that is not in its image). diff --git a/riscv/programs/regress/byte-lanes.S b/riscv/programs/regress/byte-lanes.S new file mode 100644 index 0000000..6666c22 --- /dev/null +++ b/riscv/programs/regress/byte-lanes.S @@ -0,0 +1,12 @@ +# R4: stores of bytes and half-words overwrote whole words. The RAM had a masked write port for the +# core's stores and an unmasked one for the program loader, and firtool dropped the masks of both. + la s0, d + li t0, 0x8081 + sh t0, 2(s0) + sb t0, 1(s0) + lw a0, 0(s0) # 0x80818144 when every byte is right + lh a1, 2(s0) + lbu a2, 1(s0) + ecall + .data +d: .word 0x11223344 diff --git a/riscv/programs/riscv-tests/EXCLUDED b/riscv/programs/riscv-tests/EXCLUDED new file mode 100644 index 0000000..47b77b0 --- /dev/null +++ b/riscv/programs/riscv-tests/EXCLUDED @@ -0,0 +1,2 @@ +fence_i: FENCE.I belongs to Zifencei, not RV32I +ma_data: misaligned accesses halt the course's cores (no trap handler without CSRs) diff --git a/riscv/programs/riscv-tests/LICENSE b/riscv/programs/riscv-tests/LICENSE new file mode 100644 index 0000000..48fe522 --- /dev/null +++ b/riscv/programs/riscv-tests/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2012-2015, The Regents of the University of California (Regents). +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the Regents nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, +SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING +OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED +HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE +MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. diff --git a/riscv/programs/riscv-tests/riscv_test.h b/riscv/programs/riscv-tests/riscv_test.h new file mode 100644 index 0000000..705113c --- /dev/null +++ b/riscv/programs/riscv-tests/riscv_test.h @@ -0,0 +1,13 @@ +// A CSR-free test environment for riscv-tests (replaces env/p/riscv_test.h of the riscv-tests +// repository, which sets up traps with CSRs that the course's cores do not have). A test starts at +// _start, at the first word of .text; it ends with ECALL, with a0 = 0 if it passed, or a0 = +// (number of the failing test << 1) | 1 if it failed (gp holds the test number as it runs). +#define RVTEST_RV64U +#define RVTEST_RV32U +#define TESTNUM gp +#define RVTEST_CODE_BEGIN .text; .globl _start; _start: +#define RVTEST_CODE_END +#define RVTEST_PASS fence; li TESTNUM, 1; li a0, 0; ecall +#define RVTEST_FAIL fence; 1: beqz TESTNUM, 1b; sll TESTNUM, TESTNUM, 1; or TESTNUM, TESTNUM, 1; mv a0, TESTNUM; ecall +#define RVTEST_DATA_BEGIN .data; .align 4 +#define RVTEST_DATA_END diff --git a/riscv/programs/riscv-tests/rv32ui/add.S b/riscv/programs/riscv-tests/rv32ui/add.S new file mode 100644 index 0000000..0607daa --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/add.S @@ -0,0 +1,43 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/add.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0x00000002) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0x00000003) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000007) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0x0000000a) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0xffffffff7fff8000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0x0000000080007ffe) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0xffffffff80007fff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0x000000007fff7fff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0xfffffffffffffffe) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x11, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); add x14, x11, x12;; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((13) & ((1 << (32 - 1) << 1) - 1)); li x12, ((11) & ((1 << (32 - 1) << 1) - 1)); add x11, x11, x12;; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_18: li gp, 18; li x11, ((14) & ((1 << (32 - 1) << 1) - 1)); li x12, ((11) & ((1 << (32 - 1) << 1) - 1)); add x12, x11, x12;; li x7, ((25) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_19: li gp, 19; li x11, ((13) & ((1 << (32 - 1) << 1) - 1)); add x11, x11, x11;; li x7, ((26) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); add x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); add x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((25) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); add x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((26) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((25) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_25: li gp, 25; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; nop; add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((26) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_26: li gp, 26; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_27: li gp, 27; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((25) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_28: li gp, 28; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((26) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_29: li gp, 29; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_30: li gp, 30; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((25) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_31: li gp, 31; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); nop; nop; add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((26) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_32: li gp, 32; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_33: li gp, 33; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((25) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_34: li gp, 34; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); add x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((26) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_35: li gp, 35; li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); add x2, x0, x1;; li x7, ((15) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_36: li gp, 36; li x1, ((32) & ((1 << (32 - 1) << 1) - 1)); add x2, x1, x0;; li x7, ((32) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_37: li gp, 37; add x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_38: li gp, 38; li x1, ((16) & ((1 << (32 - 1) << 1) - 1)); li x2, ((30) & ((1 << (32 - 1) << 1) - 1)); add x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/addi.S b/riscv/programs/riscv-tests/rv32ui/addi.S new file mode 100644 index 0000000..7645fb0 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/addi.S @@ -0,0 +1,30 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/addi.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x13, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x000) | (-(((0x000) >> 11) & 1) << 11));; li x7, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x13, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x001) | (-(((0x001) >> 11) & 1) << 11));; li x7, ((0x00000002) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x13, ((0x00000003) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x007) | (-(((0x007) >> 11) & 1) << 11));; li x7, ((0x0000000a) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x800) | (-(((0x800) >> 11) & 1) << 11));; li x7, ((0xfffffffffffff800) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x000) | (-(((0x000) >> 11) & 1) << 11));; li x7, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x800) | (-(((0x800) >> 11) & 1) << 11));; li x7, ((0xffffffff7ffff800) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x13, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x7ff) | (-(((0x7ff) >> 11) & 1) << 11));; li x7, ((0x00000000000007ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x13, ((0x7fffffff) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x000) | (-(((0x000) >> 11) & 1) << 11));; li x7, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x13, ((0x7fffffff) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x7ff) | (-(((0x7ff) >> 11) & 1) << 11));; li x7, ((0x00000000800007fe) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x7ff) | (-(((0x7ff) >> 11) & 1) << 11));; li x7, ((0xffffffff800007ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x800) | (-(((0x800) >> 11) & 1) << 11));; li x7, ((0x000000007ffff7ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x001) | (-(((0x001) >> 11) & 1) << 11));; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((0xfffffffffffffffe) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x13, ((0x7fffffff) & ((1 << (32 - 1) << 1) - 1)); addi x14, x13, ((0x001) | (-(((0x001) >> 11) & 1) << 11));; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((13) & ((1 << (32 - 1) << 1) - 1)); addi x11, x11, ((11) | (-(((11) >> 11) & 1) << 11));; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_18: li gp, 18; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); addi x14, x1, ((11) | (-(((11) >> 11) & 1) << 11)); addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); addi x14, x1, ((10) | (-(((10) >> 11) & 1) << 11)); nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((23) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); addi x14, x1, ((9) | (-(((9) >> 11) & 1) << 11)); nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((22) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); addi x14, x1, ((11) | (-(((11) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; addi x14, x1, ((10) | (-(((10) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((23) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; nop; addi x14, x1, ((9) | (-(((9) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((22) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; addi x1, x0, ((32) | (-(((32) >> 11) & 1) << 11));; li x7, ((32) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_25: li gp, 25; li x1, ((33) & ((1 << (32 - 1) << 1) - 1)); addi x0, x1, ((50) | (-(((50) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/and.S b/riscv/programs/riscv-tests/rv32ui/and.S new file mode 100644 index 0000000..380dcf0 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/and.S @@ -0,0 +1,32 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/and.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); and x14, x11, x12;; li x7, ((0x0f000f00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); and x14, x11, x12;; li x7, ((0x00f000f0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); and x14, x11, x12;; li x7, ((0x000f000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); and x14, x11, x12;; li x7, ((0xf000f000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); and x11, x11, x12;; li x7, ((0x0f000f00) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_7: li gp, 7; li x11, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); and x12, x11, x12;; li x7, ((0x00f000f0) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_8: li gp, 8; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); and x11, x11, x11;; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_9: li gp, 9; li x4, 0; 1: li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); and x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0f000f00) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_10: li gp, 10; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); and x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00f000f0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_11: li gp, 11; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); and x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000f000f) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_12: li gp, 12; li x4, 0; 1: li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0f000f00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); nop; and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00f000f0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); nop; nop; and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000f000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x4, 0; 1: li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0f000f00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); nop; and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00f000f0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000f000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_18: li gp, 18; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0f000f00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); nop; and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00f000f0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); nop; nop; and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000f000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0f000f00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); nop; and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00f000f0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); and x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000f000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); and x2, x0, x1;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_25: li gp, 25; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); and x2, x1, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_26: li gp, 26; and x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_27: li gp, 27; li x1, ((0x11111111) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x22222222) & ((1 << (32 - 1) << 1) - 1)); and x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/andi.S b/riscv/programs/riscv-tests/rv32ui/andi.S new file mode 100644 index 0000000..9fbd7de --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/andi.S @@ -0,0 +1,19 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/andi.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x13, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); andi x14, x13, ((0xf0f) | (-(((0xf0f) >> 11) & 1) << 11));; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x13, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); andi x14, x13, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0x000000f0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x13, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); andi x14, x13, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11));; li x7, ((0x0000000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x13, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); andi x14, x13, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); andi x11, x11, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_7: li gp, 7; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); andi x14, x1, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11)); addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00000700) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_8: li gp, 8; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); andi x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000000f0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_9: li gp, 9; li x4, 0; 1: li x1, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); andi x14, x1, ((0xf0f) | (-(((0xf0f) >> 11) & 1) << 11)); nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_10: li gp, 10; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); andi x14, x1, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00000700) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); nop; andi x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000000f0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x4, 0; 1: li x1, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); nop; nop; andi x14, x1, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; andi x1, x0, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_14: li gp, 14; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); andi x0, x1, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/auipc.S b/riscv/programs/riscv-tests/rv32ui/auipc.S new file mode 100644 index 0000000..ce71ec7 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/auipc.S @@ -0,0 +1,8 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/auipc.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; .align 3; lla a0, 1f + 10000; jal a1, 1f; 1: sub a0, a0, a1;; li x7, ((10000) & ((1 << (32 - 1) << 1) - 1)); bne a0, x7, fail; + test_3: li gp, 3; .align 3; lla a0, 1f - 10000; jal a1, 1f; 1: sub a0, a0, a1;; li x7, ((-10000) & ((1 << (32 - 1) << 1) - 1)); bne a0, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/beq.S b/riscv/programs/riscv-tests/rv32ui/beq.S new file mode 100644 index 0000000..cfd96c9 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/beq.S @@ -0,0 +1,26 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/beq.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x1, 0; li x2, 0; beq x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: beq x1, x2, 1b; bne x0, gp, fail; 3:; + test_3: li gp, 3; li x1, 1; li x2, 1; beq x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: beq x1, x2, 1b; bne x0, gp, fail; 3:; + test_4: li gp, 4; li x1, -1; li x2, -1; beq x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: beq x1, x2, 1b; bne x0, gp, fail; 3:; + test_5: li gp, 5; li x1, 0; li x2, 1; beq x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: beq x1, x2, 1b; 3:; + test_6: li gp, 6; li x1, 1; li x2, 0; beq x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: beq x1, x2, 1b; 3:; + test_7: li gp, 7; li x1, -1; li x2, 1; beq x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: beq x1, x2, 1b; 3:; + test_8: li gp, 8; li x1, 1; li x2, -1; beq x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: beq x1, x2, 1b; 3:; + test_9: li gp, 9; li x4, 0; 1: li x1, 0; li x2, -1; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_10: li gp, 10; li x4, 0; 1: li x1, 0; li x2, -1; nop; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_11: li gp, 11; li x4, 0; 1: li x1, 0; li x2, -1; nop; nop; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_12: li gp, 12; li x4, 0; 1: li x1, 0; nop; li x2, -1; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_13: li gp, 13; li x4, 0; 1: li x1, 0; nop; li x2, -1; nop; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_14: li gp, 14; li x4, 0; 1: li x1, 0; nop; nop; li x2, -1; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_15: li gp, 15; li x4, 0; 1: li x1, 0; li x2, -1; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: li x1, 0; li x2, -1; nop; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: li x1, 0; li x2, -1; nop; nop; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; li x4, 0; 1: li x1, 0; nop; li x2, -1; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_19: li gp, 19; li x4, 0; 1: li x1, 0; nop; li x2, -1; nop; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_20: li gp, 20; li x4, 0; 1: li x1, 0; nop; nop; li x2, -1; beq x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_21: li gp, 21; li x1, 1; beq x0, x0, 1f; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; 1: addi x1, x1, 1; addi x1, x1, 1;; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/bge.S b/riscv/programs/riscv-tests/rv32ui/bge.S new file mode 100644 index 0000000..9b1e314 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/bge.S @@ -0,0 +1,29 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/bge.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x1, 0; li x2, 0; bge x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bge x1, x2, 1b; bne x0, gp, fail; 3:; + test_3: li gp, 3; li x1, 1; li x2, 1; bge x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bge x1, x2, 1b; bne x0, gp, fail; 3:; + test_4: li gp, 4; li x1, -1; li x2, -1; bge x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bge x1, x2, 1b; bne x0, gp, fail; 3:; + test_5: li gp, 5; li x1, 1; li x2, 0; bge x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bge x1, x2, 1b; bne x0, gp, fail; 3:; + test_6: li gp, 6; li x1, 1; li x2, -1; bge x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bge x1, x2, 1b; bne x0, gp, fail; 3:; + test_7: li gp, 7; li x1, -1; li x2, -2; bge x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bge x1, x2, 1b; bne x0, gp, fail; 3:; + test_8: li gp, 8; li x1, 0; li x2, 1; bge x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bge x1, x2, 1b; 3:; + test_9: li gp, 9; li x1, -1; li x2, 1; bge x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bge x1, x2, 1b; 3:; + test_10: li gp, 10; li x1, -2; li x2, -1; bge x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bge x1, x2, 1b; 3:; + test_11: li gp, 11; li x1, -2; li x2, 1; bge x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bge x1, x2, 1b; 3:; + test_12: li gp, 12; li x4, 0; 1: li x1, -1; li x2, 0; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_13: li gp, 13; li x4, 0; 1: li x1, -1; li x2, 0; nop; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_14: li gp, 14; li x4, 0; 1: li x1, -1; li x2, 0; nop; nop; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_15: li gp, 15; li x4, 0; 1: li x1, -1; nop; li x2, 0; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: li x1, -1; nop; li x2, 0; nop; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: li x1, -1; nop; nop; li x2, 0; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; li x4, 0; 1: li x1, -1; li x2, 0; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_19: li gp, 19; li x4, 0; 1: li x1, -1; li x2, 0; nop; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_20: li gp, 20; li x4, 0; 1: li x1, -1; li x2, 0; nop; nop; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_21: li gp, 21; li x4, 0; 1: li x1, -1; nop; li x2, 0; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_22: li gp, 22; li x4, 0; 1: li x1, -1; nop; li x2, 0; nop; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_23: li gp, 23; li x4, 0; 1: li x1, -1; nop; nop; li x2, 0; bge x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_24: li gp, 24; li x1, 1; bge x1, x0, 1f; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; 1: addi x1, x1, 1; addi x1, x1, 1;; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/bgeu.S b/riscv/programs/riscv-tests/rv32ui/bgeu.S new file mode 100644 index 0000000..023a345 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/bgeu.S @@ -0,0 +1,29 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/bgeu.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x1, 0x00000000; li x2, 0x00000000; bgeu x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bgeu x1, x2, 1b; bne x0, gp, fail; 3:; + test_3: li gp, 3; li x1, 0x00000001; li x2, 0x00000001; bgeu x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bgeu x1, x2, 1b; bne x0, gp, fail; 3:; + test_4: li gp, 4; li x1, 0xffffffff; li x2, 0xffffffff; bgeu x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bgeu x1, x2, 1b; bne x0, gp, fail; 3:; + test_5: li gp, 5; li x1, 0x00000001; li x2, 0x00000000; bgeu x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bgeu x1, x2, 1b; bne x0, gp, fail; 3:; + test_6: li gp, 6; li x1, 0xffffffff; li x2, 0xfffffffe; bgeu x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bgeu x1, x2, 1b; bne x0, gp, fail; 3:; + test_7: li gp, 7; li x1, 0xffffffff; li x2, 0x00000000; bgeu x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bgeu x1, x2, 1b; bne x0, gp, fail; 3:; + test_8: li gp, 8; li x1, 0x00000000; li x2, 0x00000001; bgeu x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bgeu x1, x2, 1b; 3:; + test_9: li gp, 9; li x1, 0xfffffffe; li x2, 0xffffffff; bgeu x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bgeu x1, x2, 1b; 3:; + test_10: li gp, 10; li x1, 0x00000000; li x2, 0xffffffff; bgeu x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bgeu x1, x2, 1b; 3:; + test_11: li gp, 11; li x1, 0x7fffffff; li x2, 0x80000000; bgeu x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bgeu x1, x2, 1b; 3:; + test_12: li gp, 12; li x4, 0; 1: li x1, 0xefffffff; li x2, 0xf0000000; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_13: li gp, 13; li x4, 0; 1: li x1, 0xefffffff; li x2, 0xf0000000; nop; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_14: li gp, 14; li x4, 0; 1: li x1, 0xefffffff; li x2, 0xf0000000; nop; nop; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_15: li gp, 15; li x4, 0; 1: li x1, 0xefffffff; nop; li x2, 0xf0000000; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: li x1, 0xefffffff; nop; li x2, 0xf0000000; nop; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: li x1, 0xefffffff; nop; nop; li x2, 0xf0000000; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; li x4, 0; 1: li x1, 0xefffffff; li x2, 0xf0000000; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_19: li gp, 19; li x4, 0; 1: li x1, 0xefffffff; li x2, 0xf0000000; nop; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_20: li gp, 20; li x4, 0; 1: li x1, 0xefffffff; li x2, 0xf0000000; nop; nop; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_21: li gp, 21; li x4, 0; 1: li x1, 0xefffffff; nop; li x2, 0xf0000000; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_22: li gp, 22; li x4, 0; 1: li x1, 0xefffffff; nop; li x2, 0xf0000000; nop; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_23: li gp, 23; li x4, 0; 1: li x1, 0xefffffff; nop; nop; li x2, 0xf0000000; bgeu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_24: li gp, 24; li x1, 1; bgeu x1, x0, 1f; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; 1: addi x1, x1, 1; addi x1, x1, 1;; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/blt.S b/riscv/programs/riscv-tests/rv32ui/blt.S new file mode 100644 index 0000000..26b360a --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/blt.S @@ -0,0 +1,26 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/blt.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x1, 0; li x2, 1; blt x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: blt x1, x2, 1b; bne x0, gp, fail; 3:; + test_3: li gp, 3; li x1, -1; li x2, 1; blt x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: blt x1, x2, 1b; bne x0, gp, fail; 3:; + test_4: li gp, 4; li x1, -2; li x2, -1; blt x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: blt x1, x2, 1b; bne x0, gp, fail; 3:; + test_5: li gp, 5; li x1, 1; li x2, 0; blt x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: blt x1, x2, 1b; 3:; + test_6: li gp, 6; li x1, 1; li x2, -1; blt x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: blt x1, x2, 1b; 3:; + test_7: li gp, 7; li x1, -1; li x2, -2; blt x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: blt x1, x2, 1b; 3:; + test_8: li gp, 8; li x1, 1; li x2, -2; blt x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: blt x1, x2, 1b; 3:; + test_9: li gp, 9; li x4, 0; 1: li x1, 0; li x2, -1; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_10: li gp, 10; li x4, 0; 1: li x1, 0; li x2, -1; nop; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_11: li gp, 11; li x4, 0; 1: li x1, 0; li x2, -1; nop; nop; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_12: li gp, 12; li x4, 0; 1: li x1, 0; nop; li x2, -1; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_13: li gp, 13; li x4, 0; 1: li x1, 0; nop; li x2, -1; nop; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_14: li gp, 14; li x4, 0; 1: li x1, 0; nop; nop; li x2, -1; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_15: li gp, 15; li x4, 0; 1: li x1, 0; li x2, -1; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: li x1, 0; li x2, -1; nop; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: li x1, 0; li x2, -1; nop; nop; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; li x4, 0; 1: li x1, 0; nop; li x2, -1; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_19: li gp, 19; li x4, 0; 1: li x1, 0; nop; li x2, -1; nop; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_20: li gp, 20; li x4, 0; 1: li x1, 0; nop; nop; li x2, -1; blt x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_21: li gp, 21; li x1, 1; blt x0, x1, 1f; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; 1: addi x1, x1, 1; addi x1, x1, 1;; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/bltu.S b/riscv/programs/riscv-tests/rv32ui/bltu.S new file mode 100644 index 0000000..c4749d5 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/bltu.S @@ -0,0 +1,26 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/bltu.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x1, 0x00000000; li x2, 0x00000001; bltu x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bltu x1, x2, 1b; bne x0, gp, fail; 3:; + test_3: li gp, 3; li x1, 0xfffffffe; li x2, 0xffffffff; bltu x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bltu x1, x2, 1b; bne x0, gp, fail; 3:; + test_4: li gp, 4; li x1, 0x00000000; li x2, 0xffffffff; bltu x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bltu x1, x2, 1b; bne x0, gp, fail; 3:; + test_5: li gp, 5; li x1, 0x00000001; li x2, 0x00000000; bltu x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bltu x1, x2, 1b; 3:; + test_6: li gp, 6; li x1, 0xffffffff; li x2, 0xfffffffe; bltu x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bltu x1, x2, 1b; 3:; + test_7: li gp, 7; li x1, 0xffffffff; li x2, 0x00000000; bltu x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bltu x1, x2, 1b; 3:; + test_8: li gp, 8; li x1, 0x80000000; li x2, 0x7fffffff; bltu x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bltu x1, x2, 1b; 3:; + test_9: li gp, 9; li x4, 0; 1: li x1, 0xf0000000; li x2, 0xefffffff; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_10: li gp, 10; li x4, 0; 1: li x1, 0xf0000000; li x2, 0xefffffff; nop; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_11: li gp, 11; li x4, 0; 1: li x1, 0xf0000000; li x2, 0xefffffff; nop; nop; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_12: li gp, 12; li x4, 0; 1: li x1, 0xf0000000; nop; li x2, 0xefffffff; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_13: li gp, 13; li x4, 0; 1: li x1, 0xf0000000; nop; li x2, 0xefffffff; nop; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_14: li gp, 14; li x4, 0; 1: li x1, 0xf0000000; nop; nop; li x2, 0xefffffff; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_15: li gp, 15; li x4, 0; 1: li x1, 0xf0000000; li x2, 0xefffffff; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: li x1, 0xf0000000; li x2, 0xefffffff; nop; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: li x1, 0xf0000000; li x2, 0xefffffff; nop; nop; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; li x4, 0; 1: li x1, 0xf0000000; nop; li x2, 0xefffffff; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_19: li gp, 19; li x4, 0; 1: li x1, 0xf0000000; nop; li x2, 0xefffffff; nop; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_20: li gp, 20; li x4, 0; 1: li x1, 0xf0000000; nop; nop; li x2, 0xefffffff; bltu x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_21: li gp, 21; li x1, 1; bltu x0, x1, 1f; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; 1: addi x1, x1, 1; addi x1, x1, 1;; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/bne.S b/riscv/programs/riscv-tests/rv32ui/bne.S new file mode 100644 index 0000000..3898824 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/bne.S @@ -0,0 +1,26 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/bne.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x1, 0; li x2, 1; bne x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bne x1, x2, 1b; bne x0, gp, fail; 3:; + test_3: li gp, 3; li x1, 1; li x2, 0; bne x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bne x1, x2, 1b; bne x0, gp, fail; 3:; + test_4: li gp, 4; li x1, -1; li x2, 1; bne x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bne x1, x2, 1b; bne x0, gp, fail; 3:; + test_5: li gp, 5; li x1, 1; li x2, -1; bne x1, x2, 2f; bne x0, gp, fail; 1: bne x0, gp, 3f; 2: bne x1, x2, 1b; bne x0, gp, fail; 3:; + test_6: li gp, 6; li x1, 0; li x2, 0; bne x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bne x1, x2, 1b; 3:; + test_7: li gp, 7; li x1, 1; li x2, 1; bne x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bne x1, x2, 1b; 3:; + test_8: li gp, 8; li x1, -1; li x2, -1; bne x1, x2, 1f; bne x0, gp, 2f; 1: bne x0, gp, fail; 2: bne x1, x2, 1b; 3:; + test_9: li gp, 9; li x4, 0; 1: li x1, 0; li x2, 0; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_10: li gp, 10; li x4, 0; 1: li x1, 0; li x2, 0; nop; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_11: li gp, 11; li x4, 0; 1: li x1, 0; li x2, 0; nop; nop; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_12: li gp, 12; li x4, 0; 1: li x1, 0; nop; li x2, 0; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_13: li gp, 13; li x4, 0; 1: li x1, 0; nop; li x2, 0; nop; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_14: li gp, 14; li x4, 0; 1: li x1, 0; nop; nop; li x2, 0; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_15: li gp, 15; li x4, 0; 1: li x1, 0; li x2, 0; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: li x1, 0; li x2, 0; nop; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: li x1, 0; li x2, 0; nop; nop; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; li x4, 0; 1: li x1, 0; nop; li x2, 0; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_19: li gp, 19; li x4, 0; 1: li x1, 0; nop; li x2, 0; nop; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_20: li gp, 20; li x4, 0; 1: li x1, 0; nop; nop; li x2, 0; bne x1, x2, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_21: li gp, 21; li x1, 1; bne x1, x0, 1f; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; addi x1, x1, 1; 1: addi x1, x1, 1; addi x1, x1, 1;; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/jal.S b/riscv/programs/riscv-tests/rv32ui/jal.S new file mode 100644 index 0000000..b9769e6 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/jal.S @@ -0,0 +1,18 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/jal.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: +test_2: + li gp, 2 + li ra, 0 + jal x4, target_2 +linkaddr_2: + nop + nop + j fail +target_2: + la x2, linkaddr_2 + bne x2, x4, fail + test_3: li gp, 3; li ra, 1; jal x0, 1f; addi ra, ra, 1; addi ra, ra, 1; addi ra, ra, 1; addi ra, ra, 1; 1: addi ra, ra, 1; addi ra, ra, 1;; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne ra, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/jalr.S b/riscv/programs/riscv-tests/rv32ui/jalr.S new file mode 100644 index 0000000..733c347 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/jalr.S @@ -0,0 +1,33 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/jalr.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: +test_2: + li gp, 2 + li t0, 0 + la t1, target_2 + jalr t0, t1, 0 +linkaddr_2: + j fail +target_2: + la t1, linkaddr_2 + bne t0, t1, fail +test_3: + li gp, 3 + la t0, target_3 + jalr t0, t0, 0 +linkaddr_3: + j fail +target_3: + la t1, linkaddr_3 + bne t0, t1, fail + test_4: li gp, 4; li x4, 0; 1: la x6, 2f; jalr x13, x6, 0; bne x0, gp, fail; 2: addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_5: li gp, 5; li x4, 0; 1: la x6, 2f; nop; jalr x13, x6, 0; bne x0, gp, fail; 2: addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_6: li gp, 6; li x4, 0; 1: la x6, 2f; nop; nop; jalr x13, x6, 0; bne x0, gp, fail; 2: addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + .option push + .align 2 + .option norvc + test_7: li gp, 7; li t0, 1; la t1, 1f; jr t1, -4; addi t0, t0, 1; addi t0, t0, 1; addi t0, t0, 1; addi t0, t0, 1; 1: addi t0, t0, 1; addi t0, t0, 1;; li x7, ((4) & ((1 << (32 - 1) << 1) - 1)); bne t0, x7, fail; + .option pop + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/lb.S b/riscv/programs/riscv-tests/rv32ui/lb.S new file mode 100644 index 0000000..5e9ae78 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/lb.S @@ -0,0 +1,29 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/lb.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x15, 0xffffffffffffffff; la x2, tdat; lb x14, 0(x2);; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x15, 0x0000000000000000; la x2, tdat; lb x14, 1(x2);; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x15, 0xfffffffffffffff0; la x2, tdat; lb x14, 2(x2);; li x7, ((0xfffffffffffffff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x15, 0x000000000000000f; la x2, tdat; lb x14, 3(x2);; li x7, ((0x000000000000000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x15, 0xffffffffffffffff; la x2, tdat4; lb x14, -3(x2);; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x15, 0x0000000000000000; la x2, tdat4; lb x14, -2(x2);; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x15, 0xfffffffffffffff0; la x2, tdat4; lb x14, -1(x2);; li x7, ((0xfffffffffffffff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x15, 0x000000000000000f; la x2, tdat4; lb x14, 0(x2);; li x7, ((0x000000000000000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; la x1, tdat; addi x1, x1, -32; lb x5, 32(x1);; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_11: li gp, 11; la x1, tdat; addi x1, x1, -6; lb x5, 7(x1);; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_12: li gp, 12; li x4, 0; 1: la x13, tdat2; lb x14, 1(x13); addi x6, x14, 0; li x7, 0xfffffffffffffff0; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_13: li gp, 13; li x4, 0; 1: la x13, tdat3; lb x14, 1(x13); nop; addi x6, x14, 0; li x7, 0x000000000000000f; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_14: li gp, 14; li x4, 0; 1: la x13, tdat1; lb x14, 1(x13); nop; nop; addi x6, x14, 0; li x7, 0x0000000000000000; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_15: li gp, 15; li x4, 0; 1: la x13, tdat2; lb x14, 1(x13); li x7, 0xfffffffffffffff0; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: la x13, tdat3; nop; lb x14, 1(x13); li x7, 0x000000000000000f; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: la x13, tdat1; nop; nop; lb x14, 1(x13); li x7, 0x0000000000000000; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; la x5, tdat; lb x2, 0(x5); li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + test_19: li gp, 19; la x5, tdat; lb x2, 0(x5); nop; li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: +tdat1: .byte 0xff +tdat2: .byte 0x00 +tdat3: .byte 0xf0 +tdat4: .byte 0x0f diff --git a/riscv/programs/riscv-tests/rv32ui/lbu.S b/riscv/programs/riscv-tests/rv32ui/lbu.S new file mode 100644 index 0000000..3a024bb --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/lbu.S @@ -0,0 +1,29 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/lbu.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x15, 0x00000000000000ff; la x2, tdat; lbu x14, 0(x2);; li x7, ((0x00000000000000ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x15, 0x0000000000000000; la x2, tdat; lbu x14, 1(x2);; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x15, 0x00000000000000f0; la x2, tdat; lbu x14, 2(x2);; li x7, ((0x00000000000000f0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x15, 0x000000000000000f; la x2, tdat; lbu x14, 3(x2);; li x7, ((0x000000000000000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x15, 0x00000000000000ff; la x2, tdat4; lbu x14, -3(x2);; li x7, ((0x00000000000000ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x15, 0x0000000000000000; la x2, tdat4; lbu x14, -2(x2);; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x15, 0x00000000000000f0; la x2, tdat4; lbu x14, -1(x2);; li x7, ((0x00000000000000f0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x15, 0x000000000000000f; la x2, tdat4; lbu x14, 0(x2);; li x7, ((0x000000000000000f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; la x1, tdat; addi x1, x1, -32; lbu x5, 32(x1);; li x7, ((0x00000000000000ff) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_11: li gp, 11; la x1, tdat; addi x1, x1, -6; lbu x5, 7(x1);; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_12: li gp, 12; li x4, 0; 1: la x13, tdat2; lbu x14, 1(x13); addi x6, x14, 0; li x7, 0x00000000000000f0; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_13: li gp, 13; li x4, 0; 1: la x13, tdat3; lbu x14, 1(x13); nop; addi x6, x14, 0; li x7, 0x000000000000000f; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_14: li gp, 14; li x4, 0; 1: la x13, tdat1; lbu x14, 1(x13); nop; nop; addi x6, x14, 0; li x7, 0x0000000000000000; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_15: li gp, 15; li x4, 0; 1: la x13, tdat2; lbu x14, 1(x13); li x7, 0x00000000000000f0; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: la x13, tdat3; nop; lbu x14, 1(x13); li x7, 0x000000000000000f; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: la x13, tdat1; nop; nop; lbu x14, 1(x13); li x7, 0x0000000000000000; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; la x5, tdat; lbu x2, 0(x5); li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + test_19: li gp, 19; la x5, tdat; lbu x2, 0(x5); nop; li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: +tdat1: .byte 0xff +tdat2: .byte 0x00 +tdat3: .byte 0xf0 +tdat4: .byte 0x0f diff --git a/riscv/programs/riscv-tests/rv32ui/ld_st.S b/riscv/programs/riscv-tests/rv32ui/ld_st.S new file mode 100644 index 0000000..c3b15ea --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/ld_st.S @@ -0,0 +1,62 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/ld_st.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; la x2, tdat; li x1, 0xffffffffffffffdd; sb x1, 0(x2); lb x14, 0(x2); sb x14, 0(x2); lb x2, 0(x2); li x7, 0xffffffffffffffdd; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 0(x4); bne x4, x2, fail; lb x14, 0(x4); bne x14, x7, fail;; + test_3: li gp, 3; la x2, tdat; li x1, 0xffffffffffffffcd; sb x1, 1(x2); lb x14, 1(x2); sb x14, 1(x2); lb x2, 1(x2); li x7, 0xffffffffffffffcd; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 1(x4); bne x4, x2, fail; lb x14, 1(x4); bne x14, x7, fail;; + test_4: li gp, 4; la x2, tdat; li x1, 0xffffffffffffffcc; sb x1, 2(x2); lb x14, 2(x2); sb x14, 2(x2); lb x2, 2(x2); li x7, 0xffffffffffffffcc; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 2(x4); bne x4, x2, fail; lb x14, 2(x4); bne x14, x7, fail;; + test_5: li gp, 5; la x2, tdat; li x1, 0xffffffffffffffbc; sb x1, 3(x2); lb x14, 3(x2); sb x14, 3(x2); lb x2, 3(x2); li x7, 0xffffffffffffffbc; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 3(x4); bne x4, x2, fail; lb x14, 3(x4); bne x14, x7, fail;; + test_6: li gp, 6; la x2, tdat; li x1, 0xffffffffffffffbb; sb x1, 4(x2); lb x14, 4(x2); sb x14, 4(x2); lb x2, 4(x2); li x7, 0xffffffffffffffbb; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 4(x4); bne x4, x2, fail; lb x14, 4(x4); bne x14, x7, fail;; + test_7: li gp, 7; la x2, tdat; li x1, 0xffffffffffffffab; sb x1, 5(x2); lb x14, 5(x2); sb x14, 5(x2); lb x2, 5(x2); li x7, 0xffffffffffffffab; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 5(x4); bne x4, x2, fail; lb x14, 5(x4); bne x14, x7, fail;; + test_8: li gp, 8; la x2, tdat; li x1, 0x33; sb x1, 0(x2); lb x14, 0(x2); sb x14, 0(x2); lb x2, 0(x2); li x7, 0x33; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 0(x4); bne x4, x2, fail; lb x14, 0(x4); bne x14, x7, fail;; + test_9: li gp, 9; la x2, tdat; li x1, 0x23; sb x1, 1(x2); lb x14, 1(x2); sb x14, 1(x2); lb x2, 1(x2); li x7, 0x23; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 1(x4); bne x4, x2, fail; lb x14, 1(x4); bne x14, x7, fail;; + test_10: li gp, 10; la x2, tdat; li x1, 0x22; sb x1, 2(x2); lb x14, 2(x2); sb x14, 2(x2); lb x2, 2(x2); li x7, 0x22; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 2(x4); bne x4, x2, fail; lb x14, 2(x4); bne x14, x7, fail;; + test_11: li gp, 11; la x2, tdat; li x1, 0x12; sb x1, 3(x2); lb x14, 3(x2); sb x14, 3(x2); lb x2, 3(x2); li x7, 0x12; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 3(x4); bne x4, x2, fail; lb x14, 3(x4); bne x14, x7, fail;; + test_12: li gp, 12; la x2, tdat; li x1, 0x11; sb x1, 4(x2); lb x14, 4(x2); sb x14, 4(x2); lb x2, 4(x2); li x7, 0x11; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 4(x4); bne x4, x2, fail; lb x14, 4(x4); bne x14, x7, fail;; + test_13: li gp, 13; la x2, tdat; li x1, 0x01; sb x1, 5(x2); lb x14, 5(x2); sb x14, 5(x2); lb x2, 5(x2); li x7, 0x01; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 5(x4); bne x4, x2, fail; lb x14, 5(x4); bne x14, x7, fail;; + test_14: li gp, 14; la x2, tdat; li x1, 0x33; sb x1, 0(x2); lbu x14, 0(x2); sb x14, 0(x2); lbu x2, 0(x2); li x7, 0x33; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 0(x4); bne x4, x2, fail; lbu x14, 0(x4); bne x14, x7, fail;; + test_15: li gp, 15; la x2, tdat; li x1, 0x23; sb x1, 1(x2); lbu x14, 1(x2); sb x14, 1(x2); lbu x2, 1(x2); li x7, 0x23; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 1(x4); bne x4, x2, fail; lbu x14, 1(x4); bne x14, x7, fail;; + test_16: li gp, 16; la x2, tdat; li x1, 0x22; sb x1, 2(x2); lbu x14, 2(x2); sb x14, 2(x2); lbu x2, 2(x2); li x7, 0x22; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 2(x4); bne x4, x2, fail; lbu x14, 2(x4); bne x14, x7, fail;; + test_17: li gp, 17; la x2, tdat; li x1, 0x12; sb x1, 3(x2); lbu x14, 3(x2); sb x14, 3(x2); lbu x2, 3(x2); li x7, 0x12; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 3(x4); bne x4, x2, fail; lbu x14, 3(x4); bne x14, x7, fail;; + test_18: li gp, 18; la x2, tdat; li x1, 0x11; sb x1, 4(x2); lbu x14, 4(x2); sb x14, 4(x2); lbu x2, 4(x2); li x7, 0x11; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 4(x4); bne x4, x2, fail; lbu x14, 4(x4); bne x14, x7, fail;; + test_19: li gp, 19; la x2, tdat; li x1, 0x01; sb x1, 5(x2); lbu x14, 5(x2); sb x14, 5(x2); lbu x2, 5(x2); li x7, 0x01; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sb x1, 5(x4); bne x4, x2, fail; lbu x14, 5(x4); bne x14, x7, fail;; + test_20: li gp, 20; la x2, tdat; li x1, 0xffffffffaabbccdd; sw x1, 0(x2); lw x14, 0(x2); sw x14, 0(x2); lw x2, 0(x2); li x7, 0xffffffffaabbccdd; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 0(x4); bne x4, x2, fail; lw x14, 0(x4); bne x14, x7, fail;; + test_21: li gp, 21; la x2, tdat; li x1, 0xffffffffdaabbccd; sw x1, 4(x2); lw x14, 4(x2); sw x14, 4(x2); lw x2, 4(x2); li x7, 0xffffffffdaabbccd; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 4(x4); bne x4, x2, fail; lw x14, 4(x4); bne x14, x7, fail;; + test_22: li gp, 22; la x2, tdat; li x1, 0xffffffffddaabbcc; sw x1, 8(x2); lw x14, 8(x2); sw x14, 8(x2); lw x2, 8(x2); li x7, 0xffffffffddaabbcc; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 8(x4); bne x4, x2, fail; lw x14, 8(x4); bne x14, x7, fail;; + test_23: li gp, 23; la x2, tdat; li x1, 0xffffffffcddaabbc; sw x1, 12(x2); lw x14, 12(x2); sw x14, 12(x2); lw x2, 12(x2); li x7, 0xffffffffcddaabbc; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 12(x4); bne x4, x2, fail; lw x14, 12(x4); bne x14, x7, fail;; + test_24: li gp, 24; la x2, tdat; li x1, 0xffffffffccddaabb; sw x1, 16(x2); lw x14, 16(x2); sw x14, 16(x2); lw x2, 16(x2); li x7, 0xffffffffccddaabb; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 16(x4); bne x4, x2, fail; lw x14, 16(x4); bne x14, x7, fail;; + test_25: li gp, 25; la x2, tdat; li x1, 0xffffffffbccddaab; sw x1, 20(x2); lw x14, 20(x2); sw x14, 20(x2); lw x2, 20(x2); li x7, 0xffffffffbccddaab; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 20(x4); bne x4, x2, fail; lw x14, 20(x4); bne x14, x7, fail;; + test_26: li gp, 26; la x2, tdat; li x1, 0x00112233; sw x1, 0(x2); lw x14, 0(x2); sw x14, 0(x2); lw x2, 0(x2); li x7, 0x00112233; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 0(x4); bne x4, x2, fail; lw x14, 0(x4); bne x14, x7, fail;; + test_27: li gp, 27; la x2, tdat; li x1, 0x30011223; sw x1, 4(x2); lw x14, 4(x2); sw x14, 4(x2); lw x2, 4(x2); li x7, 0x30011223; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 4(x4); bne x4, x2, fail; lw x14, 4(x4); bne x14, x7, fail;; + test_28: li gp, 28; la x2, tdat; li x1, 0x33001122; sw x1, 8(x2); lw x14, 8(x2); sw x14, 8(x2); lw x2, 8(x2); li x7, 0x33001122; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 8(x4); bne x4, x2, fail; lw x14, 8(x4); bne x14, x7, fail;; + test_29: li gp, 29; la x2, tdat; li x1, 0x23300112; sw x1, 12(x2); lw x14, 12(x2); sw x14, 12(x2); lw x2, 12(x2); li x7, 0x23300112; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 12(x4); bne x4, x2, fail; lw x14, 12(x4); bne x14, x7, fail;; + test_30: li gp, 30; la x2, tdat; li x1, 0x22330011; sw x1, 16(x2); lw x14, 16(x2); sw x14, 16(x2); lw x2, 16(x2); li x7, 0x22330011; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 16(x4); bne x4, x2, fail; lw x14, 16(x4); bne x14, x7, fail;; + test_31: li gp, 31; la x2, tdat; li x1, 0x12233001; sw x1, 20(x2); lw x14, 20(x2); sw x14, 20(x2); lw x2, 20(x2); li x7, 0x12233001; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sw x1, 20(x4); bne x4, x2, fail; lw x14, 20(x4); bne x14, x7, fail;; + test_32: li gp, 32; la x2, tdat; li x1, 0xffffffffffffccdd; sh x1, 0(x2); lh x14, 0(x2); sh x14, 0(x2); lh x2, 0(x2); li x7, 0xffffffffffffccdd; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 0(x4); bne x4, x2, fail; lh x14, 0(x4); bne x14, x7, fail;; + test_33: li gp, 33; la x2, tdat; li x1, 0xffffffffffffbccd; sh x1, 2(x2); lh x14, 2(x2); sh x14, 2(x2); lh x2, 2(x2); li x7, 0xffffffffffffbccd; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 2(x4); bne x4, x2, fail; lh x14, 2(x4); bne x14, x7, fail;; + test_34: li gp, 34; la x2, tdat; li x1, 0xffffffffffffbbcc; sh x1, 4(x2); lh x14, 4(x2); sh x14, 4(x2); lh x2, 4(x2); li x7, 0xffffffffffffbbcc; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 4(x4); bne x4, x2, fail; lh x14, 4(x4); bne x14, x7, fail;; + test_35: li gp, 35; la x2, tdat; li x1, 0xffffffffffffabbc; sh x1, 6(x2); lh x14, 6(x2); sh x14, 6(x2); lh x2, 6(x2); li x7, 0xffffffffffffabbc; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 6(x4); bne x4, x2, fail; lh x14, 6(x4); bne x14, x7, fail;; + test_36: li gp, 36; la x2, tdat; li x1, 0xffffffffffffaabb; sh x1, 8(x2); lh x14, 8(x2); sh x14, 8(x2); lh x2, 8(x2); li x7, 0xffffffffffffaabb; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 8(x4); bne x4, x2, fail; lh x14, 8(x4); bne x14, x7, fail;; + test_37: li gp, 37; la x2, tdat; li x1, 0xffffffffffffdaab; sh x1, 10(x2); lh x14, 10(x2); sh x14, 10(x2); lh x2, 10(x2); li x7, 0xffffffffffffdaab; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 10(x4); bne x4, x2, fail; lh x14, 10(x4); bne x14, x7, fail;; + test_38: li gp, 38; la x2, tdat; li x1, 0x2233; sh x1, 0(x2); lh x14, 0(x2); sh x14, 0(x2); lh x2, 0(x2); li x7, 0x2233; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 0(x4); bne x4, x2, fail; lh x14, 0(x4); bne x14, x7, fail;; + test_39: li gp, 39; la x2, tdat; li x1, 0x1223; sh x1, 2(x2); lh x14, 2(x2); sh x14, 2(x2); lh x2, 2(x2); li x7, 0x1223; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 2(x4); bne x4, x2, fail; lh x14, 2(x4); bne x14, x7, fail;; + test_40: li gp, 40; la x2, tdat; li x1, 0x1122; sh x1, 4(x2); lh x14, 4(x2); sh x14, 4(x2); lh x2, 4(x2); li x7, 0x1122; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 4(x4); bne x4, x2, fail; lh x14, 4(x4); bne x14, x7, fail;; + test_41: li gp, 41; la x2, tdat; li x1, 0x0112; sh x1, 6(x2); lh x14, 6(x2); sh x14, 6(x2); lh x2, 6(x2); li x7, 0x0112; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 6(x4); bne x4, x2, fail; lh x14, 6(x4); bne x14, x7, fail;; + test_42: li gp, 42; la x2, tdat; li x1, 0x0011; sh x1, 8(x2); lh x14, 8(x2); sh x14, 8(x2); lh x2, 8(x2); li x7, 0x0011; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 8(x4); bne x4, x2, fail; lh x14, 8(x4); bne x14, x7, fail;; + test_43: li gp, 43; la x2, tdat; li x1, 0x3001; sh x1, 10(x2); lh x14, 10(x2); sh x14, 10(x2); lh x2, 10(x2); li x7, 0x3001; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 10(x4); bne x4, x2, fail; lh x14, 10(x4); bne x14, x7, fail;; + test_44: li gp, 44; la x2, tdat; li x1, 0x2233; sh x1, 0(x2); lhu x14, 0(x2); sh x14, 0(x2); lhu x2, 0(x2); li x7, 0x2233; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 0(x4); bne x4, x2, fail; lhu x14, 0(x4); bne x14, x7, fail;; + test_45: li gp, 45; la x2, tdat; li x1, 0x1223; sh x1, 2(x2); lhu x14, 2(x2); sh x14, 2(x2); lhu x2, 2(x2); li x7, 0x1223; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 2(x4); bne x4, x2, fail; lhu x14, 2(x4); bne x14, x7, fail;; + test_46: li gp, 46; la x2, tdat; li x1, 0x1122; sh x1, 4(x2); lhu x14, 4(x2); sh x14, 4(x2); lhu x2, 4(x2); li x7, 0x1122; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 4(x4); bne x4, x2, fail; lhu x14, 4(x4); bne x14, x7, fail;; + test_47: li gp, 47; la x2, tdat; li x1, 0x0112; sh x1, 6(x2); lhu x14, 6(x2); sh x14, 6(x2); lhu x2, 6(x2); li x7, 0x0112; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 6(x4); bne x4, x2, fail; lhu x14, 6(x4); bne x14, x7, fail;; + test_48: li gp, 48; la x2, tdat; li x1, 0x0011; sh x1, 8(x2); lhu x14, 8(x2); sh x14, 8(x2); lhu x2, 8(x2); li x7, 0x0011; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 8(x4); bne x4, x2, fail; lhu x14, 8(x4); bne x14, x7, fail;; + test_49: li gp, 49; la x2, tdat; li x1, 0x3001; sh x1, 10(x2); lhu x14, 10(x2); sh x14, 10(x2); lhu x2, 10(x2); li x7, 0x3001; bne x2, x7, fail; la x2, tdat; sw x2,8(x2); lw x4,8(x2); sh x1, 10(x4); bne x4, x2, fail; lhu x14, 10(x4); bne x14, x7, fail;; + li a0, 0xef # Immediate load for manual store test + la a1, tdat # Load address of tdat + sb a0, 3(a1) # Store byte at offset 3 of tdat + lb a2, 3(a1) # Load byte back for verification + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: + .rept 20 + .word 0xdeadbeef + .endr diff --git a/riscv/programs/riscv-tests/rv32ui/lh.S b/riscv/programs/riscv-tests/rv32ui/lh.S new file mode 100644 index 0000000..a041472 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/lh.S @@ -0,0 +1,29 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/lh.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x15, 0x00000000000000ff; la x2, tdat; lh x14, 0(x2);; li x7, ((0x00000000000000ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x15, 0xffffffffffffff00; la x2, tdat; lh x14, 2(x2);; li x7, ((0xffffffffffffff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x15, 0x0000000000000ff0; la x2, tdat; lh x14, 4(x2);; li x7, ((0x0000000000000ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x15, 0xfffffffffffff00f; la x2, tdat; lh x14, 6(x2);; li x7, ((0xfffffffffffff00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x15, 0x00000000000000ff; la x2, tdat4; lh x14, -6(x2);; li x7, ((0x00000000000000ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x15, 0xffffffffffffff00; la x2, tdat4; lh x14, -4(x2);; li x7, ((0xffffffffffffff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x15, 0x0000000000000ff0; la x2, tdat4; lh x14, -2(x2);; li x7, ((0x0000000000000ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x15, 0xfffffffffffff00f; la x2, tdat4; lh x14, 0(x2);; li x7, ((0xfffffffffffff00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; la x1, tdat; addi x1, x1, -32; lh x5, 32(x1);; li x7, ((0x00000000000000ff) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_11: li gp, 11; la x1, tdat; addi x1, x1, -5; lh x5, 7(x1);; li x7, ((0xffffffffffffff00) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_12: li gp, 12; li x4, 0; 1: la x13, tdat2; lh x14, 2(x13); addi x6, x14, 0; li x7, 0x0000000000000ff0; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_13: li gp, 13; li x4, 0; 1: la x13, tdat3; lh x14, 2(x13); nop; addi x6, x14, 0; li x7, 0xfffffffffffff00f; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_14: li gp, 14; li x4, 0; 1: la x13, tdat1; lh x14, 2(x13); nop; nop; addi x6, x14, 0; li x7, 0xffffffffffffff00; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_15: li gp, 15; li x4, 0; 1: la x13, tdat2; lh x14, 2(x13); li x7, 0x0000000000000ff0; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: la x13, tdat3; nop; lh x14, 2(x13); li x7, 0xfffffffffffff00f; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: la x13, tdat1; nop; nop; lh x14, 2(x13); li x7, 0xffffffffffffff00; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; la x5, tdat; lh x2, 0(x5); li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + test_19: li gp, 19; la x5, tdat; lh x2, 0(x5); nop; li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: +tdat1: .half 0x00ff +tdat2: .half 0xff00 +tdat3: .half 0x0ff0 +tdat4: .half 0xf00f diff --git a/riscv/programs/riscv-tests/rv32ui/lhu.S b/riscv/programs/riscv-tests/rv32ui/lhu.S new file mode 100644 index 0000000..f6989da --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/lhu.S @@ -0,0 +1,29 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/lhu.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x15, 0x00000000000000ff; la x2, tdat; lhu x14, 0(x2);; li x7, ((0x00000000000000ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x15, 0x000000000000ff00; la x2, tdat; lhu x14, 2(x2);; li x7, ((0x000000000000ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x15, 0x0000000000000ff0; la x2, tdat; lhu x14, 4(x2);; li x7, ((0x0000000000000ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x15, 0x000000000000f00f; la x2, tdat; lhu x14, 6(x2);; li x7, ((0x000000000000f00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x15, 0x00000000000000ff; la x2, tdat4; lhu x14, -6(x2);; li x7, ((0x00000000000000ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x15, 0x000000000000ff00; la x2, tdat4; lhu x14, -4(x2);; li x7, ((0x000000000000ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x15, 0x0000000000000ff0; la x2, tdat4; lhu x14, -2(x2);; li x7, ((0x0000000000000ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x15, 0x000000000000f00f; la x2, tdat4; lhu x14, 0(x2);; li x7, ((0x000000000000f00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; la x1, tdat; addi x1, x1, -32; lhu x5, 32(x1);; li x7, ((0x00000000000000ff) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_11: li gp, 11; la x1, tdat; addi x1, x1, -5; lhu x5, 7(x1);; li x7, ((0x000000000000ff00) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_12: li gp, 12; li x4, 0; 1: la x13, tdat2; lhu x14, 2(x13); addi x6, x14, 0; li x7, 0x0000000000000ff0; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_13: li gp, 13; li x4, 0; 1: la x13, tdat3; lhu x14, 2(x13); nop; addi x6, x14, 0; li x7, 0x000000000000f00f; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_14: li gp, 14; li x4, 0; 1: la x13, tdat1; lhu x14, 2(x13); nop; nop; addi x6, x14, 0; li x7, 0x000000000000ff00; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_15: li gp, 15; li x4, 0; 1: la x13, tdat2; lhu x14, 2(x13); li x7, 0x0000000000000ff0; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: la x13, tdat3; nop; lhu x14, 2(x13); li x7, 0x000000000000f00f; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: la x13, tdat1; nop; nop; lhu x14, 2(x13); li x7, 0x000000000000ff00; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; la x5, tdat; lhu x2, 0(x5); li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + test_19: li gp, 19; la x5, tdat; lhu x2, 0(x5); nop; li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: +tdat1: .half 0x00ff +tdat2: .half 0xff00 +tdat3: .half 0x0ff0 +tdat4: .half 0xf00f diff --git a/riscv/programs/riscv-tests/rv32ui/lui.S b/riscv/programs/riscv-tests/rv32ui/lui.S new file mode 100644 index 0000000..4aa1872 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/lui.S @@ -0,0 +1,11 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/lui.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; lui x1, 0x00000; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_3: li gp, 3; lui x1, 0xfffff;sra x1,x1,1; li x7, ((0xfffffffffffff800) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_4: li gp, 4; lui x1, 0x7ffff;sra x1,x1,20; li x7, ((0x00000000000007ff) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_5: li gp, 5; lui x1, 0x80000;sra x1,x1,20; li x7, ((0xfffffffffffff800) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_6: li gp, 6; lui x0, 0x80000; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/lw.S b/riscv/programs/riscv-tests/rv32ui/lw.S new file mode 100644 index 0000000..ec0ad11 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/lw.S @@ -0,0 +1,29 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/lw.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x15, 0x0000000000ff00ff; la x2, tdat; lw x14, 0(x2);; li x7, ((0x0000000000ff00ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x15, 0xffffffffff00ff00; la x2, tdat; lw x14, 4(x2);; li x7, ((0xffffffffff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x15, 0x000000000ff00ff0; la x2, tdat; lw x14, 8(x2);; li x7, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x15, 0xfffffffff00ff00f; la x2, tdat; lw x14, 12(x2);; li x7, ((0xfffffffff00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x15, 0x0000000000ff00ff; la x2, tdat4; lw x14, -12(x2);; li x7, ((0x0000000000ff00ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x15, 0xffffffffff00ff00; la x2, tdat4; lw x14, -8(x2);; li x7, ((0xffffffffff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x15, 0x000000000ff00ff0; la x2, tdat4; lw x14, -4(x2);; li x7, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x15, 0xfffffffff00ff00f; la x2, tdat4; lw x14, 0(x2);; li x7, ((0xfffffffff00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; la x1, tdat; addi x1, x1, -32; lw x5, 32(x1);; li x7, ((0x0000000000ff00ff) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_11: li gp, 11; la x1, tdat; addi x1, x1, -3; lw x5, 7(x1);; li x7, ((0xffffffffff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_12: li gp, 12; li x4, 0; 1: la x13, tdat2; lw x14, 4(x13); addi x6, x14, 0; li x7, 0x000000000ff00ff0; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_13: li gp, 13; li x4, 0; 1: la x13, tdat3; lw x14, 4(x13); nop; addi x6, x14, 0; li x7, 0xfffffffff00ff00f; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_14: li gp, 14; li x4, 0; 1: la x13, tdat1; lw x14, 4(x13); nop; nop; addi x6, x14, 0; li x7, 0xffffffffff00ff00; bne x6, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b;; + test_15: li gp, 15; li x4, 0; 1: la x13, tdat2; lw x14, 4(x13); li x7, 0x000000000ff00ff0; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: la x13, tdat3; nop; lw x14, 4(x13); li x7, 0xfffffffff00ff00f; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: la x13, tdat1; nop; nop; lw x14, 4(x13); li x7, 0xffffffffff00ff00; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; la x5, tdat; lw x2, 0(x5); li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + test_19: li gp, 19; la x5, tdat; lw x2, 0(x5); nop; li x2, 2;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: +tdat1: .word 0x00ff00ff +tdat2: .word 0xff00ff00 +tdat3: .word 0x0ff00ff0 +tdat4: .word 0xf00ff00f diff --git a/riscv/programs/riscv-tests/rv32ui/or.S b/riscv/programs/riscv-tests/rv32ui/or.S new file mode 100644 index 0000000..340dabf --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/or.S @@ -0,0 +1,32 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/or.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); or x14, x11, x12;; li x7, ((0xff0fff0f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); or x14, x11, x12;; li x7, ((0xfff0fff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); or x14, x11, x12;; li x7, ((0x0fff0fff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); or x14, x11, x12;; li x7, ((0xf0fff0ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); or x11, x11, x12;; li x7, ((0xff0fff0f) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_7: li gp, 7; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); or x12, x11, x12;; li x7, ((0xff0fff0f) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_8: li gp, 8; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); or x11, x11, x11;; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_9: li gp, 9; li x4, 0; 1: li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); or x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff0fff0f) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_10: li gp, 10; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); or x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfff0fff0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_11: li gp, 11; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); or x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0fff0fff) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_12: li gp, 12; li x4, 0; 1: li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff0fff0f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); nop; or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfff0fff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); nop; nop; or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0fff0fff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x4, 0; 1: li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff0fff0f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); nop; or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfff0fff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0fff0fff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_18: li gp, 18; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff0fff0f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); nop; or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfff0fff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); nop; nop; or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0fff0fff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff0fff0f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); nop; or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfff0fff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); or x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0fff0fff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); or x2, x0, x1;; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_25: li gp, 25; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); or x2, x1, x0;; li x7, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_26: li gp, 26; or x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_27: li gp, 27; li x1, ((0x11111111) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x22222222) & ((1 << (32 - 1) << 1) - 1)); or x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/ori.S b/riscv/programs/riscv-tests/rv32ui/ori.S new file mode 100644 index 0000000..965254f --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/ori.S @@ -0,0 +1,19 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/ori.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x13, ((0xffffffffff00ff00) & ((1 << (32 - 1) << 1) - 1)); ori x14, x13, ((0xf0f) | (-(((0xf0f) >> 11) & 1) << 11));; li x7, ((0xffffffffffffff0f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x13, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); ori x14, x13, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x13, ((0x0000000000ff00ff) & ((1 << (32 - 1) << 1) - 1)); ori x14, x13, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11));; li x7, ((0x0000000000ff07ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x13, ((0xfffffffff00ff00f) & ((1 << (32 - 1) << 1) - 1)); ori x14, x13, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0xfffffffff00ff0ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); ori x11, x11, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0xff00fff0) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_7: li gp, 7; li x4, 0; 1: li x1, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); ori x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_8: li gp, 8; li x4, 0; 1: li x1, ((0x0000000000ff00ff) & ((1 << (32 - 1) << 1) - 1)); ori x14, x1, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11)); nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000ff07ff) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_9: li gp, 9; li x4, 0; 1: li x1, ((0xfffffffff00ff00f) & ((1 << (32 - 1) << 1) - 1)); ori x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffff00ff0ff) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_10: li gp, 10; li x4, 0; 1: li x1, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); ori x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x4, 0; 1: li x1, ((0x0000000000ff00ff) & ((1 << (32 - 1) << 1) - 1)); nop; ori x14, x1, ((0xf0f) | (-(((0xf0f) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x4, 0; 1: li x1, ((0xfffffffff00ff00f) & ((1 << (32 - 1) << 1) - 1)); nop; nop; ori x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffff00ff0ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; ori x1, x0, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0x0f0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_14: li gp, 14; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); ori x0, x1, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/sb.S b/riscv/programs/riscv-tests/rv32ui/sb.S new file mode 100644 index 0000000..db6151d --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/sb.S @@ -0,0 +1,42 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/sb.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; la x2, tdat; li x1, 0xffffffffffffffaa; la x15, 7f; sb x1, 0(x2); lb x14, 0(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffffffffaa) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; la x2, tdat; li x1, 0x0000000000000000; la x15, 7f; sb x1, 1(x2); lb x14, 1(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; la x2, tdat; li x1, 0xffffffffffffefa0; la x15, 7f; sb x1, 2(x2); lh x14, 2(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffffffefa0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; la x2, tdat; li x1, 0x000000000000000a; la x15, 7f; sb x1, 3(x2); lb x14, 3(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x000000000000000a) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; la x2, tdat8; li x1, 0xffffffffffffffaa; la x15, 7f; sb x1, -3(x2); lb x14, -3(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffffffffaa) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; la x2, tdat8; li x1, 0x0000000000000000; la x15, 7f; sb x1, -2(x2); lb x14, -2(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; la x2, tdat8; li x1, 0xffffffffffffffa0; la x15, 7f; sb x1, -1(x2); lb x14, -1(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffffffffa0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; la x2, tdat8; li x1, 0x000000000000000a; la x15, 7f; sb x1, 0(x2); lb x14, 0(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x000000000000000a) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; la x1, tdat9; li x2, 0x12345678; addi x4, x1, -32; sb x2, 32(x4); lb x5, 0(x1);; li x7, ((0x78) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_11: li gp, 11; la x1, tdat9; li x2, 0x00003098; addi x1, x1, -6; sb x2, 7(x1); la x4, tdat10; lb x5, 0(x4);; li x7, ((0xffffffffffffff98) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_12: li gp, 12; li x4, 0; 1: li x13, 0xffffffffffffffdd; la x12, tdat; sb x13, 0(x12); lb x14, 0(x12); li x7, 0xffffffffffffffdd; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_13: li gp, 13; li x4, 0; 1: li x13, 0xffffffffffffffcd; la x12, tdat; nop; sb x13, 1(x12); lb x14, 1(x12); li x7, 0xffffffffffffffcd; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_14: li gp, 14; li x4, 0; 1: li x13, 0xffffffffffffffcc; la x12, tdat; nop; nop; sb x13, 2(x12); lb x14, 2(x12); li x7, 0xffffffffffffffcc; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_15: li gp, 15; li x4, 0; 1: li x13, 0xffffffffffffffbc; nop; la x12, tdat; sb x13, 3(x12); lb x14, 3(x12); li x7, 0xffffffffffffffbc; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: li x13, 0xffffffffffffffbb; nop; la x12, tdat; nop; sb x13, 4(x12); lb x14, 4(x12); li x7, 0xffffffffffffffbb; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: li x13, 0xffffffffffffffab; nop; nop; la x12, tdat; sb x13, 5(x12); lb x14, 5(x12); li x7, 0xffffffffffffffab; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; li x4, 0; 1: la x2, tdat; li x1, 0x33; sb x1, 0(x2); lb x14, 0(x2); li x7, 0x33; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_19: li gp, 19; li x4, 0; 1: la x2, tdat; li x1, 0x23; nop; sb x1, 1(x2); lb x14, 1(x2); li x7, 0x23; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_20: li gp, 20; li x4, 0; 1: la x2, tdat; li x1, 0x22; nop; nop; sb x1, 2(x2); lb x14, 2(x2); li x7, 0x22; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_21: li gp, 21; li x4, 0; 1: la x2, tdat; nop; li x1, 0x12; sb x1, 3(x2); lb x14, 3(x2); li x7, 0x12; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_22: li gp, 22; li x4, 0; 1: la x2, tdat; nop; li x1, 0x11; nop; sb x1, 4(x2); lb x14, 4(x2); li x7, 0x11; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_23: li gp, 23; li x4, 0; 1: la x2, tdat; nop; nop; li x1, 0x01; sb x1, 5(x2); lb x14, 5(x2); li x7, 0x01; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + li a0, 0xef + la a1, tdat + sb a0, 3(a1) + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: +tdat1: .byte 0xef +tdat2: .byte 0xef +tdat3: .byte 0xef +tdat4: .byte 0xef +tdat5: .byte 0xef +tdat6: .byte 0xef +tdat7: .byte 0xef +tdat8: .byte 0xef +tdat9: .byte 0xef +tdat10: .byte 0xef diff --git a/riscv/programs/riscv-tests/rv32ui/sh.S b/riscv/programs/riscv-tests/rv32ui/sh.S new file mode 100644 index 0000000..c4b257d --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/sh.S @@ -0,0 +1,42 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/sh.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; la x2, tdat; li x1, 0x00000000000000aa; la x15, 7f; sh x1, 0(x2); lh x14, 0(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x00000000000000aa) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; la x2, tdat; li x1, 0xffffffffffffaa00; la x15, 7f; sh x1, 2(x2); lh x14, 2(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffffffaa00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; la x2, tdat; li x1, 0xffffffffbeef0aa0; la x15, 7f; sh x1, 4(x2); lw x14, 4(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffbeef0aa0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; la x2, tdat; li x1, 0xffffffffffffa00a; la x15, 7f; sh x1, 6(x2); lh x14, 6(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffffffa00a) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; la x2, tdat8; li x1, 0x00000000000000aa; la x15, 7f; sh x1, -6(x2); lh x14, -6(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x00000000000000aa) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; la x2, tdat8; li x1, 0xffffffffffffaa00; la x15, 7f; sh x1, -4(x2); lh x14, -4(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffffffaa00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; la x2, tdat8; li x1, 0x0000000000000aa0; la x15, 7f; sh x1, -2(x2); lh x14, -2(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x0000000000000aa0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; la x2, tdat8; li x1, 0xffffffffffffa00a; la x15, 7f; sh x1, 0(x2); lh x14, 0(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffffffa00a) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; la x1, tdat9; li x2, 0x12345678; addi x4, x1, -32; sh x2, 32(x4); lh x5, 0(x1);; li x7, ((0x5678) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_11: li gp, 11; la x1, tdat9; li x2, 0x00003098; addi x1, x1, -5; sh x2, 7(x1); la x4, tdat10; lh x5, 0(x4);; li x7, ((0x3098) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_12: li gp, 12; li x4, 0; 1: li x13, 0xffffffffffffccdd; la x12, tdat; sh x13, 0(x12); lh x14, 0(x12); li x7, 0xffffffffffffccdd; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_13: li gp, 13; li x4, 0; 1: li x13, 0xffffffffffffbccd; la x12, tdat; nop; sh x13, 2(x12); lh x14, 2(x12); li x7, 0xffffffffffffbccd; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_14: li gp, 14; li x4, 0; 1: li x13, 0xffffffffffffbbcc; la x12, tdat; nop; nop; sh x13, 4(x12); lh x14, 4(x12); li x7, 0xffffffffffffbbcc; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_15: li gp, 15; li x4, 0; 1: li x13, 0xffffffffffffabbc; nop; la x12, tdat; sh x13, 6(x12); lh x14, 6(x12); li x7, 0xffffffffffffabbc; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: li x13, 0xffffffffffffaabb; nop; la x12, tdat; nop; sh x13, 8(x12); lh x14, 8(x12); li x7, 0xffffffffffffaabb; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: li x13, 0xffffffffffffdaab; nop; nop; la x12, tdat; sh x13, 10(x12); lh x14, 10(x12); li x7, 0xffffffffffffdaab; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; li x4, 0; 1: la x2, tdat; li x1, 0x2233; sh x1, 0(x2); lh x14, 0(x2); li x7, 0x2233; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_19: li gp, 19; li x4, 0; 1: la x2, tdat; li x1, 0x1223; nop; sh x1, 2(x2); lh x14, 2(x2); li x7, 0x1223; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_20: li gp, 20; li x4, 0; 1: la x2, tdat; li x1, 0x1122; nop; nop; sh x1, 4(x2); lh x14, 4(x2); li x7, 0x1122; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_21: li gp, 21; li x4, 0; 1: la x2, tdat; nop; li x1, 0x0112; sh x1, 6(x2); lh x14, 6(x2); li x7, 0x0112; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_22: li gp, 22; li x4, 0; 1: la x2, tdat; nop; li x1, 0x0011; nop; sh x1, 8(x2); lh x14, 8(x2); li x7, 0x0011; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_23: li gp, 23; li x4, 0; 1: la x2, tdat; nop; nop; li x1, 0x3001; sh x1, 10(x2); lh x14, 10(x2); li x7, 0x3001; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + li a0, 0xbeef + la a1, tdat + sh a0, 6(a1) + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: +tdat1: .half 0xbeef +tdat2: .half 0xbeef +tdat3: .half 0xbeef +tdat4: .half 0xbeef +tdat5: .half 0xbeef +tdat6: .half 0xbeef +tdat7: .half 0xbeef +tdat8: .half 0xbeef +tdat9: .half 0xbeef +tdat10: .half 0xbeef diff --git a/riscv/programs/riscv-tests/rv32ui/simple.S b/riscv/programs/riscv-tests/rv32ui/simple.S new file mode 100644 index 0000000..efca0be --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/simple.S @@ -0,0 +1,6 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/simple.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: +fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/sll.S b/riscv/programs/riscv-tests/rv32ui/sll.S new file mode 100644 index 0000000..f86b6df --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/sll.S @@ -0,0 +1,47 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/sll.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((1) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000000000000002) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000000000000080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000000000004000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((31) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((1) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0xfffffffffffffffe) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0xffffffffffffff80) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0xffffffffffffc000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((31) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((1) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000000042424242) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000001090909080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000084848484000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((31) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x1090909080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffc0) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_18: li gp, 18; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffc1) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000000042424242) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_19: li gp, 19; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffc7) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000001090909080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_20: li gp, 20; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffce) & ((1 << (32 - 1) << 1) - 1)); sll x14, x11, x12;; li x7, ((0x0000084848484000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x11, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); sll x11, x11, x12;; li x7, ((0x00000080) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_23: li gp, 23; li x11, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); sll x12, x11, x12;; li x7, ((0x00004000) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_24: li gp, 24; li x11, ((3) & ((1 << (32 - 1) << 1) - 1)); sll x11, x11, x11;; li x7, ((24) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_25: li gp, 25; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); sll x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000000080) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_26: li gp, 26; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); sll x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000004000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_27: li gp, 27; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); sll x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_28: li gp, 28; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000000080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_29: li gp, 29; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000004000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_30: li gp, 30; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); nop; nop; sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_31: li gp, 31; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000000080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_32: li gp, 32; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000004000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_33: li gp, 33; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_34: li gp, 34; li x4, 0; 1: li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000000080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_35: li gp, 35; li x4, 0; 1: li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); nop; sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000004000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_36: li gp, 36; li x4, 0; 1: li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); nop; nop; sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_37: li gp, 37; li x4, 0; 1: li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000000080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_38: li gp, 38; li x4, 0; 1: li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); nop; sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000004000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_39: li gp, 39; li x4, 0; 1: li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); sll x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_40: li gp, 40; li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); sll x2, x0, x1;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_41: li gp, 41; li x1, ((32) & ((1 << (32 - 1) << 1) - 1)); sll x2, x1, x0;; li x7, ((32) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_42: li gp, 42; sll x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_43: li gp, 43; li x1, ((1024) & ((1 << (32 - 1) << 1) - 1)); li x2, ((2048) & ((1 << (32 - 1) << 1) - 1)); sll x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/slli.S b/riscv/programs/riscv-tests/rv32ui/slli.S new file mode 100644 index 0000000..54392ce --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/slli.S @@ -0,0 +1,30 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/slli.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x13, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((0) | (-(((0) >> 11) & 1) << 11));; li x7, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x13, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((1) | (-(((1) >> 11) & 1) << 11));; li x7, ((0x0000000000000002) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x13, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((0x0000000000000080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x13, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((14) | (-(((14) >> 11) & 1) << 11));; li x7, ((0x0000000000004000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x13, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((0) | (-(((0) >> 11) & 1) << 11));; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((1) | (-(((1) >> 11) & 1) << 11));; li x7, ((0xfffffffffffffffe) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((0xffffffffffffff80) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((14) | (-(((14) >> 11) & 1) << 11));; li x7, ((0xffffffffffffc000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((0) | (-(((0) >> 11) & 1) << 11));; li x7, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((1) | (-(((1) >> 11) & 1) << 11));; li x7, ((0x0000000042424242) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((0x0000001090909080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((14) | (-(((14) >> 11) & 1) << 11));; li x7, ((0x0000084848484000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); slli x14, x13, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((0x1090909080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); slli x11, x11, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((0x00000080) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_18: li gp, 18; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slli x14, x1, ((7) | (-(((7) >> 11) & 1) << 11)); addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000000080) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slli x14, x1, ((14) | (-(((14) >> 11) & 1) << 11)); nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000004000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slli x14, x1, ((31) | (-(((31) >> 11) & 1) << 11)); nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slli x14, x1, ((7) | (-(((7) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000000080) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); nop; slli x14, x1, ((14) | (-(((14) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000004000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); nop; nop; slli x14, x1, ((31) | (-(((31) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000080000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; slli x1, x0, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_25: li gp, 25; li x1, ((33) & ((1 << (32 - 1) << 1) - 1)); slli x0, x1, ((20) | (-(((20) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/slt.S b/riscv/programs/riscv-tests/rv32ui/slt.S new file mode 100644 index 0000000..5a2fcdb --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/slt.S @@ -0,0 +1,43 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/slt.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0x0000000000000003) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000007) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0x0000000000000007) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000003) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); slt x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((14) & ((1 << (32 - 1) << 1) - 1)); li x12, ((13) & ((1 << (32 - 1) << 1) - 1)); slt x11, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_18: li gp, 18; li x11, ((11) & ((1 << (32 - 1) << 1) - 1)); li x12, ((13) & ((1 << (32 - 1) << 1) - 1)); slt x12, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_19: li gp, 19; li x11, ((13) & ((1 << (32 - 1) << 1) - 1)); slt x11, x11, x11;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((11) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); slt x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); slt x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((12) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); slt x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; li x4, 0; 1: li x1, ((11) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_25: li gp, 25; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; nop; slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_26: li gp, 26; li x4, 0; 1: li x1, ((10) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_27: li gp, 27; li x4, 0; 1: li x1, ((16) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_28: li gp, 28; li x4, 0; 1: li x1, ((9) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_29: li gp, 29; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); li x1, ((17) & ((1 << (32 - 1) << 1) - 1)); slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_30: li gp, 30; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); li x1, ((8) & ((1 << (32 - 1) << 1) - 1)); nop; slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_31: li gp, 31; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); li x1, ((18) & ((1 << (32 - 1) << 1) - 1)); nop; nop; slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_32: li gp, 32; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((7) & ((1 << (32 - 1) << 1) - 1)); slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_33: li gp, 33; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((19) & ((1 << (32 - 1) << 1) - 1)); nop; slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_34: li gp, 34; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((6) & ((1 << (32 - 1) << 1) - 1)); slt x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_35: li gp, 35; li x1, ((-1) & ((1 << (32 - 1) << 1) - 1)); slt x2, x0, x1;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_36: li gp, 36; li x1, ((-1) & ((1 << (32 - 1) << 1) - 1)); slt x2, x1, x0;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_37: li gp, 37; slt x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_38: li gp, 38; li x1, ((16) & ((1 << (32 - 1) << 1) - 1)); li x2, ((30) & ((1 << (32 - 1) << 1) - 1)); slt x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/slti.S b/riscv/programs/riscv-tests/rv32ui/slti.S new file mode 100644 index 0000000..f64367b --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/slti.S @@ -0,0 +1,30 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/slti.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x000) | (-(((0x000) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x13, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x001) | (-(((0x001) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x13, ((0x0000000000000003) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x007) | (-(((0x007) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x13, ((0x0000000000000007) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x003) | (-(((0x003) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x800) | (-(((0x800) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x000) | (-(((0x000) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x800) | (-(((0x800) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x7ff) | (-(((0x7ff) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x000) | (-(((0x000) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x7ff) | (-(((0x7ff) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x7ff) | (-(((0x7ff) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x800) | (-(((0x800) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0x001) | (-(((0x001) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); slti x14, x13, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((11) & ((1 << (32 - 1) << 1) - 1)); slti x11, x11, ((13) | (-(((13) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_18: li gp, 18; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); slti x14, x1, ((10) | (-(((10) >> 11) & 1) << 11)); addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x1, ((10) & ((1 << (32 - 1) << 1) - 1)); slti x14, x1, ((16) | (-(((16) >> 11) & 1) << 11)); nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((16) & ((1 << (32 - 1) << 1) - 1)); slti x14, x1, ((9) | (-(((9) >> 11) & 1) << 11)); nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((11) & ((1 << (32 - 1) << 1) - 1)); slti x14, x1, ((15) | (-(((15) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((17) & ((1 << (32 - 1) << 1) - 1)); nop; slti x14, x1, ((8) | (-(((8) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((12) & ((1 << (32 - 1) << 1) - 1)); nop; nop; slti x14, x1, ((14) | (-(((14) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; slti x1, x0, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_25: li gp, 25; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); slti x0, x1, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/sltiu.S b/riscv/programs/riscv-tests/rv32ui/sltiu.S new file mode 100644 index 0000000..1b8908e --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/sltiu.S @@ -0,0 +1,30 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/sltiu.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x000) | (-(((0x000) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x13, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x001) | (-(((0x001) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x13, ((0x0000000000000003) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x007) | (-(((0x007) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x13, ((0x0000000000000007) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x003) | (-(((0x003) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x800) | (-(((0x800) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x000) | (-(((0x000) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x800) | (-(((0x800) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x7ff) | (-(((0x7ff) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x000) | (-(((0x000) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x7ff) | (-(((0x7ff) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x7ff) | (-(((0x7ff) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x800) | (-(((0x800) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x13, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0x001) | (-(((0x001) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x13, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((11) & ((1 << (32 - 1) << 1) - 1)); sltiu x11, x11, ((13) | (-(((13) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_18: li gp, 18; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x1, ((10) | (-(((10) >> 11) & 1) << 11)); addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x1, ((10) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x1, ((16) | (-(((16) >> 11) & 1) << 11)); nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((16) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x1, ((9) | (-(((9) >> 11) & 1) << 11)); nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((11) & ((1 << (32 - 1) << 1) - 1)); sltiu x14, x1, ((15) | (-(((15) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((17) & ((1 << (32 - 1) << 1) - 1)); nop; sltiu x14, x1, ((8) | (-(((8) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((12) & ((1 << (32 - 1) << 1) - 1)); nop; nop; sltiu x14, x1, ((14) | (-(((14) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; sltiu x1, x0, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_25: li gp, 25; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); sltiu x0, x1, ((0xfff) | (-(((0xfff) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/sltu.S b/riscv/programs/riscv-tests/rv32ui/sltu.S new file mode 100644 index 0000000..e9927cc --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/sltu.S @@ -0,0 +1,43 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/sltu.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0x00000003) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000007) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0x00000007) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000003) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffff8000) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x11, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x11, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffff8000) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x11, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00007fff) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x11, ((0x7fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x11, ((0x7fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00007fff) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x11, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00007fff) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x11, ((0x7fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffff8000) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x11, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffff) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x11, ((0xffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x11, ((0xffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffff) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((14) & ((1 << (32 - 1) << 1) - 1)); li x12, ((13) & ((1 << (32 - 1) << 1) - 1)); sltu x11, x11, x12;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_18: li gp, 18; li x11, ((11) & ((1 << (32 - 1) << 1) - 1)); li x12, ((13) & ((1 << (32 - 1) << 1) - 1)); sltu x12, x11, x12;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_19: li gp, 19; li x11, ((13) & ((1 << (32 - 1) << 1) - 1)); sltu x11, x11, x11;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((11) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((12) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; li x4, 0; 1: li x1, ((11) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_25: li gp, 25; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; nop; sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_26: li gp, 26; li x4, 0; 1: li x1, ((10) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_27: li gp, 27; li x4, 0; 1: li x1, ((16) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_28: li gp, 28; li x4, 0; 1: li x1, ((9) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_29: li gp, 29; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); li x1, ((17) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_30: li gp, 30; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); li x1, ((8) & ((1 << (32 - 1) << 1) - 1)); nop; sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_31: li gp, 31; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); li x1, ((18) & ((1 << (32 - 1) << 1) - 1)); nop; nop; sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_32: li gp, 32; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((7) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_33: li gp, 33; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((19) & ((1 << (32 - 1) << 1) - 1)); nop; sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_34: li gp, 34; li x4, 0; 1: li x2, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((6) & ((1 << (32 - 1) << 1) - 1)); sltu x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_35: li gp, 35; li x1, ((-1) & ((1 << (32 - 1) << 1) - 1)); sltu x2, x0, x1;; li x7, ((1) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_36: li gp, 36; li x1, ((-1) & ((1 << (32 - 1) << 1) - 1)); sltu x2, x1, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_37: li gp, 37; sltu x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_38: li gp, 38; li x1, ((16) & ((1 << (32 - 1) << 1) - 1)); li x2, ((30) & ((1 << (32 - 1) << 1) - 1)); sltu x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/sra.S b/riscv/programs/riscv-tests/rv32ui/sra.S new file mode 100644 index 0000000..00bcfcd --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/sra.S @@ -0,0 +1,48 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/sra.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((1) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffffc0000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xffffffff80000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((31) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((1) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0x000000003fffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0x0000000000ffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0x000000000001ffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((31) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((1) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffffc0c0c0c0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffffff030303) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xfffffffffffe0606) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((31) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffc0) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_18: li gp, 18; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffc1) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffffc0c0c0c0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_19: li gp, 19; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffc7) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffffff030303) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_20: li gp, 20; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffce) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xfffffffffffe0606) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_21: li gp, 21; li x11, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); sra x14, x11, x12;; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); sra x11, x11, x12;; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_23: li gp, 23; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); sra x12, x11, x12;; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_24: li gp, 24; li x11, ((7) & ((1 << (32 - 1) << 1) - 1)); sra x11, x11, x11;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_25: li gp, 25; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); sra x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_26: li gp, 26; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); sra x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_27: li gp, 27; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); sra x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_28: li gp, 28; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_29: li gp, 29; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_30: li gp, 30; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); nop; nop; sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_31: li gp, 31; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_32: li gp, 32; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_33: li gp, 33; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_34: li gp, 34; li x4, 0; 1: li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_35: li gp, 35; li x4, 0; 1: li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); nop; sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_36: li gp, 36; li x4, 0; 1: li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); nop; nop; sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_37: li gp, 37; li x4, 0; 1: li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_38: li gp, 38; li x4, 0; 1: li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); nop; sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_39: li gp, 39; li x4, 0; 1: li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); sra x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_40: li gp, 40; li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); sra x2, x0, x1;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_41: li gp, 41; li x1, ((32) & ((1 << (32 - 1) << 1) - 1)); sra x2, x1, x0;; li x7, ((32) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_42: li gp, 42; sra x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_43: li gp, 43; li x1, ((1024) & ((1 << (32 - 1) << 1) - 1)); li x2, ((2048) & ((1 << (32 - 1) << 1) - 1)); sra x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/srai.S b/riscv/programs/riscv-tests/rv32ui/srai.S new file mode 100644 index 0000000..606b0c1 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/srai.S @@ -0,0 +1,30 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/srai.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x13, ((0xffffff8000000000) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((0) | (-(((0) >> 11) & 1) << 11));; li x7, ((0xffffff8000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((1) | (-(((1) >> 11) & 1) << 11));; li x7, ((0xffffffffc0000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((14) | (-(((14) >> 11) & 1) << 11));; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x13, ((0xffffffff80000001) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((0) | (-(((0) >> 11) & 1) << 11));; li x7, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((1) | (-(((1) >> 11) & 1) << 11));; li x7, ((0x000000003fffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((0x0000000000ffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((14) | (-(((14) >> 11) & 1) << 11));; li x7, ((0x000000000001ffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x13, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x13, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((0) | (-(((0) >> 11) & 1) << 11));; li x7, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x13, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((1) | (-(((1) >> 11) & 1) << 11));; li x7, ((0xffffffffc0c0c0c0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x13, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((0xffffffffff030303) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x13, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((14) | (-(((14) >> 11) & 1) << 11));; li x7, ((0xfffffffffffe0606) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x13, ((0xffffffff81818181) & ((1 << (32 - 1) << 1) - 1)); srai x14, x13, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srai x11, x11, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_18: li gp, 18; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srai x14, x1, ((7) | (-(((7) >> 11) & 1) << 11)); addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srai x14, x1, ((14) | (-(((14) >> 11) & 1) << 11)); nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((0xffffffff80000001) & ((1 << (32 - 1) << 1) - 1)); srai x14, x1, ((31) | (-(((31) >> 11) & 1) << 11)); nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srai x14, x1, ((7) | (-(((7) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffff000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); nop; srai x14, x1, ((14) | (-(((14) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffffffe0000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((0xffffffff80000001) & ((1 << (32 - 1) << 1) - 1)); nop; nop; srai x14, x1, ((31) | (-(((31) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; srai x1, x0, ((4) | (-(((4) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_25: li gp, 25; li x1, ((33) & ((1 << (32 - 1) << 1) - 1)); srai x0, x1, ((10) | (-(((10) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/srl.S b/riscv/programs/riscv-tests/rv32ui/srl.S new file mode 100644 index 0000000..b7873b8 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/srl.S @@ -0,0 +1,48 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/srl.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffff80000000) & ((1 << (32 -1) << 1) - 1)) >> (0)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((1) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffff80000000) & ((1 << (32 -1) << 1) - 1)) >> (1)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffff80000000) & ((1 << (32 -1) << 1) - 1)) >> (7)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffff80000000) & ((1 << (32 -1) << 1) - 1)) >> (14)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xffffffff80000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((31) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffff80000001) & ((1 << (32 -1) << 1) - 1)) >> (31)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (0)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((1) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (1)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (7)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (14)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((31) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (31)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (0)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((1) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (1)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (7)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (14)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((31) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (31)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffc0) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_18: li gp, 18; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffc1) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((0x0000000010909090) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_19: li gp, 19; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffc7) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((0x0000000000424242) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_20: li gp, 20; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffce) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((0x0000000000008484) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_21: li gp, 21; li x11, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); srl x14, x11, x12;; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x11, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((7) & ((1 << (32 - 1) << 1) - 1)); srl x11, x11, x12;; li x7, ((0x01000000) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_23: li gp, 23; li x11, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((14) & ((1 << (32 - 1) << 1) - 1)); srl x12, x11, x12;; li x7, ((0x00020000) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_24: li gp, 24; li x11, ((7) & ((1 << (32 - 1) << 1) - 1)); srl x11, x11, x11;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_25: li gp, 25; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); srl x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x01000000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_26: li gp, 26; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); srl x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00020000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_27: li gp, 27; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); srl x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_28: li gp, 28; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x01000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_29: li gp, 29; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00020000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_30: li gp, 30; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); nop; nop; srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_31: li gp, 31; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x01000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_32: li gp, 32; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00020000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_33: li gp, 33; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_34: li gp, 34; li x4, 0; 1: li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x01000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_35: li gp, 35; li x4, 0; 1: li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); nop; srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00020000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_36: li gp, 36; li x4, 0; 1: li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); nop; nop; srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_37: li gp, 37; li x4, 0; 1: li x2, ((7) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x01000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_38: li gp, 38; li x4, 0; 1: li x2, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); nop; srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00020000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_39: li gp, 39; li x4, 0; 1: li x2, ((31) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); srl x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_40: li gp, 40; li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); srl x2, x0, x1;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_41: li gp, 41; li x1, ((32) & ((1 << (32 - 1) << 1) - 1)); srl x2, x1, x0;; li x7, ((32) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_42: li gp, 42; srl x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_43: li gp, 43; li x1, ((1024) & ((1 << (32 - 1) << 1) - 1)); li x2, ((2048) & ((1 << (32 - 1) << 1) - 1)); srl x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/srli.S b/riscv/programs/riscv-tests/rv32ui/srli.S new file mode 100644 index 0000000..be984e4 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/srli.S @@ -0,0 +1,30 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/srli.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((0) | (-(((0) >> 11) & 1) << 11));; li x7, ((((0xffffffff80000000) & ((1 << (32 -1) << 1) - 1)) >> (0)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((1) | (-(((1) >> 11) & 1) << 11));; li x7, ((((0xffffffff80000000) & ((1 << (32 -1) << 1) - 1)) >> (1)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((((0xffffffff80000000) & ((1 << (32 -1) << 1) - 1)) >> (7)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x13, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((14) | (-(((14) >> 11) & 1) << 11));; li x7, ((((0xffffffff80000000) & ((1 << (32 -1) << 1) - 1)) >> (14)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x13, ((0xffffffff80000001) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((((0xffffffff80000001) & ((1 << (32 -1) << 1) - 1)) >> (31)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((0) | (-(((0) >> 11) & 1) << 11));; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (0)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((1) | (-(((1) >> 11) & 1) << 11));; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (1)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (7)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((14) | (-(((14) >> 11) & 1) << 11));; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (14)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x13, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((((0xffffffffffffffff) & ((1 << (32 -1) << 1) - 1)) >> (31)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((0) | (-(((0) >> 11) & 1) << 11));; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (0)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((1) | (-(((1) >> 11) & 1) << 11));; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (1)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (7)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((14) | (-(((14) >> 11) & 1) << 11));; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (14)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x13, ((0x0000000021212121) & ((1 << (32 - 1) << 1) - 1)); srli x14, x13, ((31) | (-(((31) >> 11) & 1) << 11));; li x7, ((((0x0000000021212121) & ((1 << (32 -1) << 1) - 1)) >> (31)) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x11, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); srli x11, x11, ((7) | (-(((7) >> 11) & 1) << 11));; li x7, ((0x01000000) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_18: li gp, 18; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); srli x14, x1, ((7) | (-(((7) >> 11) & 1) << 11)); addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x01000000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); srli x14, x1, ((14) | (-(((14) >> 11) & 1) << 11)); nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00020000) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((0x80000001) & ((1 << (32 - 1) << 1) - 1)); srli x14, x1, ((31) | (-(((31) >> 11) & 1) << 11)); nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); srli x14, x1, ((7) | (-(((7) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x01000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((0x80000000) & ((1 << (32 - 1) << 1) - 1)); nop; srli x14, x1, ((14) | (-(((14) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00020000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((0x80000001) & ((1 << (32 - 1) << 1) - 1)); nop; nop; srli x14, x1, ((31) | (-(((31) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x00000001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; srli x1, x0, ((4) | (-(((4) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_25: li gp, 25; li x1, ((33) & ((1 << (32 - 1) << 1) - 1)); srli x0, x1, ((10) | (-(((10) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/st_ld.S b/riscv/programs/riscv-tests/rv32ui/st_ld.S new file mode 100644 index 0000000..436accb --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/st_ld.S @@ -0,0 +1,62 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/st_ld.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; la x2, tdat; li x1, 0xffffffffffffffdd; sb x1, 0(x2); lb x14, 0(x2); li x7, 0xffffffffffffffdd; bne x14, x7, fail;; + test_3: li gp, 3; la x2, tdat; li x1, 0xffffffffffffffcd; sb x1, 1(x2); lb x14, 1(x2); li x7, 0xffffffffffffffcd; bne x14, x7, fail;; + test_4: li gp, 4; la x2, tdat; li x1, 0xffffffffffffffcc; sb x1, 2(x2); lb x14, 2(x2); li x7, 0xffffffffffffffcc; bne x14, x7, fail;; + test_5: li gp, 5; la x2, tdat; li x1, 0xffffffffffffffbc; sb x1, 3(x2); lb x14, 3(x2); li x7, 0xffffffffffffffbc; bne x14, x7, fail;; + test_6: li gp, 6; la x2, tdat; li x1, 0xffffffffffffffbb; sb x1, 4(x2); lb x14, 4(x2); li x7, 0xffffffffffffffbb; bne x14, x7, fail;; + test_7: li gp, 7; la x2, tdat; li x1, 0xffffffffffffffab; sb x1, 5(x2); lb x14, 5(x2); li x7, 0xffffffffffffffab; bne x14, x7, fail;; + test_8: li gp, 8; la x2, tdat; li x1, 0x33; sb x1, 0(x2); lb x14, 0(x2); li x7, 0x33; bne x14, x7, fail;; + test_9: li gp, 9; la x2, tdat; li x1, 0x23; sb x1, 1(x2); lb x14, 1(x2); li x7, 0x23; bne x14, x7, fail;; + test_10: li gp, 10; la x2, tdat; li x1, 0x22; sb x1, 2(x2); lb x14, 2(x2); li x7, 0x22; bne x14, x7, fail;; + test_11: li gp, 11; la x2, tdat; li x1, 0x12; sb x1, 3(x2); lb x14, 3(x2); li x7, 0x12; bne x14, x7, fail;; + test_12: li gp, 12; la x2, tdat; li x1, 0x11; sb x1, 4(x2); lb x14, 4(x2); li x7, 0x11; bne x14, x7, fail;; + test_13: li gp, 13; la x2, tdat; li x1, 0x01; sb x1, 5(x2); lb x14, 5(x2); li x7, 0x01; bne x14, x7, fail;; + test_14: li gp, 14; la x2, tdat; li x1, 0x33; sb x1, 0(x2); lbu x14, 0(x2); li x7, 0x33; bne x14, x7, fail;; + test_15: li gp, 15; la x2, tdat; li x1, 0x23; sb x1, 1(x2); lbu x14, 1(x2); li x7, 0x23; bne x14, x7, fail;; + test_16: li gp, 16; la x2, tdat; li x1, 0x22; sb x1, 2(x2); lbu x14, 2(x2); li x7, 0x22; bne x14, x7, fail;; + test_17: li gp, 17; la x2, tdat; li x1, 0x12; sb x1, 3(x2); lbu x14, 3(x2); li x7, 0x12; bne x14, x7, fail;; + test_18: li gp, 18; la x2, tdat; li x1, 0x11; sb x1, 4(x2); lbu x14, 4(x2); li x7, 0x11; bne x14, x7, fail;; + test_19: li gp, 19; la x2, tdat; li x1, 0x01; sb x1, 5(x2); lbu x14, 5(x2); li x7, 0x01; bne x14, x7, fail;; + test_20: li gp, 20; la x2, tdat; li x1, 0xffffffffaabbccdd; sw x1, 0(x2); lw x14, 0(x2); li x7, 0xffffffffaabbccdd; bne x14, x7, fail;; + test_21: li gp, 21; la x2, tdat; li x1, 0xffffffffdaabbccd; sw x1, 4(x2); lw x14, 4(x2); li x7, 0xffffffffdaabbccd; bne x14, x7, fail;; + test_22: li gp, 22; la x2, tdat; li x1, 0xffffffffddaabbcc; sw x1, 8(x2); lw x14, 8(x2); li x7, 0xffffffffddaabbcc; bne x14, x7, fail;; + test_23: li gp, 23; la x2, tdat; li x1, 0xffffffffcddaabbc; sw x1, 12(x2); lw x14, 12(x2); li x7, 0xffffffffcddaabbc; bne x14, x7, fail;; + test_24: li gp, 24; la x2, tdat; li x1, 0xffffffffccddaabb; sw x1, 16(x2); lw x14, 16(x2); li x7, 0xffffffffccddaabb; bne x14, x7, fail;; + test_25: li gp, 25; la x2, tdat; li x1, 0xffffffffbccddaab; sw x1, 20(x2); lw x14, 20(x2); li x7, 0xffffffffbccddaab; bne x14, x7, fail;; + test_26: li gp, 26; la x2, tdat; li x1, 0x00112233; sw x1, 0(x2); lw x14, 0(x2); li x7, 0x00112233; bne x14, x7, fail;; + test_27: li gp, 27; la x2, tdat; li x1, 0x30011223; sw x1, 4(x2); lw x14, 4(x2); li x7, 0x30011223; bne x14, x7, fail;; + test_28: li gp, 28; la x2, tdat; li x1, 0x33001122; sw x1, 8(x2); lw x14, 8(x2); li x7, 0x33001122; bne x14, x7, fail;; + test_29: li gp, 29; la x2, tdat; li x1, 0x23300112; sw x1, 12(x2); lw x14, 12(x2); li x7, 0x23300112; bne x14, x7, fail;; + test_30: li gp, 30; la x2, tdat; li x1, 0x22330011; sw x1, 16(x2); lw x14, 16(x2); li x7, 0x22330011; bne x14, x7, fail;; + test_31: li gp, 31; la x2, tdat; li x1, 0x12233001; sw x1, 20(x2); lw x14, 20(x2); li x7, 0x12233001; bne x14, x7, fail;; + test_32: li gp, 32; la x2, tdat; li x1, 0xffffffffffffccdd; sh x1, 0(x2); lh x14, 0(x2); li x7, 0xffffffffffffccdd; bne x14, x7, fail;; + test_33: li gp, 33; la x2, tdat; li x1, 0xffffffffffffbccd; sh x1, 2(x2); lh x14, 2(x2); li x7, 0xffffffffffffbccd; bne x14, x7, fail;; + test_34: li gp, 34; la x2, tdat; li x1, 0xffffffffffffbbcc; sh x1, 4(x2); lh x14, 4(x2); li x7, 0xffffffffffffbbcc; bne x14, x7, fail;; + test_35: li gp, 35; la x2, tdat; li x1, 0xffffffffffffabbc; sh x1, 6(x2); lh x14, 6(x2); li x7, 0xffffffffffffabbc; bne x14, x7, fail;; + test_36: li gp, 36; la x2, tdat; li x1, 0xffffffffffffaabb; sh x1, 8(x2); lh x14, 8(x2); li x7, 0xffffffffffffaabb; bne x14, x7, fail;; + test_37: li gp, 37; la x2, tdat; li x1, 0xffffffffffffdaab; sh x1, 10(x2); lh x14, 10(x2); li x7, 0xffffffffffffdaab; bne x14, x7, fail;; + test_38: li gp, 38; la x2, tdat; li x1, 0x2233; sh x1, 0(x2); lh x14, 0(x2); li x7, 0x2233; bne x14, x7, fail;; + test_39: li gp, 39; la x2, tdat; li x1, 0x1223; sh x1, 2(x2); lh x14, 2(x2); li x7, 0x1223; bne x14, x7, fail;; + test_40: li gp, 40; la x2, tdat; li x1, 0x1122; sh x1, 4(x2); lh x14, 4(x2); li x7, 0x1122; bne x14, x7, fail;; + test_41: li gp, 41; la x2, tdat; li x1, 0x0112; sh x1, 6(x2); lh x14, 6(x2); li x7, 0x0112; bne x14, x7, fail;; + test_42: li gp, 42; la x2, tdat; li x1, 0x0011; sh x1, 8(x2); lh x14, 8(x2); li x7, 0x0011; bne x14, x7, fail;; + test_43: li gp, 43; la x2, tdat; li x1, 0x3001; sh x1, 10(x2); lh x14, 10(x2); li x7, 0x3001; bne x14, x7, fail;; + test_44: li gp, 44; la x2, tdat; li x1, 0x2233; sh x1, 0(x2); lhu x14, 0(x2); li x7, 0x2233; bne x14, x7, fail;; + test_45: li gp, 45; la x2, tdat; li x1, 0x1223; sh x1, 2(x2); lhu x14, 2(x2); li x7, 0x1223; bne x14, x7, fail;; + test_46: li gp, 46; la x2, tdat; li x1, 0x1122; sh x1, 4(x2); lhu x14, 4(x2); li x7, 0x1122; bne x14, x7, fail;; + test_47: li gp, 47; la x2, tdat; li x1, 0x0112; sh x1, 6(x2); lhu x14, 6(x2); li x7, 0x0112; bne x14, x7, fail;; + test_48: li gp, 48; la x2, tdat; li x1, 0x0011; sh x1, 8(x2); lhu x14, 8(x2); li x7, 0x0011; bne x14, x7, fail;; + test_49: li gp, 49; la x2, tdat; li x1, 0x3001; sh x1, 10(x2); lhu x14, 10(x2); li x7, 0x3001; bne x14, x7, fail;; + li a0, 0xef # Immediate load for manual store test + la a1, tdat # Load address of tdat + sb a0, 3(a1) # Store byte at offset 3 of tdat + lb a2, 3(a1) # Load byte back for verification + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: + .rept 20 + .word 0xdeadbeef + .endr diff --git a/riscv/programs/riscv-tests/rv32ui/sub.S b/riscv/programs/riscv-tests/rv32ui/sub.S new file mode 100644 index 0000000..89c9409 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/sub.S @@ -0,0 +1,42 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/sub.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0x0000000000000003) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000007) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0xfffffffffffffffc) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0x0000000000008000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0xffffffff80008000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0xffffffffffff8001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0x000000007fff8000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x11, ((0xffffffff80000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000007fff) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0xffffffff7fff8001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x11, ((0x000000007fffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0x0000000080007fff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x11, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0000000000000001) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0xfffffffffffffffe) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x11, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xffffffffffffffff) & ((1 << (32 - 1) << 1) - 1)); sub x14, x11, x12;; li x7, ((0x0000000000000000) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x11, ((13) & ((1 << (32 - 1) << 1) - 1)); li x12, ((11) & ((1 << (32 - 1) << 1) - 1)); sub x11, x11, x12;; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_17: li gp, 17; li x11, ((14) & ((1 << (32 - 1) << 1) - 1)); li x12, ((11) & ((1 << (32 - 1) << 1) - 1)); sub x12, x11, x12;; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_18: li gp, 18; li x11, ((13) & ((1 << (32 - 1) << 1) - 1)); sub x11, x11, x11;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); sub x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); sub x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); sub x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((4) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; nop; sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((4) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_25: li gp, 25; li x4, 0; 1: li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_26: li gp, 26; li x4, 0; 1: li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_27: li gp, 27; li x4, 0; 1: li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((4) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_28: li gp, 28; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_29: li gp, 29; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_30: li gp, 30; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); nop; nop; sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((4) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_31: li gp, 31; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((13) & ((1 << (32 - 1) << 1) - 1)); sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((2) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_32: li gp, 32; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((14) & ((1 << (32 - 1) << 1) - 1)); nop; sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((3) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_33: li gp, 33; li x4, 0; 1: li x2, ((11) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((15) & ((1 << (32 - 1) << 1) - 1)); sub x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((4) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_34: li gp, 34; li x1, ((-15) & ((1 << (32 - 1) << 1) - 1)); sub x2, x0, x1;; li x7, ((15) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_35: li gp, 35; li x1, ((32) & ((1 << (32 - 1) << 1) - 1)); sub x2, x1, x0;; li x7, ((32) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_36: li gp, 36; sub x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_37: li gp, 37; li x1, ((16) & ((1 << (32 - 1) << 1) - 1)); li x2, ((30) & ((1 << (32 - 1) << 1) - 1)); sub x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/sw.S b/riscv/programs/riscv-tests/rv32ui/sw.S new file mode 100644 index 0000000..c8895bc --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/sw.S @@ -0,0 +1,39 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/sw.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; la x2, tdat; li x1, 0x0000000000aa00aa; la x15, 7f; sw x1, 0(x2); lw x14, 0(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x0000000000aa00aa) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; la x2, tdat; li x1, 0xffffffffaa00aa00; la x15, 7f; sw x1, 4(x2); lw x14, 4(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffaa00aa00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; la x2, tdat; li x1, 0x000000000aa00aa0; la x15, 7f; sw x1, 8(x2); lw x14, 8(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x000000000aa00aa0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; la x2, tdat; li x1, 0xffffffffa00aa00a; la x15, 7f; sw x1, 12(x2); lw x14, 12(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffa00aa00a) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; la x2, tdat8; li x1, 0x0000000000aa00aa; la x15, 7f; sw x1, -12(x2); lw x14, -12(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x0000000000aa00aa) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_7: li gp, 7; la x2, tdat8; li x1, 0xffffffffaa00aa00; la x15, 7f; sw x1, -8(x2); lw x14, -8(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffaa00aa00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_8: li gp, 8; la x2, tdat8; li x1, 0x000000000aa00aa0; la x15, 7f; sw x1, -4(x2); lw x14, -4(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0x000000000aa00aa0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_9: li gp, 9; la x2, tdat8; li x1, 0xffffffffa00aa00a; la x15, 7f; sw x1, 0(x2); lw x14, 0(x2); j 8f; 7: mv x14, x1; 8:; li x7, ((0xffffffffa00aa00a) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_10: li gp, 10; la x1, tdat9; li x2, 0x12345678; addi x4, x1, -32; sw x2, 32(x4); lw x5, 0(x1);; li x7, ((0x12345678) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_11: li gp, 11; la x1, tdat9; li x2, 0x58213098; addi x1, x1, -3; sw x2, 7(x1); la x4, tdat10; lw x5, 0(x4);; li x7, ((0x58213098) & ((1 << (32 - 1) << 1) - 1)); bne x5, x7, fail; + test_12: li gp, 12; li x4, 0; 1: li x13, 0xffffffffaabbccdd; la x12, tdat; sw x13, 0(x12); lw x14, 0(x12); li x7, 0xffffffffaabbccdd; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_13: li gp, 13; li x4, 0; 1: li x13, 0xffffffffdaabbccd; la x12, tdat; nop; sw x13, 4(x12); lw x14, 4(x12); li x7, 0xffffffffdaabbccd; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_14: li gp, 14; li x4, 0; 1: li x13, 0xffffffffddaabbcc; la x12, tdat; nop; nop; sw x13, 8(x12); lw x14, 8(x12); li x7, 0xffffffffddaabbcc; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_15: li gp, 15; li x4, 0; 1: li x13, 0xffffffffcddaabbc; nop; la x12, tdat; sw x13, 12(x12); lw x14, 12(x12); li x7, 0xffffffffcddaabbc; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_16: li gp, 16; li x4, 0; 1: li x13, 0xffffffffccddaabb; nop; la x12, tdat; nop; sw x13, 16(x12); lw x14, 16(x12); li x7, 0xffffffffccddaabb; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_17: li gp, 17; li x4, 0; 1: li x13, 0xffffffffbccddaab; nop; nop; la x12, tdat; sw x13, 20(x12); lw x14, 20(x12); li x7, 0xffffffffbccddaab; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_18: li gp, 18; li x4, 0; 1: la x2, tdat; li x1, 0x00112233; sw x1, 0(x2); lw x14, 0(x2); li x7, 0x00112233; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_19: li gp, 19; li x4, 0; 1: la x2, tdat; li x1, 0x30011223; nop; sw x1, 4(x2); lw x14, 4(x2); li x7, 0x30011223; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_20: li gp, 20; li x4, 0; 1: la x2, tdat; li x1, 0x33001122; nop; nop; sw x1, 8(x2); lw x14, 8(x2); li x7, 0x33001122; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_21: li gp, 21; li x4, 0; 1: la x2, tdat; nop; li x1, 0x23300112; sw x1, 12(x2); lw x14, 12(x2); li x7, 0x23300112; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_22: li gp, 22; li x4, 0; 1: la x2, tdat; nop; li x1, 0x22330011; nop; sw x1, 16(x2); lw x14, 16(x2); li x7, 0x22330011; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + test_23: li gp, 23; li x4, 0; 1: la x2, tdat; nop; nop; li x1, 0x12233001; sw x1, 20(x2); lw x14, 20(x2); li x7, 0x12233001; bne x14, x7, fail; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 +tdat: +tdat1: .word 0xdeadbeef +tdat2: .word 0xdeadbeef +tdat3: .word 0xdeadbeef +tdat4: .word 0xdeadbeef +tdat5: .word 0xdeadbeef +tdat6: .word 0xdeadbeef +tdat7: .word 0xdeadbeef +tdat8: .word 0xdeadbeef +tdat9: .word 0xdeadbeef +tdat10: .word 0xdeadbeef diff --git a/riscv/programs/riscv-tests/rv32ui/xor.S b/riscv/programs/riscv-tests/rv32ui/xor.S new file mode 100644 index 0000000..fb56a24 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/xor.S @@ -0,0 +1,32 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/xor.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); xor x14, x11, x12;; li x7, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x11, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); xor x14, x11, x12;; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x11, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); xor x14, x11, x12;; li x7, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x11, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); xor x14, x11, x12;; li x7, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); xor x11, x11, x12;; li x7, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_7: li gp, 7; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x12, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); xor x12, x11, x12;; li x7, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x12, x7, fail;; + test_8: li gp, 8; li x11, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); xor x11, x11, x11;; li x7, ((0x00000000) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_9: li gp, 9; li x4, 0; 1: li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); xor x14, x1, x2; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_10: li gp, 10; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); xor x14, x1, x2; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_11: li gp, 11; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); xor x14, x1, x2; nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_12: li gp, 12; li x4, 0; 1: li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); nop; xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_14: li gp, 14; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); nop; nop; xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_15: li gp, 15; li x4, 0; 1: li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_16: li gp, 16; li x4, 0; 1: li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); nop; li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); nop; xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_17: li gp, 17; li x4, 0; 1: li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_18: li gp, 18; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_19: li gp, 19; li x4, 0; 1: li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); nop; xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_20: li gp, 20; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); nop; nop; xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_21: li gp, 21; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xf00ff00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_22: li gp, 22; li x4, 0; 1: li x2, ((0xf0f0f0f0) & ((1 << (32 - 1) << 1) - 1)); nop; li x1, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); nop; xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_23: li gp, 23; li x4, 0; 1: li x2, ((0x0f0f0f0f) & ((1 << (32 - 1) << 1) - 1)); nop; nop; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); xor x14, x1, x2; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0ff00ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_24: li gp, 24; li x1, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); xor x2, x0, x1;; li x7, ((0xff00ff00) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_25: li gp, 25; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); xor x2, x1, x0;; li x7, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); bne x2, x7, fail;; + test_26: li gp, 26; xor x1, x0, x0;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_27: li gp, 27; li x1, ((0x11111111) & ((1 << (32 - 1) << 1) - 1)); li x2, ((0x22222222) & ((1 << (32 - 1) << 1) - 1)); xor x0, x1, x2;; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/riscv-tests/rv32ui/xori.S b/riscv/programs/riscv-tests/rv32ui/xori.S new file mode 100644 index 0000000..04bae68 --- /dev/null +++ b/riscv/programs/riscv-tests/rv32ui/xori.S @@ -0,0 +1,19 @@ +# riscv-tests 3df703cd52d5, isa/rv32ui/xori.S, expanded by tools/import-riscv-tests.py +# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE. +.text; .globl _start; _start: + test_2: li gp, 2; li x13, ((0x0000000000ff0f00) & ((1 << (32 - 1) << 1) - 1)); xori x14, x13, ((0xf0f) | (-(((0xf0f) >> 11) & 1) << 11));; li x7, ((0xffffffffff00f00f) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_3: li gp, 3; li x13, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); xori x14, x13, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0x000000000ff00f00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_4: li gp, 4; li x13, ((0x0000000000ff08ff) & ((1 << (32 - 1) << 1) - 1)); xori x14, x13, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11));; li x7, ((0x0000000000ff0ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_5: li gp, 5; li x13, ((0xfffffffff00ff00f) & ((1 << (32 - 1) << 1) - 1)); xori x14, x13, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0xfffffffff00ff0ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_6: li gp, 6; li x11, ((0xffffffffff00f700) & ((1 << (32 - 1) << 1) - 1)); xori x11, x11, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11));; li x7, ((0xffffffffff00f00f) & ((1 << (32 - 1) << 1) - 1)); bne x11, x7, fail;; + test_7: li gp, 7; li x4, 0; 1: li x1, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); xori x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000000000ff00f00) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_8: li gp, 8; li x4, 0; 1: li x1, ((0x0000000000ff08ff) & ((1 << (32 - 1) << 1) - 1)); xori x14, x1, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11)); nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000ff0ff0) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_9: li gp, 9; li x4, 0; 1: li x1, ((0xfffffffff00ff00f) & ((1 << (32 - 1) << 1) - 1)); xori x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); nop; nop; addi x6, x14, 0; addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffff00ff0ff) & ((1 << (32 - 1) << 1) - 1)); bne x6, x7, fail;; + test_10: li gp, 10; li x4, 0; 1: li x1, ((0x000000000ff00ff0) & ((1 << (32 - 1) << 1) - 1)); xori x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x000000000ff00f00) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_11: li gp, 11; li x4, 0; 1: li x1, ((0x0000000000ff0fff) & ((1 << (32 - 1) << 1) - 1)); nop; xori x14, x1, ((0x00f) | (-(((0x00f) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0x0000000000ff0ff0) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_12: li gp, 12; li x4, 0; 1: li x1, ((0xfffffffff00ff00f) & ((1 << (32 - 1) << 1) - 1)); nop; nop; xori x14, x1, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11)); addi x4, x4, 1; li x5, 2; bne x4, x5, 1b; li x7, ((0xfffffffff00ff0ff) & ((1 << (32 - 1) << 1) - 1)); bne x14, x7, fail;; + test_13: li gp, 13; xori x1, x0, ((0x0f0) | (-(((0x0f0) >> 11) & 1) << 11));; li x7, ((0x0f0) & ((1 << (32 - 1) << 1) - 1)); bne x1, x7, fail;; + test_14: li gp, 14; li x1, ((0x00ff00ff) & ((1 << (32 - 1) << 1) - 1)); xori x0, x1, ((0x70f) | (-(((0x70f) >> 11) & 1) << 11));; li x7, ((0) & ((1 << (32 - 1) << 1) - 1)); bne x0, x7, fail;; + bne x0, gp, pass; fail: fence; 1: beqz gp, 1b; sll gp, gp, 1; or gp, gp, 1; mv a0, gp; ecall; pass: fence; li gp, 1; li a0, 0; ecall + .data +.data; .align 4 diff --git a/riscv/programs/src/fact.S b/riscv/programs/src/fact.S new file mode 100644 index 0000000..cf528fb --- /dev/null +++ b/riscv/programs/src/fact.S @@ -0,0 +1,45 @@ +# factorial(5) = 120 in a0 (and in `result`), then ECALL. RV32I has no multiply instruction, so +# `mul` is a subroutine (shift and add); factorial is recursive, so this also checks calls, the +# stack and memory. + .text +_start: + li sp, 0x80010000 # the top of the 64 KB RAM + li a0, 5 + call factorial + la t0, result + sw a0, 0(t0) + ecall +1: j 1b + +# a0 = factorial(a0) +factorial: + li t0, 1 + ble a0, t0, 2f # factorial(n) = 1 for n <= 1 + addi sp, sp, -8 + sw ra, 4(sp) + sw a0, 0(sp) + addi a0, a0, -1 + call factorial # a0 = factorial(n - 1) + lw a1, 0(sp) + call mul # a0 = factorial(n - 1) * n + lw ra, 4(sp) + addi sp, sp, 8 + ret +2: li a0, 1 + ret + +# a0 = a0 * a1 (the low 32 bits), by shift and add; uses t0 and t1 +mul: + mv t0, a0 + li a0, 0 +1: beqz a1, 2f + andi t1, a1, 1 + beqz t1, 3f + add a0, a0, t0 +3: slli t0, t0, 1 + srli a1, a1, 1 + j 1b +2: ret + + .data +result: .word 0 diff --git a/riscv/programs/src/fib.S b/riscv/programs/src/fib.S new file mode 100644 index 0000000..6f9f117 --- /dev/null +++ b/riscv/programs/src/fib.S @@ -0,0 +1,17 @@ +# Fibonacci(10) = 55 in a0, then ECALL. Uses only additions, branches and jumps. + .section .text.init + .globl _start +_start: + li t0, 10 # how many steps + li a0, 0 # fib(0) + li a1, 1 # fib(1) +loop: + beqz t0, done + add t1, a0, a1 + mv a0, a1 + mv a1, t1 + addi t0, t0, -1 + j loop +done: + ecall +1: j 1b diff --git a/riscv/programs/src/hello.S b/riscv/programs/src/hello.S new file mode 100644 index 0000000..c358496 --- /dev/null +++ b/riscv/programs/src/hello.S @@ -0,0 +1,13 @@ +# Prints "Hello, world!" through the UART at 0x1000_0000 (a system with a bus: riscv.SocSystem), +# then ECALL. A store to the UART's data register waits while the UART is still sending. + .text + li t0, 0x10000000 # the UART's data register + la t1, msg +1: lbu t2, 0(t1) + beqz t2, 2f # the string ends with a 0 byte + sb t2, 0(t0) + addi t1, t1, 1 + j 1b +2: ecall + .data +msg: .string "Hello, world!\n" diff --git a/riscv/programs/src/sum.S b/riscv/programs/src/sum.S new file mode 100644 index 0000000..ccd9f9c --- /dev/null +++ b/riscv/programs/src/sum.S @@ -0,0 +1,20 @@ +# Sums a table of 64 words twice, then ECALL with the sum in a0 (2 * 2016 = 4032): a loop of loads. + .text + li a0, 0 + li t2, 2 # passes +1: la t0, table + li t1, 64 # words +2: lw t3, 0(t0) + add a0, a0, t3 + addi t0, t0, 4 + addi t1, t1, -1 + bnez t1, 2b + addi t2, t2, -1 + bnez t2, 1b + ecall + .data +table: + .word 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 + .word 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 + .word 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47 + .word 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 diff --git a/riscv/project/build.properties b/riscv/project/build.properties new file mode 100644 index 0000000..3686073 --- /dev/null +++ b/riscv/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.13.1 diff --git a/riscv/solutions/main/scala/riscv/Alu.scala b/riscv/solutions/main/scala/riscv/Alu.scala new file mode 100644 index 0000000..df57c0f --- /dev/null +++ b/riscv/solutions/main/scala/riscv/Alu.scala @@ -0,0 +1,32 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** The ALU: `out` is `a op b`. Shifts use the low log2(width) bits of `b`; `Slt` and `Sltu` give 1 + * or 0 (signed and unsigned comparison). + */ +class Alu(width: Int = 32) extends Module { + val io = IO(new Bundle { + val op = Input(AluOp()) + val a = Input(UInt(width.W)) + val b = Input(UInt(width.W)) + val out = Output(UInt(width.W)) + }) + + val shamt = io.b(log2Ceil(width) - 1, 0) + io.out := MuxLookup(io.op, 0.U)( + Seq( + AluOp.Add -> (io.a + io.b), + AluOp.Sub -> (io.a - io.b), + AluOp.Sll -> (io.a << shamt)(width - 1, 0), + AluOp.Slt -> (io.a.asSInt < io.b.asSInt), + AluOp.Sltu -> (io.a < io.b), + AluOp.Xor -> (io.a ^ io.b), + AluOp.Srl -> (io.a >> shamt), + AluOp.Sra -> (io.a.asSInt >> shamt).asUInt, + AluOp.Or -> (io.a | io.b), + AluOp.And -> (io.a & io.b) + ) + ) +} diff --git a/riscv/solutions/main/scala/riscv/BranchUnit.scala b/riscv/solutions/main/scala/riscv/BranchUnit.scala new file mode 100644 index 0000000..f799a36 --- /dev/null +++ b/riscv/solutions/main/scala/riscv/BranchUnit.scala @@ -0,0 +1,27 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** The branch comparator: whether a branch is taken, from its funct3 (`beq` 0, `bne` 1, `blt` 4, + * `bge` 5, `bltu` 6, `bgeu` 7) and its two registers. `lt` and `ge` compare as signed numbers, + * `ltu` and `geu` as unsigned ones. + */ +class BranchUnit extends Module { + val io = IO(new Bundle { + val funct3 = Input(UInt(3.W)) + val a = Input(UInt(32.W)) + val b = Input(UInt(32.W)) + val taken = Output(Bool()) + }) + + // funct3 bit 0 negates the condition: bne, bge and bgeu are the opposites of beq, blt and bltu + val condition = MuxLookup(io.funct3(2, 1), false.B)( + Seq( + 0.U -> (io.a === io.b), + 2.U -> (io.a.asSInt < io.b.asSInt), + 3.U -> (io.a < io.b) + ) + ) + io.taken := condition =/= io.funct3(0) +} diff --git a/riscv/solutions/main/scala/riscv/DecodeRows.scala b/riscv/solutions/main/scala/riscv/DecodeRows.scala new file mode 100644 index 0000000..f9a9d1c --- /dev/null +++ b/riscv/solutions/main/scala/riscv/DecodeRows.scala @@ -0,0 +1,64 @@ +package riscv + +/** The decode table: the control signals of each RV32I instruction (see `Row` and `Control` in + * Decoder.scala). The datapath derives the rest from the kind: the register write, its source, + * the memory access size (funct3) and the branch condition (funct3, evaluated by a comparator of + * its own, as the ALU computes the branch target). + */ +object DecodeRows { + import AluOp._ + import ImmFormat.{B, I, J, S, U} + + // the common shapes of rows + private def reg(op: AluOp.Type) = Row(Kind.Alu, Some(op), None, Some(ASel.Rs1), Some(BSel.Rs2)) // add rd, rs1, rs2 + private def imm(op: AluOp.Type) = Row(Kind.Alu, Some(op), Some(I), Some(ASel.Rs1), Some(BSel.Imm)) // addi + // the ALU computes the address (register + offset) or the target (pc + offset) + private val load = Row(Kind.Load, Some(Add), Some(I), Some(ASel.Rs1), Some(BSel.Imm)) + private val store = Row(Kind.Store, Some(Add), Some(S), Some(ASel.Rs1), Some(BSel.Imm)) + private val branch = Row(Kind.Branch, Some(Add), Some(B), Some(ASel.Pc), Some(BSel.Imm)) + + // a def, not a val: an unfinished row fails each time the table is used, not once for good + def table: Map[String, Row] = Map( + "LUI" -> Row(Kind.Alu, Some(Add), Some(U), Some(ASel.Zero), Some(BSel.Imm)), // 0 + imm + "AUIPC" -> Row(Kind.Alu, Some(Add), Some(U), Some(ASel.Pc), Some(BSel.Imm)), // pc + imm + "JAL" -> Row(Kind.Jal, Some(Add), Some(J), Some(ASel.Pc), Some(BSel.Imm)), // target pc + imm + "JALR" -> Row(Kind.Jalr, Some(Add), Some(I), Some(ASel.Rs1), Some(BSel.Imm)), // target rs1 + imm + "BEQ" -> branch, + "BNE" -> branch, + "BLT" -> branch, + "BGE" -> branch, + "BLTU" -> branch, + "BGEU" -> branch, + "LB" -> load, + "LH" -> load, + "LW" -> load, + "LBU" -> load, + "LHU" -> load, + "SB" -> store, + "SH" -> store, + "SW" -> store, + "ADDI" -> imm(Add), + "SLTI" -> imm(Slt), + "SLTIU" -> imm(Sltu), + "XORI" -> imm(Xor), + "ORI" -> imm(Or), + "ANDI" -> imm(And), + // shifts: the immediate's upper bits hold funct7, but the ALU uses only its low 5 bits + "SLLI" -> imm(Sll), + "SRLI" -> imm(Srl), + "SRAI" -> imm(Sra), + "ADD" -> reg(Add), + "SUB" -> reg(Sub), + "SLL" -> reg(Sll), + "SLT" -> reg(Slt), + "SLTU" -> reg(Sltu), + "XOR" -> reg(Xor), + "SRL" -> reg(Srl), + "SRA" -> reg(Sra), + "OR" -> reg(Or), + "AND" -> reg(And), + "FENCE" -> Row(Kind.Fence), // a no-op here: nothing else matters + "ECALL" -> Row(Kind.Ecall), + "EBREAK" -> Row(Kind.Ebreak) + ) +} diff --git a/riscv/solutions/main/scala/riscv/Forward.scala b/riscv/solutions/main/scala/riscv/Forward.scala new file mode 100644 index 0000000..807512f --- /dev/null +++ b/riscv/solutions/main/scala/riscv/Forward.scala @@ -0,0 +1,27 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** A register value that an older instruction is about to write: its register number and the value. */ +class Result extends Bundle { + val rd = UInt(5.W) + val value = UInt(32.W) +} + +/** The value of register `rs` for the instruction in EX: the newest result an older instruction in + * the pipeline has for it (in EX/MEM, then in MEM/WB), or else the value read from the register file + * in ID. A result for x0 does not count: x0 is always 0. + */ +class Forward extends Module { + val io = IO(new Bundle { + val rs = Input(UInt(5.W)) + val regValue = Input(UInt(32.W)) // read in ID + val exMem = Input(Valid(new Result)) // the instruction one ahead + val memWb = Input(Valid(new Result)) // the instruction two ahead + val value = Output(UInt(32.W)) + }) + + def has(r: Valid[Result]) = r.valid && r.bits.rd =/= 0.U && r.bits.rd === io.rs + io.value := MuxCase(io.regValue, Seq(has(io.exMem) -> io.exMem.bits.value, has(io.memWb) -> io.memWb.bits.value)) +} diff --git a/riscv/solutions/main/scala/riscv/LoadExtend.scala b/riscv/solutions/main/scala/riscv/LoadExtend.scala new file mode 100644 index 0000000..41c6aee --- /dev/null +++ b/riscv/solutions/main/scala/riscv/LoadExtend.scala @@ -0,0 +1,30 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** Takes the loaded value out of the memory word: `rdata` is the whole word at the (word-aligned) + * address, `offset` the byte address's low two bits, and `funct3` the load (`lb` 0, `lh` 1, `lw` 2, + * `lbu` 4, `lhu` 5). The byte or half-word starts at byte `offset` of the word (little-endian), and + * is sign-extended (`lb`, `lh`) or zero-extended (`lbu`, `lhu`) to 32 bits. The address is aligned: + * a half-word starts at offset 0 or 2. + */ +class LoadExtend extends Module { + val io = IO(new Bundle { + val funct3 = Input(UInt(3.W)) + val offset = Input(UInt(2.W)) + val rdata = Input(UInt(32.W)) + val value = Output(UInt(32.W)) + }) + + val shifted = io.rdata >> (io.offset ## 0.U(3.W)) // offset * 8 + val unsigned = io.funct3(2) + val byte = shifted(7, 0) + val half = shifted(15, 0) + io.value := MuxLookup(io.funct3(1, 0), shifted)( + Seq( + 0.U -> Cat(Fill(24, byte(7) && !unsigned), byte), + 1.U -> Cat(Fill(16, half(15) && !unsigned), half) + ) + ) +} diff --git a/riscv/solutions/main/scala/riscv/PipelineFlush.scala b/riscv/solutions/main/scala/riscv/PipelineFlush.scala new file mode 100644 index 0000000..1a429c8 --- /dev/null +++ b/riscv/solutions/main/scala/riscv/PipelineFlush.scala @@ -0,0 +1,25 @@ +package riscv + +import chisel3._ + +/** Which stage registers of the five-stage pipeline take a bubble instead of the instruction + * coming from the stage before (IF -> IF/ID -> ID -> ID/EX -> EX -> EX/MEM -> MEM -> MEM/WB -> WB): + * + * - `redirect`: the instruction in EX is a jump or a taken branch, so the two instructions + * fetched after it (now in IF and ID) are on the wrong path; + * - `halt`: the instruction in MEM halts the core, so every younger instruction (in IF, ID and + * EX) must not reach MEM or WB, where instructions change memory and registers; fetching stops. + */ +class PipelineFlush extends Module { + val io = IO(new Bundle { + val redirect = Input(Bool()) + val halt = Input(Bool()) + val flushIfId = Output(Bool()) // the instruction in IF does not enter ID + val flushIdEx = Output(Bool()) // the instruction in ID does not enter EX + val flushExMem = Output(Bool()) // the instruction in EX does not enter MEM + }) + + io.flushIfId := io.redirect || io.halt + io.flushIdEx := io.redirect || io.halt + io.flushExMem := io.halt // the jump or branch in EX itself goes on +} diff --git a/riscv/solutions/main/scala/riscv/UartTx.scala b/riscv/solutions/main/scala/riscv/UartTx.scala new file mode 100644 index 0000000..ab35578 --- /dev/null +++ b/riscv/solutions/main/scala/riscv/UartTx.scala @@ -0,0 +1,35 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** A UART transmitter: sends a byte on `txd` as a frame of 10 bits, each `divider` clock cycles + * long: a start bit (0), the 8 data bits, least significant first, and a stop bit (1). Between + * frames `txd` is 1. It takes a byte (`send`) only when it is not `busy`. + */ +class UartTx(divider: Int) extends Module { + require(divider >= 1) + val io = IO(new Bundle { + val send = Input(Valid(UInt(8.W))) + val busy = Output(Bool()) + val txd = Output(Bool()) + }) + + val frame = RegInit(1.U(10.W)) // the bits still to send, the next one in bit 0 + val left = RegInit(0.U(4.W)) // how many + val count = RegInit(0.U(log2Ceil(divider + 1).W)) // cycles left of the current bit + io.busy := left =/= 0.U + io.txd := Mux(io.busy, frame(0), true.B) + + when(!io.busy && io.send.valid) { + frame := 1.U(1.W) ## io.send.bits ## 0.U(1.W) + left := 10.U + count := (divider - 1).U + }.elsewhen(io.busy) { + when(count === 0.U) { + frame := frame >> 1 + left := left - 1.U + count := (divider - 1).U + }.otherwise(count := count - 1.U) + } +} diff --git a/riscv/src/main/scala/riscv/Alu.scala b/riscv/src/main/scala/riscv/Alu.scala new file mode 100644 index 0000000..a0768e5 --- /dev/null +++ b/riscv/src/main/scala/riscv/Alu.scala @@ -0,0 +1,18 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** The ALU: `out` is `a op b`. Shifts use the low log2(width) bits of `b`; `Slt` and `Sltu` give 1 + * or 0 (signed and unsigned comparison). + */ +class Alu(width: Int = 32) extends Module { + val io = IO(new Bundle { + val op = Input(AluOp()) + val a = Input(UInt(width.W)) + val b = Input(UInt(width.W)) + val out = Output(UInt(width.W)) + }) + + io.out := ??? // Exercise: compute `a op b` for every AluOp +} diff --git a/riscv/src/main/scala/riscv/AluOp.scala b/riscv/src/main/scala/riscv/AluOp.scala new file mode 100644 index 0000000..18342eb --- /dev/null +++ b/riscv/src/main/scala/riscv/AluOp.scala @@ -0,0 +1,23 @@ +package riscv + +import chisel3._ + +/** The operations of the RV32I ALU (the R-type and I-type arithmetic instructions). */ +object AluOp extends ChiselEnum { + val Add, Sub, Sll, Slt, Sltu, Xor, Srl, Sra, Or, And = Value + + /** The RV32I instruction that does `op` on two registers (`add`, `sltu`, ...). */ + def mnemonic(op: Type): String = op match { + case Add => "add" + case Sub => "sub" + case Sll => "sll" + case Slt => "slt" + case Sltu => "sltu" + case Xor => "xor" + case Srl => "srl" + case Sra => "sra" + case Or => "or" + case And => "and" + case _ => throw new IllegalArgumentException(s"not a literal AluOp: $op") // a hardware value + } +} diff --git a/riscv/src/main/scala/riscv/Asm.scala b/riscv/src/main/scala/riscv/Asm.scala new file mode 100644 index 0000000..59d1f31 --- /dev/null +++ b/riscv/src/main/scala/riscv/Asm.scala @@ -0,0 +1,855 @@ +package riscv + +import scala.collection.mutable + +/** RV32I in software: the instruction formats, the registers' ABI names, an encoder, a decoder and an + * assembler. Plain Scala (no hardware): the notebooks and tests use it to build programs, so the + * course needs no RISC-V compiler. + */ +object Reg { + + /** ABI names of x0..x31 */ + val names: IndexedSeq[String] = IndexedSeq("zero", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1") ++ + (0 to 7).map("a" + _) ++ (2 to 11).map("s" + _) ++ (3 to 6).map("t" + _) + + // every name of every register: x0..x31, the ABI names, and fp (another name of s0) + private val numbers: Map[String, Int] = (names.zipWithIndex ++ (0 until 32).map(n => s"x$n" -> n)).toMap + ("fp" -> 8) + + def isReg(name: String): Boolean = numbers.contains(name) + + /** The number of a register given as `x5`, `t0` or `fp`. */ + def apply(name: String): Int = + numbers.getOrElse(name, throw new IllegalArgumentException(s"unknown register '$name'")) +} + +/** The six instruction formats; they differ in which fields exist and how the immediate is split. */ +sealed trait Format +object Format { + case object R extends Format // rd, rs1, rs2 + case object I extends Format // rd, rs1, imm[11:0] + case object S extends Format // rs1, rs2, imm[11:0] (stores) + case object B extends Format // rs1, rs2, imm[12:1] (branches) + case object U extends Format // rd, imm[31:12] + case object J extends Format // rd, imm[20:1] (jal) +} + +/** A decoded instruction. Fields that the format does not have are 0; `imm` is the sign-extended + * immediate (for U-type, the value with its 12 low zero bits: `lui a0, 1` has imm 0x1000). + */ +case class Inst(name: String, rd: Int = 0, rs1: Int = 0, rs2: Int = 0, imm: Int = 0) + +object Rv32i { + import Format._ + + /** name -> (format, opcode, funct3, funct7). funct7 also tells SRAI from SRLI. */ + case class Encoding(format: Format, opcode: Int, funct3: Int = 0, funct7: Int = 0) + + val encodings: Map[String, Encoding] = Map( + "lui" -> Encoding(U, 0x37), + "auipc" -> Encoding(U, 0x17), + "jal" -> Encoding(J, 0x6f), + "jalr" -> Encoding(I, 0x67, 0), + "beq" -> Encoding(B, 0x63, 0), + "bne" -> Encoding(B, 0x63, 1), + "blt" -> Encoding(B, 0x63, 4), + "bge" -> Encoding(B, 0x63, 5), + "bltu" -> Encoding(B, 0x63, 6), + "bgeu" -> Encoding(B, 0x63, 7), + "lb" -> Encoding(I, 0x03, 0), + "lh" -> Encoding(I, 0x03, 1), + "lw" -> Encoding(I, 0x03, 2), + "lbu" -> Encoding(I, 0x03, 4), + "lhu" -> Encoding(I, 0x03, 5), + "sb" -> Encoding(S, 0x23, 0), + "sh" -> Encoding(S, 0x23, 1), + "sw" -> Encoding(S, 0x23, 2), + "addi" -> Encoding(I, 0x13, 0), + "slti" -> Encoding(I, 0x13, 2), + "sltiu" -> Encoding(I, 0x13, 3), + "xori" -> Encoding(I, 0x13, 4), + "ori" -> Encoding(I, 0x13, 6), + "andi" -> Encoding(I, 0x13, 7), + "slli" -> Encoding(I, 0x13, 1, 0x00), + "srli" -> Encoding(I, 0x13, 5, 0x00), + "srai" -> Encoding(I, 0x13, 5, 0x20), + "add" -> Encoding(R, 0x33, 0, 0x00), + "sub" -> Encoding(R, 0x33, 0, 0x20), + "sll" -> Encoding(R, 0x33, 1, 0x00), + "slt" -> Encoding(R, 0x33, 2, 0x00), + "sltu" -> Encoding(R, 0x33, 3, 0x00), + "xor" -> Encoding(R, 0x33, 4, 0x00), + "srl" -> Encoding(R, 0x33, 5, 0x00), + "sra" -> Encoding(R, 0x33, 5, 0x20), + "or" -> Encoding(R, 0x33, 6, 0x00), + "and" -> Encoding(R, 0x33, 7, 0x00), + "fence" -> Encoding(I, 0x0f, 0), + "ecall" -> Encoding(I, 0x73, 0), + "ebreak" -> Encoding(I, 0x73, 0) + ) + + def isShiftImm(name: String): Boolean = name == "slli" || name == "srli" || name == "srai" + def isLoad(name: String): Boolean = encodings.get(name).exists(_.opcode == 0x03) + def isAluImm(name: String): Boolean = encodings.get(name).exists(_.opcode == 0x13) // addi ... srai + + private def bits(x: Long, hi: Int, lo: Int): Int = ((x >>> lo) & ((1L << (hi - lo + 1)) - 1)).toInt + def signExtend(x: Int, width: Int): Int = (x << (32 - width)) >> (32 - width) + + /** The 32-bit word of `i` (as a non-negative Long). */ + def encode(i: Inst): Long = { + val e = encodings.getOrElse(i.name, throw new IllegalArgumentException(s"not an RV32I instruction: ${i.name}")) + def check(cond: Boolean, what: String) = require(cond, s"${i.name}: $what out of range: ${i.imm}") + for (r <- Seq(i.rd, i.rs1, i.rs2)) require(r >= 0 && r < 32, s"${i.name}: there is no register x$r") + if (i.name == "ecall" || i.name == "ebreak") require(i == Inst(i.name), s"${i.name} has no operands") + val imm = i.imm.toLong + val word: Long = e.format match { + case R => (e.funct7.toLong << 25) | (i.rs2 << 20) | (i.rs1 << 15) | (e.funct3 << 12) | (i.rd << 7) + case I if isShiftImm(i.name) => + check(i.imm >= 0 && i.imm < 32, "shift amount") + (e.funct7.toLong << 25) | (imm << 20) | (i.rs1 << 15) | (e.funct3 << 12) | (i.rd << 7) + case I if i.name == "ebreak" => 1L << 20 + case I => + check(i.imm >= -2048 && i.imm < 2048, "immediate") + ((imm & 0xfff) << 20) | (i.rs1 << 15) | (e.funct3 << 12) | (i.rd << 7) + case S => + check(i.imm >= -2048 && i.imm < 2048, "offset") + ((imm >> 5 & 0x7f) << 25) | (i.rs2 << 20) | (i.rs1 << 15) | (e.funct3 << 12) | ((imm & 0x1f) << 7) + case B => + check(i.imm >= -4096 && i.imm < 4096 && i.imm % 2 == 0, "offset") + ((imm >> 12 & 1) << 31) | ((imm >> 5 & 0x3f) << 25) | (i.rs2 << 20) | (i.rs1 << 15) | + (e.funct3 << 12) | ((imm >> 1 & 0xf) << 8) | ((imm >> 11 & 1) << 7) + case U => + check((i.imm & 0xfff) == 0, "immediate (low 12 bits must be 0)") + (imm & 0xfffff000L) | (i.rd << 7) + case J => + check(i.imm >= -(1 << 20) && i.imm < (1 << 20) && i.imm % 2 == 0, "offset") + ((imm >> 20 & 1) << 31) | ((imm >> 1 & 0x3ff) << 21) | ((imm >> 11 & 1) << 20) | + ((imm >> 12 & 0xff) << 12) | (i.rd << 7) + } + word | e.opcode + } + + private val byOpcode = encodings.toSeq.groupBy(_._2.opcode) + + /** The instruction of a 32-bit word, or None if it is not an RV32I instruction. */ + def decode(word: Long): Option[Inst] = { + val opcode = bits(word, 6, 0) + val rd = bits(word, 11, 7) + val funct3 = bits(word, 14, 12) + val rs1 = bits(word, 19, 15) + val rs2 = bits(word, 24, 20) + val funct7 = bits(word, 31, 25) + val candidates = byOpcode.getOrElse(opcode, Nil).filter { case (name, e) => + e.format match { + case U | J => true + case _ if e.format == R || isShiftImm(name) => e.funct3 == funct3 && e.funct7 == funct7 + case _ => e.funct3 == funct3 + } + } + candidates.map(_._1).toList.sorted match { + case List("ebreak", "ecall") => // the SYSTEM opcode: only these two exact words are RV32I + if (word == 0x00000073L) Some(Inst("ecall")) + else if (word == 0x00100073L) Some(Inst("ebreak")) + else None + case List(name) => + val e = encodings(name) + Some(e.format match { + case R => Inst(name, rd, rs1, rs2) + case I if isShiftImm(name) => Inst(name, rd, rs1, imm = rs2) + case I => Inst(name, rd, rs1, imm = signExtend(bits(word, 31, 20), 12)) + case S => Inst(name, rs1 = rs1, rs2 = rs2, imm = signExtend(funct7 << 5 | rd, 12)) + case B => + val imm = + bits(word, 31, 31) << 12 | bits(word, 7, 7) << 11 | bits(word, 30, 25) << 5 | bits(word, 11, 8) << 1 + Inst(name, rs1 = rs1, rs2 = rs2, imm = signExtend(imm, 13)) + case U => Inst(name, rd, imm = (word & 0xfffff000L).toInt) + case J => + val imm = + bits(word, 31, 31) << 20 | bits(word, 19, 12) << 12 | bits(word, 20, 20) << 11 | bits(word, 30, 21) << 1 + Inst(name, rd, imm = signExtend(imm, 21)) + }) + case _ => None + } + } + + /** `word` as assembly, much as `objdump -d -M no-aliases` shows it (ABI register names, no + * pseudo-instructions, ", " between operands, shift amounts in decimal): branch and jump targets + * are absolute, computed from `pc`; `fence` shows no operands; a word that is not RV32I shows as + * `.word`. + */ + def disassemble(word: Long, pc: Long = 0): String = decode(word).fold(f".word 0x${word & 0xffffffffL}%08x") { i => + def r(n: Int) = Reg.names(n) + def target = f"0x${(pc + i.imm) & 0xffffffffL}%x" + if (i.name == "fence" || i.name == "ecall" || i.name == "ebreak") i.name + else + encodings(i.name).format match { + case R => s"${i.name} ${r(i.rd)}, ${r(i.rs1)}, ${r(i.rs2)}" + case I if i.name == "jalr" || isLoad(i.name) => s"${i.name} ${r(i.rd)}, ${i.imm}(${r(i.rs1)})" + case I => s"${i.name} ${r(i.rd)}, ${r(i.rs1)}, ${i.imm}" + case S => s"${i.name} ${r(i.rs2)}, ${i.imm}(${r(i.rs1)})" + case B => s"${i.name} ${r(i.rs1)}, ${r(i.rs2)}, $target" + case U => f"${i.name} ${r(i.rd)}, 0x${i.imm >>> 12}%x" + case J => s"${i.name} ${r(i.rd)}, $target" + } + } +} + +/** An assembled program. `words` is the memory image from `base`, one little-endian 32-bit word per + * element: the `.text` section, then the `.data` section (from the next word, or the next multiple of + * its largest `.align`, zeros in between). `.bss` follows the + * data; it is not in the image, and nothing clears it. `symbols` holds the address of every + * label (except numeric ones). + */ +case class Program(base: Long, words: IndexedSeq[Long], symbols: Map[String, Long]) { + + /** The image as `$readmemh` reads it: one word per line, in hex. */ + def hex: String = words.map(w => f"$w%08x\n").mkString +} + +/** An RV32I assembler in the GNU syntax, so that the course needs no RISC-V toolchain (like the + * assembler built into the Ripes simulator). It reads + * + * - statements one per line or separated by `;`, `#` comments, labels (`loop:`, alone or before + * a statement) and numeric local labels (`1:`, referred to as `1b` backwards or `1f` forwards); + * - the sections `.text`, `.data` and `.bss` (also `.section .text.init` and the like; + * `.rodata` goes to `.data`); + * - the directives `.word`/`.long`, `.half`/`.short`, `.byte`, `.ascii`, `.string`/`.asciz`, + * `.zero`/`.space`, `.fill`, `.align`/`.p2align` (a power of 2), `.balign`, `.equ`/`.set`, + * `.rept n` ... `.endr` (n a number), and `.globl`/`.global` and `.option` (nothing to do); + * - every RV32I instruction. An immediate is an expression of numbers (decimal, octal `010`, + * `0x`, `0b`, `'c'`; 64-bit, as in GNU as), symbols, parentheses, unary `-` and `~`, and the binary + * operators of GNU as with its precedence (`*`, `/`, `%`, `<<`, `>>` above `|`, `&`, `^` above + * `+`, `-`; `>>` is logical), and `%hi`, `%lo`, `%pcrel_hi` and `%pcrel_lo`. A register-register + * ALU instruction with an immediate is its immediate form (`sll a0, a0, 1` is `slli`); + * - the RV32I pseudo-instructions `nop`, `li` (any 32-bit value), `la` (and `lla`), `mv`, `not`, + * `neg`, `seqz`, `snez`, `sltz`, `sgtz`, `beqz`, `bnez`, `blez`, `bgez`, `bltz`, `bgtz`, `bgt`, + * `ble`, `bgtu`, `bleu`, `j`, `jal label`, `jr rs` (and `jr rs, offset`), `jalr rs`, `ret`, + * `call`, `tail`, and loads and stores of a symbol (`lw rd, symbol` and `sw rs, symbol, rt`, + * through `auipc`). + * + * It assembles the rv32ui tests of riscv-tests (riscv/programs/riscv-tests) exactly as GNU as does. + * A branch or jump target that uses a symbol is an address; a plain number is an offset from the + * instruction (`beq a0, a1, 8` skips one instruction). GNU as reads a plain number as an address + * instead; the course's programs use labels, which mean the same in both. Execution starts at the + * first word of `.text`, at `base`. + */ +object Asm { + + /** The memory image of `source` assembled for address `base` (see [[Program]]). */ + def apply(source: String, base: Long = Ram.base): Seq[Long] = assemble(source, base).words + + /** `source` assembled with `padding` nops after every instruction (after each of the instructions + * of a pseudo-instruction too): a pipeline without hazard handling then needs nothing else. Labels + * keep working; a branch or jump offset written as a number or relative to `.` (`j .+8`) does not + * account for the nops, and an instruction written as data (`.word`) gets none after it. + */ + def padded(source: String, padding: Int, base: Long = Ram.base): Seq[Long] = { + require(padding >= 0, s"padding $padding") + new Assembler(source, base, padding).program.words + } + + def assemble(source: String, base: Long = Ram.base): Program = new Assembler(source, base).program + + /** `sbt "runMain riscv.Asm in.S out.hex"` writes the memory image of `in.S` for `$readmemh`. */ + def main(args: Array[String]): Unit = args match { + case Array(in, out) => + val source = java.nio.file.Files.readString(java.nio.file.Paths.get(in)) + java.nio.file.Files.writeString(java.nio.file.Paths.get(out), assemble(source).hex) + case _ => sys.error("usage: riscv.Asm ") + } +} + +/** The two passes of [[Asm]]: the first finds every statement's section and offset (so every + * label's address), the second produces the bytes. + */ +private final class Assembler(source: String, base: Long, padding: Int = 0) { + private def fail(msg: String): Nothing = throw new IllegalArgumentException(msg) + + // ---- lexing + + /** The statements of a line: GNU as separates them with `;`, and `#` starts a comment (both + * outside strings and character literals). + */ + private def statements(line: String): Seq[String] = { + val out = mutable.ListBuffer[String]() + var quote: Char = 0 + var start = 0 + var i = 0 + while (i < line.length && !(quote == 0 && line(i) == '#')) { + val c = line(i) + if (quote != 0) { if (c == '\\') i += 1 else if (c == quote) quote = 0 } + else if (c == '"' || c == '\'') quote = c + else if (c == ';') { out += line.substring(start, i); start = i + 1 } + i += 1 + } + (out += line.substring(start, i.min(line.length))).toSeq + } + + /** The operands, split at the commas that are outside strings, character literals and parentheses. */ + private def operands(s: String): List[String] = { + val out = mutable.ListBuffer[String]() + val cur = new StringBuilder + var depth = 0 + var quote: Char = 0 + var i = 0 + while (i < s.length) { + val c = s(i) + if (quote != 0) { + cur += c + if (c == '\\' && i + 1 < s.length) { i += 1; cur += s(i) } + else if (c == quote) quote = 0 + } else + c match { + case '"' | '\'' => quote = c; cur += c + case '(' => depth += 1; cur += c + case ')' => depth -= 1; cur += c + case ',' if depth == 0 => out += cur.toString.trim; cur.clear() + case _ => cur += c + } + i += 1 + } + if (quote != 0) fail(s"missing closing $quote") + if (depth != 0) fail("unbalanced parentheses") + if (s.trim.nonEmpty) out += cur.toString.trim + if (out.exists(_.isEmpty)) fail("empty operand") + out.toList + } + + private val labelDef = """\s*([A-Za-z_.$][\w.$]*|\d+)\s*:(.*)""".r + private val memRef = """(.*)\(\s*(\w+)\s*\)\s*""".r + private val localRef = """(\d+)([bf])""".r + + private def unescape(c: Char): Char = c match { + case 'n' => '\n' + case 't' => '\t' + case 'r' => '\r' + case c => c // \\, \", \' + } + + /** The character of the escape sequence whose backslash is `s(i)`, and the index after it: `\n` and + * the like, up to three octal digits (`\0`, `\012`) or `\x` and hex digits, as GNU as reads them. + */ + private def escape(s: String, i: Int, end: Int): (Char, Int) = { + val after = s.slice(i + 1, end) + val octal = after.take(3).takeWhile(c => c >= '0' && c <= '7') + if (octal.nonEmpty) ((Integer.parseInt(octal, 8) & 0xff).toChar, i + 1 + octal.length) + else if (after.startsWith("x")) { + val hex = after.drop(1).takeWhile(Character.digit(_, 16) >= 0) + if (hex.isEmpty) fail(s"\\x without hex digits in $s") + ((BigInt(hex, 16) & 0xff).toChar, i + 2 + hex.length) + } else if (after.isEmpty) fail(s"nothing after \\ in $s") + else (unescape(after.head), i + 2) + } + + private def string(s: String): Array[Byte] = { + if (s.length < 2 || s.head != '"' || s.last != '"') fail(s"not a string: $s") + val out = mutable.ArrayBuffer[Byte]() + var i = 1 + while (i < s.length - 1) { + if (s(i) == '\\') { val (c, next) = escape(s, i, s.length - 1); out += c.toByte; i = next } + else { out ++= s(i).toString.getBytes("UTF-8"); i += 1 } + } + out.toArray + } + + /** Runs `body` for one source line, adding the line to the message of any error. */ + private def at[T](line: Int, text: String)(body: => T): T = + try body + catch { + case e: IllegalArgumentException => throw new IllegalArgumentException(s"line $line: ${e.getMessage}: $text", e) + } + + // ---- pass 1: statements, their sections and offsets, and the labels + + private case class Stmt( + line: Int, + text: String, + op: String, + args: List[String], + section: String, + offset: Int, + size: Int + ) + + /** A numeric label such as `1:`, defined just before statement number `seq`. */ + private case class Local(number: String, seq: Int, section: String, offset: Int) + + private val stmts = mutable.ArrayBuffer[Stmt]() + private val labels = mutable.Map[String, (String, Int)]() // name -> (section, offset) + private val locals = mutable.ArrayBuffer[Local]() + private val equs = mutable.Map[String, Long]() + private val equSeq = mutable.Map[String, Int]() // name -> the number of the first statement after its .equ + private val sizes = mutable.Map("text" -> 0, "data" -> 0, "bss" -> 0) + private var section = "text" + private var inPass1 = true // labels have no address yet + private val pcrelHi = mutable.Map[Long, Long]() // address of an auipc with %pcrel_hi -> the address it aims at + + private def defined(name: String) = labels.contains(name) || equs.contains(name) + + private def sectionOf(name: String): String = { + def is(prefixes: String*) = prefixes.exists(p => name == p || name.startsWith(p + ".")) + if (is(".text")) "text" + else if (is(".data", ".rodata", ".sdata", ".srodata")) "data" + else if (is(".bss", ".sbss")) "bss" + else fail(s"unknown section $name") + } + + /** The value of an expression of numbers and `.equ` symbols defined above. */ + private def constant(expr: String): Long = + evaluate(expr, 0, n => equs.getOrElse(n, fail(s"$n is not a constant defined above")))._1 + + /** The alignment in bytes of `.align n`, `.p2align n` or `.balign n`. */ + private def alignment(op: String, arg: String): Long = { + val a = if (op == ".balign") constant(arg) else 1L << constant(arg).min(13) + if (a <= 0 || a > 4096 || (a & (a - 1)) != 0) fail(s"bad alignment $arg") + a + } + + /** The padding that an alignment directive adds at `offset`. */ + private def padding(op: String, arg: String, offset: Int): Int = { + val a = alignment(op, arg) + ((a - offset % a) % a).toInt + } + + // the largest alignment of each section (at least a word), which its start address must have too + private val sectionAlign = mutable.Map("text" -> 4L, "data" -> 4L, "bss" -> 4L) + + private val alignments = Set(".align", ".p2align", ".balign") + private val maxSize = 16L << 20 // per section: far beyond the course's memories, and no huge arrays + + /** The repeat count and the size of `.fill repeat[, size[, value]]` (size 1 by default). */ + private def fill(args: List[String]): (Long, Long) = args match { + case r :: rest if rest.size <= 2 => + val (repeat, each) = (constant(r), rest.headOption.map(constant).getOrElse(1L)) + if (repeat < 0 || repeat > maxSize || each < 0 || each > 8 || repeat * each > maxSize) + fail(s"bad .fill $repeat, $each") + (repeat, each) + case _ => fail(".fill needs a repeat count, and maybe a size and a value") + } + + private def one(op: String, args: List[String]): String = args match { + case List(a) => a + case _ => fail(s"$op needs one operand") + } + + private def size(op: String, args: List[String], offset: Int): Int = op match { + case ".word" | ".long" => 4 * args.size + case ".half" | ".short" => 2 * args.size + case ".byte" => args.size + case ".ascii" => args.map(string(_).length).sum + case ".string" | ".asciz" => args.map(string(_).length + 1).sum + case ".zero" | ".space" => val n = constant(one(op, args)); if (n < 0 || n > maxSize) fail(s"bad size $n"); n.toInt + case ".fill" => val (repeat, each) = fill(args); (repeat * each).toInt + case a if alignments(a) => + sectionAlign(section) = sectionAlign(section).max(alignment(op, one(op, args))) + padding(op, one(op, args), offset) + case d if d.startsWith(".") => fail(s"unknown directive $d") + case _ if section != "text" => fail(s"instructions belong in .text, not .$section") + case _ if offset % 4 != 0 => fail("instruction not on a 4-byte boundary (add .align 2 before it)") + case _ => 4 * instructions(op, args, 0, stmts.size).size + } + + /** `(line, statement)` with each `.rept n` ... `.endr` block written out n times. The count must + * be a number (`.equ` symbols are not known yet when blocks are written out). + */ + private def unroll(stmts: List[(Int, String)]): List[(Int, String)] = { + def directive(text: String) = text.trim.takeWhile(!_.isWhitespace) + val out = mutable.ListBuffer[(Int, String)]() + var work = 0L // repetitions and statements: bounded, even for empty blocks + def go(stmts: List[(Int, String)]): Unit = { + var rest = stmts + while (rest.nonEmpty) { + val (line, text) = rest.head + directive(text) match { + case ".rept" => + val n = at(line, text)(constant(text.trim.stripPrefix(".rept").trim)) + if (n < 0 || n > maxSize) at(line, text)(fail(s"bad .rept count $n")) + // the matching .endr: count the .rept and .endr in between, stopping there + var depth = 1 + val body = rest.tail.takeWhile { case (_, t) => + directive(t) match { + case ".rept" => depth += 1 + case ".endr" => depth -= 1 + case _ => + } + depth > 0 + } + if (depth > 0) at(line, text)(fail(".rept without .endr")) + for (_ <- 0L until n) { + work += 1 + go(body) + if (work > maxSize) at(line, text)(fail(".rept writes out too many statements")) + } + rest = rest.tail.drop(body.size + 1) + case ".endr" => at(line, text)(fail(".endr without .rept")) + case _ => out += rest.head; work += 1; rest = rest.tail + } + } + } + go(stmts) + out.toList + } + + /** The labels at the start of a statement, each as a statement of its own, then the rest (so that + * `loop: .rept 2` and `1: .endr` are seen by `unroll`). + */ + private def splitLabels(text: String): List[String] = text match { + case labelDef(name, after) => s"$name:" :: splitLabels(after) + case _ => List(text) + } + + private val lines: List[(Int, String)] = unroll( + source.linesIterator.zipWithIndex.flatMap { case (raw, index) => + statements(raw).flatMap(splitLabels).map((index + 1, _)) + }.toList + ) + + for ((line, text) <- lines) at(line, text.trim) { + var rest = text + var more = true + while (more) rest match { + case labelDef(name, after) => + if (name.head.isDigit) locals += Local(name, stmts.size, section, sizes(section)) + else if (defined(name)) fail(s"$name defined twice") + else labels(name) = (section, sizes(section)) + rest = after + case _ => more = false + } + rest = rest.trim + if (rest.nonEmpty) { + val (op, tail) = rest.span(!_.isWhitespace) + val args = operands(tail) + op match { + case ".text" | ".data" | ".bss" => section = sectionOf(op) + case ".section" => section = sectionOf(args.headOption.getOrElse(fail("missing section name"))) + case ".globl" | ".global" | ".option" => // nothing to do (.option: rvc, push, pop, ...) + case ".equ" | ".set" => + val (name, value) = args match { + case List(n, v) => (n, v) + case _ => fail(s"$op needs a name and a value") + } + if (defined(name)) fail(s"$name defined twice") + equs(name) = constant(value) + equSeq(name) = stmts.size + case _ => + if (section == "bss" && !(op == ".zero" || op == ".space" || alignments(op))) + fail(s"$op in .bss, which holds no data") + val n = size(op, args, sizes(section)) + stmts += Stmt(line, text.trim, op, args, section, sizes(section), n) + sizes(section) += n + if (sizes(section) > maxSize) fail(s".$section is larger than ${maxSize >> 20} MB") + } + } + } + + // the labels of .text are aligned only if .text starts at an address aligned as it requires + if (base % sectionAlign("text") != 0) fail(f"base 0x$base%x is not aligned to the .align of .text") + + private def align4(n: Long) = (n + 3) & ~3L + private def alignUp(n: Long, a: Long) = (n + a - 1) & -a + // as GNU as, .text ends padded (with nops) to its largest alignment, and .data comes after that + private val textEnd = sizes("text") + sizes("text") = alignUp(textEnd, sectionAlign("text")).toInt + private val sectionBase = { + val data = alignUp(base + sizes("text"), sectionAlign("data")) + Map("text" -> base, "data" -> data, "bss" -> alignUp(data + sizes("data"), sectionAlign("bss"))) + } + private def address(section: String, offset: Int): Long = sectionBase(section) + offset + + // ---- expressions + + /** `1b` is the closest `1:` at or before statement `seq`, `1f` the closest after it. */ + private def symbol(name: String, seq: Int): Long = name match { + case localRef(n, dir) => + val found = + if (dir == "b") locals.filter(l => l.number == n && l.seq <= seq).lastOption + else locals.find(l => l.number == n && l.seq > seq) + found.map(l => address(l.section, l.offset)).getOrElse(fail(s"no label $n: for $name")) + case _ => + equs + .get(name) + .orElse(labels.get(name).map { case (s, o) => address(s, o) }) + .getOrElse(fail(s"unknown symbol $name")) + } + + private def hi20(x: Long): Long = ((x + 0x800) >> 12) & 0xfffff + private def lo12(x: Long): Long = ((x & 0xfff) ^ 0x800) - 0x800 + + /** The value of `expr` at address `pc`, with `sym` giving the value of a symbol, and whether it uses + * a label (then it is an address). A `.equ` symbol defined after statement number `seq` counts as + * a label: pass 1 did not know its value, so it must expand the statement to the same size. + */ + private def evaluate(expr: String, pc: Long, sym: String => Long, seq: Int = Int.MaxValue): (Long, Boolean) = { + var i = 0 + var symbolic = false + def ws(): Unit = while (i < expr.length && expr(i).isWhitespace) i += 1 + def word(): String = { + val start = i + while (i < expr.length && (expr(i).isLetterOrDigit || "_.$".contains(expr(i)))) i += 1 + expr.substring(start, i) + } + def expect(c: Char): Unit = { + ws(); if (i < expr.length && expr(i) == c) i += 1 else fail(s"expected '$c' in '$expr'") + } + // GNU as's binary operators, from the lowest precedence: + and -; then |, & and ^; then *, /, + // %, << and >> (not C's order). Values are 64-bit, as in GNU as. + // (an operator of two characters must come before one that is its first character) + def binary(next: () => Long, ops: Seq[(String, (Long, Long) => Long)]): Long = { + var v = next() + var more = true + while (more) { + ws() + ops.find { case (op, _) => expr.startsWith(op, i) } match { + case Some((op, f)) => i += op.length; v = f(v, next()) + case None => more = false + } + } + v + } + def shift(b: Long)(f: => Long): Long = if (b < 0 || b > 63) 0 else f // as GNU as (with a warning) + def sum(): Long = binary(() => logic(), Seq("+" -> (_ + _), "-" -> (_ - _))) + def logic(): Long = binary(() => product(), Seq("|" -> (_ | _), "&" -> (_ & _), "^" -> (_ ^ _))) + def product(): Long = binary( + () => term(), + Seq( + "<<" -> ((a, b) => shift(b)(a << b)), + ">>" -> ((a, b) => shift(b)(a >>> b)), // logical, as GNU as + "*" -> (_ * _), + "/" -> ((a, b) => if (b == 0) fail(s"division by zero in '$expr'") else a / b), + "%" -> ((a, b) => if (b == 0) fail(s"division by zero in '$expr'") else a % b) + ) + ) + def term(): Long = { + ws() + if (i >= expr.length) fail(s"missing value in '$expr'") + expr(i) match { + case '-' => i += 1; -term() + case '~' => i += 1; ~term() + case '(' => i += 1; val v = sum(); expect(')'); v + case '\'' => + i += 1 + if (i >= expr.length) fail(s"bad character in '$expr'") + val c = + if (expr(i) == '\\') { val (e, next) = escape(expr, i, expr.length); i = next; e } + else { i += 1; expr(i - 1) } + expect('\'') + c.toLong + case '%' => + i += 1 + val op = word() + expect('(') + val v = sum() + expect(')') + op match { + case "hi" => hi20(v) + case "lo" => lo12(v) + case "pcrel_hi" => if (!inPass1) pcrelHi(pc) = v; hi20(v - pc) + case "pcrel_lo" if inPass1 => 0 + case "pcrel_lo" => + lo12(pcrelHi.getOrElse(v, fail("%pcrel_lo needs the label of an earlier auipc with %pcrel_hi")) - v) + case _ => fail(s"unknown operator %$op") + } + case c if c.isDigit => + val w = word() + w match { + case localRef(_, _) => symbolic = true; sym(w) + // up to 64 bits, which wrap as in GNU as (0xffffffffffffffff is -1) + case _ if w.startsWith("0x") || w.startsWith("0X") => java.lang.Long.parseUnsignedLong(w.drop(2), 16) + case _ if w.startsWith("0b") || w.startsWith("0B") => java.lang.Long.parseUnsignedLong(w.drop(2), 2) + // a leading 0 makes it octal, as in GNU as (010 is 8) + case _ if w.length > 1 && w.head == '0' => java.lang.Long.parseUnsignedLong(w.drop(1), 8) + case _ => java.lang.Long.parseUnsignedLong(w) + } + case c if c.isLetter || c == '_' || c == '.' || c == '$' => + val w = word() + if (!equSeq.get(w).exists(_ <= seq)) symbolic = true + sym(w) + case c => fail(s"unexpected '$c' in '$expr'") + } + } + val v = + try sum() + catch { case _: NumberFormatException => fail(s"bad number in '$expr'") } + ws() + if (i != expr.length) fail(s"unexpected '${expr.substring(i)}' in '$expr'") + (v, symbolic) + } + + // ---- instructions + + /** A value as a 32-bit Int: from -2^31 to 2^32 - 1, the upper half read as unsigned. */ + private def int32(v: Long): Int = { + if (v < Int.MinValue || v > 0xffffffffL) fail(s"$v does not fit in 32 bits") + v.toInt + } + + /** The instructions of a statement, each followed by `padding` nops. */ + private def instructions(op: String, args: List[String], pc: Long, seq: Int): Seq[Inst] = + expand(op, args, pc, seq).flatMap(i => i +: Seq.fill(padding)(Inst("addi"))) + + /** The I-type instruction that does what R-type `op` does, with an immediate (`sltu` -> `sltiu`). */ + private def immediateForm(op: String): String = if (op == "sltu") "sltiu" else op + "i" + + /** The instructions of statement number `seq`, `op args`, at address `pc`. In pass 1 only their + * number matters, so labels count as 0. + */ + private def expand(op: String, args: List[String], pc: Long, seq: Int): Seq[Inst] = { + def r(s: String) = Reg(s) + def value(e: String): (Long, Boolean) = + evaluate(e, pc, if (inPass1) n => equs.getOrElse(n, 0L) else symbol(_, seq), seq) + def imm(e: String): Int = { // a signed immediate: 0xffffffff is out of range, not -1 (only li wraps) + val v = value(e)._1 + if (v < Int.MinValue || v > Int.MaxValue) fail(s"$v is out of range") + v.toInt + } + // a branch or jump target: with a label, an address; a plain number is an offset + def target(e: String): Int = { val (v, isAddress) = value(e); int32(if (isAddress) v - pc else v) } + def upper(e: String): Int = { // the operand of lui and auipc: the upper 20 bits + val v = value(e)._1 + if (v < 0 || v > 0xfffff) fail(s"$v is not a 20-bit value (use li, or %hi)") + (v << 12).toInt + } + object Mem { // an operand offset(rs1), as (offset, rs1) + def unapply(e: String): Option[(Int, Int)] = e match { + case memRef(off, reg) if Reg.isReg(reg) => Some((if (off.trim.isEmpty) 0 else imm(off), r(reg))) + case _ => None + } + } + // auipc plus an instruction that adds the low 12 bits: reaches `sym` from anywhere + def far(sym: String, rd: Int)(low: Int => Inst): Seq[Inst] = { + val delta = value(sym)._1 - pc + Seq(Inst("auipc", rd, imm = (hi20(delta) << 12).toInt), low(lo12(delta).toInt)) + } + def fenceSet(s: String): Int = + if (s.isEmpty || !s.forall("iorw".contains(_))) fail(s"bad fence operand '$s'") + else s.distinct.map(c => 8 >> "iorw".indexOf(c)).sum + val format = Rv32i.encodings.get(op).map(_.format) + + (op, args) match { + case ("nop", Nil) => Seq(Inst("addi")) + case ("li", List(rd, e)) => + // lui sets the upper 20 bits, rounded up when bit 11 is set (as addi sign-extends the low 12). + // An address is not known in pass 1, so it always takes both instructions. + val (v, isAddress) = value(e) + val x = int32(v) + val (hi, lo) = ((hi20(x) << 12).toInt, lo12(x).toInt) + if (!isAddress && hi == 0) Seq(Inst("addi", r(rd), imm = lo)) + else if (!isAddress && lo == 0) Seq(Inst("lui", r(rd), imm = hi)) + else Seq(Inst("lui", r(rd), imm = hi), Inst("addi", r(rd), r(rd), imm = lo)) + case ("la" | "lla", List(rd, sym)) => far(sym, r(rd))(lo => Inst("addi", r(rd), r(rd), imm = lo)) + case ("call", List(sym)) => far(sym, 1)(lo => Inst("jalr", 1, 1, imm = lo)) + case ("tail", List(sym)) => far(sym, 6)(lo => Inst("jalr", 0, 6, imm = lo)) + case ("mv", List(rd, rs)) => Seq(Inst("addi", r(rd), r(rs))) + case ("not", List(rd, rs)) => Seq(Inst("xori", r(rd), r(rs), imm = -1)) + case ("neg", List(rd, rs)) => Seq(Inst("sub", r(rd), 0, r(rs))) + case ("seqz", List(rd, rs)) => Seq(Inst("sltiu", r(rd), r(rs), imm = 1)) + case ("snez", List(rd, rs)) => Seq(Inst("sltu", r(rd), 0, r(rs))) + case ("sltz", List(rd, rs)) => Seq(Inst("slt", r(rd), r(rs), 0)) + case ("sgtz", List(rd, rs)) => Seq(Inst("slt", r(rd), 0, r(rs))) + case ("beqz", List(rs, t)) => Seq(Inst("beq", rs1 = r(rs), imm = target(t))) + case ("bnez", List(rs, t)) => Seq(Inst("bne", rs1 = r(rs), imm = target(t))) + case ("blez", List(rs, t)) => Seq(Inst("bge", rs2 = r(rs), imm = target(t))) + case ("bgez", List(rs, t)) => Seq(Inst("bge", rs1 = r(rs), imm = target(t))) + case ("bltz", List(rs, t)) => Seq(Inst("blt", rs1 = r(rs), imm = target(t))) + case ("bgtz", List(rs, t)) => Seq(Inst("blt", rs2 = r(rs), imm = target(t))) + case ("bgt", List(a, b, t)) => Seq(Inst("blt", rs1 = r(b), rs2 = r(a), imm = target(t))) + case ("ble", List(a, b, t)) => Seq(Inst("bge", rs1 = r(b), rs2 = r(a), imm = target(t))) + case ("bgtu", List(a, b, t)) => Seq(Inst("bltu", rs1 = r(b), rs2 = r(a), imm = target(t))) + case ("bleu", List(a, b, t)) => Seq(Inst("bgeu", rs1 = r(b), rs2 = r(a), imm = target(t))) + case ("j", List(t)) => Seq(Inst("jal", 0, imm = target(t))) + case ("jal", List(t)) => Seq(Inst("jal", 1, imm = target(t))) + case ("jr", List(rs)) => Seq(Inst("jalr", 0, r(rs))) + case ("jr", List(rs, e)) => Seq(Inst("jalr", 0, r(rs), imm = imm(e))) // jr rs, offset + case ("jalr", List(rs)) => Seq(Inst("jalr", 1, r(rs))) + case ("ret", Nil) => Seq(Inst("jalr", 0, 1)) + case ("fence", Nil) => Seq(Inst("fence", imm = 0xff)) // fence iorw, iorw + case ("fence", List(p, s)) => Seq(Inst("fence", imm = fenceSet(p) << 4 | fenceSet(s))) + case ("ecall" | "ebreak", Nil) => Seq(Inst(op)) + case ("jal", List(rd, t)) => Seq(Inst("jal", r(rd), imm = target(t))) + case ("jalr", List(rd, Mem(o, rs))) => Seq(Inst("jalr", r(rd), rs, imm = o)) + case ("jalr", List(rd, rs, e)) => Seq(Inst("jalr", r(rd), r(rs), imm = imm(e))) + case (_, List(rd, Mem(o, rs))) if Rv32i.isLoad(op) => Seq(Inst(op, r(rd), rs, imm = o)) + case (_, List(rd, sym)) if Rv32i.isLoad(op) => // lw rd, symbol + // rd holds the address first: x0 cannot (the load would read address lo, not the symbol) + if (r(rd) == 0) fail(s"$op: $rd cannot hold the address of $sym") + far(sym, r(rd))(lo => Inst(op, r(rd), r(rd), imm = lo)) + // GNU as also takes an immediate for the register-register ALU instructions: sll a0, a0, 1 + case (_, List(rd, rs1, e)) if format.contains(Format.R) && !Reg.isReg(e) && Rv32i.isAluImm(immediateForm(op)) => + Seq(Inst(immediateForm(op), r(rd), r(rs1), imm = imm(e))) + case (_, List(rd, rs1, rs2)) if format.contains(Format.R) => Seq(Inst(op, r(rd), r(rs1), r(rs2))) + case (_, List(rd, rs1, e)) if Rv32i.isAluImm(op) => Seq(Inst(op, r(rd), r(rs1), imm = imm(e))) + case (_, List(rs2, Mem(o, rs1))) if format.contains(Format.S) => Seq(Inst(op, rs1 = rs1, rs2 = r(rs2), imm = o)) + case (_, List(rs2, sym, rt)) if format.contains(Format.S) => // sw rs2, symbol, rt + // rt holds the address: x0 cannot, and rs2 would be overwritten before it is stored + if (r(rt) == 0 || r(rt) == r(rs2)) fail(s"$op: the address register $rt must be neither x0 nor $rs2") + far(sym, r(rt))(lo => Inst(op, rs1 = r(rt), rs2 = r(rs2), imm = lo)) + case (_, List(rs1, rs2, t)) if format.contains(Format.B) => + Seq(Inst(op, rs1 = r(rs1), rs2 = r(rs2), imm = target(t))) + case (_, List(rd, e)) if format.contains(Format.U) => Seq(Inst(op, r(rd), imm = upper(e))) + case _ => fail(s"unknown instruction, or wrong operands for $op") + } + } + + // ---- pass 2: the bytes of each section + + inPass1 = false + private val bytes = Map("text" -> new Array[Byte](sizes("text")), "data" -> new Array[Byte](sizes("data"))) + + private def put(sect: String, offset: Int, value: Long, n: Int): Unit = + for (k <- 0 until n) bytes(sect)(offset + k) = (value >> (8 * k)).toByte + + for ((s, seq) <- stmts.zipWithIndex if s.section != "bss") at(s.line, s.text) { + val pc = address(s.section, s.offset) + def values(width: Int): Unit = for ((e, k) <- s.args.zipWithIndex) { + val v = evaluate(e, pc, symbol(_, seq))._1 + if (v < -(1L << (8 * width - 1)) || v >= (1L << (8 * width))) fail(s"$v does not fit in $width bytes") + put(s.section, s.offset + width * k, v, width) + } + s.op match { + case ".word" | ".long" => values(4) + case ".half" | ".short" => values(2) + case ".byte" => values(1) + case ".ascii" | ".string" | ".asciz" => + val zero = if (s.op == ".ascii") 0 else 1 + s.args.foldLeft(s.offset) { (o, a) => + val b = string(a); b.copyToArray(bytes(s.section), o); o + b.length + zero + } + case ".fill" => // repeat copies of value, each `size` bytes (little-endian) + val (repeat, each) = fill(s.args) + val value = s.args.lift(2).map(evaluate(_, pc, symbol(_, seq))._1).getOrElse(0L) + // as GNU as: a size above 4 gets the value's low 4 bytes, then zeros + val low = if (each > 4) value & 0xffffffffL else value + for (k <- 0L until repeat) put(s.section, s.offset + (k * each).toInt, low, each.toInt) + case ".zero" | ".space" => // the arrays start as zeros + case a if alignments(a) => // padding: zeros in .data, nops in .text + val pad = padding(a, s.args.head, s.offset) // one operand: checked in pass 1 + if (s.section == "text" && pad > 0) { + // as GNU as: a zero byte up to a half-word, the 2-byte c.nop (0x0001) up to a word, then + // nops (only after data such as .byte is the offset not a whole word) + val half = (s.offset + 1) & ~1 + val word = (s.offset + 3) & ~3 + if (half < word && word <= s.offset + pad) put("text", half, 0x0001, 2) + for (o <- word until s.offset + pad by 4) put("text", o, Rv32i.encode(Inst("addi")), 4) + } + case op => + val insts = instructions(op, s.args, pc, seq) + if (4 * insts.size != s.size) fail("the expansion changed size between the passes") // a bug in expand + for ((inst, k) <- insts.zipWithIndex) put("text", s.offset + 4 * k, Rv32i.encode(inst), 4) + } + } + for (o <- align4(textEnd).toInt until sizes("text") by 4) put("text", o, Rv32i.encode(Inst("addi")), 4) + + val program: Program = { + def words(b: Array[Byte]): IndexedSeq[Long] = + b.padTo(align4(b.length.toLong).toInt, 0.toByte) + .grouped(4) + .map(_.zipWithIndex.map { case (x, k) => (x & 0xffL) << (8 * k) }.sum) + .toIndexedSeq + Program( + base, + // the gap up to an aligned .data is zeros; an empty .data adds nothing (as GNU ld) + if (bytes("data").isEmpty) words(bytes("text")) + else words(bytes("text").padTo((sectionBase("data") - base).toInt, 0.toByte)) ++ words(bytes("data")), + labels.map { case (n, (s, o)) => n -> address(s, o) }.toMap + ) + } +} diff --git a/riscv/src/main/scala/riscv/Board.scala b/riscv/src/main/scala/riscv/Board.scala new file mode 100644 index 0000000..27893a3 --- /dev/null +++ b/riscv/src/main/scala/riscv/Board.scala @@ -0,0 +1,50 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** The system of Module 5.8 on a ULX3S board (Lattice ECP5 FPGA, 25 MHz clock): it boots by copying + * `program` (an image from `Asm`) from a ROM into the RAM, holding the system in reset meanwhile, + * then runs it. The UART sends to the board's USB serial port at `baud` bits per second, and the + * LEDs show that the program has booted (LED 0) and halted (LED 1), and the 6 low bits of a0 + * (LEDs 2-7). A program must fit in the RAM and keep its stack there (`hello.S` does; `fact.S` + * puts its stack at the top of the 64 KB of the simulations). The port names are those of + * `riscv/fpga/ulx3s.lpf`, which gives their pins. Registers start at their reset values when the + * FPGA is configured, so the boot starts then, and again on a reset (button F1, `btn[1]`, which two + * flip-flops synchronize to the clock: it changes at any time, not at a clock edge). + */ +class Ulx3sTop(program: Seq[Long], ramWords: Int = 1024, clockHz: Int = 25000000, baud: Int = 115200) extends Module { + require(program.nonEmpty && program.size <= ramWords, "the program must fit in the RAM") + val led = IO(Output(UInt(8.W))) + val ftdi_rxd = IO(Output(Bool())) // the board's serial input (the FTDI chip receives): our txd + + val pressed = withReset(false.B)(RegNext(RegNext(reset.asBool))) // the button, synchronized + val rom = VecInit((program :+ 0L).map(_.U(32.W))) // a word more, read when `next` = program.size + val next = withReset(pressed)(RegInit(0.U(log2Ceil(program.size + 1).W))) // the next word to copy + val booted = next === program.size.U + when(!booted)(next := next + 1.U) + + val soc = withReset(pressed || !booted)(Module(new SocSystem(clockHz / baud, ramWords = ramWords))) + soc.io.load.valid := !booted + soc.io.load.bits.addr := Ram.base.U + (next << 2) + soc.io.load.bits.data := rom(next) + soc.io.dbg.addr := 10.U // a0 + ftdi_rxd := soc.txd + led := Cat(soc.io.dbg.data(5, 0), soc.io.halted, booted) +} + +/** Writes the SystemVerilog of [[Ulx3sTop]] for `programs/src/.S` (hello by default), as + * Yosys reads it, to `fpga/build/Ulx3sTop.sv`: `cd riscv && sbt "runMain riscv.Ulx3s hello"`. + */ +object Ulx3s extends App { + val name = args.headOption.getOrElse("hello") + require(name.matches("[A-Za-z0-9_-]+"), s"not the name of a program of programs/src: $name") + val riscv = if (os.isDir(os.pwd / "fpga")) os.pwd else os.pwd / "riscv" // sbt runs in riscv/ + val out = riscv / "fpga" / "build" / "Ulx3sTop.sv" + os.write.over( + out, + Yosys.verilog(new Ulx3sTop(Asm(Programs.source("programs/src", name)))), + createFolders = true + ) + println(s"wrote $out") +} diff --git a/riscv/src/main/scala/riscv/BranchUnit.scala b/riscv/src/main/scala/riscv/BranchUnit.scala new file mode 100644 index 0000000..63f9972 --- /dev/null +++ b/riscv/src/main/scala/riscv/BranchUnit.scala @@ -0,0 +1,19 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** The branch comparator: whether a branch is taken, from its funct3 (`beq` 0, `bne` 1, `blt` 4, + * `bge` 5, `bltu` 6, `bgeu` 7) and its two registers. `lt` and `ge` compare as signed numbers, + * `ltu` and `geu` as unsigned ones. + */ +class BranchUnit extends Module { + val io = IO(new Bundle { + val funct3 = Input(UInt(3.W)) + val a = Input(UInt(32.W)) + val b = Input(UInt(32.W)) + val taken = Output(Bool()) + }) + + io.taken := ??? // Exercise: compare a and b as funct3 says +} diff --git a/riscv/src/main/scala/riscv/Bus.scala b/riscv/src/main/scala/riscv/Bus.scala new file mode 100644 index 0000000..21db0cd --- /dev/null +++ b/riscv/src/main/scala/riscv/Bus.scala @@ -0,0 +1,75 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** The address range of a device on the bus. */ +case class Region(base: Long, size: Long) { + def contains(addr: UInt): Bool = addr >= base.U && addr < (base + size).U +} + +/** A bus with one master (the core's data port) and devices at address ranges. It takes one + * request at a time: it accepts a request (`req.fire`) when it is idle, registers it, and passes it + * the next cycle to the device whose range holds the address, which answers when it can (a device + * may make the master wait: backpressure). The device sees the request (`req.valid`) in every + * cycle until it answers (`resp.valid`), and must act on it once, in the cycle it answers, as + * `Ram`, `Uart` and `Delay` do; the bus ignores the device's `req.ready`. The answer goes + * back to the master; then the bus takes the next request, so requests are answered in order. An + * address that no device holds is answered with an error. + */ +class Bus(regions: Seq[Region]) extends Module { + require(regions.nonEmpty && regions.forall(_.size > 0), "regions must not be empty") + // the bus routes the word address (the master's requests are whole words with byte strobes) + require(regions.forall(r => r.base % 4 == 0 && r.size % 4 == 0), "regions must be whole words") + for (Seq(a, b) <- regions.sortBy(_.base).sliding(2)) + require(a.base + a.size <= b.base, s"regions overlap: $a and $b") + val io = IO(new Bundle { + val master = Flipped(new MemPort) + val devices = Vec(regions.size, new MemPort) + }) + + val busy = RegInit(false.B) + val request = Reg(new MemReq) + val selected = Reg(UInt(log2Ceil(regions.size max 2).W)) + val unmapped = Reg(Bool()) + + io.master.req.ready := !busy + when(io.master.req.fire) { + busy := true.B + request := io.master.req.bits + val hits = regions.map(_.contains(io.master.req.bits.addr)) + selected := PriorityEncoder(hits) + unmapped := !hits.reduce(_ || _) + } + + for ((device, i) <- io.devices.zipWithIndex) { + device.req.valid := busy && !unmapped && selected === i.U + device.req.bits := request + } + val answer = io.devices(selected).resp + io.master.resp.valid := busy && (unmapped || answer.valid) + io.master.resp.bits.rdata := answer.bits.rdata + io.master.resp.bits.error := unmapped || answer.bits.error + when(io.master.resp.valid)(busy := false.B) +} + +/** A slower memory: passes each request to `out` only after it has waited `latency` cycles, as a + * DRAM would make it wait, then holds it until `out` answers (the tests of `ForwardingCore` use it + * to check that the pipeline waits for a slow data memory). It takes the request (`in.req.ready`) only with that answer, so a master that + * sends a request once (`ForwardingCore`) does not drop it while a slow device keeps it waiting. + */ +class Delay(latency: Int) extends Module { + require(latency >= 0) + val io = IO(new Bundle { + val in = Flipped(new MemPort) + val out = new MemPort + }) + val waited = RegInit(0.U(log2Ceil(latency + 1).max(1).W)) + val go = io.in.req.valid && waited === latency.U + when(!io.in.req.valid || io.out.resp.valid)(waited := 0.U).elsewhen(!go)(waited := waited + 1.U) + io.out.req.valid := go + io.out.req.bits := io.in.req.bits + io.in.req.ready := go && io.out.resp.valid + io.in.resp.valid := go && io.out.resp.valid + io.in.resp.bits := io.out.resp.bits +} diff --git a/riscv/src/main/scala/riscv/CoSim.scala b/riscv/src/main/scala/riscv/CoSim.scala new file mode 100644 index 0000000..d4adc37 --- /dev/null +++ b/riscv/src/main/scala/riscv/CoSim.scala @@ -0,0 +1,122 @@ +package riscv + +import chisel3._ +import chisel3.simulator.PeekPokeAPI._ + +import scala.collection.mutable + +/** Runs programs on a simulated core with its RAM (a [[RiscvSystem]], such as + * [[SingleCycleSystem]]) and compares what it retires with the golden model ([[IsaSim]]). Use it + * inside `simulate(new SingleCycleSystem) { c => ... }`. + */ +object CoSim { + + /** Writes `image` into the RAM from the reset pc (with reset held), then releases reset. The rest + * of the RAM keeps what it held (unknown at first; zeroing 64 KB would take 16384 cycles), where + * the golden model has zeros: a program must not read memory that it did not load or store. + */ + def load(c: RiscvSystem, image: Seq[Long]): Unit = { + c.reset.poke(true.B) + c.io.load.valid.poke(true.B) + for ((word, i) <- image.zipWithIndex) { + c.io.load.bits.addr.poke((Ram.base + 4L * i).U) // where the core starts, and Asm's base + c.io.load.bits.data.poke(word.U) + c.clock.step() + } + c.io.load.valid.poke(false.B) + c.clock.step() // reset the core once more, now that the program is in place + c.reset.poke(false.B) + } + + private val causes = Map( + HaltCause.Ecall.litValue -> Halt.Ecall, + HaltCause.Ebreak.litValue -> Halt.Ebreak, + HaltCause.Illegal.litValue -> Halt.Illegal, + HaltCause.Misaligned.litValue -> Halt.Misaligned, + HaltCause.BadAddress.litValue -> Halt.BadAddress + ) + + /** The instruction the core retires in this cycle, as a golden-model record, if any. */ + def retired(c: RiscvSystem): Option[Retire] = + if (!c.io.retire.valid.peek().litToBoolean) None + else { + val r = c.io.retire.bits + val mem = r.mem.bits + Some( + Retire( + pc = r.pc.peek().litValue.toLong, + inst = r.inst.peek().litValue.toLong, + nextPc = r.nextPc.peek().litValue.toLong, + rd = r.rd.peek().litValue.toInt, + rdValue = r.rdValue.peek().litValue.toLong, + mem = Option.when(r.mem.valid.peek().litToBoolean)( + MemAccess( + mem.addr.peek().litValue.toLong, + mem.write.peek().litToBoolean, + mem.bytes.peek().litValue.toInt, + mem.data.peek().litValue.toLong + ) + ), + halt = causes.get(r.halt.peek().litValue) + ) + ) + } + + /** Runs the loaded program until the instruction that halts the core retires, for at most + * `maxCycles` cycles; returns what retired (in order). A core may retire nothing in a cycle (a + * pipeline filling up, a stall), but at most one instruction. + */ + def run(c: RiscvSystem, maxCycles: Int = 100000): Seq[Retire] = timed(c, maxCycles)._1 + + /** As `run`, and the number of cycles the program took: from the first cycle after reset to the one + * in which the halting instruction retired, both included. + */ + def timed(c: RiscvSystem, maxCycles: Int = 100000): (Seq[Retire], Int) = { + val trace = mutable.ArrayBuffer[Retire]() + var cycles = 0 + var done = false + while (!done && cycles < maxCycles) { + val r = retired(c) // before `halted`: a core may raise it in the cycle its halt retires + trace ++= r + done = r.exists(_.halt.isDefined) || c.io.halted.peek().litToBoolean + if (!done) c.clock.step() // stay on the halt: the registers can be read + cycles += 1 + } + (trace.toSeq, cycles) + } + + /** The value of register `n` (through the debug port). */ + def reg(c: RiscvSystem, n: Int): Long = { + c.io.dbg.addr.poke(n.U) + c.io.dbg.data.peek().litValue.toLong + } + + /** Runs `image` on the core and on the golden model (see `load`: it must not read memory past its + * image that it has not written); returns the first difference between what + * they retire, or that the core did not halt in `maxCycles` cycles, or that it retired something + * in the few cycles it is run past its halt (None if they retire the same instructions and both + * halt). + */ + def compare(c: RiscvSystem, image: Seq[Long], maxCycles: Int = 100000): Option[String] = { + load(c, image) + val core = run(c, maxCycles) + val golden = c.model(image).run(maxCycles) + def show(r: Option[Retire]) = r.fold("(nothing)")(_.toString) + def differ(i: Int) = + Some(s"instruction $i:\n core: ${show(core.lift(i))}\n model: ${show(golden.lift(i))}") + val i = core.zip(golden).indexWhere { case (a, b) => a != b } + if (i >= 0) differ(i) + else if (!core.lastOption.exists(_.halt.isDefined)) + Some(s"the core did not halt within $maxCycles cycles (it retired ${core.size} instructions)") + else if (core.size != golden.size) differ(core.size min golden.size) + else afterHalt(c) + } + + /** Nothing may retire after the instruction that halts the core: a pipeline that failed to flush + * a younger instruction would retire it a few cycles later (after changing memory or registers). + */ + private def afterHalt(c: RiscvSystem, cycles: Int = 8): Option[String] = + (1 to cycles).iterator.flatMap { _ => c.clock.step(); retired(c) }.nextOption().map { r => + s"an instruction retired after the one that halted the core:\n $r" + } +} diff --git a/riscv/src/main/scala/riscv/DecodeRows.scala b/riscv/src/main/scala/riscv/DecodeRows.scala new file mode 100644 index 0000000..ba5d732 --- /dev/null +++ b/riscv/src/main/scala/riscv/DecodeRows.scala @@ -0,0 +1,64 @@ +package riscv + +/** The decode table: the control signals of each RV32I instruction (see `Row` and `Control` in + * Decoder.scala). The datapath derives the rest from the kind: the register write, its source, + * the memory access size (funct3) and the branch condition (funct3, evaluated by a comparator of + * its own, as the ALU computes the branch target). + */ +object DecodeRows { + import AluOp._ + import ImmFormat.{B, I, J, S, U} + + // the common shapes of rows + private def reg(op: AluOp.Type) = Row(Kind.Alu, Some(op), None, Some(ASel.Rs1), Some(BSel.Rs2)) // add rd, rs1, rs2 + private def imm(op: AluOp.Type) = Row(Kind.Alu, Some(op), Some(I), Some(ASel.Rs1), Some(BSel.Imm)) // addi + // the ALU computes the address (register + offset) or the target (pc + offset) + private val load = Row(Kind.Load, Some(Add), Some(I), Some(ASel.Rs1), Some(BSel.Imm)) + private val store = Row(Kind.Store, Some(Add), Some(S), Some(ASel.Rs1), Some(BSel.Imm)) + private val branch = Row(Kind.Branch, Some(Add), Some(B), Some(ASel.Pc), Some(BSel.Imm)) + + // a def, not a val: an unfinished row fails each time the table is used, not once for good + def table: Map[String, Row] = Map( + "LUI" -> Row(Kind.Alu, Some(Add), Some(U), Some(ASel.Zero), Some(BSel.Imm)), // 0 + imm + "AUIPC" -> Row(Kind.Alu, Some(Add), Some(U), Some(ASel.Pc), Some(BSel.Imm)), // pc + imm + "JAL" -> Row(Kind.Jal, Some(Add), Some(J), Some(ASel.Pc), Some(BSel.Imm)), // target pc + imm + "JALR" -> Row(Kind.Jalr, Some(Add), Some(I), Some(ASel.Rs1), Some(BSel.Imm)), // target rs1 + imm + "BEQ" -> branch, + "BNE" -> branch, + "BLT" -> branch, + "BGE" -> branch, + "BLTU" -> branch, + "BGEU" -> ??? /* Exercise */, + "LB" -> load, + "LH" -> load, + "LW" -> load, + "LBU" -> load, + "LHU" -> load, + "SB" -> store, + "SH" -> store, + "SW" -> store, + "ADDI" -> imm(Add), + "SLTI" -> imm(Slt), + "SLTIU" -> ??? /* Exercise */, + "XORI" -> imm(Xor), + "ORI" -> imm(Or), + "ANDI" -> imm(And), + // shifts: the immediate's upper bits hold funct7, but the ALU uses only its low 5 bits + "SLLI" -> imm(Sll), + "SRLI" -> imm(Srl), + "SRAI" -> imm(Sra), + "ADD" -> reg(Add), + "SUB" -> reg(Sub), + "SLL" -> reg(Sll), + "SLT" -> reg(Slt), + "SLTU" -> reg(Sltu), + "XOR" -> reg(Xor), + "SRL" -> reg(Srl), + "SRA" -> ??? /* Exercise */, + "OR" -> reg(Or), + "AND" -> reg(And), + "FENCE" -> Row(Kind.Fence), // a no-op here: nothing else matters + "ECALL" -> Row(Kind.Ecall), + "EBREAK" -> Row(Kind.Ebreak) + ) +} diff --git a/riscv/src/main/scala/riscv/Decoder.scala b/riscv/src/main/scala/riscv/Decoder.scala new file mode 100644 index 0000000..4f8ea5c --- /dev/null +++ b/riscv/src/main/scala/riscv/Decoder.scala @@ -0,0 +1,107 @@ +package riscv + +import chisel3._ +import chisel3.util.BitPat +import chisel3.util.experimental.decode._ + +/** What kind of instruction it is: the datapath derives the rest from it (whether rd is written, + * from where, whether memory is read or written, how the next pc is computed). + */ +object Kind extends ChiselEnum { + val Alu, Load, Store, Branch, Jal, Jalr, Fence, Ecall, Ebreak = Value +} + +/** The ALU's first operand: a register, the pc (`auipc`, jumps and branch targets), or 0 (`lui`). */ +object ASel extends ChiselEnum { + val Rs1, Pc, Zero = Value +} + +/** The ALU's second operand: a register or the immediate. */ +object BSel extends ChiselEnum { + val Rs2, Imm = Value +} + +/** The control signals of an instruction. When `legal` is false, the instruction is not RV32I and + * the other fields mean nothing. + */ +class Control extends Bundle { + val legal = Bool() + val kind = Kind() + val aluOp = AluOp() + val immFormat = ImmFormat() + val aSel = ASel() + val bSel = BSel() +} + +/** A row of the decode table: the control signals of one instruction. `None` means the instruction + * does not use that signal, so the decoder may give anything there (a don't care, which lets the + * logic minimizer make the decoder smaller). + */ +case class Row( + kind: Kind.Type, + aluOp: Option[AluOp.Type] = None, + imm: Option[ImmFormat.Type] = None, + a: Option[ASel.Type] = None, + b: Option[BSel.Type] = None +) + +/** An RV32I instruction as an input pattern of the decode table. */ +case class InstPattern(name: String, bitPat: BitPat) extends DecodePattern + +/** The table-driven decoder: `DecodeTable` builds the truth table from `DecodeRows.table` (one row + * per instruction of `Instructions.all`), and a logic minimizer (Quine-McCluskey, built into + * Chisel) turns it into gates. Words that match no row are illegal. + */ +object Decoder { + def patterns: Seq[InstPattern] = Instructions.all.map { case (name, bitPat) => InstPattern(name, bitPat) } + + private def row(op: InstPattern): Row = + DecodeRows.table.getOrElse(op.name, throw new IllegalArgumentException(s"no row for ${op.name} in DecodeRows")) + + // One field of the decoder's output per control signal; a field gives, for each instruction, the + // bit pattern of its value (BitPat(enum value), or don't care). + object LegalField extends BoolDecodeField[InstPattern] { + def name = "legal" + def genTable(op: InstPattern) = y + override def default: BitPat = n // a word that matches no instruction is illegal + } + object KindField extends DecodeField[InstPattern, Kind.Type] { + def name = "kind" + def chiselType = Kind() + def genTable(op: InstPattern) = BitPat(row(op).kind) + } + // the other fields are like KindField, but a row may leave them out (None: don't care) + class OptionField[T <: EnumType](val name: String, gen: => T, get: Row => Option[T]) + extends DecodeField[InstPattern, T] { + def chiselType = gen + def genTable(op: InstPattern) = get(row(op)).map(BitPat(_)).getOrElse(dc) + } + object AluOpField extends OptionField[AluOp.Type]("aluOp", AluOp(), _.aluOp) + object ImmField extends OptionField[ImmFormat.Type]("immFormat", ImmFormat(), _.imm) + object ASelField extends OptionField[ASel.Type]("aSel", ASel(), _.a) + object BSelField extends OptionField[BSel.Type]("bSel", BSel(), _.b) + + def table = new DecodeTable(patterns, Seq(LegalField, KindField, AluOpField, ImmField, ASelField, BSelField)) +} + +/** The decoder as a module: an instruction in, its control signals out (combinational). */ +class Decoder extends Module { + val io = IO(new Bundle { + val inst = Input(UInt(32.W)) + val ctrl = Output(new Control) + }) + + val table = Decoder.table + // decoder.qmc: Chisel's own minimizer (DecodeTable.decode would try the external espresso first). + // The cast to the enum fields is suppressed on purpose: a field may hold bits that are no value of + // its enum wherever the table does not care, that is for an illegal word (then `legal` is false) + // and for a field that the instruction's row leaves out (`None`, e.g. `aluOp` of `fence`), so the + // datapath must not use a field that the instruction's kind does not need. + val out = suppressEnumCastWarning(decoder.qmc(io.inst, table.table).asTypeOf(table.bundle)) + io.ctrl.legal := out(Decoder.LegalField) + io.ctrl.kind := out(Decoder.KindField) + io.ctrl.aluOp := out(Decoder.AluOpField) + io.ctrl.immFormat := out(Decoder.ImmField) + io.ctrl.aSel := out(Decoder.ASelField) + io.ctrl.bSel := out(Decoder.BSelField) +} diff --git a/riscv/src/main/scala/riscv/Formal.scala b/riscv/src/main/scala/riscv/Formal.scala new file mode 100644 index 0000000..103a999 --- /dev/null +++ b/riscv/src/main/scala/riscv/Formal.scala @@ -0,0 +1,24 @@ +package riscv + +import chisel3._ + +/** A formal check with Yosys (see [[Yosys]]). */ +object Formal { + + /** Proves with Yosys's SAT solver that output `ok` of `check`, a combinational module (no + * registers or memories: Yosys refuses them without a sequential proof), is 1 for every value of + * its inputs. Returns None if it is proved, or the counterexample Yosys found: the value of each + * input and output, one per line. + */ + def prove(check: => RawModule, ok: String = "io_ok"): Option[String] = { + require(ok.matches("[A-Za-z_][A-Za-z0-9_]*"), s"not a signal name: $ok") // it goes into a Yosys script + val script = s"read_verilog -sv check.sv; prep -auto-top; flatten; sat -prove $ok 1 -show-inputs -show-outputs" + val log = Yosys.run(script, Map("check.sv" -> Yosys.verilog(check))).log + if (log.contains("SAT proof finished - no model found: SUCCESS!")) None + else if (log.contains("SAT proof finished - model found: FAIL!")) { + val table = log.linesIterator.dropWhile(!_.trim.startsWith("Signal Name")).drop(2).takeWhile(_.trim.nonEmpty) + val ports = Seq("\\clock", "\\reset") // a row starts with the signal's name + Some(table.map(_.trim).filterNot(l => ports.contains(l.takeWhile(!_.isWhitespace))).mkString("\n")) + } else throw new IllegalStateException(s"yosys did not finish the proof:\n${log.takeRight(3000)}") + } +} diff --git a/riscv/src/main/scala/riscv/Forward.scala b/riscv/src/main/scala/riscv/Forward.scala new file mode 100644 index 0000000..70f5c12 --- /dev/null +++ b/riscv/src/main/scala/riscv/Forward.scala @@ -0,0 +1,26 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** A register value that an older instruction is about to write: its register number and the value. */ +class Result extends Bundle { + val rd = UInt(5.W) + val value = UInt(32.W) +} + +/** The value of register `rs` for the instruction in EX: the newest result an older instruction in + * the pipeline has for it (in EX/MEM, then in MEM/WB), or else the value read from the register file + * in ID. A result for x0 does not count: x0 is always 0. + */ +class Forward extends Module { + val io = IO(new Bundle { + val rs = Input(UInt(5.W)) + val regValue = Input(UInt(32.W)) // read in ID + val exMem = Input(Valid(new Result)) // the instruction one ahead + val memWb = Input(Valid(new Result)) // the instruction two ahead + val value = Output(UInt(32.W)) + }) + + io.value := ??? // Exercise +} diff --git a/riscv/src/main/scala/riscv/ForwardCheck.scala b/riscv/src/main/scala/riscv/ForwardCheck.scala new file mode 100644 index 0000000..3591f5e --- /dev/null +++ b/riscv/src/main/scala/riscv/ForwardCheck.scala @@ -0,0 +1,30 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** A forwarding unit next to its specification, written another way: `ok` is 1 when they agree. + * A formal tool can prove that `ok` is 1 for every input (`Formal.prove`). The specification + * says "the newest result wins" with Chisel's last-connect rule: the older result is connected + * first, the newer one after it, so the newer one wins when both write `rs`. + */ +class ForwardCheck(gen: => Forward) extends Module { + val io = IO(new Bundle { + val rs = Input(UInt(5.W)) + val regValue = Input(UInt(32.W)) + val exMem = Input(Valid(new Result)) + val memWb = Input(Valid(new Result)) + val ok = Output(Bool()) + }) + val dut = Module(gen) + dut.io.rs := io.rs + dut.io.regValue := io.regValue + dut.io.exMem := io.exMem + dut.io.memWb := io.memWb + val expected = WireDefault(io.regValue) + when(io.rs =/= 0.U) { // x0 is always 0, as the register file reads it + when(io.memWb.valid && io.memWb.bits.rd === io.rs)(expected := io.memWb.bits.value) // two ahead: older + when(io.exMem.valid && io.exMem.bits.rd === io.rs)(expected := io.exMem.bits.value) // one ahead: newer + } + io.ok := dut.io.value === expected +} diff --git a/riscv/src/main/scala/riscv/ForwardingCore.scala b/riscv/src/main/scala/riscv/ForwardingCore.scala new file mode 100644 index 0000000..102a5b8 --- /dev/null +++ b/riscv/src/main/scala/riscv/ForwardingCore.scala @@ -0,0 +1,222 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** The five-stage pipeline of [[PipelinedCore]], with its hazards handled in hardware, so programs + * need no nops: + * + * - data hazards: EX takes an operand from an older instruction still in the pipeline (EX/MEM, + * then MEM/WB) instead of the value read in ID (`Forward`); a load's value only exists after + * MEM, so an instruction that uses it right after the load waits one cycle in ID (a + * load-use stall: IF and ID hold, EX gets a bubble); + * - control hazards: as in `PipelinedCore`, fetch goes on at pc + 4 (predict not taken), and a + * jump or taken branch in EX flushes the two instructions behind it; + * - a data memory that answers late: while the access in MEM waits, the whole pipeline holds, + * and WB gets bubbles. The instruction memory must answer in the same cycle (a slow fetch + * needs a core that keeps its fetch request across a redirect). + * + * `forwardUnit` builds each of the two forwarding units (Module 5.9 passes one with a bug). + */ +class ForwardingCore(resetPc: Long = Ram.base, forwardUnit: => Forward = new Forward) extends Core { + val stopped = RegInit(false.B) // a halting instruction has passed MEM: fetch no more + val halted = RegInit(false.B) + val flush = Module(new PipelineFlush) + def is(c: Control, k: Kind.Type): Bool = c.legal && c.kind === k + + // ---- IF + val pc = RegInit(resetPc.U(32.W)) + val fetching = !reset.asBool && !stopped + io.imem.req.valid := fetching + io.imem.req.bits.addr := pc + io.imem.req.bits.wdata := 0.U + io.imem.req.bits.wstrb := 0.U + val fetched = Wire(Valid(new IfId)) + fetched.valid := fetching && io.imem.resp.valid + fetched.bits.pc := pc + fetched.bits.fetchError := io.imem.resp.bits.error + fetched.bits.inst := Mux(io.imem.resp.bits.error, 0.U, io.imem.resp.bits.rdata) + // hazards that hold stages (computed below) + val loadUse = Wire(Bool()) // ID needs the value of the load in EX + val memWait = Wire(Bool()) // the data access in MEM waits for the memory + val ifMoves = !loadUse && !memWait // IF passes its instruction on, and fetches the next + val ifId = Stage(fetched, flush.io.flushIfId, enable = ifMoves) + + // ---- ID + val decoder = Module(new Decoder) + decoder.io.inst := ifId.bits.inst + val dc = decoder.io.ctrl + val regs = Module(new RegFile) + val idRs1 = ifId.bits.inst(19, 15) + val idRs2 = ifId.bits.inst(24, 20) + regs.io.rs1 := idRs1 + regs.io.rs2 := idRs2 + regs.io.dbgAddr := io.dbg.addr + io.dbg.data := regs.io.dbgData + val immGen = Module(new ImmGen) + immGen.io.inst := ifId.bits.inst + immGen.io.format := dc.immFormat + val decoded = Wire(Valid(new IdEx)) + decoded.valid := ifId.valid + decoded.bits.pc := ifId.bits.pc + decoded.bits.inst := ifId.bits.inst + decoded.bits.ctrl := dc + // The register file is written in the first half of a cycle and read in the second (as in the + // classic five-stage pipeline): a register that WB writes in this cycle reads as its new value. + val wbRd = Wire(UInt(5.W)) + val wbValue = Wire(UInt(32.W)) + def read(index: UInt, data: UInt) = Mux(wbRd =/= 0.U && wbRd === index, wbValue, data) + decoded.bits.rs1Data := read(idRs1, regs.io.rs1Data) + decoded.bits.rs2Data := read(idRs2, regs.io.rs2Data) + decoded.bits.imm := immGen.io.imm + decoded.bits.cause := MuxCase( + HaltCause.Running, + Seq( + ifId.bits.fetchError -> HaltCause.BadAddress, + !dc.legal -> HaltCause.Illegal, + is(dc, Kind.Ecall) -> HaltCause.Ecall, + is(dc, Kind.Ebreak) -> HaltCause.Ebreak + ) + ) + // which registers the instruction in ID reads (branches compare both; aSel is the ALU's choice) + def uses(kinds: Kind.Type*) = kinds.map(is(dc, _)).reduce(_ || _) + // rs1: branches compare it, and the others that read it give it to the ALU (lui and auipc do not) + val usesRs1 = uses(Kind.Branch) || (uses(Kind.Alu, Kind.Load, Kind.Store, Kind.Jalr) && dc.aSel === ASel.Rs1) + // rs2: branches compare it, stores store it, and register-register instructions give it to the ALU + val usesRs2 = uses(Kind.Branch, Kind.Store) || (uses(Kind.Alu) && dc.bSel === BSel.Rs2) + val idEx = Stage(decoded, flush.io.flushIdEx || (loadUse && !memWait), enable = !memWait) + + // ---- EX + val e = idEx.bits + // the operands, forwarded from the instructions ahead (wired at the end, once MEM and WB exist) + val fromExMem = Wire(Valid(new Result)) + val fromMemWb = Wire(Valid(new Result)) + def forward(rs: UInt, regValue: UInt): UInt = { + val f = Module(forwardUnit) + f.io.rs := rs + f.io.regValue := regValue + f.io.exMem := fromExMem + f.io.memWb := fromMemWb + f.io.value + } + val rs1Data = forward(e.inst(19, 15), e.rs1Data) + val rs2Data = forward(e.inst(24, 20), e.rs2Data) + // While the pipeline waits for memory, WB empties: keep the forwarded operands in ID/EX, so that + // EX still has them when the pipeline moves again. + when(memWait) { + idEx.bits.rs1Data := rs1Data + idEx.bits.rs2Data := rs2Data + } + val exRd = e.inst(11, 7) + loadUse := idEx.valid && is(e.ctrl, Kind.Load) && exRd =/= 0.U && ifId.valid && + ((usesRs1 && idRs1 === exRd) || (usesRs2 && idRs2 === exRd)) + val alu = Module(new Alu) + alu.io.op := e.ctrl.aluOp + alu.io.a := MuxLookup(e.ctrl.aSel, rs1Data)(Seq(ASel.Pc -> e.pc, ASel.Zero -> 0.U)) + alu.io.b := Mux(e.ctrl.bSel === BSel.Imm, e.imm, rs2Data) + val branchUnit = Module(new BranchUnit) + branchUnit.io.funct3 := e.inst(14, 12) + branchUnit.io.a := rs1Data + branchUnit.io.b := rs2Data + val jalr = is(e.ctrl, Kind.Jalr) + val jumps = is(e.ctrl, Kind.Jal) || jalr || (is(e.ctrl, Kind.Branch) && branchUnit.io.taken) + val target = Mux(jalr, alu.io.out(31, 1) ## 0.U(1.W), alu.io.out) + val badTarget = jumps && target(1, 0) =/= 0.U + val causeEx = Mux(e.cause === HaltCause.Running && badTarget, HaltCause.Misaligned, e.cause) + val redirect = idEx.valid && jumps && causeEx === HaltCause.Running && !memWait + val executed = Wire(Valid(new ExMem)) + executed.valid := idEx.valid + executed.bits.pc := e.pc + executed.bits.inst := e.inst + executed.bits.ctrl := e.ctrl + executed.bits.result := alu.io.out + executed.bits.storeData := rs2Data + executed.bits.nextPc := Mux(jumps, target, e.pc + 4.U) + executed.bits.cause := causeEx + val exMem = Stage(executed, flush.io.flushExMem, enable = !memWait) + + // ---- MEM + val m = exMem.bits + val load = is(m.ctrl, Kind.Load) + val store = is(m.ctrl, Kind.Store) + val funct3 = m.inst(14, 12) + val size = funct3(1, 0) + val bytes = 1.U(3.W) << size + val offset = m.result(1, 0) + val shamt = offset ## 0.U(3.W) + val misaligned = (load || store) && (offset & (bytes - 1.U)(1, 0)) =/= 0.U + val access = exMem.valid && (load || store) && !misaligned && m.cause === HaltCause.Running + val strobe = ((1.U(5.W) << bytes) - 1.U)(3, 0) + val sizeMask = FillInterleaved(8, strobe) + // a request goes out once: after the memory accepts it (req.fire), MEM waits for the answer + val sent = RegInit(false.B) + when(io.dmem.resp.valid)(sent := false.B).elsewhen(io.dmem.req.fire)(sent := true.B) + io.dmem.req.valid := access && !sent + io.dmem.req.bits.addr := m.result(31, 2) ## 0.U(2.W) + io.dmem.req.bits.wdata := (m.storeData << shamt)(31, 0) + io.dmem.req.bits.wstrb := Mux(store, (strobe << offset)(3, 0), 0.U) + val extend = Module(new LoadExtend) + extend.io.funct3 := funct3 + extend.io.offset := offset + extend.io.rdata := io.dmem.resp.bits.rdata + val causeMem = MuxCase( + HaltCause.Running, + Seq( + (m.cause =/= HaltCause.Running) -> m.cause, + misaligned -> HaltCause.Misaligned, + (access && io.dmem.resp.bits.error) -> HaltCause.BadAddress + ) + ) + val halts = causeMem =/= HaltCause.Running + val linkPc = m.pc + 4.U + val link = is(m.ctrl, Kind.Jal) || is(m.ctrl, Kind.Jalr) // jal and jalr write pc + 4 + val rd = m.inst(11, 7) + val writesRd = (is(m.ctrl, Kind.Alu) || load || link) && !halts && rd =/= 0.U + val aluOrLink = Mux(link, linkPc, m.result) // what MEM can forward: not a loaded value + val writeValue = Mux(load, extend.io.value, aluOrLink) + memWait := access && !io.dmem.resp.valid + val retiring = Wire(Valid(new RetireInfo)) + val r = retiring.bits + retiring.valid := exMem.valid && !memWait + r.pc := m.pc + r.inst := m.inst + r.nextPc := Mux(halts, m.pc, m.nextPc) + r.rd := Mux(writesRd, rd, 0.U) + r.rdValue := Mux(writesRd, writeValue, 0.U) + r.mem.valid := access && !halts + r.mem.bits.addr := m.result + r.mem.bits.write := store + r.mem.bits.bytes := bytes + r.mem.bits.data := Mux(store, m.storeData, io.dmem.resp.bits.rdata >> shamt) & sizeMask + r.halt := causeMem + val haltInMem = exMem.valid && halts && !memWait + when(haltInMem)(stopped := true.B) + val memWb = Stage(retiring) + + // ---- WB + wbRd := Mux(memWb.valid, memWb.bits.rd, 0.U) // rd is 0 if nothing is written + wbValue := memWb.bits.rdValue + regs.io.wen := wbRd =/= 0.U + regs.io.rd := wbRd + regs.io.wdata := wbValue + io.retire := memWb + when(memWb.valid && memWb.bits.halt =/= HaltCause.Running)(halted := true.B) + io.halted := halted + + // ---- forwarding: the results of the instructions in MEM (not a load: its value is not there + // before MEM) and in WB + fromExMem.valid := exMem.valid && m.cause === HaltCause.Running && (is(m.ctrl, Kind.Alu) || link) + fromExMem.bits.rd := rd + fromExMem.bits.value := aluOrLink + fromMemWb.valid := memWb.valid + fromMemWb.bits.rd := memWb.bits.rd // 0 if it writes nothing + fromMemWb.bits.value := memWb.bits.rdValue + + // ---- the next pc, and the flushes + flush.io.redirect := redirect + flush.io.halt := haltInMem + when(redirect)(pc := target).elsewhen(fetched.valid && ifMoves)(pc := pc + 4.U) +} + +/** The pipeline with hazard handling, with its RAM, for tests and notebooks. */ +class ForwardingSystem extends CoreSystem(new ForwardingCore) diff --git a/riscv/src/main/scala/riscv/ImmGen.scala b/riscv/src/main/scala/riscv/ImmGen.scala new file mode 100644 index 0000000..7e3aba3 --- /dev/null +++ b/riscv/src/main/scala/riscv/ImmGen.scala @@ -0,0 +1,43 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** The instruction formats that have an immediate (R-type has none). */ +object ImmFormat extends ChiselEnum { + val I, S, B, U, J = Value + + /** The immediate format of an instruction format (R-type has no immediate). */ + def of(format: Format): Option[Type] = format match { + case Format.R => None + case Format.I => Some(I) + case Format.S => Some(S) + case Format.B => Some(B) + case Format.U => Some(U) + case Format.J => Some(J) + } +} + +/** The immediate generator: extracts the immediate of `inst` for its format, sign-extended to 32 + * bits (U-type: the upper 20 bits, the low 12 zero). The sign is always instruction bit 31, so + * every format shares it; only the order of the other bits differs. + */ +class ImmGen extends Module { + val io = IO(new Bundle { + val inst = Input(UInt(32.W)) + val format = Input(ImmFormat()) + val imm = Output(UInt(32.W)) + }) + + val i = io.inst + val sign = i(31) + io.imm := MuxLookup(io.format, 0.U)( + Seq( + ImmFormat.I -> Cat(Fill(21, sign), i(30, 20)), + ImmFormat.S -> Cat(Fill(21, sign), i(30, 25), i(11, 7)), + ImmFormat.B -> Cat(Fill(20, sign), i(7), i(30, 25), i(11, 8), 0.U(1.W)), + ImmFormat.U -> Cat(i(31, 12), 0.U(12.W)), + ImmFormat.J -> Cat(Fill(12, sign), i(19, 12), i(20), i(30, 21), 0.U(1.W)) + ) + ) +} diff --git a/riscv/src/main/scala/riscv/Isa.scala b/riscv/src/main/scala/riscv/Isa.scala new file mode 100644 index 0000000..6fb69ef --- /dev/null +++ b/riscv/src/main/scala/riscv/Isa.scala @@ -0,0 +1,149 @@ +package riscv + +import chisel3._ +import chisel3.util.BitPat + +/** RV32I encodings: the major opcodes (bits 6-0) and the instruction patterns. + * + * Pinned to "The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture", version + * 20240411. Only RV32I: no CSR instructions (see DESIGN.md), so `System` holds only ECALL and EBREAK. + */ +object Opcode extends ChiselEnum { + val Load = Value("b0000011".U) + val MiscMem = Value("b0001111".U) + val OpImm = Value("b0010011".U) + val Auipc = Value("b0010111".U) + val Store = Value("b0100011".U) + val Op = Value("b0110011".U) + val Lui = Value("b0110111".U) + val Branch = Value("b1100011".U) + val Jalr = Value("b1100111".U) + val Jal = Value("b1101111".U) + val System = Value("b1110011".U) +} + +object Instructions { + private def any(width: Int) = BitPat.dontCare(width) + private def bits(s: String) = BitPat("b" + s) + // funct7, funct3 and the opcode fixed, the registers free + private def r(funct7: String, funct3: String, opcode: Opcode.Type) = + bits(funct7) ## any(10) ## bits(funct3) ## any(5) ## BitPat(opcode) + // funct3 and the opcode fixed, everything else (registers, immediates) free + private def f3(funct3: String, opcode: Opcode.Type) = any(17) ## bits(funct3) ## any(5) ## BitPat(opcode) + private def u(opcode: Opcode.Type) = any(25) ## BitPat(opcode) + + val LUI = u(Opcode.Lui) + val AUIPC = u(Opcode.Auipc) + val JAL = u(Opcode.Jal) + val JALR = f3("000", Opcode.Jalr) + + val BEQ = f3("000", Opcode.Branch) + val BNE = f3("001", Opcode.Branch) + val BLT = f3("100", Opcode.Branch) + val BGE = f3("101", Opcode.Branch) + val BLTU = f3("110", Opcode.Branch) + val BGEU = f3("111", Opcode.Branch) + + val LB = f3("000", Opcode.Load) + val LH = f3("001", Opcode.Load) + val LW = f3("010", Opcode.Load) + val LBU = f3("100", Opcode.Load) + val LHU = f3("101", Opcode.Load) + val SB = f3("000", Opcode.Store) + val SH = f3("001", Opcode.Store) + val SW = f3("010", Opcode.Store) + + val ADDI = f3("000", Opcode.OpImm) + val SLTI = f3("010", Opcode.OpImm) + val SLTIU = f3("011", Opcode.OpImm) + val XORI = f3("100", Opcode.OpImm) + val ORI = f3("110", Opcode.OpImm) + val ANDI = f3("111", Opcode.OpImm) + val SLLI = r("0000000", "001", Opcode.OpImm) + val SRLI = r("0000000", "101", Opcode.OpImm) + val SRAI = r("0100000", "101", Opcode.OpImm) + + val ADD = r("0000000", "000", Opcode.Op) + val SUB = r("0100000", "000", Opcode.Op) + val SLL = r("0000000", "001", Opcode.Op) + val SLT = r("0000000", "010", Opcode.Op) + val SLTU = r("0000000", "011", Opcode.Op) + val XOR = r("0000000", "100", Opcode.Op) + val SRL = r("0000000", "101", Opcode.Op) + val SRA = r("0100000", "101", Opcode.Op) + val OR = r("0000000", "110", Opcode.Op) + val AND = r("0000000", "111", Opcode.Op) + + val FENCE = f3("000", Opcode.MiscMem) + val ECALL = BitPat("b00000000000000000000000001110011") + val EBREAK = BitPat("b00000000000100000000000001110011") + + /** The names of the patterns of `all` that match `word`: exactly one for an RV32I instruction. */ + def matching(word: Long): Seq[String] = { + val w = BitPat(word.U(32.W)) + all.collect { case (name, p) if p.cover(w) => name } + } + + /** A random instance of instruction `name` (as in `all`): its pattern's fixed bits, and random + * bits wherever the pattern does not care (registers, immediates). + */ + def random(name: String, rnd: scala.util.Random): Long = { + val p = pattern(name) + (rnd.nextLong() & ~p.mask.toLong | p.value.toLong) & 0xffffffffL + } + + /** `random(name)` with one of the bits its pattern fixes flipped: a word that is close to the + * instruction, and usually not an RV32I instruction at all. + */ + def nearMiss(name: String, rnd: scala.util.Random): Long = { + val fixed = (0 until 32).filter(pattern(name).mask.testBit) + random(name, rnd) ^ (1L << fixed(rnd.nextInt(fixed.size))) + } + + private def pattern(name: String): BitPat = + all.find(_._1 == name).getOrElse(throw new IllegalArgumentException(s"no instruction $name"))._2 + + /** All 40 RV32I instructions (FENCE.I belongs to Zifencei, not RV32I). */ + val all: Seq[(String, BitPat)] = Seq( + "LUI" -> LUI, + "AUIPC" -> AUIPC, + "JAL" -> JAL, + "JALR" -> JALR, + "BEQ" -> BEQ, + "BNE" -> BNE, + "BLT" -> BLT, + "BGE" -> BGE, + "BLTU" -> BLTU, + "BGEU" -> BGEU, + "LB" -> LB, + "LH" -> LH, + "LW" -> LW, + "LBU" -> LBU, + "LHU" -> LHU, + "SB" -> SB, + "SH" -> SH, + "SW" -> SW, + "ADDI" -> ADDI, + "SLTI" -> SLTI, + "SLTIU" -> SLTIU, + "XORI" -> XORI, + "ORI" -> ORI, + "ANDI" -> ANDI, + "SLLI" -> SLLI, + "SRLI" -> SRLI, + "SRAI" -> SRAI, + "ADD" -> ADD, + "SUB" -> SUB, + "SLL" -> SLL, + "SLT" -> SLT, + "SLTU" -> SLTU, + "XOR" -> XOR, + "SRL" -> SRL, + "SRA" -> SRA, + "OR" -> OR, + "AND" -> AND, + "FENCE" -> FENCE, + "ECALL" -> ECALL, + "EBREAK" -> EBREAK + ) +} diff --git a/riscv/src/main/scala/riscv/IsaSim.scala b/riscv/src/main/scala/riscv/IsaSim.scala new file mode 100644 index 0000000..ce1c6b8 --- /dev/null +++ b/riscv/src/main/scala/riscv/IsaSim.scala @@ -0,0 +1,245 @@ +package riscv + +import scala.collection.mutable + +/** Why a core stopped. There are no CSRs, so no trap handler: each of these halts the core (see + * DESIGN.md). + */ +sealed trait Halt +object Halt { + case object Ecall extends Halt // how a program ends, with its result in a0 + case object Ebreak extends Halt + case object Illegal extends Halt // not an RV32I instruction + case object Misaligned extends Halt // a load or store address, or a jump or branch target, not aligned + case object BadAddress extends Halt // a fetch, load or store outside the RAM +} + +/** A load or store: its address, its size in bytes (1, 2 or 4) and the bytes read or written, + * zero-extended (a load's sign extension shows in the register write). + */ +case class MemAccess(addr: Long, write: Boolean, bytes: Int, data: Long) + +/** One retired instruction, as the RVFI-style retire port of a core reports it. `rd` is 0 when + * nothing is written (and `rdValue` is then 0); values are 32-bit, unsigned. An instruction that + * halts the core retires with `halt` set and changes nothing. + */ +case class Retire( + pc: Long, + inst: Long, + nextPc: Long, + rd: Int = 0, + rdValue: Long = 0, + mem: Option[MemAccess] = None, + halt: Option[Halt] = None +) { + + /** One line of a trace: the pc, the instruction, and what it did, e.g. + * `80000008 00a50513 addi a0, a0, 10 a0 <- 0x0000000f`. + */ + override def toString: String = { + val effects = Seq( + Option.when(rd != 0)(f"${Reg.names(rd)} <- 0x$rdValue%08x"), + mem.map { m => + val arrow = if (m.write) "<-" else "->" + f"mem[0x${m.addr}%08x] $arrow 0x${m.data}%x (${m.bytes} bytes)" + }, + Option.when(halt.isEmpty && nextPc != ((pc + 4) & 0xffffffffL))(f"pc <- 0x$nextPc%08x"), + halt.map(h => s"halt: $h") + ).flatten + f"$pc%08x $inst%08x ${Rv32i.disassemble(inst, pc)}%-24s ${effects.mkString(", ")}".trim + } +} + +/** The golden model: an RV32I interpreter that executes one instruction per `step` and reports it + * as a [[Retire]] record, for comparison with the cores' retire ports. It is a teaching oracle + * written with the course, not an independent reference, so it shares the course's reading of + * the specification (and Rv32i.decode). + * + * The memory is one RAM of `size` bytes at `base`, holding `image` (from `Asm`) and zeros after it, + * and the memory-mapped `devices` (loads and stores only; instructions come from the RAM). + */ +class IsaSim(image: Seq[Long], val base: Long = Ram.base, val size: Int = Ram.bytes, devices: Seq[Device] = Nil) { + require( + base >= 0 && base % 4 == 0 && size % 4 == 0 && size > 0 && base + size <= (1L << 32), + "the RAM must be whole words" + ) + require(image.size * 4L <= size, "the image is larger than the RAM") + require( + devices.forall(d => d.base + d.size <= base || d.base >= base + size), + "a device overlaps the RAM" + ) + + /** Loads `program` at the address it was assembled for. */ + def this(program: Program) = this(program.words, program.base) + + private val ram = new Array[Byte](size) + for ((w, i) <- image.zipWithIndex; k <- 0 until 4) ram(4 * i + k) = (w >> (8 * k)).toByte + + private val x = new Array[Int](32) + private var _pc: Long = base + private var _halted: Option[Halt] = None + + def pc: Long = _pc + def halted: Option[Halt] = _halted + def reg(n: Int): Long = x(n) & 0xffffffffL + def regs: IndexedSeq[Long] = (0 until 32).map(reg) + + private def inRam(addr: Long, bytes: Int) = addr >= base && addr + bytes <= base + size + private def device(addr: Long, bytes: Int) = devices.find(d => addr >= d.base && addr + bytes <= d.base + d.size) + + // a load or store: from the RAM or a device (the callers checked that one of them is there) + private def load(addr: Long, bytes: Int): Long = + device(addr, bytes).fold(bytesAt(addr, bytes))(d => lowBytes(d.read(addr, bytes), bytes)) + private def store(addr: Long, bytes: Int, value: Long): Unit = + device(addr, bytes).fold(write(addr, bytes, value))(_.write(addr, bytes, value)) + + /** `bytes` bytes at `addr`, little-endian, zero-extended. */ + def read(addr: Long, bytes: Int): Long = { + require(inRam(addr, bytes), f"0x$addr%08x is outside the RAM") + bytesAt(addr, bytes) + } + + private def lowBytes(v: Long, bytes: Int): Long = v & ((1L << (8 * bytes)) - 1) + + private def bytesAt(addr: Long, bytes: Int): Long = { // unchecked: the callers checked inRam + var v = 0L + for (k <- bytes - 1 to 0 by -1) v = v << 8 | (ram((addr - base).toInt + k) & 0xffL) + v + } + + private def write(addr: Long, bytes: Int, value: Long): Unit = + for (k <- 0 until bytes) ram((addr - base).toInt + k) = (value >> (8 * k)).toByte + + // decoding is the slow part of a step; programs execute the same words again and again + private val decoded = mutable.HashMap[Long, Option[Inst]]() + + /** The core halts at `pc` for reason `h`; the instruction retires but changes nothing. */ + private def stop(pc: Long, h: Halt, inst: Long): Retire = { _halted = Some(h); Retire(pc, inst, pc, halt = Some(h)) } + + /** Executes the instruction at `pc`. A fetch outside the RAM retires with `inst` 0. */ + def step(): Retire = { + require(_halted.isEmpty, s"the core has halted (${_halted.get})") + if (!inRam(_pc, 4)) stop(_pc, Halt.BadAddress, 0) + else { + val word = bytesAt(_pc, 4) + decoded.getOrElseUpdate(word, Rv32i.decode(word)) match { + case None => stop(_pc, Halt.Illegal, word) + case Some(i) => execute(_pc, word, i) + } + } + } + + private def execute(pc: Long, word: Long, i: Inst): Retire = { + val a = x(i.rs1) + val b = x(i.rs2) + def u32(v: Long): Long = v & 0xffffffffL + // Branches and stores have no rd field (decode gives 0), so they write nothing either + def retire(next: Long, value: Int = 0, mem: Option[MemAccess] = None): Retire = { + if (i.rd != 0) x(i.rd) = value + _pc = u32(next) // the pc wraps at 2^32, as a core's 32-bit pc does + Retire(pc, word, _pc, i.rd, if (i.rd == 0) 0 else u32(value), mem) + } + // a jump or a taken branch; it halts, without writing its link register, if the target is misaligned + def jump(target: Long): Retire = + if (target % 4 != 0) stop(pc, Halt.Misaligned, word) else retire(target, (pc + 4).toInt) + // a misaligned address halts as Misaligned even if it is also outside the RAM + def access(addr: Long, bytes: Int)(body: => Retire): Retire = + if (addr % bytes != 0) stop(pc, Halt.Misaligned, word) + else if (!inRam(addr, bytes) && device(addr, bytes).isEmpty) stop(pc, Halt.BadAddress, word) + else body + lazy val addr = u32(a.toLong + i.imm) // of loads, stores and jalr + lazy val bytes = IsaSim.width(i.name) // of loads and stores + + i.name match { + case "lui" => retire(pc + 4, i.imm) + case "auipc" => retire(pc + 4, (pc + i.imm).toInt) + case "jal" => jump(u32(pc + i.imm)) + case "jalr" => jump(addr & ~1L) + case "beq" | "bne" | "blt" | "bge" | "bltu" | "bgeu" => + if (IsaSim.taken(i.name, a, b)) jump(u32(pc + i.imm)) else retire(pc + 4) + case "lb" | "lh" | "lw" | "lbu" | "lhu" => + access(addr, bytes) { + val raw = load(addr, bytes) + val value = IsaSim.loadValue(i.name, raw) + retire(pc + 4, value, Some(MemAccess(addr, write = false, bytes, raw))) + } + case "sb" | "sh" | "sw" => + access(addr, bytes) { + val data = lowBytes(u32(b), bytes) + store(addr, bytes, data) + retire(pc + 4, mem = Some(MemAccess(addr, write = true, bytes, data))) + } + // one in-order core: nothing to order. Its rd field is reserved, so it is not written. + case "fence" => _pc = u32(pc + 4); Retire(pc, word, _pc) + case "ecall" => stop(pc, Halt.Ecall, word) + case "ebreak" => stop(pc, Halt.Ebreak, word) + case name if Rv32i.isAluImm(name) => retire(pc + 4, IsaSim.alu(name.filterNot(_ == 'i'), a, i.imm)) // addi -> add + case name => retire(pc + 4, IsaSim.alu(name, a, b)) + } + } + + /** Steps until the core halts, at most `maxSteps` times; returns what retired. */ + def run(maxSteps: Int = 1000000): Seq[Retire] = { + val trace = mutable.ArrayBuffer[Retire]() + while (_halted.isEmpty && trace.size < maxSteps) trace += step() + trace.toSeq + } +} + +object IsaSim { + + /** Whether branch `name` (`beq`, ..., `bgeu`) is taken for registers `a` and `b`. */ + def taken(name: String, a: Int, b: Int): Boolean = name match { + case "beq" => a == b + case "bne" => a != b + case "blt" => a < b + case "bge" => a >= b + case "bltu" => Integer.compareUnsigned(a, b) < 0 + case "bgeu" => Integer.compareUnsigned(a, b) >= 0 + case _ => throw new IllegalArgumentException(s"not a branch: $name") + } + + /** The value load `name` (`lb`, ..., `lhu`) writes to rd, from the bytes it read (`raw`, zero-extended). */ + def loadValue(name: String, raw: Long): Int = + if (name.endsWith("u")) raw.toInt else Rv32i.signExtend(raw.toInt, 8 * width(name)) + + /** The size in bytes of a load or store (`lb`, `sh`, `lw`, ...). */ + def width(name: String): Int = name(1) match { + case 'b' => 1 + case 'h' => 2 + case 'w' => 4 + } + + /** The result of a register-register operation (`add`, ..., `and`); Int behaves like a 32-bit + * register, and shifts use the low 5 bits of `b`. + */ + def alu(op: String, a: Int, b: Int): Int = op match { + case "add" => a + b + case "sub" => a - b + case "sll" => a << b + case "slt" => if (a < b) 1 else 0 + case "sltu" => if (Integer.compareUnsigned(a, b) < 0) 1 else 0 + case "xor" => a ^ b + case "srl" => a >>> b + case "sra" => a >> b + case "or" => a | b + case "and" => a & b + case _ => throw new IllegalArgumentException(s"not an ALU operation: $op") + } + + /** Assembles `source` and runs it until it halts. */ + def run(source: String, maxSteps: Int = 1000000): (IsaSim, Seq[Retire]) = { + val sim = new IsaSim(Asm.assemble(source)) + (sim, sim.run(maxSteps)) + } +} + +/** A memory-mapped device of the golden model, at `base` to `base + size - 1`. A `read` of `bytes` + * bytes may set higher bits: the model keeps the low `bytes` bytes. + */ +trait Device { + def base: Long + def size: Long + def read(addr: Long, bytes: Int): Long + def write(addr: Long, bytes: Int, data: Long): Unit +} diff --git a/riscv/src/main/scala/riscv/LoadExtend.scala b/riscv/src/main/scala/riscv/LoadExtend.scala new file mode 100644 index 0000000..b4cc65f --- /dev/null +++ b/riscv/src/main/scala/riscv/LoadExtend.scala @@ -0,0 +1,21 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** Takes the loaded value out of the memory word: `rdata` is the whole word at the (word-aligned) + * address, `offset` the byte address's low two bits, and `funct3` the load (`lb` 0, `lh` 1, `lw` 2, + * `lbu` 4, `lhu` 5). The byte or half-word starts at byte `offset` of the word (little-endian), and + * is sign-extended (`lb`, `lh`) or zero-extended (`lbu`, `lhu`) to 32 bits. The address is aligned: + * a half-word starts at offset 0 or 2. + */ +class LoadExtend extends Module { + val io = IO(new Bundle { + val funct3 = Input(UInt(3.W)) + val offset = Input(UInt(2.W)) + val rdata = Input(UInt(32.W)) + val value = Output(UInt(32.W)) + }) + + io.value := ??? // Exercise: shift the bytes down, then extend them as funct3 says +} diff --git a/riscv/src/main/scala/riscv/Memory.scala b/riscv/src/main/scala/riscv/Memory.scala new file mode 100644 index 0000000..150e7cc --- /dev/null +++ b/riscv/src/main/scala/riscv/Memory.scala @@ -0,0 +1,90 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** A request from a core to memory: a word-aligned address, and for a write the data and the byte + * strobes (`wstrb(k)`: write byte k of the word). `wstrb` 0 is a read. + */ +class MemReq extends Bundle { + val addr = UInt(32.W) + val wdata = UInt(32.W) + val wstrb = UInt(4.W) +} + +/** The memory's answer: the word read (for a write, nothing in particular), or `error` if the + * address is not in the memory. + */ +class MemResp extends Bundle { + val rdata = UInt(32.W) + val error = Bool() +} + +/** The memory interface of the cores: the core sends a request (`req`) and the memory answers + * (`resp`). The single-cycle and 5.6 cores hold a request until its answer comes and ignore + * `ready`, so both of their ports must answer in the same cycle (the RAM of this file does). + * `ForwardingCore` sends a data request once, when it is taken (`req.fire`), and then waits for the + * answer, so a device that takes a request must keep it until it answers (the `Bus` does); its + * instruction port must still answer in the same cycle. + */ +class MemPort extends Bundle { + val req = Decoupled(new MemReq) + val resp = Flipped(Valid(new MemResp)) +} + +/** A register read by a testbench (the register file's debug port). */ +class DebugPort extends Bundle { + val addr = Input(UInt(5.W)) + val data = Output(UInt(32.W)) +} + +/** A word written into a memory by a testbench before the core runs. */ +class LoadPort extends Bundle { + val addr = UInt(32.W) + val data = UInt(32.W) +} + +object Ram { + + /** Where the RAM of the course is (the cores start there, and riscv-tests expect it), and its + * size: the cores, the golden model and the programs all use these. + */ + val base: Long = 0x80000000L + val bytes: Int = 64 * 1024 +} + +/** The RAM: `words` 32-bit words from `base`, with an instruction port and a data port that read + * combinationally and answer in the same cycle (a `Mem`), byte-strobed writes, and a load port for + * testbenches. It starts with unknown contents. The load port takes priority: a store in the same + * cycle as a load-port write is dropped (testbenches load while the core is held in reset). + */ +class Ram(words: Int = Ram.bytes / 4, base: Long = Ram.base) extends Module { + require(isPow2(words) && base % (4L * words) == 0, "the RAM must be aligned to its size") + val io = IO(new Bundle { + val imem = Flipped(new MemPort) + val dmem = Flipped(new MemPort) + val load = Input(Valid(new LoadPort)) + }) + + val mem = Mem(words, Vec(4, UInt(8.W))) + def inRam(addr: UInt): Bool = addr >= base.U && addr < (base + 4L * words).U + def index(addr: UInt): UInt = addr(log2Ceil(words) + 1, 2) + def bytes(word: UInt): Vec[UInt] = word.asTypeOf(Vec(4, UInt(8.W))) // the same bits, as bytes + + for (port <- Seq(io.imem, io.dmem)) { + port.req.ready := true.B + port.resp.valid := port.req.valid + port.resp.bits.rdata := mem(index(port.req.bits.addr)).asUInt + port.resp.bits.error := !inRam(port.req.bits.addr) + } + // One write port, shared by the load port (all four bytes) and the core's stores (the strobed + // bytes): firtool drops the masks of a memory whose other write port has no mask (a constant + // all-ones mask counts as none), and a masked write then writes every byte (see 2.8). + val store = io.dmem.req.valid && io.dmem.req.bits.wstrb.orR && inRam(io.dmem.req.bits.addr) + val wreq = Mux(io.load.valid, io.load.bits.addr, io.dmem.req.bits.addr) + val wdata = Mux(io.load.valid, io.load.bits.data, io.dmem.req.bits.wdata) + val wstrb = Mux(io.load.valid, "b1111".U, io.dmem.req.bits.wstrb) + when(io.load.valid || store) { + mem.write(index(wreq), bytes(wdata), wstrb.asBools) + } +} diff --git a/riscv/src/main/scala/riscv/PipelineFlush.scala b/riscv/src/main/scala/riscv/PipelineFlush.scala new file mode 100644 index 0000000..52549ec --- /dev/null +++ b/riscv/src/main/scala/riscv/PipelineFlush.scala @@ -0,0 +1,25 @@ +package riscv + +import chisel3._ + +/** Which stage registers of the five-stage pipeline take a bubble instead of the instruction + * coming from the stage before (IF -> IF/ID -> ID -> ID/EX -> EX -> EX/MEM -> MEM -> MEM/WB -> WB): + * + * - `redirect`: the instruction in EX is a jump or a taken branch, so the two instructions + * fetched after it (now in IF and ID) are on the wrong path; + * - `halt`: the instruction in MEM halts the core, so every younger instruction (in IF, ID and + * EX) must not reach MEM or WB, where instructions change memory and registers; fetching stops. + */ +class PipelineFlush extends Module { + val io = IO(new Bundle { + val redirect = Input(Bool()) + val halt = Input(Bool()) + val flushIfId = Output(Bool()) // the instruction in IF does not enter ID + val flushIdEx = Output(Bool()) // the instruction in ID does not enter EX + val flushExMem = Output(Bool()) // the instruction in EX does not enter MEM + }) + + io.flushIfId := ??? // Exercise + io.flushIdEx := ??? // Exercise + io.flushExMem := ??? // Exercise +} diff --git a/riscv/src/main/scala/riscv/PipelinedCore.scala b/riscv/src/main/scala/riscv/PipelinedCore.scala new file mode 100644 index 0000000..c45d6b3 --- /dev/null +++ b/riscv/src/main/scala/riscv/PipelinedCore.scala @@ -0,0 +1,214 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** A pipeline register: at each clock edge (when `enable`) it takes `next`; when `flush`ed it takes + * a bubble instead (`valid` false). It starts empty. + */ +object Stage { + def apply[T <: Data](next: Valid[T], flush: Bool = false.B, enable: Bool = true.B): Valid[T] = { + val r = RegInit(0.U.asTypeOf(chiselTypeOf(next))) + when(enable)(r := next) + when(flush)(r.valid := false.B) + r + } +} + +/** What IF hands to ID: the fetched instruction (0 if the fetch failed). */ +class IfId extends Bundle { + val pc = UInt(32.W) + val inst = UInt(32.W) + val fetchError = Bool() +} + +/** What ID hands to EX: the decoded instruction, its registers and immediate, and the reason it + * halts the core, if decoding found one. + */ +class IdEx extends Bundle { + val pc = UInt(32.W) + val inst = UInt(32.W) + val ctrl = new Control + val rs1Data = UInt(32.W) + val rs2Data = UInt(32.W) + val imm = UInt(32.W) + val cause = HaltCause() +} + +/** What EX hands to MEM: the ALU's result (a value, an address or a target), the value a store + * writes, the next pc, and the halt cause so far. + */ +class ExMem extends Bundle { + val pc = UInt(32.W) + val inst = UInt(32.W) + val ctrl = new Control + val result = UInt(32.W) + val storeData = UInt(32.W) + val nextPc = UInt(32.W) + val cause = HaltCause() +} + +/** A five-stage pipelined RV32I core: fetch (IF), decode and register read (ID), execute (EX), + * memory (MEM), write back (WB), one instruction in each. Jumps and branches are resolved in EX + * (fetch goes on at pc + 4 meanwhile, and the two instructions fetched after a jump or a taken + * branch are flushed). An instruction that halts the core flushes all younger ones when it is in + * MEM, the last stage that finds a halt cause, before they reach MEM or WB. It handles no data + * hazards: an instruction reads its registers in ID, and sees a result once its producer is in WB + * (the register file is written before it is read in a cycle), so an instruction that uses a + * result must come 3 instructions after the one that computes it (with 2 others, or nops, between). + * The memory must answer in the same cycle. + */ +class PipelinedCore(resetPc: Long = Ram.base) extends Core { + val stopped = RegInit(false.B) // a halting instruction has passed MEM: fetch no more + val halted = RegInit(false.B) + val flush = Module(new PipelineFlush) + def is(c: Control, k: Kind.Type): Bool = c.legal && c.kind === k + + // ---- IF + val pc = RegInit(resetPc.U(32.W)) + val fetching = !reset.asBool && !stopped + io.imem.req.valid := fetching + io.imem.req.bits.addr := pc + io.imem.req.bits.wdata := 0.U + io.imem.req.bits.wstrb := 0.U + val fetched = Wire(Valid(new IfId)) + fetched.valid := fetching && io.imem.resp.valid + fetched.bits.pc := pc + fetched.bits.fetchError := io.imem.resp.bits.error + fetched.bits.inst := Mux(io.imem.resp.bits.error, 0.U, io.imem.resp.bits.rdata) + val ifId = Stage(fetched, flush.io.flushIfId) + + // ---- ID + val decoder = Module(new Decoder) + decoder.io.inst := ifId.bits.inst + val dc = decoder.io.ctrl + val regs = Module(new RegFile) + regs.io.rs1 := ifId.bits.inst(19, 15) + regs.io.rs2 := ifId.bits.inst(24, 20) + regs.io.dbgAddr := io.dbg.addr + io.dbg.data := regs.io.dbgData + val immGen = Module(new ImmGen) + immGen.io.inst := ifId.bits.inst + immGen.io.format := dc.immFormat + val decoded = Wire(Valid(new IdEx)) + decoded.valid := ifId.valid + decoded.bits.pc := ifId.bits.pc + decoded.bits.inst := ifId.bits.inst + decoded.bits.ctrl := dc + // The register file is written in the first half of a cycle and read in the second (as in the + // classic five-stage pipeline): a register that WB writes in this cycle reads as its new value. + val wbRd = Wire(UInt(5.W)) + val wbValue = Wire(UInt(32.W)) + def read(index: UInt, data: UInt) = Mux(wbRd =/= 0.U && wbRd === index, wbValue, data) + decoded.bits.rs1Data := read(ifId.bits.inst(19, 15), regs.io.rs1Data) + decoded.bits.rs2Data := read(ifId.bits.inst(24, 20), regs.io.rs2Data) + decoded.bits.imm := immGen.io.imm + decoded.bits.cause := MuxCase( + HaltCause.Running, + Seq( + ifId.bits.fetchError -> HaltCause.BadAddress, + !dc.legal -> HaltCause.Illegal, + is(dc, Kind.Ecall) -> HaltCause.Ecall, + is(dc, Kind.Ebreak) -> HaltCause.Ebreak + ) + ) + val idEx = Stage(decoded, flush.io.flushIdEx) + + // ---- EX + val e = idEx.bits + val alu = Module(new Alu) + alu.io.op := e.ctrl.aluOp + alu.io.a := MuxLookup(e.ctrl.aSel, e.rs1Data)(Seq(ASel.Pc -> e.pc, ASel.Zero -> 0.U)) + alu.io.b := Mux(e.ctrl.bSel === BSel.Imm, e.imm, e.rs2Data) + val branchUnit = Module(new BranchUnit) + branchUnit.io.funct3 := e.inst(14, 12) + branchUnit.io.a := e.rs1Data + branchUnit.io.b := e.rs2Data + val jalr = is(e.ctrl, Kind.Jalr) + val jumps = is(e.ctrl, Kind.Jal) || jalr || (is(e.ctrl, Kind.Branch) && branchUnit.io.taken) + val target = Mux(jalr, alu.io.out(31, 1) ## 0.U(1.W), alu.io.out) + val badTarget = jumps && target(1, 0) =/= 0.U + val causeEx = Mux(e.cause === HaltCause.Running && badTarget, HaltCause.Misaligned, e.cause) + val redirect = idEx.valid && jumps && causeEx === HaltCause.Running + val executed = Wire(Valid(new ExMem)) + executed.valid := idEx.valid + executed.bits.pc := e.pc + executed.bits.inst := e.inst + executed.bits.ctrl := e.ctrl + executed.bits.result := alu.io.out + executed.bits.storeData := e.rs2Data + executed.bits.nextPc := Mux(jumps, target, e.pc + 4.U) + executed.bits.cause := causeEx + val exMem = Stage(executed, flush.io.flushExMem) + + // ---- MEM + val m = exMem.bits + val load = is(m.ctrl, Kind.Load) + val store = is(m.ctrl, Kind.Store) + val funct3 = m.inst(14, 12) + val size = funct3(1, 0) + val bytes = 1.U(3.W) << size + val offset = m.result(1, 0) + val shamt = offset ## 0.U(3.W) + val misaligned = (load || store) && (offset & (bytes - 1.U)(1, 0)) =/= 0.U + val access = exMem.valid && (load || store) && !misaligned && m.cause === HaltCause.Running + val strobe = ((1.U(5.W) << bytes) - 1.U)(3, 0) + val sizeMask = FillInterleaved(8, strobe) + io.dmem.req.valid := access + io.dmem.req.bits.addr := m.result(31, 2) ## 0.U(2.W) + io.dmem.req.bits.wdata := (m.storeData << shamt)(31, 0) + io.dmem.req.bits.wstrb := Mux(store, (strobe << offset)(3, 0), 0.U) + val extend = Module(new LoadExtend) + extend.io.funct3 := funct3 + extend.io.offset := offset + extend.io.rdata := io.dmem.resp.bits.rdata + val causeMem = MuxCase( + HaltCause.Running, + Seq( + (m.cause =/= HaltCause.Running) -> m.cause, + misaligned -> HaltCause.Misaligned, + (access && io.dmem.resp.bits.error) -> HaltCause.BadAddress + ) + ) + val halts = causeMem =/= HaltCause.Running + val linkPc = m.pc + 4.U + val link = is(m.ctrl, Kind.Jal) || is(m.ctrl, Kind.Jalr) // jal and jalr write pc + 4 + val rd = m.inst(11, 7) + val writesRd = (is(m.ctrl, Kind.Alu) || load || link) && !halts && rd =/= 0.U + val writeValue = Mux(load, extend.io.value, Mux(link, linkPc, m.result)) + val retiring = Wire(Valid(new RetireInfo)) + val r = retiring.bits + retiring.valid := exMem.valid + r.pc := m.pc + r.inst := m.inst + r.nextPc := Mux(halts, m.pc, m.nextPc) + r.rd := Mux(writesRd, rd, 0.U) + r.rdValue := Mux(writesRd, writeValue, 0.U) + r.mem.valid := access && !halts + r.mem.bits.addr := m.result + r.mem.bits.write := store + r.mem.bits.bytes := bytes + r.mem.bits.data := Mux(store, m.storeData, io.dmem.resp.bits.rdata >> shamt) & sizeMask + r.halt := causeMem + val haltInMem = exMem.valid && halts + when(haltInMem)(stopped := true.B) + val memWb = Stage(retiring) + + // ---- WB + wbRd := Mux(memWb.valid, memWb.bits.rd, 0.U) // rd is 0 if nothing is written + wbValue := memWb.bits.rdValue + regs.io.wen := wbRd =/= 0.U + regs.io.rd := wbRd + regs.io.wdata := wbValue + io.retire := memWb + when(memWb.valid && memWb.bits.halt =/= HaltCause.Running)(halted := true.B) + io.halted := halted + + // ---- the next pc, and the flushes + flush.io.redirect := redirect + flush.io.halt := haltInMem + when(redirect)(pc := target).elsewhen(fetched.valid)(pc := pc + 4.U) +} + +/** The pipelined core with its RAM, for tests and notebooks. */ +class PipelinedSystem extends CoreSystem(new PipelinedCore) diff --git a/riscv/src/main/scala/riscv/Programs.scala b/riscv/src/main/scala/riscv/Programs.scala new file mode 100644 index 0000000..9764c1b --- /dev/null +++ b/riscv/src/main/scala/riscv/Programs.scala @@ -0,0 +1,37 @@ +package riscv + +/** The `.S` programs of the course, in directories of riscv/ such as `programs/src`: from sbt, which + * runs in riscv/, or from a notebook, which runs in the repository's root (a directory is looked up + * in the current directory first, then in riscv/). + */ +object Programs { + + private def resolve(dir: String): os.Path = + Seq(os.pwd, os.pwd / "riscv") + .map(_ / os.RelPath(dir)) + .find(os.isDir) + .getOrElse(throw new IllegalArgumentException(s"no directory $dir, here or in riscv/")) + + private def files(dir: String, ext: String = "S"): Seq[os.Path] = + os.list(resolve(dir)).filter(_.ext == ext).sortBy(_.baseName) + + /** The names of the programs in `dir`, sorted, without their extension `ext` (given without the dot). */ + def names(dir: String, ext: String = "S"): Seq[String] = files(dir, ext).map(_.baseName) + + /** The source of program `name` of `dir` (or its file with extension `ext`, such as `hex`). */ + def source(dir: String, name: String, ext: String = "S"): String = os.read(resolve(dir) / s"$name.$ext") + + /** Each program of `dir`, by name, assembled (an error names the program that does not assemble). */ + def images(dir: String): Seq[(String, Seq[Long])] = files(dir).map { f => + try f.baseName -> Asm(os.read(f)) + catch { case e: IllegalArgumentException => throw new IllegalArgumentException(s"$f: ${e.getMessage}", e) } + } + + /** The programs a core is checked with, by name, assembled: those of the course (`programs/src`, + * but `hello`, which needs the UART of Module 5.8), a random program for each of `seeds` (named + * `RandomProgram(seed)`), and the official rv32ui tests. + */ + def corpus(seeds: Seq[Long]): Seq[(String, Seq[Long])] = + images("programs/src").filterNot(_._1 == "hello") ++ + seeds.map(s => s"RandomProgram($s)" -> Asm(RandomProgram(s))) ++ images("programs/riscv-tests/rv32ui") +} diff --git a/riscv/src/main/scala/riscv/RandomProgram.scala b/riscv/src/main/scala/riscv/RandomProgram.scala new file mode 100644 index 0000000..12ffb65 --- /dev/null +++ b/riscv/src/main/scala/riscv/RandomProgram.scala @@ -0,0 +1,65 @@ +package riscv + +import scala.util.Random + +/** Constrained random RV32I programs, in assembly, for comparing cores with the golden model + * ([[IsaSim]]). Every program ends with `ecall` and halts by construction: + * + * - branches and jumps only go forward, by at most a few slots, to the start of a slot of the + * program (a slot is one instruction, or a pair: `auipc s10` + `jalr`, so that `jalr` always + * uses the address its `auipc` just computed, or `addi` + a load that uses it as its base); + * - loads and stores use `s11` (never written) as the base of a word-aligned 1 KB data area, + * with offsets inside it that are multiples of the access size (some loads use a base of + * their own, set from `s11` just before, with a negative offset, and overwrite it); + * - no instruction that halts (`ebreak`, illegal words) and no CSR instruction (there are none). + * + * A failing program can be saved as it is (it is a `.S` file) and replayed as a regression test. + */ +object RandomProgram { + private val dataSize = 1024 + private val loads = Seq("lb", "lbu", "lh", "lhu", "lw") + // registers a random instruction may write: not s10 (jalr's base, written only as jalr's own + // link) and not s11 (the data base); x0 too, to check that writes to it are ignored + private val writable = (0 to 25) ++ (28 to 31) + + /** A program of `length` slots, then `ecall`. */ + def apply(seed: Long, length: Int = 200): String = { + val rnd = new Random(seed) + def pick[T](xs: Seq[T]): T = xs(rnd.nextInt(xs.size)) + def rd = s"x${pick(writable)}" + def rs = s"x${rnd.nextInt(32)}" + def imm12 = rnd.nextInt(4096) - 2048 + // an offset in the data area that suits the size of load or store `op` + def offset(op: String) = { val bytes = IsaSim.width(op); rnd.nextInt(dataSize / bytes) * bytes } + // slot n is labelled L; L is the final ecall + def forward(n: Int) = s"L${(n + 1 + rnd.nextInt(4)).min(length)}" + + val slots = (0 until length).map { n => + rnd.nextInt(12) match { + case 0 | 1 | 2 => + s"${pick(Seq("add", "sub", "sll", "slt", "sltu", "xor", "srl", "sra", "or", "and"))} $rd, $rs, $rs" + case 3 | 4 => s"${pick(Seq("addi", "slti", "sltiu", "xori", "ori", "andi"))} $rd, $rs, $imm12" + case 5 => s"${pick(Seq("slli", "srli", "srai"))} $rd, $rs, ${rnd.nextInt(32)}" + case 6 => s"${pick(Seq("lui", "auipc"))} $rd, ${rnd.nextInt(1 << 20)}" + case 7 if rnd.nextBoolean() => + // a base register of its own, in the middle of the data area (so the offset may be + // negative), which the load then overwrites + val (op, base) = (pick(loads), s"x${pick(writable.filter(_ != 0))}") + s"addi $base, s11, ${dataSize / 2}\n $op $base, ${offset(op) - dataSize / 2}($base)" + case 7 => val op = pick(loads); s"$op $rd, ${offset(op)}(s11)" + case 8 => val op = pick(Seq("sb", "sh", "sw")); s"$op $rs, ${offset(op)}(s11)" + case 9 => s"${pick(Seq("beq", "bne", "blt", "bge", "bltu", "bgeu"))} $rs, $rs, ${forward(n)}" + case 10 => s"jal $rd, ${forward(n)}" + case 11 if rnd.nextInt(4) == 0 => "fence" + case 11 => // an odd offset too: jalr clears bit 0 of the target; sometimes rd is the base + val link = if (rnd.nextInt(4) == 0) "s10" else rd + s"auipc s10, %pcrel_hi(${forward(n)})\n jalr $link, %pcrel_lo(L$n)+${rnd.nextInt(2)}(s10)" + } + } + // every register a program may read starts with a known value: a core's registers start unknown + val init = (1 to 31).filter(_ != Reg("s11")).map(r => s" li x$r, ${rnd.nextInt()}") // s11: see la + (Seq(s"# RandomProgram(seed = $seed, length = $length)", " la s11, data") ++ init ++ + slots.zipWithIndex.map { case (s, n) => s"L$n: $s" } ++ + Seq(s"L$length: ecall", " .data", " .align 2", s"data: .zero $dataSize")).mkString("", "\n", "\n") + } +} diff --git a/riscv/src/main/scala/riscv/RegFile.scala b/riscv/src/main/scala/riscv/RegFile.scala new file mode 100644 index 0000000..fc52281 --- /dev/null +++ b/riscv/src/main/scala/riscv/RegFile.scala @@ -0,0 +1,30 @@ +package riscv + +import chisel3._ + +/** The 32 integer registers (the one of Module 2.8): two combinational read ports, one write port + * (written at the clock edge), and a debug read port for tests. `x0` reads 0 and ignores writes. + * The other registers start with unknown values, as in hardware. + */ +class RegFile extends Module { + val io = IO(new Bundle { + val rs1 = Input(UInt(5.W)) + val rs2 = Input(UInt(5.W)) + val rs1Data = Output(UInt(32.W)) + val rs2Data = Output(UInt(32.W)) + val wen = Input(Bool()) + val rd = Input(UInt(5.W)) + val wdata = Input(UInt(32.W)) + val dbgAddr = Input(UInt(5.W)) + val dbgData = Output(UInt(32.W)) + }) + val regs = Mem(32, UInt(32.W)) + + def read(addr: UInt): UInt = Mux(addr === 0.U, 0.U, regs(addr)) + io.rs1Data := read(io.rs1) + io.rs2Data := read(io.rs2) + io.dbgData := read(io.dbgAddr) + when(io.wen && io.rd =/= 0.U) { + regs.write(io.rd, io.wdata) + } +} diff --git a/riscv/src/main/scala/riscv/SingleCycleCore.scala b/riscv/src/main/scala/riscv/SingleCycleCore.scala new file mode 100644 index 0000000..400a834 --- /dev/null +++ b/riscv/src/main/scala/riscv/SingleCycleCore.scala @@ -0,0 +1,151 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** Why a core halted (see DESIGN.md); `Running` while it has not. */ +object HaltCause extends ChiselEnum { + val Running, Ecall, Ebreak, Illegal, Misaligned, BadAddress = Value +} + +/** What a core reports for each retired instruction (the RVFI-style retire port), with the same + * meaning as the golden model's `Retire` record: `rd` is 0 if no register is written; `mem` is + * the access (byte address, size in bytes, the bytes read or written, zero-extended); an + * instruction that halts the core reports its cause, `nextPc = pc`, and nothing written. + */ +class RetireInfo extends Bundle { + val pc = UInt(32.W) + val inst = UInt(32.W) + val nextPc = UInt(32.W) + val rd = UInt(5.W) + val rdValue = UInt(32.W) + val mem = Valid(new Bundle { + val addr = UInt(32.W) + val write = Bool() + val bytes = UInt(3.W) + val data = UInt(32.W) + }) + val halt = HaltCause() +} + +/** A single-cycle RV32I core: each instruction is fetched, decoded, executed and retired in one + * clock cycle, through the instruction and data ports, which must answer in the same cycle (see + * `MemPort`: the core does not track requests). It starts at `resetPc`, and halts as DESIGN.md says. + * Its ports, `io` (memory ports, retire port, `halted`, register debug port), are `CoreIO`, which + * every core of the course has (System.scala). + */ +class SingleCycleCore(resetPc: Long = Ram.base) extends Core { + + val pc = RegInit(resetPc.U(32.W)) + val halted = RegInit(false.B) + // the core does nothing while reset is held (a testbench loads the program then) or once halted + val running = !halted && !reset.asBool + + // fetch + io.imem.req.valid := running + io.imem.req.bits.addr := pc + io.imem.req.bits.wdata := 0.U + io.imem.req.bits.wstrb := 0.U + val fetched = io.imem.resp.valid + val fetchError = io.imem.resp.bits.error + val inst = Mux(fetchError, 0.U, io.imem.resp.bits.rdata) + + // decode, and read the registers + val decoder = Module(new Decoder) + decoder.io.inst := inst + val c = decoder.io.ctrl + val funct3 = inst(14, 12) + val rd = inst(11, 7) + val regs = Module(new RegFile) + regs.io.rs1 := inst(19, 15) + regs.io.rs2 := inst(24, 20) + regs.io.dbgAddr := io.dbg.addr + io.dbg.data := regs.io.dbgData + val immGen = Module(new ImmGen) + immGen.io.inst := inst + immGen.io.format := c.immFormat + + // execute: the ALU computes the result, the memory address or the jump/branch target + val alu = Module(new Alu) + alu.io.op := c.aluOp + alu.io.a := MuxLookup(c.aSel, regs.io.rs1Data)(Seq(ASel.Pc -> pc, ASel.Zero -> 0.U)) + alu.io.b := Mux(c.bSel === BSel.Imm, immGen.io.imm, regs.io.rs2Data) + val result = alu.io.out + + def is(k: Kind.Type): Bool = c.legal && c.kind === k + val (load, store, branch, jal, jalr) = (is(Kind.Load), is(Kind.Store), is(Kind.Branch), is(Kind.Jal), is(Kind.Jalr)) + + // memory: a byte, half-word or word at `result`, which must be aligned to its size + val size = funct3(1, 0) // 0 byte, 1 half-word, 2 word + val bytes = 1.U(3.W) << size + val offset = result(1, 0) + val misaligned = (load || store) && (offset & (bytes - 1.U)(1, 0)) =/= 0.U + val access = (load || store) && !misaligned + val strobe = ((1.U(5.W) << bytes) - 1.U)(3, 0) // 0001, 0011 or 1111 + val sizeMask = FillInterleaved(8, strobe) // the same, one bit per bit + io.dmem.req.valid := running && fetched && access + io.dmem.req.bits.addr := result(31, 2) ## 0.U(2.W) + val shamt = offset ## 0.U(3.W) // the byte offset in bits + io.dmem.req.bits.wdata := (regs.io.rs2Data << shamt)(31, 0) + io.dmem.req.bits.wstrb := Mux(store, (strobe << offset)(3, 0), 0.U) + val extend = Module(new LoadExtend) + extend.io.funct3 := funct3 + extend.io.offset := offset + extend.io.rdata := io.dmem.resp.bits.rdata + + // the next pc + val branchUnit = Module(new BranchUnit) + branchUnit.io.funct3 := funct3 + branchUnit.io.a := regs.io.rs1Data + branchUnit.io.b := regs.io.rs2Data + val jumps = jal || jalr || (branch && branchUnit.io.taken) + val target = Mux(jalr, result(31, 1) ## 0.U(1.W), result) + val badTarget = jumps && target(1, 0) =/= 0.U + val pcPlus4 = pc + 4.U + val nextPc = Mux(jumps, target, pcPlus4) + + // why the core halts, if it does (the first that applies, as the golden model checks them) + val cause = MuxCase( + HaltCause.Running, + Seq( + fetchError -> HaltCause.BadAddress, + !c.legal -> HaltCause.Illegal, + is(Kind.Ecall) -> HaltCause.Ecall, + is(Kind.Ebreak) -> HaltCause.Ebreak, + (misaligned || badTarget) -> HaltCause.Misaligned, + (access && io.dmem.resp.bits.error) -> HaltCause.BadAddress + ) + ) + val halts = cause =/= HaltCause.Running + + // retire: once the instruction (and its data access, if any) has its answers + val retires = running && fetched && (!access || io.dmem.resp.valid) + val writesRd = (is(Kind.Alu) || load || jal || jalr) && !halts && rd =/= 0.U + val writeValue = Mux(load, extend.io.value, Mux(jal || jalr, pcPlus4, result)) + regs.io.wen := retires && writesRd + regs.io.rd := rd + regs.io.wdata := writeValue + when(retires) { + when(halts)(halted := true.B).otherwise(pc := nextPc) + } + io.halted := halted + + val r = io.retire.bits + io.retire.valid := retires + r.pc := pc + r.inst := inst + r.nextPc := Mux(halts, pc, nextPc) + r.rd := Mux(writesRd, rd, 0.U) + r.rdValue := Mux(writesRd, writeValue, 0.U) + r.mem.valid := access && !halts + r.mem.bits.addr := result + r.mem.bits.write := store + r.mem.bits.bytes := bytes + r.mem.bits.data := Mux(store, regs.io.rs2Data, io.dmem.resp.bits.rdata >> shamt) & sizeMask + r.halt := cause +} + +/** The single-cycle core with its RAM, for tests and notebooks: the testbench writes the program + * through `load` (with reset held), then lets the core run. + */ +class SingleCycleSystem extends CoreSystem(new SingleCycleCore) diff --git a/riscv/src/main/scala/riscv/Soc.scala b/riscv/src/main/scala/riscv/Soc.scala new file mode 100644 index 0000000..c69ec11 --- /dev/null +++ b/riscv/src/main/scala/riscv/Soc.scala @@ -0,0 +1,62 @@ +package riscv + +import chisel3._ +import chisel3.simulator.PeekPokeAPI._ + +/** A small system on a chip: the forwarding core, whose data port goes through a `Bus` to the RAM + * and a `Uart`; instructions come straight from the RAM's instruction port (which answers in the + * same cycle, as `ForwardingCore` needs). `txd` is the UART's serial output. `ramWords` is the size + * of the RAM (a board has less memory than the simulations). + */ +class SocSystem(val divider: Int = 4, ramWords: Int = Ram.bytes / 4) extends RiscvSystem { + val txd = IO(Output(Bool())) + val core = Module(new ForwardingCore) + val ram = Module(new Ram(ramWords)) + val uart = Module(new Uart(divider)) + val memory = Region(Ram.base, 4L * ramWords) + val bus = Module(new Bus(Seq(memory, Region(Uart.base, Uart.bytes)))) + ram.io.imem <> core.io.imem + bus.io.master <> core.io.dmem + ram.io.dmem <> bus.io.devices(0) + uart.io.port <> bus.io.devices(1) + ram.io.load := io.load + io.retire := core.io.retire + io.halted := core.io.halted + io.dbg <> core.io.dbg + txd := uart.io.txd + + override def model(image: Seq[Long]): IsaSim = new IsaSim(image, size = 4 * ramWords, devices = Seq(new UartModel)) +} + +object Soc { + + /** Runs the loaded program until it halts and the UART has sent everything; returns what the UART + * printed (decoded from `txd`). Fails, with what it printed so far, if that takes over `maxCycles`. + */ + def run(c: SocSystem, maxCycles: Int = 200000): String = + listen(c.clock, c.txd, c.io.halted.peek().litToBoolean, c.divider, maxCycles) + + /** As `run`, for any design with a UART line `txd` (`divider` cycles per bit) and a way to tell + * that its program has `halted`: the cycles go on until it has, and the line has been idle for a + * whole frame. Fails if that has not happened within `maxCycles` cycles. + */ + def listen(clock: Clock, txd: Bool, halted: => Boolean, divider: Int, maxCycles: Int = 200000): String = { + val receiver = new UartReceiver(divider) + val out = new StringBuilder + var cycles = 0 + var idle = 0 // cycles since the core halted with the line idle + val frame = 12 * divider + while (idle < frame && cycles < maxCycles) { + val line = txd.peek().litToBoolean + out ++= receiver.sample(line) + if (halted && line) idle += 1 else idle = 0 + clock.step() + cycles += 1 + } + if (idle < frame) { + val why = if (halted) "the UART is still sending" else "no halt" + throw new IllegalStateException(s"not finished within $maxCycles cycles ($why); printed so far: $out") + } + out.toString + } +} diff --git a/riscv/src/main/scala/riscv/SwitchDecoder.scala b/riscv/src/main/scala/riscv/SwitchDecoder.scala new file mode 100644 index 0000000..5c565b5 --- /dev/null +++ b/riscv/src/main/scala/riscv/SwitchDecoder.scala @@ -0,0 +1,55 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** The decoder written by hand, with `switch` on the opcode, as a comparison for the table-driven + * [[Decoder]]: Module 5.3 checks that the two agree (on random instructions, in the fields that + * matter for each), and Module 5.10 compares their sizes after synthesis. + */ +class SwitchDecoder extends Module { + val io = IO(new Bundle { + val inst = Input(UInt(32.W)) + val ctrl = Output(new Control) + }) + val inst = io.inst + val (opcode, f3, f7) = (inst(6, 0), inst(14, 12), inst(31, 25)) + val c = io.ctrl + c.legal := false.B + c.kind := Kind.Alu + c.aluOp := AluOp.Add + c.immFormat := ImmFormat.I + c.aSel := ASel.Rs1 + c.bSel := BSel.Imm + // the ALU operation that funct3 selects (funct7 bit 5 turns add into sub and srl into sra) + val byF3 = VecInit(AluOp.Add, AluOp.Sll, AluOp.Slt, AluOp.Sltu, AluOp.Xor, AluOp.Srl, AluOp.Or, AluOp.And)(f3) + switch(opcode) { + is("b0110111".U) { c.legal := true.B; c.immFormat := ImmFormat.U; c.aSel := ASel.Zero } // lui + is("b0010111".U) { c.legal := true.B; c.immFormat := ImmFormat.U; c.aSel := ASel.Pc } // auipc + is("b1101111".U) { c.legal := true.B; c.kind := Kind.Jal; c.immFormat := ImmFormat.J; c.aSel := ASel.Pc } + is("b1100111".U) { c.legal := f3 === 0.U; c.kind := Kind.Jalr } + is("b1100011".U) { + c.legal := f3 =/= 2.U && f3 =/= 3.U + c.kind := Kind.Branch + c.immFormat := ImmFormat.B + c.aSel := ASel.Pc + } + is("b0000011".U) { c.legal := f3 =/= 3.U && f3 < 6.U; c.kind := Kind.Load } + is("b0100011".U) { c.legal := f3 < 3.U; c.kind := Kind.Store; c.immFormat := ImmFormat.S } + is("b0010011".U) { // addi ... srai + val shift = f3 === 1.U || f3 === 5.U + c.legal := !shift || f7 === 0.U || (f3 === 5.U && f7 === "b0100000".U) + c.aluOp := Mux(f3 === 5.U && f7(5), AluOp.Sra, byF3) + } + is("b0110011".U) { // add ... and + c.legal := f7 === 0.U || (f7 === "b0100000".U && (f3 === 0.U || f3 === 5.U)) + c.aluOp := Mux(f7(5), Mux(f3 === 0.U, AluOp.Sub, AluOp.Sra), byF3) + c.bSel := BSel.Rs2 + } + is("b0001111".U) { c.legal := f3 === 0.U; c.kind := Kind.Fence } + is("b1110011".U) { + c.legal := inst === "h00000073".U || inst === "h00100073".U + c.kind := Mux(inst(20), Kind.Ebreak, Kind.Ecall) + } + } +} diff --git a/riscv/src/main/scala/riscv/Synth.scala b/riscv/src/main/scala/riscv/Synth.scala new file mode 100644 index 0000000..a710e9d --- /dev/null +++ b/riscv/src/main/scala/riscv/Synth.scala @@ -0,0 +1,95 @@ +package riscv + +import chisel3.RawModule +import org.json4s.{JInt, JObject} +import org.json4s.native.JsonMethods + +/** The cells of a design after synthesis for one FPGA family, by type (e.g. `SB_LUT4` -> 103). */ +case class Cells(family: String, byType: Map[String, Int]) { + private def count(p: String => Boolean) = byType.collect { case (t, n) if p(t) => n }.sum + + /** Look-up tables used as logic: each computes any function of 4 inputs (ECP5's `PFUMX` and + * `L6MUX21` combine LUTs into wider functions, and are not counted). + */ + def luts: Int = count(t => t == "SB_LUT4" || t == "LUT4") + + /** Flip-flops: the bits of the registers. */ + def flipFlops: Int = count(t => t.startsWith("SB_DFF") || t == "TRELLIS_FF") + + /** Block RAMs: 4 Kbit (iCE40 `SB_RAM40_4K`) or 18 Kbit (ECP5 `DP16KD`), read a cycle after the + * address. + */ + def blockRams: Int = count(t => t.startsWith("SB_RAM") || t == "DP16KD") + + /** LUT RAMs (ECP5): pairs of LUTs used as a 16-word, 4-bit RAM, read combinationally. */ + def lutRams: Int = count(_ == "TRELLIS_DPR16X4") + + /** Carry cells, for fast adders and comparators. */ + def carries: Int = count(t => t == "SB_CARRY" || t == "CCU2C") +} + +/** Synthesis with Yosys, and a lint with Verilator, for Module 5.10. */ +object Synth { + + /** The FPGA families Yosys synthesizes for here: Lattice iCE40 and ECP5, which the open + * place-and-route tool nextpnr supports. + */ + val families: Seq[String] = Seq("ice40", "ecp5") + + /** Synthesizes `gen` for each of `families` and counts its cells: one SystemVerilog, read once by + * one Yosys run that synthesizes a fresh copy of the design for each family. + */ + def cells(gen: => RawModule, families: Seq[String]): Map[String, Cells] = { + require(families.forall(this.families.contains), s"not among ${this.families.mkString(", ")}: $families") + val steps = families.map { f => + s"design -load rtl; synth_$f; delete t:$$scopeinfo; tee -q -o $f.json stat -json" + } + val script = ("read_verilog -sv top.sv; hierarchy -auto-top; design -save rtl" +: steps).mkString("; ") + val result = Yosys.run(script, Map("top.sv" -> Yosys.verilog(gen)), families.map(f => s"$f.json")) + families.map { f => + val json = + result.files.getOrElse(s"$f.json", sys.error(s"yosys did not synthesize:\n${result.log.takeRight(3000)}")) + val byType = JsonMethods.parse(json) \ "design" \ "num_cells_by_type" match { + case JObject(fields) => fields.collect { case (t, JInt(n)) => t -> n.toInt } + case _ => sys.error(s"no cell counts in Yosys's statistics:\n$json") + } + f -> Cells(f, byType.toMap) + }.toMap + } + + /** Synthesizes `gen` for one `family` and counts its cells. */ + def cells(gen: => RawModule, family: String): Cells = cells(gen, Seq(family))(family) + + /** The warnings of `verilator --lint-only -Wall` on the SystemVerilog of `gen` (but the one that + * the file is not named after the module); an error if Verilator fails otherwise. + */ + def lint(gen: => RawModule): Seq[String] = { + val command = Seq("verilator", "--lint-only", "-Wall", "-Wno-fatal", "-Wno-DECLFILENAME", "top.sv") + val result = Yosys.runIn(command, Map("top.sv" -> Yosys.verilog(gen))) + if (result.exitCode != 0) sys.error(s"verilator failed:\n${result.log}") + result.log.linesIterator.filter(_.startsWith("%Warning")).toSeq + } + + /** The designs of Module 5 that `SynthReport` synthesizes. */ + val all: Seq[(String, () => RawModule)] = Seq( + "Decoder (table)" -> (() => new Decoder), + "SwitchDecoder (hand)" -> (() => new SwitchDecoder), + "SingleCycleCore" -> (() => new SingleCycleCore), + "PipelinedCore" -> (() => new PipelinedCore), + "ForwardingCore" -> (() => new ForwardingCore) + ) + + /** A table of the cells of `designs` for each family. */ + def report(designs: Seq[(String, () => RawModule)] = all): String = { + val row = "%-22s %-6s %6s %6s %6s %6s %5s" + val rows = + for ((name, gen) <- designs; (family, c) <- { val m = cells(gen(), families); families.map(f => f -> m(f)) }) + yield row.format(name, family, c.luts, c.flipFlops, c.carries, c.lutRams, c.blockRams) + (row.format("design", "family", "LUTs", "FFs", "carry", "LUTRAM", "BRAM") +: rows).mkString("\n") + } +} + +/** Prints the synthesis report of Module 5: `cd riscv && sbt "runMain riscv.SynthReport"`. */ +object SynthReport extends App { + println(Synth.report()) +} diff --git a/riscv/src/main/scala/riscv/System.scala b/riscv/src/main/scala/riscv/System.scala new file mode 100644 index 0000000..8c1f8ff --- /dev/null +++ b/riscv/src/main/scala/riscv/System.scala @@ -0,0 +1,56 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** What a testbench sees of a core with its RAM: the load port (write the program while reset is + * held), the retire port (at most one instruction per cycle, in program order; the instruction + * that halts the core retires too), whether the core has halted, and the debug port of its + * registers. Reset clears neither the RAM nor the registers. + */ +class SystemIO extends Bundle { + val load = Input(Valid(new LoadPort)) + val retire = Output(Valid(new RetireInfo)) + val halted = Output(Bool()) + val dbg = new DebugPort +} + +/** A core with its RAM, as `CoSim` drives it: each core of the course has one (the single-cycle + * core's is [[SingleCycleSystem]]). + */ +abstract class RiscvSystem extends Module { + val io = IO(new SystemIO) + + /** The golden model of this system for a program (`CoSim.compare` uses it): the RAM, and the + * system's devices if it has any. + */ + def model(image: Seq[Long]): IsaSim = new IsaSim(image) +} + +/** The ports of a core: instruction and data memory, the retire port, whether it has halted, and + * the debug port of its registers. + */ +class CoreIO extends Bundle { + val imem = new MemPort + val dmem = new MemPort + val retire = Output(Valid(new RetireInfo)) + val halted = Output(Bool()) + val dbg = new DebugPort +} + +/** A core of the course (single-cycle, pipelined): it starts at its reset pc (`Ram.base` by default). */ +abstract class Core extends Module { + val io = IO(new CoreIO) +} + +/** A core with the RAM, for tests and notebooks. */ +class CoreSystem(gen: => Core) extends RiscvSystem { + val core = Module(gen) + val ram = Module(new Ram) + ram.io.imem <> core.io.imem + ram.io.dmem <> core.io.dmem + ram.io.load := io.load + io.retire := core.io.retire + io.halted := core.io.halted + io.dbg <> core.io.dbg +} diff --git a/riscv/src/main/scala/riscv/Uart.scala b/riscv/src/main/scala/riscv/Uart.scala new file mode 100644 index 0000000..5601b5f --- /dev/null +++ b/riscv/src/main/scala/riscv/Uart.scala @@ -0,0 +1,73 @@ +package riscv + +import chisel3._ + +object Uart { + + /** Where the UART is on the bus: its data register, then its status register at +4. */ + val base: Long = 0x10000000L + val bytes: Int = 8 // the two registers +} + +/** A UART on the bus: writing a byte to its data register (`Uart.base`) sends it on `txd`; while + * the transmitter is still sending the previous byte, the write is not answered, so the core waits + * (backpressure: a program needs no status loop). Its status register (`Uart.base + 4`) reads 1 + * while the transmitter is busy (the golden model's `UartModel` sends at once, so its status reads + * 0: a program that reads the status retires different values on a core). Writes to the status + * register, and to the other bytes of the data register, do nothing. + */ +class Uart(divider: Int) extends Module { + val io = IO(new Bundle { + val port = Flipped(new MemPort) + val txd = Output(Bool()) + }) + val tx = Module(new UartTx(divider)) + val req = io.port.req + val data = req.bits.addr(2) === 0.U + val write = req.valid && req.bits.wstrb.orR + val toData = write && data && req.bits.wstrb(0) // a byte for the data register (byte lane 0) + val sends = toData && !tx.io.busy + req.ready := true.B + io.port.resp.valid := req.valid && !(toData && tx.io.busy) + io.port.resp.bits.rdata := Mux(data, 0.U, tx.io.busy.asUInt) + io.port.resp.bits.error := false.B + tx.io.send.valid := sends + tx.io.send.bits := req.bits.wdata(7, 0) // the byte at the register's address (byte lane 0) + io.txd := tx.io.txd +} + +/** A UART receiver in software, for testbenches: fed the `txd` line once per clock cycle, it + * returns each byte when its stop bit has been sent. A frame whose stop bit is 0 counts as a + * framing error (and no byte); the receiver then waits for the line to go back to 1. + */ +class UartReceiver(divider: Int) { + private var countdown = -1 // cycles to the middle of the next bit; -1: idle; -2: after an error + private var bit = 0 // 1 to 8 the data bits, 9 the stop bit + private var byte = 0 + var framingErrors = 0 + + def sample(txd: Boolean): Option[Char] = countdown match { + case -2 => if (txd) countdown = -1; None // wait for the line to be idle again + case -1 => + // a start bit began: the middle of data bit 0 is a bit and a half later + if (!txd) { countdown = divider + divider / 2 - 1; bit = 0; byte = 0 } + None + case n if n > 0 => countdown -= 1; None + case _ => + countdown = divider - 1 + bit += 1 + if (bit <= 8) { if (txd) byte |= 1 << (bit - 1); None } + else if (txd) { countdown = -1; Some(byte.toChar) } // the stop bit + else { framingErrors += 1; countdown = -2; None } + } +} + +/** The golden model of the UART: a byte written to its data register (`base`) is + * sent at once, and its status register (`base + 4`) reads 0 (never busy). + */ +class UartModel(val base: Long = Uart.base) extends Device { + val size = Uart.bytes.toLong + val output = new StringBuilder + def read(addr: Long, bytes: Int): Long = 0 + def write(addr: Long, bytes: Int, data: Long): Unit = if (addr == base) output += (data & 0xff).toChar +} diff --git a/riscv/src/main/scala/riscv/UartTx.scala b/riscv/src/main/scala/riscv/UartTx.scala new file mode 100644 index 0000000..ebf18c8 --- /dev/null +++ b/riscv/src/main/scala/riscv/UartTx.scala @@ -0,0 +1,35 @@ +package riscv + +import chisel3._ +import chisel3.util._ + +/** A UART transmitter: sends a byte on `txd` as a frame of 10 bits, each `divider` clock cycles + * long: a start bit (0), the 8 data bits, least significant first, and a stop bit (1). Between + * frames `txd` is 1. It takes a byte (`send`) only when it is not `busy`. + */ +class UartTx(divider: Int) extends Module { + require(divider >= 1) + val io = IO(new Bundle { + val send = Input(Valid(UInt(8.W))) + val busy = Output(Bool()) + val txd = Output(Bool()) + }) + + val frame = RegInit(1.U(10.W)) // the bits still to send, the next one in bit 0 + val left = RegInit(0.U(4.W)) // how many + val count = RegInit(0.U(log2Ceil(divider + 1).W)) // cycles left of the current bit + io.busy := left =/= 0.U + io.txd := Mux(io.busy, frame(0), true.B) + + when(!io.busy && io.send.valid) { + frame := ??? // Exercise: the stop bit, the data, and the start bit (sent first) + left := 10.U + count := (divider - 1).U + }.elsewhen(io.busy) { + when(count === 0.U) { + frame := ??? // Exercise: the next bit to bit 0 + left := left - 1.U + count := (divider - 1).U + }.otherwise(count := count - 1.U) + } +} diff --git a/riscv/src/main/scala/riscv/Vcd.scala b/riscv/src/main/scala/riscv/Vcd.scala new file mode 100644 index 0000000..c44a29d --- /dev/null +++ b/riscv/src/main/scala/riscv/Vcd.scala @@ -0,0 +1,72 @@ +package riscv + +import scala.collection.mutable + +/** A waveform read from a VCD (Value Change Dump) file, as `simulate(..., waves = ...)` writes: + * every signal's value over time. Signals are named by their path, e.g. + * `TOP.svsimTestbench.dut.core.f.io_value`. + */ +class Vcd(lines: Iterator[String]) { + def this(text: String) = this(text.linesIterator) + + private val ids = mutable.LinkedHashMap[String, String]() // signal path -> VCD identifier + private val changes = mutable.Map[String, mutable.ArrayBuffer[(Long, BigInt)]]() + + locally { + val scope = mutable.ArrayBuffer[String]() + var time = 0L + def parse(bits: String): BigInt = if (bits.forall("01".contains(_))) BigInt(bits, 2) else -1 // x or z: -1 + def change(id: String, bits: String) = changes.getOrElseUpdate(id, mutable.ArrayBuffer()) += time -> parse(bits) + for (tokens <- lines.map(_.trim.split("\\s+").toList).filter(_.head.nonEmpty)) tokens match { + case "$scope" :: _ :: name :: _ => scope += name + case "$upscope" :: _ => scope.remove(scope.size - 1) + case "$var" :: _ :: _ :: id :: name :: _ => ids((scope :+ name).mkString(".")) = id + case t :: Nil if t.startsWith("#") => time = t.drop(1).toLong + case v :: id :: Nil if v.startsWith("b") => change(id, v.drop(1)) + case v :: Nil if "01xzXZ".contains(v.head) && v.size > 1 => change(v.drop(1), v.take(1)) + case _ => // other declarations, $dumpvars, $end + } + } + + /** The paths of all signals, in the order the file declares them. */ + def signals: Seq[String] = ids.keys.toSeq + + /** The one signal whose path is `suffix` or ends with `.suffix` (e.g. `core.f.io_value`). */ + def find(suffix: String): String = signals.filter(s => s == suffix || s.endsWith("." + suffix)) match { + case Seq(one) => one + case none if none.isEmpty => throw new NoSuchElementException(s"no signal ends with $suffix") + case many => throw new IllegalArgumentException(s"$suffix is ambiguous: ${many.mkString(", ")}") + } + + private def changesOf(signal: String) = + changes.getOrElse(ids(if (ids.contains(signal)) signal else find(signal)), Nil) + + /** `signal` (a path, or the end of one) as a function of time: its value at a time (-1 for x or + * z, before its first change, or for a real-valued signal, which this reader does not decode). + * The signal is looked up once, and each value is found by binary search. + */ + def apply(signal: String): Long => BigInt = { + val c = changesOf(signal) // in time order, as the file lists them + time => { + // the last change at or before `time`: c(lo - 1) once lo and hi meet + var lo = 0 + var hi = c.size + while (lo < hi) { + val mid = (lo + hi) / 2 + if (c(mid)._1 <= time) lo = mid + 1 else hi = mid + } + if (lo == 0) BigInt(-1) else c(lo - 1)._2 + } + } + + /** The times at which `clock` rises: one per cycle. */ + def risingEdges(clock: String): Seq[Long] = + changesOf(clock).toSeq.sliding(2).collect { case Seq((_, a), (t, b)) if a == 0 && b == 1 => t }.toSeq +} + +object Vcd { + + /** Reads the file line by line: a long simulation's dump need not fit in memory as one string. */ + def read(path: os.Path): Vcd = + scala.util.Using.resource(scala.io.Source.fromFile(path.toIO))(s => new Vcd(s.getLines())) +} diff --git a/riscv/src/main/scala/riscv/Yosys.scala b/riscv/src/main/scala/riscv/Yosys.scala new file mode 100644 index 0000000..d5ddf75 --- /dev/null +++ b/riscv/src/main/scala/riscv/Yosys.scala @@ -0,0 +1,62 @@ +package riscv + +import chisel3.RawModule +import _root_.circt.stage.ChiselStage + +/** Running Yosys from Scala: `yosys`, or `yowasp-yosys` (YoWASP's build, which the bootcamp image + * has), on the PATH. + */ +object Yosys { + + /** The Yosys command on the PATH, if there is one. */ + lazy val command: Option[String] = { + val path = sys.env.getOrElse("PATH", "").split(java.io.File.pathSeparator) + Seq("yosys", "yowasp-yosys").find(cmd => path.exists(d => new java.io.File(d, cmd).canExecute)) + } + + /** Whether Yosys can be run. */ + def available: Boolean = command.isDefined + + /** The SystemVerilog of `gen`, as Yosys's reader takes it: without layers (assertions), random + * initial values, packed arrays, or variables declared inside `always` blocks. + */ + def verilog(gen: => RawModule): String = ChiselStage.emitSystemVerilog( + gen, + firtoolOpts = Array( + "-disable-all-randomization", + "-strip-debug-info", + "-default-layer-specialization=disable", + "--lowering-options=disallowLocalVariables,disallowPackedArrays" + ) + ) + + /** What a tool printed (its output and errors), its exit code, and the files it wrote. */ + case class Result(log: String, exitCode: Int, files: Map[String, String]) + + /** Runs `command` in a temporary directory that holds `files` (name -> contents), and returns + * what it printed and the files named in `outputs` that it wrote. The directory is removed. + */ + def runIn(command: Seq[String], files: Map[String, String], outputs: Seq[String] = Nil): Result = { + val dir = os.temp.dir(prefix = "tool", deleteOnExit = false) + try { + for ((name, text) <- files) os.write(dir / name, text) + val out = os + .proc(command) + .call( + cwd = dir, + check = false, + mergeErrIntoOut = true, + timeout = 15 * 60 * 1000 + ) // Yosys's first run compiles it + Result( + out.out.text(), + out.exitCode, + outputs.filter(o => os.exists(dir / o)).map(o => o -> os.read(dir / o)).toMap + ) + } finally os.remove.all(dir) + } + + /** Runs the Yosys `script` on `files` (see `runIn`). */ + def run(script: String, files: Map[String, String], outputs: Seq[String] = Nil): Result = + runIn(Seq(command.getOrElse(sys.error("Yosys is not installed")), "-p", script), files, outputs) +} diff --git a/riscv/src/test/scala/riscv/AluSpec.scala b/riscv/src/test/scala/riscv/AluSpec.scala new file mode 100644 index 0000000..4aab0cb --- /dev/null +++ b/riscv/src/test/scala/riscv/AluSpec.scala @@ -0,0 +1,30 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +/** Checks the ALU against the golden model's ALU (IsaSim.alu) on random operands (a fixed seed, + * so failures repeat). + */ +class AluSpec extends AnyFlatSpec with ChiselSim { + def model(op: AluOp.Type, a: Int, b: Int): Int = IsaSim.alu(AluOp.mnemonic(op), a, b) + + private def unsigned(x: Int) = BigInt(Integer.toUnsignedLong(x)) + + "Alu" should "match the Scala model for every operation" in { + simulate(new Alu) { c => + val rnd = new scala.util.Random(1) + // random values, and the corner cases random values rarely hit + val corners = Seq(0, 1, -1, Int.MaxValue, Int.MinValue) + def operand() = if (rnd.nextInt(4) == 0) corners(rnd.nextInt(corners.size)) else rnd.nextInt() + for (op <- AluOp.all; _ <- 0 until 200) { + val (a, b) = (operand(), operand()) + c.io.op.poke(op) + c.io.a.poke(unsigned(a).U) + c.io.b.poke(unsigned(b).U) + c.io.out.expect(unsigned(model(op, a, b)).U, s"$op($a, $b)") + } + } + } +} diff --git a/riscv/src/test/scala/riscv/AsmSpec.scala b/riscv/src/test/scala/riscv/AsmSpec.scala new file mode 100644 index 0000000..43a5656 --- /dev/null +++ b/riscv/src/test/scala/riscv/AsmSpec.scala @@ -0,0 +1,350 @@ +package riscv + +import org.scalatest.flatspec.AnyFlatSpec + +import scala.util.Random + +/** Checks the software encoder, decoder and assembler against the hardware patterns of Isa.scala and + * against GNU as (riscv-none-elf-as 2.44 -march=rv32i -mno-relax, which produced the expected words + * below and the committed programs/hex files). + */ +class AsmSpec extends AnyFlatSpec { + import Format._ + + val rnd = new Random(1) + + /** A random instruction `name` whose fields are all in range. */ + def random(name: String): Inst = { + def reg = rnd.nextInt(32) + def even(bits: Int) = (rnd.nextInt(1 << bits) - (1 << (bits - 1))) & ~1 + def set = 1 + rnd.nextInt(15) // a nonempty subset of iorw + name match { + case "ecall" | "ebreak" => Inst(name) + case "fence" => Inst(name, imm = set << 4 | set) // what `fence pred, succ` can say + case _ if Rv32i.isShiftImm(name) => Inst(name, reg, reg, imm = rnd.nextInt(32)) + case _ => + Rv32i.encodings(name).format match { + case R => Inst(name, reg, reg, reg) + case I => Inst(name, reg, reg, imm = rnd.nextInt(4096) - 2048) + case S => Inst(name, rs1 = reg, rs2 = reg, imm = rnd.nextInt(4096) - 2048) + case B => Inst(name, rs1 = reg, rs2 = reg, imm = even(13)) + case U => Inst(name, reg, imm = rnd.nextInt() & 0xfffff000) + case J => Inst(name, reg, imm = even(21)) + } + } + } + + /** `i` in assembly (branch and jump targets as offsets, which Asm reads as such). */ + def text(i: Inst): String = { + def x(n: Int) = s"x$n" + def iorw(bits: Int) = "iorw".zipWithIndex.collect { case (c, k) if (bits & (8 >> k)) != 0 => c }.mkString + i.name match { + case "ecall" | "ebreak" => i.name + case "fence" => s"fence ${iorw(i.imm >> 4)}, ${iorw(i.imm & 0xf)}" + case n if Rv32i.isLoad(n) || n == "jalr" => s"$n ${x(i.rd)}, ${i.imm}(${x(i.rs1)})" + case n => + Rv32i.encodings(n).format match { + case R => s"$n ${x(i.rd)}, ${x(i.rs1)}, ${x(i.rs2)}" + case I => s"$n ${x(i.rd)}, ${x(i.rs1)}, ${i.imm}" + case S => s"$n ${x(i.rs2)}, ${i.imm}(${x(i.rs1)})" + case B => s"$n ${x(i.rs1)}, ${x(i.rs2)}, ${i.imm}" + case U => s"$n ${x(i.rd)}, ${i.imm >>> 12}" + case J => s"$n ${x(i.rd)}, ${i.imm}" + } + } + } + + "Rv32i.encodings" should "have the 40 instructions of Instructions.all" in { + assert(Rv32i.encodings.keySet == Instructions.all.map(_._1.toLowerCase).toSet) + } + + "Every RV32I instruction" should "round-trip through the assembler, the BitPats and the decoder" in { + for ((upper, pattern) <- Instructions.all; _ <- 1 to 100) { + val inst = random(upper.toLowerCase) + val word = Rv32i.encode(inst) + assert(word >= 0 && word < (1L << 32), inst) + assert(Asm(text(inst), base = 0) == Seq(word), text(inst)) + assert(Instructions.matching(word) == Seq(upper), f"$inst -> 0x$word%08x") + assert(Rv32i.decode(word) == Some(inst), f"0x$word%08x") + } + } + + "Rv32i.decode" should "reject words that are not RV32I" in { + val notRv32i = Seq( + 0x00000000L, // all zeros: an illegal instruction by design + 0xffffffffL, + 0x0000000bL, // custom-0 opcode + 0x30200073L, // mret (privileged) + 0x34011073L, // csrrw (Zicsr) + 0x00000033L | (1L << 25), // mul (M extension) + 0x00007003L, // load with funct3 = 7 + 0x40001013L, // slli with funct7 = 0x20 + 0x00200073L // SYSTEM opcode, funct3 = 0, but neither ECALL nor EBREAK + ) + for (word <- notRv32i) assert(Rv32i.decode(word) == None, f"0x$word%08x") + } + + "Rv32i.encode" should "reject fields out of range" in { + val bad = Seq( + Inst("addi", imm = 2048), + Inst("addi", imm = -2049), + Inst("slli", imm = 32), + Inst("srai", imm = -1), + Inst("beq", imm = 3), + Inst("beq", imm = 4096), + Inst("beq", imm = -4098), + Inst("jal", imm = 1 << 20), + Inst("jal", imm = -(1 << 20) - 2), + Inst("lui", imm = 1), + Inst("add", rd = 32), + Inst("ecall", rd = 1) + ) + for (inst <- bad) assertThrows[IllegalArgumentException](Rv32i.encode(inst)) + } + + "Asm" should "assemble instructions like GNU as" in { + val source = """ + back: lw a0, -4(sp) + sw a1, 8(s0) + lbu t0, 0(a0) + lh t1, -2048(a1) + sb t2, 2047(a2) + jalr ra, 0(t1) + ret + jal fn + lui a0, 0x12345 + auipc t0, 1 + srai a0, a0, 31 + slli a1, a1, 1 + sltiu a2, a3, -1 + xori a4, a5, 0x7ff + bltu a0, a1, back + bgeu x31, zero, fn + sra s11, t6, fp + fence + ebreak + fn: ecall + """ + val expected = Seq(0xffc12503L, 0x00b42423L, 0x00054283L, 0x80059303L, 0x7e760fa3L, 0x000300e7L, 0x00008067L, + 0x030000efL, 0x12345537L, 0x00001297L, 0x41f55513L, 0x00159593L, 0xfff6b613L, 0x7ff7c713L, 0xfcb564e3L, + 0x000ff863L, 0x408fddb3L, 0x0ff0000fL, 0x00100073L, 0x00000073L) + assert(Asm(source, base = 0) == expected) + } + + it should "assemble directives, sections and pseudo-instructions like GNU as" in { + val source = """ + .equ N, 10 + .globl _start + .text + _start: + li a0, 0x12345678 + li a1, -1 + li a2, 0x800 + li a3, 0x7ffff800 + li a4, 0x80000000 + li a5, N + li a6, 0x1000 + la s0, table + lw t0, table + sw t0, value, t1 + lbu t2, msg + call fn + tail fn + not a0, a1 + neg a0, a1 + seqz a0, a1 + snez a0, a1 + sltz a0, a1 + sgtz a0, a1 + 1: blez a0, 1b + bgez a0, 1f + bltz a0, 1b + 1: bgtz a0, 1b + bgt a0, a1, fn + ble a0, a1, fn + bgtu a0, a1, fn + bleu a0, a1, fn + jr t0 + jalr t0 + jalr ra, t0, 4 + lw a0, (sp) + fence rw, w + fence i, o + lui a0, %hi(table) + addi a0, a0, %lo(table) + 2: auipc a1, %pcrel_hi(msg) + addi a1, a1, %pcrel_lo(2b) + .align 2 + fn: ret + .data + table: .word 1, -2, fn, 'A' + value: .half 0x1234, -1 + msg: .string "hi\n" + .byte 7 + .align 2 + .ascii "ab" + .zero 3 + end: .word end - table + """ + val expected = Seq(0x12345537L, 0x67850513L, 0xfff00593L, 0x00001637L, 0x80060613L, 0x800006b7L, 0x80068693L, + 0x80000737L, 0x00a00793L, 0x00001837L, 0x00000417L, 0x09440413L, 0x00000297L, 0x08c2a283L, 0x00000317L, + 0x08532a23L, 0x00000397L, 0x0903c383L, 0x00000097L, 0x070080e7L, 0x00000317L, 0x06830067L, 0xfff5c513L, + 0x40b00533L, 0x0015b513L, 0x00b03533L, 0x0005a533L, 0x00b02533L, 0x00a05063L, 0x00055463L, 0xfe054ce3L, + 0x00a04063L, 0x02a5cc63L, 0x02a5da63L, 0x02a5e863L, 0x02a5f663L, 0x00028067L, 0x000280e7L, 0x004280e7L, + 0x00012503L, 0x0310000fL, 0x0840000fL, 0x80000537L, 0x0bc50513L, 0x00000597L, 0x02058593L, 0x00008067L, + 0x00000001L, 0xfffffffeL, 0x800000b8L, 0x00000041L, 0xffff1234L, 0x000a6968L, 0x00000007L, 0x00006261L, + 0x00002100L, 0x00000000L) + val program = Asm.assemble(source) + assert(program.words == expected) + assert(program.symbols("fn") == 0x800000b8L && program.symbols("table") == 0x800000bcL) + assert(program.symbols("end") == 0x800000ddL) + } + + it should "read riscv-tests' syntax like GNU as: ; separators, GNU operator precedence, .rept, .fill" in { + val source = """ + li a0, ((0xffffffffffff8000) & ((1 << (32 - 1) << 1) - 1)); li a1, ~0x10 + 2 * 3 + li a2, ((-((0x8180) >> ((16)-1)) << (16)) | ((0x8180) & ((1 << (16))-1))) + li a3, 1 + 2 << 3 ; li a4, 7 & 3 + 1 ; li a5, 100 / 7 % 4 # 17, 4 and 2: not C's precedence + sll t0, t0, 3; sltu t1, t2, 5; xor t3, t3, -1 # slli, sltiu, xori + 1: lla t4, 1b + jr t4, -4 + .rept 2 + nop + .endr + .option norvc + ecall + .data + .fill 3, 2, 0x1234 + .byte 9 + """ + val expected = Seq(0xffff8537L, 0xff500593L, 0xffff8637L, 0x18060613L, 0x01100693L, 0x00400713L, 0x00200793L, + 0x00329293L, 0x0053b313L, 0xfffe4e13L, 0x00000e97L, 0x000e8e93L, 0xffce8067L, 0x00000013L, 0x00000013L, + 0x00000073L, 0x12341234L, 0x00091234L) + assert(Asm(source, base = 0x80000000L) == expected) + } + + it should "shift and fill like GNU as" in { + // GNU as: >> is logical on 64-bit values, shifts of 64 or more give 0, .fill's size is 1 by + // default, and a size above 4 gets the value's low 4 bytes + val source = """ + .data + .word (-8 >> 62), (1 << 64), (-8 >> 1) >> 32 + .fill 2 + .byte 7 + .fill 1, 8, 0x1122334455667788 + """ + assert(Asm(source) == Seq(3L, 0L, 0x7fffffffL, 0x88070000L, 0x00556677L, 0L)) + } + + it should "take a label before .rept and .endr" in { + assert(Asm("loop: .rept 2\nnop\n1: .endr\nj loop", base = 0) == Seq(0x13L, 0x13L, 0xff9ff06fL)) + } + + it should "leave an empty .data out of the image, whatever its alignment" in { + assert(Asm("nop\n.data\n.align 4") == Seq(0x13L)) + } + + it should "read octal numbers and pad after data in .text like GNU as" in { + // 010 is octal; after .byte, GNU as pads with a zero byte, a 2-byte c.nop, then nops + assert( + Asm("li a0, 010\nli a1, 0\n.byte 1\n.align 3\nnop", base = 0) == + Seq(0x00800513L, 0x00000593L, 0x00010001L, 0x00000013L, 0x00000013L, 0x00000013L) + ) + assertThrows[IllegalArgumentException](Asm("li a0, 08")) + } + + it should "pad .text with nops" in { + // .text also ends padded to its largest alignment (8 bytes here), as with GNU as + assert(Asm("nop\n.align 3\nebreak", base = 0) == Seq(0x13L, 0x13L, 0x00100073L, 0x13L)) + assert(Asm.assemble("nop\n.data\n.byte 1, 2").hex == "00000013\n00000201\n") + // the default base is Ram.base, and a base not aligned to .text's largest alignment is an error + assert(Asm.assemble("nop").base == Ram.base) + assertThrows[IllegalArgumentException](Asm("nop\n.align 3\nnop", base = 4)) + } + + it should "align .data and .bss to their largest .align" in { + val program = Asm.assemble("nop\n.data\n.byte 1\n.align 3\nx: .word 2\n.bss\n.align 4\ny: .zero 4", base = 0) + assert(program.words == Seq(0x13L, 0L, 1L, 0L, 2L)) + assert(program.symbols("x") == 16 && program.symbols("y") == 32) + } + + it should "read octal and hex escapes like GNU as" in { + assert(Asm(".data\n.ascii \"\\012\\x41\\0B\"", base = 0) == Seq(0x4200410aL)) + assert(Asm("li a0, '\\101'", base = 0) == Seq(0x04100513L)) + } + + it should "take a .equ defined below as it took it in the first pass" in { + assert(Asm("li a0, N\n.equ N, 5", base = 0) == Seq(0x00000537L, 0x00550513L)) + } + + it should "assemble each program of programs/src into its committed programs/hex image" in { + val programs = Programs.names("programs/src") + assert( + programs.nonEmpty && programs == Programs.names("programs/hex", "hex"), + "a .S without its .hex, or the other way" + ) + for (p <- programs) { + assert( + Asm.assemble(Programs.source("programs/src", p)).hex == Programs.source("programs/hex", p, "hex"), + s"$p: run sbt \"runMain riscv.Asm programs/src/$p.S programs/hex/$p.hex\"" + ) + } + } + + it should "report what it cannot assemble, with the line" in { + val bad = Seq( + "mul a0, a1, a2", // not RV32I + "addi a0, a1", // missing operand + "addi a0, 4(sp)", // a memory operand on a non-load + "add a0, a1, x32", // no such register + "ecall a0, a1, 5", // ecall has no operands + "lui a0, 0x100000", // more than 20 bits + "lui a0, -1", + "li a0, 0x100000000", // more than 32 bits + "j nowhere", // unknown label + "j 1b", // no numeric label + "x: nop\nx: nop", // label defined twice + ".data\nnop", // an instruction outside .text + ".byte 1\nnop", // an instruction not on a word + ".bss\n.word 1", // data in .bss + ".frobnicate", // unknown directive + "addi a0, a0, %pcrel_lo(0)", + ".word 1,,2", + ".rept 2\nnop", // .rept without .endr + ".endr", // .endr without .rept + ".rept 1000000\n.rept 1000000\n.endr\n.endr", // empty blocks, repeated too often + "li a0, 1 / 0", // division by zero + ".data\n.fill 1, 9, 0", // a .fill size above 8 + "sub a0, a0, 1", // there is no subi + ".zero", // missing size + ".zero 0x7fffffff", // too large + ".equ N", // missing value + ".align", // missing alignment + ".data\n.string \"a\\\"", // unterminated string + "addi a0, a0, 0xffffffff", // not -1 + "lw a0, 4(sp", // unbalanced parentheses + "li a0, 'a", // unterminated character + "sw a0, x, a0\nx: .word 0", // the address register is the stored one + "sw a0, x, zero\nx: .word 0", // x0 cannot hold the address + "lw zero, x\nx: .word 0" // nor for a load + ) + for (source <- bad) { + val e = intercept[IllegalArgumentException](Asm(source)) + assert(e.getMessage.startsWith("line "), e.getMessage) + } + } + + "Rv32i.disassemble" should "give text that assembles back into the same word" in { + val dirs = Seq("programs/src", "programs/riscv-tests/rv32ui") + val words = dirs.flatMap(d => Programs.images(d).flatMap(_._2)).distinct + val insts = words.filter(w => Rv32i.decode(w).exists(_.name != "fence")) // fence shows no operands + assert(insts.size > 500) + for (w <- insts) { + val text = Rv32i.disassemble(w) // at pc 0, a target is the offset, which is what Asm takes + assert(Asm(text) == Seq(w), f"0x$w%08x: $text") + } + assert(Rv32i.disassemble(0) == ".word 0x00000000") + assert(Rv32i.disassemble(0x00a50513L) == "addi a0, a0, 10") + assert(Rv32i.disassemble(0xfe0718e3L, 0x80000010L) == "bne a4, zero, 0x80000000") + } +} diff --git a/riscv/src/test/scala/riscv/ComplianceSpec.scala b/riscv/src/test/scala/riscv/ComplianceSpec.scala new file mode 100644 index 0000000..8e7447f --- /dev/null +++ b/riscv/src/test/scala/riscv/ComplianceSpec.scala @@ -0,0 +1,37 @@ +package riscv + +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +/** The rv32ui tests of riscv-tests (riscv/programs/riscv-tests, imported by + * tools/import-riscv-tests.py). A test passes if it ends with ECALL and a0 = 0; otherwise a0 is + * (the number of the failing test << 1) | 1. + */ +class ComplianceSpec extends AnyFlatSpec with ChiselSim { + val dir = "programs/riscv-tests/rv32ui" + // each test assembled once, for the golden model and the core alike + val all = Programs.images(dir) + val tests = all.map(_._1) + val images = all.toMap + + "The rv32ui tests" should "be there" in { + assert(tests.size == 40 && tests.contains("add") && tests.contains("ld_st")) + } + + they should "pass on the golden model" in { + for (name <- tests) { + val sim = new IsaSim(images(name)) + sim.run(100000) + assert(sim.halted.contains(Halt.Ecall) && sim.reg(Reg("a0")) == 0, s"$name: a0 = ${sim.reg(Reg("a0"))}") + } + } + + they should "pass on the single-cycle core, retiring like the golden model" in { + simulate(new SingleCycleSystem) { c => + for (name <- tests) { + CoSim.compare(c, images(name)).foreach(d => fail(s"$name: $d")) + assert(CoSim.reg(c, Reg("a0")) == 0, name) + } + } + } +} diff --git a/riscv/src/test/scala/riscv/DebugSpec.scala b/riscv/src/test/scala/riscv/DebugSpec.scala new file mode 100644 index 0000000..56e1ff5 --- /dev/null +++ b/riscv/src/test/scala/riscv/DebugSpec.scala @@ -0,0 +1,73 @@ +package riscv + +import chisel3._ +import chisel3.util._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +/** A seeded bug: forwards the older result (MEM/WB) before the newer one (EX/MEM). */ +class OldestFirst extends Forward { + def writes(r: Valid[Result]) = r.valid && r.bits.rd =/= 0.U && r.bits.rd === io.rs + io.value := MuxCase( + io.regValue, + Seq(writes(io.memWb) -> io.memWb.bits.value, writes(io.exMem) -> io.exMem.bits.value) + ) +} + +class DebugSpec extends AnyFlatSpec with ChiselSim { + + "Retire" should "read as a line of a trace" in { + val r = Retire(0x80000008L, Asm("addi a0, a0, 10").head, 0x8000000cL, rd = 10, rdValue = 15) + assert(r.toString == "80000008 00a50513 addi a0, a0, 10 a0 <- 0x0000000f") + val halt = Retire(0x80000010L, 0x73, 0x80000010L, halt = Some(Halt.Ecall)) + assert(halt.toString == "80000010 00000073 ecall halt: Ecall") + } + + "Vcd" should "read signals by path and sample them at each rising clock edge" in { + val vcd = new Vcd( + """$timescale 1ns $end + |$scope module TOP $end + |$var wire 1 ! clock $end + |$scope module dut $end + |$var wire 4 " count [3:0] $end + |$upscope $end + |$upscope $end + |$enddefinitions $end + |#0 + |$dumpvars + |0! + |bx " + |$end + |#1 + |1! + |b0 " + |#2 + |0! + |#3 + |1! + |b101 " + |""".stripMargin + ) + assert(vcd.signals == Seq("TOP.clock", "TOP.dut.count")) + assert(vcd.risingEdges("clock") == Seq(1L, 3L)) + val count = vcd("dut.count") + assert(count(0) == -1 && count(2) == 0 && count(3) == 5 && vcd("TOP.dut.count")(3) == 5) + } + + "Co-simulation" should "find a forwarding unit that forwards the older result first" in { + simulate(new CoreSystem(new ForwardingCore(forwardUnit = new OldestFirst))) { c => + val bug = CoSim.compare(c, Asm("li a0, 1\nli a0, 2\nadd a1, a0, a0\necall")) + assert(bug.exists(_.contains("a1 <- 0x00000004")), bug) // the model's a1; the core computes 1 + 1 + assert(CoSim.compare(c, Asm(Programs.source("programs/src", "fib"))).isEmpty, "fib does not show it") + } + } + + "Formal.prove" should "prove the forwarding unit, and give a counterexample for the seeded bug" in { + assume(Yosys.available, "yosys is not on the PATH") + assert(Formal.prove(new ForwardCheck(new Forward)).isEmpty) + val cex = Formal.prove(new ForwardCheck(new OldestFirst)).get + def value(name: String) = cex.linesIterator.find(_.startsWith(s"\\io_$name ")).get.split("\\s+")(1).toLong + assert(value("ok") == 0 && value("exMem_valid") == 1 && value("memWb_valid") == 1, cex) + assert(value("exMem_bits_rd") == value("rs") && value("memWb_bits_rd") == value("rs") && value("rs") != 0, cex) + } +} diff --git a/riscv/src/test/scala/riscv/DecoderSpec.scala b/riscv/src/test/scala/riscv/DecoderSpec.scala new file mode 100644 index 0000000..5d6986c --- /dev/null +++ b/riscv/src/test/scala/riscv/DecoderSpec.scala @@ -0,0 +1,71 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +class DecoderSpec extends AnyFlatSpec with ChiselSim { + + /** The row an instruction must have, worked out from its opcode and name alone (Rv32i), not from + * the table: an independent description to check the table against. + */ + def expectedRow(name: String): Row = { + val e = Rv32i.encodings(name.toLowerCase) + val alu = AluOp.all.find(AluOp.mnemonic(_) == name.toLowerCase.filterNot(_ == 'i')) // addi -> add + def row(kind: Kind.Type, a: ASel.Type, b: BSel.Type, op: Option[AluOp.Type] = Some(AluOp.Add)) = + Row(kind, op, ImmFormat.of(e.format), Some(a), Some(b)) + e.opcode match { + case 0x37 => row(Kind.Alu, ASel.Zero, BSel.Imm) // lui: 0 + imm + case 0x17 => row(Kind.Alu, ASel.Pc, BSel.Imm) // auipc: pc + imm + case 0x6f => row(Kind.Jal, ASel.Pc, BSel.Imm) // the target + case 0x67 => row(Kind.Jalr, ASel.Rs1, BSel.Imm) + case 0x63 => row(Kind.Branch, ASel.Pc, BSel.Imm) + case 0x03 => row(Kind.Load, ASel.Rs1, BSel.Imm) // the address + case 0x23 => row(Kind.Store, ASel.Rs1, BSel.Imm) + case 0x13 => row(Kind.Alu, ASel.Rs1, BSel.Imm, alu) + case 0x33 => row(Kind.Alu, ASel.Rs1, BSel.Rs2, alu) + case 0x0f => Row(Kind.Fence) + case 0x73 => Row(if (name == "ECALL") Kind.Ecall else Kind.Ebreak) + } + } + + // a row as plain values, to compare rows (enum values compare by their encoding) + def values(r: Row) = + (r.kind.litValue, r.aluOp.map(_.litValue), r.imm.map(_.litValue), r.a.map(_.litValue), r.b.map(_.litValue)) + + "DecodeRows.table" should "give every RV32I instruction the row its opcode implies" in { + val table = DecodeRows.table + assert(table.keySet == Instructions.all.map(_._1).toSet) + for ((name, row) <- table) assert(values(row) == values(expectedRow(name)), name) + } + + "Decoder" should "decode every RV32I instruction as its row says, and flag other words as illegal" in { + val table = DecodeRows.table + simulate(new Decoder) { c => + val rnd = new scala.util.Random(1) + for ((name, _) <- Instructions.all; _ <- 0 until 50) { + val word = Instructions.random(name, rnd) + val row = table(name) + c.io.inst.poke(word.U) + val what = f"$name 0x$word%08x" + c.io.ctrl.legal.expect(true.B, what) + c.io.ctrl.kind.expect(row.kind, what) + row.aluOp.foreach(c.io.ctrl.aluOp.expect(_, what)) + row.imm.foreach(c.io.ctrl.immFormat.expect(_, what)) + row.a.foreach(c.io.ctrl.aSel.expect(_, what)) + row.b.foreach(c.io.ctrl.bSel.expect(_, what)) + } + // words close to instructions (random words would hardly ever be), random words, and known + // non-RV32I words, keeping those that the software decoder rejects + val words = Instructions.all.flatMap { case (n, _) => Seq.fill(20)(Instructions.nearMiss(n, rnd)) } ++ + Seq.fill(5000)(rnd.nextLong() & 0xffffffffL) ++ + Seq(0x00000000L, 0xffffffffL, 0x30200073L, 0x34011073L, 0x02208033L, 0x0000100fL) + val illegal = words.filter(Rv32i.decode(_).isEmpty) + for (word <- illegal) { + c.io.inst.poke(word.U) + c.io.ctrl.legal.expect(false.B, f"0x$word%08x") + } + assert(illegal.size > 3000) + } + } +} diff --git a/riscv/src/test/scala/riscv/ForwardingSpec.scala b/riscv/src/test/scala/riscv/ForwardingSpec.scala new file mode 100644 index 0000000..0cc4e40 --- /dev/null +++ b/riscv/src/test/scala/riscv/ForwardingSpec.scala @@ -0,0 +1,126 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +/** The forwarding core with a data memory that answers `delay` cycles late. */ +class SlowDataSystem(delay: Int) extends RiscvSystem { + val core = Module(new ForwardingCore) + val ram = Module(new Ram) + val slow = Module(new Delay(delay)) + ram.io.imem <> core.io.imem + slow.io.in <> core.io.dmem + ram.io.dmem <> slow.io.out + ram.io.load := io.load + io.retire := core.io.retire + io.halted := core.io.halted + io.dbg <> core.io.dbg +} + +class ForwardingSpec extends AnyFlatSpec with ChiselSim { + "Forward" should "take the newest result for the register, and never one for x0" in { + simulate(new Forward) { c => + def check(rs: Int, ex: Option[(Int, Int)], wb: Option[(Int, Int)], expected: Int) = { + c.io.rs.poke(rs.U) + c.io.regValue.poke(1.U) + for ((port, r) <- Seq(c.io.exMem -> ex, c.io.memWb -> wb)) { + port.valid.poke(r.isDefined.B) + port.bits.rd.poke(r.map(_._1).getOrElse(0).U) + port.bits.value.poke(r.map(_._2).getOrElse(0).U) + } + c.io.value.expect(expected.U, s"rs $rs, EX/MEM $ex, MEM/WB $wb") + } + check(5, None, None, 1) + check(5, Some(5 -> 2), None, 2) + check(5, None, Some(5 -> 3), 3) + check(5, Some(5 -> 2), Some(5 -> 3), 2) // the newest + check(5, Some(6 -> 2), Some(5 -> 3), 3) + check(5, Some(6 -> 2), Some(7 -> 3), 1) + check(0, Some(0 -> 2), Some(0 -> 3), 1) // x0 is never forwarded + } + } + + // every hazard of the five-stage pipeline, unpadded + val hazards = Seq( + "EX/MEM to EX" -> "li a0, 5\naddi a1, a0, 1\necall", + "MEM/WB to EX" -> "li a0, 5\nnop\naddi a1, a0, 1\necall", + "WB to ID" -> "li a0, 5\nnop\nnop\naddi a1, a0, 1\necall", + "the newest result wins" -> "li a0, 1\nli a0, 2\nadd a1, a0, a0\necall", + "both operands" -> "li a0, 3\nli a1, 4\nsub a2, a1, a0\necall", + "x0 is not forwarded" -> "addi zero, zero, 7\nadd a0, zero, zero\necall", + "load-use" -> "la t0, d\nlw a0, 0(t0)\naddi a1, a0, 1\necall\n.data\nd: .word 41", + "load-use, second operand" -> "la t0, d\nlw a0, 0(t0)\nadd a1, t0, a0\necall\n.data\nd: .word 41", + "load then store" -> "la t0, d\nlw a0, 0(t0)\nsw a0, 4(t0)\nlw a1, 4(t0)\necall\n.data\nd: .word 41, 0", + "load into the base" -> "la t0, d\nlw t0, 0(t0)\nlw a0, 0(t0)\necall\n.data\nd: .word d", + "branch on a fresh value" -> "li a0, 1\nbnez a0, 1f\nebreak\n1: ecall", + "branch on a loaded value" -> "la t0, d\nlw a0, 0(t0)\nbnez a0, 1f\nebreak\n1: ecall\n.data\nd: .word 1", + "jalr on a fresh base" -> "la t0, 1f\njalr ra, 0(t0)\nebreak\n1: ecall", + "jal link used at once" -> "jal ra, 1f\nebreak\n1: addi a0, ra, 0\necall", + "wrong-path stores" -> "la t0, d\nj 1f\nsw t0, 0(t0)\nsw t0, 4(t0)\n1: lw a0, 0(t0)\necall\n.data\nd: .word 7, 8", + "a store behind a halt" -> "la t0, d\nebreak\nsw t0, 0(t0)\n.data\nd: .word 7" + ) + + "ForwardingCore" should "resolve every hazard without nops, like the golden model" in { + simulate(new ForwardingSystem) { c => + for ((name, source) <- hazards) CoSim.compare(c, Asm(source), maxCycles = 1000).foreach(d => fail(s"$name: $d")) + } + } + + it should "run the committed, regression and random programs unpadded" in { + simulate(new ForwardingSystem) { c => + for ((name, result) <- Seq("fib" -> 55, "fact" -> 120)) { + CoSim.compare(c, Asm(Programs.source("programs/src", name))).foreach(d => fail(s"$name: $d")) + assert(CoSim.reg(c, riscv.Reg("a0")) == result, name) + } + for ((name, image) <- Programs.images("programs/regress")) + CoSim.compare(c, image).foreach(d => fail(s"$name: $d")) + for (seed <- 1L to 20L) + CoSim.compare(c, Asm(RandomProgram(seed))).foreach(d => fail(s"RandomProgram($seed): $d")) + } + } + + it should "pass the rv32ui tests" in { + simulate(new ForwardingSystem) { c => + for ((name, image) <- Programs.images("programs/riscv-tests/rv32ui")) { + CoSim.compare(c, image).foreach(d => fail(s"$name: $d")) + assert(CoSim.reg(c, riscv.Reg("a0")) == 0, name) + } + } + } + + it should "wait for a data memory that answers late" in { + simulate(new SlowDataSystem(delay = 2)) { c => + for (name <- Seq("fib", "fact")) + CoSim.compare(c, Asm(Programs.source("programs/src", name))).foreach(d => fail(s"$name: $d")) + for ((name, source) <- hazards) CoSim.compare(c, Asm(source), maxCycles = 1000).foreach(d => fail(s"$name: $d")) + for (seed <- 1L to 5L) + CoSim.compare(c, Asm(RandomProgram(seed))).foreach(d => fail(s"RandomProgram($seed): $d")) + for (name <- Seq("ld_st", "st_ld", "lw", "sb")) // the rv32ui tests that load and store most + CoSim.compare(c, Asm(Programs.source("programs/riscv-tests/rv32ui", name))).foreach(d => fail(s"$name: $d")) + } + } + + it should "take fewer cycles than the nop-padded pipeline of 5.6" in { + val programs = Seq("fib", "fact").map(n => Programs.source("programs/src", n)) + def cycles(system: => RiscvSystem, images: Seq[Seq[Long]]): Seq[Int] = { + var result = Seq.empty[Int] + simulate(system) { c => + result = images.map { image => + CoSim.load(c, image) + val (trace, n) = CoSim.timed(c) + assert(trace.lastOption.exists(_.halt.isDefined), "the program did not halt") + n + } + } + result + } + val forward = cycles(new ForwardingSystem, programs.map(Asm(_))) + val padded = cycles(new PipelinedSystem, programs.map(Asm.padded(_, 2))) + for (((f, p), source) <- forward.zip(padded).zip(programs)) { + val instructions = new IsaSim(Asm(source)).run().size + println(f"$instructions%4d instructions: $f%4d cycles (CPI ${f.toDouble / instructions}%.2f), padded 5.6: $p%4d") + assert(f < p && f < 2 * instructions) + } + } +} diff --git a/riscv/src/test/scala/riscv/ImmGenRegFileSpec.scala b/riscv/src/test/scala/riscv/ImmGenRegFileSpec.scala new file mode 100644 index 0000000..56f4031 --- /dev/null +++ b/riscv/src/test/scala/riscv/ImmGenRegFileSpec.scala @@ -0,0 +1,60 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +/** Checks ImmGen against the software decoder (Rv32i.decode) and RegFile against a Scala model. */ +class ImmGenRegFileSpec extends AnyFlatSpec with ChiselSim { + private def unsigned(x: Int) = BigInt(Integer.toUnsignedLong(x)) + + "ImmGen" should "extract the immediate of every format like Rv32i.decode" in { + // (not slli/srli/srai: their immediate field also holds funct7; the ALU uses only bits 4:0) + val formats = Seq( + ImmFormat.I -> Seq("ADDI", "LW", "JALR"), + ImmFormat.S -> Seq("SW", "SB"), + ImmFormat.B -> Seq("BEQ", "BGEU"), + ImmFormat.U -> Seq("LUI", "AUIPC"), + ImmFormat.J -> Seq("JAL") + ) + simulate(new ImmGen) { c => + val rnd = new scala.util.Random(1) + for ((format, names) <- formats; name <- names; _ <- 0 until 200) { + val word = Instructions.random(name, rnd) + val expected = Rv32i.decode(word).get.imm + c.io.inst.poke(word.U) + c.io.format.poke(format) + c.io.imm.expect(unsigned(expected).U, f"$name 0x$word%08x") + } + } + } + + "RegFile" should "read two registers, write one at the clock edge, and keep x0 at 0" in { + simulate(new RegFile) { c => + val rnd = new scala.util.Random(2) + val model = Array.fill(32)(BigInt(0)) + c.io.wen.poke(true.B) // first give every register a known value + for (r <- 0 until 32) { + model(r) = if (r == 0) 0 else BigInt(32, rnd) + c.io.rd.poke(r.U) + c.io.wdata.poke(if (r == 0) 12345.U else model(r).U) // the write to x0 is ignored + c.clock.step() + } + for (cycle <- 0 until 1000) { + val (rs1, rs2, rd, dbg) = (rnd.nextInt(32), rnd.nextInt(32), rnd.nextInt(32), rnd.nextInt(32)) + val (wen, wdata) = (rnd.nextBoolean(), BigInt(32, rnd)) + c.io.rs1.poke(rs1.U) + c.io.rs2.poke(rs2.U) + c.io.dbgAddr.poke(dbg.U) + c.io.wen.poke(wen.B) + c.io.rd.poke(rd.U) + c.io.wdata.poke(wdata.U) + c.io.rs1Data.expect(model(rs1).U, s"cycle $cycle: x$rs1") + c.io.rs2Data.expect(model(rs2).U, s"cycle $cycle: x$rs2") + c.io.dbgData.expect(model(dbg).U, s"cycle $cycle: x$dbg (debug port)") + c.clock.step() + if (wen && rd != 0) model(rd) = wdata + } + } + } +} diff --git a/riscv/src/test/scala/riscv/IsaSimSpec.scala b/riscv/src/test/scala/riscv/IsaSimSpec.scala new file mode 100644 index 0000000..04254c3 --- /dev/null +++ b/riscv/src/test/scala/riscv/IsaSimSpec.scala @@ -0,0 +1,188 @@ +package riscv + +import org.scalatest.flatspec.AnyFlatSpec + +class IsaSimSpec extends AnyFlatSpec { + + def program(name: String): Program = + Asm.assemble(Programs.source("programs/src", name)) // AsmSpec: equals hex/ + + /** Runs `source` and returns the simulator, checking that it ends with ECALL. */ + def run(source: String): IsaSim = { + val (sim, trace) = IsaSim.run(source, maxSteps = 10000) + assert(sim.halted.contains(Halt.Ecall), trace.lastOption) + sim + } + + "IsaSim" should "run the committed programs" in { + val fib = new IsaSim(program("fib")) + fib.run() + assert(fib.halted.contains(Halt.Ecall) && fib.reg(Reg("a0")) == 55) + + val factProgram = program("fact") + val fact = new IsaSim(factProgram) + val trace = fact.run() + assert(fact.halted.contains(Halt.Ecall) && fact.reg(Reg("a0")) == 120) + val result = factProgram.symbols("result") + assert(fact.read(result, 4) == 120) + assert(trace.last.halt.contains(Halt.Ecall) && trace.exists(_.mem.exists(m => m.write && m.addr == result))) + } + + it should "compute like RV32I" in { + val sim = run(""" + li a0, -8 + srai a1, a0, 1 # -4 + srli a2, a0, 28 # 0xf + sltu a3, a2, a0 # 1: 15 < 0xfffffff8 unsigned + slt a4, a2, a0 # 0 + sltiu a5, zero, 1 # 1 + lui a6, 0x80000 + addi a6, a6, -1 # 0x7fffffff + addi a6, a6, 1 # wraps to 0x80000000 + auipc a7, 0 # its own address + li t0, 33 + sll t1, a5, t0 # shifts use the low 5 bits: 1 << 1 + add zero, a5, a5 # x0 stays 0 + ecall + """) + val r = (n: String) => sim.reg(Reg(n)) + assert(r("a1") == 0xfffffffcL && r("a2") == 0xf && r("a3") == 1 && r("a4") == 0 && r("a5") == 1) + assert(r("a6") == 0x80000000L && r("a7") == 0x80000000L + 4 * 9 && r("t1") == 2 && r("zero") == 0) + } + + it should "compare, subtract and shift negative numbers like RV32I" in { + val sim = run(""" + li s0, -1 + li s1, 1 + li a0, 0 + blt s0, s1, 1f # taken: -1 < 1 + ori a0, a0, 1 + 1: bltu s0, s1, 2f # not taken: 0xffffffff > 1 + ori a0, a0, 2 + 2: bge s1, s0, 3f # taken + ori a0, a0, 4 + 3: bgeu s1, s0, 4f # not taken + ori a0, a0, 8 + 4: beq s0, s0, 5f # taken + ori a0, a0, 16 + 5: bne s0, s0, 6f # not taken + ori a0, a0, 32 + 6: sub a1, s1, s0 # 2 + li t0, 4 + sra a2, s0, t0 # -1 + srl a3, s0, t0 # 0x0fffffff + ecall + """) + assert(sim.reg(Reg("a0")) == (2 | 8 | 32) && sim.reg(Reg("a1")) == 2) + assert(sim.reg(Reg("a2")) == 0xffffffffL && sim.reg(Reg("a3")) == 0x0fffffffL) + } + + it should "load and store bytes, halves and words, little-endian" in { + val sim = run(""" + la s0, d + li t0, 0x8081 + sh t0, 0(s0) + lb a0, 0(s0) # 0x81 sign-extended + lbu a1, 1(s0) # 0x80 + lh a2, 0(s0) # 0xffff8081 + lhu a3, 0(s0) + sb t0, 3(s0) + lw a4, 0(s0) # 0x81008081 + ecall + .data + d: .word 0 + """) + val r = (n: String) => sim.reg(Reg(n)) + assert(r("a0") == 0xffffff81L && r("a1") == 0x80 && r("a2") == 0xffff8081L && r("a3") == 0x8081) + assert(r("a4") == 0x81008081L) + } + + it should "jump and link, and report each retired instruction" in { + val (sim, trace) = IsaSim.run(""" + jal f # 0x80000000 + ecall # 0x80000004 + f: addi a0, zero, 7 # 0x80000008 + jalr t0, 0(ra) # back to 0x80000004, t0 = 0x80000010 + """) + assert(sim.halted.contains(Halt.Ecall) && sim.reg(Reg("t0")) == 0x80000010L) + assert(trace.map(_.pc) == Seq(0x80000000L, 0x80000008L, 0x8000000cL, 0x80000004L)) + assert(trace.head == Retire(0x80000000L, Asm("jal 8").head, 0x80000008L, rd = 1, rdValue = 0x80000004L)) + assert(trace(1).rd == Reg("a0") && trace(1).rdValue == 7) + } + + it should "halt on ebreak, illegal instructions, misalignment and bad addresses, changing nothing" in { + val cases = Seq( + "ebreak" -> Halt.Ebreak, + ".word 0x30200073" -> Halt.Illegal, // mret: no CSRs + ".word 0" -> Halt.Illegal, + "li t0, 4\nlw a0, 0(t0)" -> Halt.BadAddress, // address 4: no RAM there + "la t0, x\nlw a0, 1(t0)\nx: nop" -> Halt.Misaligned, + "la t0, x\nsh a0, 1(t0)\nx: nop" -> Halt.Misaligned, + "la ra, x\njalr ra, 2(ra)\nx: nop" -> Halt.Misaligned, + "lui t0, 0x10\njr t0" -> Halt.BadAddress, // fetch from 0x10000 + "beq zero, zero, 2" -> Halt.Misaligned, // a taken branch to pc + 2 + "li t0, -4\nlw a0, 8(t0)" -> Halt.BadAddress, // 0xfffffffc + 8 wraps to 4 + "li t0, 0x80010000\nlw a0, -2(t0)" -> Halt.Misaligned // misaligned first, though also outside + ) + for ((source, why) <- cases) { + val (sim, trace) = IsaSim.run(source, maxSteps = 10) + assert(sim.halted.contains(why), source) + val last = trace.last + assert(last.halt.contains(why) && last.rd == 0 && last.mem.isEmpty && last.nextPc == last.pc, source) + assert(sim.reg(Reg("a0")) == 0 && sim.pc == last.pc, source) + } + val (sim, _) = IsaSim.run("la ra, x\njalr ra, 2(ra)\nx: nop") + assert(sim.reg(1) == sim.base + 12, "a jump that halts does not write its link register") // ra = x + } + + it should "not halt on a branch that is not taken, odd jalr offsets, or the top word of the RAM" in { + val sim = run(""" + bne zero, zero, 2 # not taken: the misaligned target does not matter + la t0, 1f + jalr ra, 1(t0) # bit 0 of the target is cleared + 1: li t1, 0x80010000 + li t2, 42 + sw t2, -4(t1) # the last word of the RAM + lw a0, -4(t1) + ecall + """) + assert(sim.reg(Reg("a0")) == 42) + val (_, trace) = IsaSim.run("auipc t0, 0\nlw zero, 0(t0)\necall") // a load into x0 still reads + assert(trace(1).rd == 0 && trace(1).rdValue == 0 && trace(1).mem.exists(m => !m.write && m.data == 0x297)) + } + + it should "wrap the pc at 2^32" in { + val top = new IsaSim(Seq.fill(1024)(0x00000013L), base = 0xfffff000L, size = 4096) // nops to the top + val trace = top.run(1024) + assert(trace.last.pc == 0xfffffffcL && trace.last.nextPc == 0 && top.pc == 0) + } + + it should "keep only the bytes a load reads from a device" in { + val ones = new Device { // a device whose reads set every bit + val base = 0x10000000L + val size = 4L + def read(addr: Long, bytes: Int) = 0xffffffffL + def write(addr: Long, bytes: Int, data: Long) = () + } + val sim = new IsaSim(Asm("li t0, 0x10000000\nlbu a0, 0(t0)\nlhu a1, 0(t0)\necall"), devices = Seq(ones)) + val ret = sim.run() + assert(sim.reg(Reg("a0")) == 0xff && sim.reg(Reg("a1")) == 0xffff) + assert(ret.flatMap(_.mem).map(_.data) == Seq(0xffL, 0xffffL)) + } + + it should "reject a RAM that is not whole words inside the 32-bit address space" in { + for ((base, size) <- Seq(2L -> 1024, 0L -> 1022, 0xffff0000L -> 0x20000, -4L -> 1024)) + assertThrows[IllegalArgumentException](new IsaSim(Nil, base, size)) + } + + "RandomProgram" should "make programs that assemble, halt with ECALL, and repeat for a seed" in { + for (seed <- 1L to 30L) { + val source = RandomProgram(seed) + assert(source == RandomProgram(seed)) + val (sim, trace) = IsaSim.run(source, maxSteps = 1000) + assert(sim.halted.contains(Halt.Ecall), s"seed $seed: ${trace.lastOption}") + assert(sim.reg(0) == 0) + assert(trace.exists(_.mem.exists(_.write)) && trace.exists(_.mem.exists(!_.write)), s"seed $seed") + } + } +} diff --git a/riscv/src/test/scala/riscv/IsaSpec.scala b/riscv/src/test/scala/riscv/IsaSpec.scala new file mode 100644 index 0000000..9be0418 --- /dev/null +++ b/riscv/src/test/scala/riscv/IsaSpec.scala @@ -0,0 +1,64 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +class IsaSpec extends AnyFlatSpec with ChiselSim { + + "Instructions.all" should "list the 40 RV32I instructions once each" in { + assert(Instructions.all.size == 40) + assert(Instructions.all.map(_._1).distinct.size == 40) + } + + it should "have 32-bit patterns whose opcode is a major opcode of Opcode" in { + val opcodes = Opcode.all.map(_.litValue).toSet + for ((name, p) <- Instructions.all) { + assert(p.getWidth == 32, name) + assert((p.mask & 0x7f) == 0x7f && opcodes(p.value & 0x7f), name) + } + } + + it should "not contain two patterns that match the same instruction word" in { + for (((n1, p1), i) <- Instructions.all.zipWithIndex; (n2, p2) <- Instructions.all.drop(i + 1)) + assert(!p1.overlap(p2), s"$n1 and $n2 overlap") + } + + it should "decode known encodings" in { + val examples = Seq( + 0x00500093L -> "ADDI", // addi x1, x0, 5 + 0x002081b3L -> "ADD", // add x3, x1, x2 + 0x40208233L -> "SUB", // sub x4, x1, x2 + 0x00209093L -> "SLLI", // slli x1, x1, 2 + 0x4020d093L -> "SRAI", // srai x1, x1, 2 + 0x0020d093L -> "SRLI", // srli x1, x1, 2 + 0x0040a103L -> "LW", // lw x2, 4(x1) + 0x0020a223L -> "SW", // sw x2, 4(x1) + 0x00208463L -> "BEQ", // beq x1, x2, 8 + 0x008000efL -> "JAL", // jal x1, 8 + 0x00000073L -> "ECALL" + ) + for ((word, name) <- examples) { + assert(Instructions.matching(word) == Seq(name), f"0x$word%08x") + } + } + + "Opcode.safe" should "recognise the major opcodes in hardware" in { + class OpcodeCheck extends Module { + val io = IO(new Bundle { + val bits = Input(UInt(7.W)) + val isOp = Output(Bool()) + val valid = Output(Bool()) + }) + val (opcode, valid) = Opcode.safe(io.bits) + io.isOp := valid && opcode === Opcode.Op + io.valid := valid + } + simulate(new OpcodeCheck) { c => + c.io.bits.poke("b0110011".U) + c.io.isOp.expect(true.B) + c.io.bits.poke("b0000000".U) + c.io.valid.expect(false.B) + } + } +} diff --git a/riscv/src/test/scala/riscv/MemorySpec.scala b/riscv/src/test/scala/riscv/MemorySpec.scala new file mode 100644 index 0000000..2ed5202 --- /dev/null +++ b/riscv/src/test/scala/riscv/MemorySpec.scala @@ -0,0 +1,64 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +/** Unit tests of the RAM and of the slow memory of the bus, which have no exercise in them and so + * pass from the start (Module 2.6 shows this file as an example of tests in files). + */ +class MemorySpec extends AnyFlatSpec with ChiselSim { + + "Ram" should "return the word written through its load port, and change only the bytes a store selects" in { + simulate(new Ram(words = 16)) { c => + def request(addr: Long, wdata: Long = 0, wstrb: Int = 0) = { + c.io.dmem.req.valid.poke(true.B) + c.io.dmem.req.bits.addr.poke(addr.U) + c.io.dmem.req.bits.wdata.poke(wdata.U) + c.io.dmem.req.bits.wstrb.poke(wstrb.U) + } + c.io.load.valid.poke(true.B) // as CoSim.load writes a program + c.io.load.bits.addr.poke((Ram.base + 4).U) + c.io.load.bits.data.poke(0x11223344L.U) + c.clock.step() + c.io.load.valid.poke(false.B) + request(Ram.base + 4) + c.io.dmem.resp.bits.rdata.expect(0x11223344L.U) + c.io.dmem.resp.bits.error.expect(false.B) + request(Ram.base + 4, wdata = 0xaa0000L, wstrb = 0x4) // byte 2 + c.clock.step() + request(Ram.base + 4) + c.io.dmem.resp.bits.rdata.expect(0x11aa3344L.U, "only byte 2 changed") + request(Ram.base - 4) // just below the RAM + c.io.dmem.resp.bits.error.expect(true.B) + request(Ram.base + 68, wdata = 0xffffffffL, wstrb = 0xf) // past the 16 words, where word 1 aliases + c.io.dmem.resp.bits.error.expect(true.B) + c.clock.step() + request(Ram.base + 4) + c.io.dmem.resp.bits.rdata.expect(0x11aa3344L.U, "a store outside the RAM writes nothing") + } + } + + "Delay" should "pass a request on after its latency, and take it with the answer" in { + simulate(new Delay(3)) { c => + c.io.in.req.valid.poke(true.B) + c.io.out.req.ready.poke(true.B) + c.io.out.resp.valid.poke(false.B) + for (cycle <- 0 until 3) { + c.io.out.req.valid.expect(false.B, s"cycle $cycle") + c.clock.step() + } + for (cycle <- 3 until 6) { // a slow device: it answers at cycle 6 + c.io.out.req.valid.expect(true.B, s"cycle $cycle") + c.io.in.req.ready.expect(false.B, "taken only with the answer") + c.clock.step() + } + c.io.out.resp.valid.poke(true.B) + c.io.in.resp.valid.expect(true.B) + c.io.in.req.ready.expect(true.B) + c.clock.step() + c.io.out.resp.valid.poke(false.B) + c.io.out.req.valid.expect(false.B, "the next request waits its latency again") + } + } +} diff --git a/riscv/src/test/scala/riscv/PipelinedSpec.scala b/riscv/src/test/scala/riscv/PipelinedSpec.scala new file mode 100644 index 0000000..3f225a1 --- /dev/null +++ b/riscv/src/test/scala/riscv/PipelinedSpec.scala @@ -0,0 +1,105 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +/** The five-stage pipeline, on programs padded with 2 nops after every instruction (it handles no + * data hazards), compared instruction by instruction with the golden model. + */ +class PipelinedSpec extends AnyFlatSpec with ChiselSim { + val nops = 2 + + "PipelineFlush" should "flush the wrong path after a jump, and everything younger after a halt" in { + simulate(new PipelineFlush) { c => + for (redirect <- Seq(false, true); halt <- Seq(false, true)) { + c.io.redirect.poke(redirect.B) + c.io.halt.poke(halt.B) + c.io.flushIfId.expect((redirect || halt).B) + c.io.flushIdEx.expect((redirect || halt).B) + c.io.flushExMem.expect(halt.B) + } + } + } + + // one feature each, and every halt cause (the halting instruction comes after padded ones too) + val programs = Seq( + "arithmetic" -> """ + li a0, 0x12345678 + lui a1, 0xfffff + sub a2, zero, a0 + sra a3, a2, a1 + sltu a4, a2, a0 + add zero, a0, a0 + ecall + """, + "branches and jumps" -> """ + li s0, -1 + li s1, 1 + blt s0, s1, 1f + ebreak + 1: bltu s0, s1, 2f + bgeu s0, s1, 2f + ebreak + 2: jal ra, 3f + j 4f + 3: jalr t0, 0(ra) + 4: la t1, 5f + jalr zero, 1(t1) + ebreak + 5: ecall + """, + "loads and stores" -> """ + la s0, d + li t0, 0x8081 + sh t0, 2(s0) + sb t0, 1(s0) + lb a0, 1(s0) + lhu a1, 2(s0) + lw a2, 0(s0) + ecall + .data + d: .word 0x11223344 + """, + "ebreak" -> "ebreak", + "illegal" -> ".word 0x30200073", + "misaligned load" -> "la t0, x\nlw a0, 1(t0)\nx: nop", + "misaligned jalr" -> "la ra, x\njalr ra, 2(ra)\nx: nop", + "store outside the RAM" -> "li t0, 4\nsw t0, 0(t0)", + "fetch outside the RAM" -> "lui t0, 0x10\njr t0", + "stores after a halt" -> "la t0, d\nebreak\nsw t0, 0(t0)\n.data\nd: .word 7" // must not store + ) + + "PipelinedCore" should "retire padded programs like the golden model" in { + simulate(new PipelinedSystem) { c => + for ((name, source) <- programs) + CoSim.compare(c, Asm.padded(source, nops), maxCycles = 2000).foreach(d => fail(s"$name: $d")) + for ((name, result) <- Seq("fib" -> 55, "fact" -> 120)) { + CoSim.compare(c, Asm.padded(Programs.source("programs/src", name), nops)).foreach(d => fail(s"$name: $d")) + assert(CoSim.reg(c, riscv.Reg("a0")) == result, name) + } + for (seed <- 1L to 10L) + CoSim.compare(c, Asm.padded(RandomProgram(seed), nops)).foreach(d => fail(s"RandomProgram($seed): $d")) + } + } + + // Unpadded, with the dependencies spaced by hand: younger instructions with side effects really sit + // in the pipeline when a jump redirects it or an instruction halts it + val flushed = Seq( + "a store in EX during a halt" -> "auipc t0, 0\nnop\nnop\nebreak\nsw t0, 0(t0)\nsw t0, 4(t0)", + "stores on the wrong path" -> "auipc t0, 0\nnop\nnop\nj 1f\nsw t0, 0(t0)\nsw t0, 4(t0)\n1: ecall" + ) + + it should "let no younger instruction take effect after a jump or a halt" in { + simulate(new PipelinedSystem) { c => + for ((name, source) <- flushed) CoSim.compare(c, Asm(source)).foreach(d => fail(s"$name: $d")) + } + } + + it should "need the padding: without it, an instruction reads a register before it is written" in { + simulate(new PipelinedSystem) { c => + val difference = CoSim.compare(c, Asm("li a0, 5\naddi a1, a0, 1\necall")) + assert(difference.exists(_.startsWith("instruction 1:")), difference) + } + } +} diff --git a/riscv/src/test/scala/riscv/RegressSpec.scala b/riscv/src/test/scala/riscv/RegressSpec.scala new file mode 100644 index 0000000..62213e3 --- /dev/null +++ b/riscv/src/test/scala/riscv/RegressSpec.scala @@ -0,0 +1,21 @@ +package riscv + +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +/** Replays riscv/programs/regress: programs that once exposed a bug, one test per program. */ +class RegressSpec extends AnyFlatSpec with ChiselSim { + val dir = "programs/regress" + val programs = Programs.names(dir) + + "The regression programs" should "be there" in { + assert(programs.nonEmpty) + } + + for (name <- programs) + they should s"retire $name on the single-cycle core as on the golden model" in { + simulate(new SingleCycleSystem) { c => + CoSim.compare(c, Asm(Programs.source(dir, name))).foreach(d => fail(d)) + } + } +} diff --git a/riscv/src/test/scala/riscv/SingleCycleSpec.scala b/riscv/src/test/scala/riscv/SingleCycleSpec.scala new file mode 100644 index 0000000..b585f35 --- /dev/null +++ b/riscv/src/test/scala/riscv/SingleCycleSpec.scala @@ -0,0 +1,140 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +class SingleCycleSpec extends AnyFlatSpec with ChiselSim { + private def unsigned(x: Int) = BigInt(Integer.toUnsignedLong(x)) + + "BranchUnit" should "decide branches like the golden model" in { + simulate(new BranchUnit) { c => + val rnd = new scala.util.Random(1) + val corners = Seq(0, 1, -1, Int.MaxValue, Int.MinValue) + def operand = if (rnd.nextInt(3) == 0) corners(rnd.nextInt(corners.size)) else rnd.nextInt() + for ( + (f3, name) <- Seq(0 -> "beq", 1 -> "bne", 4 -> "blt", 5 -> "bge", 6 -> "bltu", 7 -> "bgeu"); _ <- 0 until 300 + ) { + val (a, b) = if (rnd.nextInt(5) == 0) { val x = operand; (x, x) } + else (operand, operand) + c.io.funct3.poke(f3.U) + c.io.a.poke(unsigned(a).U) + c.io.b.poke(unsigned(b).U) + c.io.taken.expect(IsaSim.taken(name, a, b).B, s"$name $a, $b") + } + } + } + + "LoadExtend" should "take bytes and half-words out of the word like the golden model" in { + simulate(new LoadExtend) { c => + val rnd = new scala.util.Random(2) + for (_ <- 0 until 500; (f3, name) <- Seq(0 -> "lb", 1 -> "lh", 2 -> "lw", 4 -> "lbu", 5 -> "lhu")) { + val bytes = IsaSim.width(name) + val word = rnd.nextInt() + val offset = rnd.nextInt(4 / bytes) * bytes + val raw = (Integer.toUnsignedLong(word) >>> (8 * offset)) & ((1L << (8 * bytes)) - 1) + c.io.funct3.poke(f3.U) + c.io.offset.poke(offset.U) + c.io.rdata.poke(unsigned(word).U) + c.io.value.expect(unsigned(IsaSim.loadValue(name, raw)).U, f"$name offset $offset word 0x$word%08x") + } + } + } + + // Directed programs, one feature each. They run one after the other in one simulation: + // CoSim.load resets the core, but not the RAM or the registers, so each program writes the + // registers and the memory it reads. + val directed = Seq( + "arithmetic, immediates and x0" -> """ + li a0, 0x12345678 # lui + addi + lui a1, 0xfffff # a negative upper immediate + addi a2, a1, -1 + slti a3, a1, 0 # signed + sltiu a4, a1, 0 # unsigned + sub a5, zero, a0 + sra a6, a5, a3 + srai a7, a5, 31 + xori t0, a0, -1 + auipc t1, 0x10 + add zero, a0, a0 # x0 stays 0 + addi t2, zero, 0 + .word 0x0ff0008f # fence with rd = x1: writes nothing + ecall + """, + "branches and jumps" -> """ + li s0, -1 + li s1, 1 + blt s0, s1, 1f # taken (signed) + ebreak + 1: bltu s0, s1, 2f # not taken (unsigned) + bgeu s0, s1, 2f # taken + ebreak + 2: bne s0, s0, 3f # not taken + beq s0, s0, 3f # taken + ebreak + 3: jal ra, 4f + j 5f + 4: jalr t0, 0(ra) # back after the jal + 5: la t1, 6f + jalr zero, 1(t1) # bit 0 of the target is cleared + ebreak + 6: bne zero, zero, 2 # not taken: the misaligned target does not matter + la t2, 7f + jalr t2, 0(t2) # rd = rs1 + ebreak + 7: ecall + """, + "loads and stores" -> """ + la s0, d + li t0, 0x8081 + sh t0, 2(s0) + sb t0, 1(s0) + lb a0, 1(s0) + lbu a1, 1(s0) + lh a2, 2(s0) + lhu a3, 2(s0) + lw a4, 0(s0) + sw a4, 4(s0) + lw a5, 4(s0) + lw zero, 0(s0) # a load into x0 still reads + addi s1, s0, 8 + lw s1, -8(s1) # a load into its own base register, with a negative offset + ecall + .data + d: .word 0x11223344, 0 + """, + // the halts: each instruction that halts changes nothing + "ebreak" -> "ebreak", + "illegal (mret)" -> ".word 0x30200073", + "illegal (csrrw)" -> ".word 0x00001073", + "misaligned load" -> "la t0, x\nlw a0, 1(t0)\nx: nop", + "misaligned store" -> "la t0, x\nsh a0, 1(t0)\nx: nop", + "misaligned and outside" -> "li t0, 4\nlw a0, 2(t0)", + "misaligned branch" -> "beq zero, zero, 2", + "misaligned jal" -> "jal ra, 2", + "misaligned jalr" -> "la ra, x\njalr ra, 2(ra)\nx: nop", + "load outside the RAM" -> "li t0, 4\nlw a0, 0(t0)", + "store outside the RAM" -> "li t0, 4\nsw t0, 0(t0)", + "fetch outside the RAM" -> "lui t0, 0x10\njr t0" + ) + + def program(name: String): String = Programs.source("programs/src", name) + + "SingleCycleCore" should "retire directed programs, every halt, and the committed programs like the golden model" in { + simulate(new SingleCycleSystem) { c => + for ((name, source) <- directed) + CoSim.compare(c, Asm(source), maxCycles = 1000).foreach(d => fail(s"$name: $d")) + for ((name, result) <- Seq("fib" -> 55, "fact" -> 120)) { + CoSim.compare(c, Asm(program(name))).foreach(d => fail(s"$name: $d")) + assert(CoSim.reg(c, riscv.Reg("a0")) == result, name) // the core has halted; a0 holds the result + } + } + } + + it should "retire random programs like the golden model" in { + simulate(new SingleCycleSystem) { c => + for (seed <- 1L to 20L) + CoSim.compare(c, Asm(RandomProgram(seed))).foreach(d => fail(s"RandomProgram($seed): $d")) + } + } +} diff --git a/riscv/src/test/scala/riscv/SocSpec.scala b/riscv/src/test/scala/riscv/SocSpec.scala new file mode 100644 index 0000000..82fbbe4 --- /dev/null +++ b/riscv/src/test/scala/riscv/SocSpec.scala @@ -0,0 +1,63 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +class SocSpec extends AnyFlatSpec with ChiselSim { + + "UartTx" should "send each byte as a start bit, 8 data bits (LSB first) and a stop bit" in { + for (divider <- Seq(1, 4, 7)) simulate(new UartTx(divider)) { c => + val receiver = new UartReceiver(divider) + val text = "Hi!\u0000ÿ" + val out = new StringBuilder + var pending = text.toList + var cycles = 0 + while (out.size < text.size && cycles < 20 * divider * text.size) { + val busy = c.io.busy.peek().litToBoolean + c.io.send.valid.poke((!busy && pending.nonEmpty).B) + c.io.send.bits.poke(pending.headOption.getOrElse(0.toChar).toInt.U) + if (!busy && pending.nonEmpty) pending = pending.tail + out ++= receiver.sample(c.io.txd.peek().litToBoolean) + c.clock.step() + cycles += 1 + } + assert(out.toString == text && receiver.framingErrors == 0, s"divider $divider") + // a frame takes 10 bits of `divider` cycles, and the next byte is taken one cycle after it + assert(cycles <= (10 * divider + 1) * text.size + 2 * divider, s"divider $divider: $cycles cycles") + } + } + + "SocSystem" should "print Hello, world through the UART" in { + simulate(new SocSystem) { c => + val image = Asm(Programs.source("programs/src", "hello")) + CoSim.compare(c, image).foreach(d => fail(d)) // on the bus, as on the model + CoSim.load(c, image) + assert(Soc.run(c) == "Hello, world!\n") + val uart = new UartModel // and the golden model printed the same + new IsaSim(image, devices = Seq(uart)).run() + assert(uart.output.toString == "Hello, world!\n") + } + } + + it should "run programs through the bus as the golden model does" in { + simulate(new SocSystem) { c => + for ((name, image) <- Programs.corpus(seeds = 1L to 5L)) + CoSim.compare(c, image).foreach(d => fail(s"$name: $d")) + } + } + + it should "answer an address that no device holds with an error, and read the UART's status" in { + simulate(new SocSystem) { c => + val programs = Seq( + "li t0, 0x20000000\nlw a0, 0(t0)", // unmapped: halts with BadAddress + "li t0, 0x10000000\nli a0, 65\nsb a0, 0(t0)\nlw a1, 4(t0)\necall" // status (the model reads 0) + ) + CoSim.compare(c, Asm(programs(0))).foreach(d => fail(d)) + CoSim.load(c, Asm(programs(1))) + val trace = CoSim.run(c) + assert(trace.last.halt.contains(Halt.Ecall)) + assert(CoSim.reg(c, riscv.Reg("a1")) == 1, "the UART is still sending the byte") + } + } +} diff --git a/riscv/src/test/scala/riscv/SynthSpec.scala b/riscv/src/test/scala/riscv/SynthSpec.scala new file mode 100644 index 0000000..7912bc1 --- /dev/null +++ b/riscv/src/test/scala/riscv/SynthSpec.scala @@ -0,0 +1,37 @@ +package riscv + +import chisel3._ +import chisel3.simulator.scalatest.ChiselSim +import org.scalatest.flatspec.AnyFlatSpec + +class SynthSpec extends AnyFlatSpec with ChiselSim { + + "Ulx3sTop" should "boot its program into the RAM, run it, and print through the UART" in { + val divider = 4 + simulate(new Ulx3sTop(Asm(Programs.source("programs/src", "hello")), clockHz = 100 * divider, baud = 100)) { c => + c.reset.poke(true.B) + c.clock.step() + c.reset.poke(false.B) + val out = Soc.listen(c.clock, c.ftdi_rxd, (c.led.peek().litValue & 2) != 0, divider, maxCycles = 20000) + assert(out == "Hello, world!\n", out) + assert((c.led.peek().litValue & 3) == 3, "LED 0: booted; LED 1: halted") + } + } + + "Synth" should "synthesize the decoders, the hand-written one smaller" in { + assume(Yosys.available, "yosys is not on the PATH") + val (table, hand) = (Synth.cells(new Decoder, "ice40"), Synth.cells(new SwitchDecoder, "ice40")) + assert(hand.luts > 0 && hand.luts < table.luts && table.flipFlops == 0, s"$table, $hand") + } + + it should "fit the board's system in the smallest ULX3S (LFE5U-12F: 12K LUTs, 32 block RAMs)" in { + assume(Yosys.available, "yosys is not on the PATH") + val c = Synth.cells(new Ulx3sTop(Asm(Programs.source("programs/src", "hello"))), "ecp5") + assert(c.luts > 1000 && c.luts + 2 * c.lutRams < 12000 && c.blockRams <= 32 && c.flipFlops > 0, c.toString) + } + + "Synth.lint" should "run Verilator's lint on a design" in { + val warnings = Synth.lint(new Decoder) // a Module whose clock and reset the decoder does not use + assert(warnings.nonEmpty && warnings.forall(_.contains("UNUSEDSIGNAL")), warnings.mkString("\n")) + } +} diff --git a/runtest.py b/runtest.py index a3fff11..a975b16 100755 --- a/runtest.py +++ b/runtest.py @@ -7,23 +7,28 @@ Usage: runtest.py [notebook_name.ipynb] [notebook_name_2.ipynb] [...] """ + import itertools import json import os import queue +import re +import shutil import subprocess import sys import time from typing import Dict, List, Tuple -from jupyter_client.manager import start_new_kernel - ROOT = os.path.dirname(os.path.abspath(__file__)) # The first cell downloads and compiles dependencies, each `simulate` runs Verilator. CELL_TIMEOUT = int(os.environ.get("BOOTCAMP_CELL_TIMEOUT", "600")) NOT_IMPLEMENTED = "scala.NotImplementedError" +# A deprecated API makes the kernel print a deprecation warning (see `source/load-ivy.sc`); it is +# reported as an error so that deprecations do not creep back in. Notebooks must therefore not +# print the word themselves. +DEPRECATION = re.compile(r"^.*\bdeprecat.*$", re.IGNORECASE | re.MULTILINE) COMPILATION_FAILED = "Compilation Failed" @@ -32,6 +37,9 @@ def _notebook_run(path: str) -> List[Tuple[int, str]]: :returns the errors as a list of (cell index, ": "). """ + # Imported here so that other scripts can import `notebooks` without Jupyter installed + from jupyter_client.manager import start_new_kernel + with open(path, encoding="utf-8") as f: nb = json.load(f) @@ -62,7 +70,12 @@ def _notebook_run(path: str) -> List[Tuple[int, str]]: break if msg["parent_header"].get("msg_id") != msg_id: continue - if msg["msg_type"] == "error": + if msg["msg_type"] == "stream": + errors += [ + (index, "Deprecation: " + m.group(0).strip()) + for m in DEPRECATION.finditer(msg["content"]["text"]) + ] + elif msg["msg_type"] == "error": content = msg["content"] errors.append((index, "{}: {}".format(content["ename"], content["evalue"]))) elif msg["msg_type"] == "status" and msg["content"]["execution_state"] == "idle": @@ -93,8 +106,7 @@ def check_errors(file_name: str, expected: List[str], actual: List[Tuple[int, st print("=" * 100, file=sys.stderr) print(f"Errors detected in {file_name}", file=sys.stderr) got = "-- No Error --" if a is None else f"cell {a[0]}: {a[1][:100]!r}" - print(f"No match for {i}-th expected error {e if e else '-- No Error --'!r}, got {got}", - file=sys.stderr) + print(f"No match for {i}-th expected error {e if e else '-- No Error --'!r}, got {got}", file=sys.stderr) return_value = False if not return_value: print("=" * 100, file=sys.stderr) @@ -112,23 +124,37 @@ def check_errors(file_name: str, expected: List[str], actual: List[Tuple[int, st "2.4_sequential_logic.ipynb": [NOT_IMPLEMENTED] * 2, "2.5_exercise.ipynb": [NOT_IMPLEMENTED] * 3, "2.6_chiselsim.ipynb": [], + "2.7_enums_and_bundles.ipynb": [NOT_IMPLEMENTED] * 3, + "2.8_memories.ipynb": [NOT_IMPLEMENTED] * 2, "3.1_parameters.ipynb": ["java.util.NoSuchElementException"], "3.2_collections.ipynb": [NOT_IMPLEMENTED], "3.2_interlude.ipynb": [], - "3.3_higher-order_functions.ipynb": [NOT_IMPLEMENTED] + - ["java.lang.UnsupportedOperationException"] + - [NOT_IMPLEMENTED] * 3, + "3.3_higher-order_functions.ipynb": [NOT_IMPLEMENTED] + + ["java.lang.UnsupportedOperationException"] + + [NOT_IMPLEMENTED] * 3, "3.4_functional_programming.ipynb": [NOT_IMPLEMENTED, COMPILATION_FAILED, NOT_IMPLEMENTED, COMPILATION_FAILED], "3.5_object_oriented_programming.ipynb": [], - "3.6_types.ipynb": ["ChiselException: Connection between sink"] + - ["I give up!"] + - ['expected ")"'] + - [NOT_IMPLEMENTED] * 2 + - [COMPILATION_FAILED] * 4, + "3.6_types.ipynb": ["ChiselException: Connection between sink"] + + ["I give up!"] + + ['expected ")"'] + + [NOT_IMPLEMENTED] * 2 + + [COMPILATION_FAILED] * 4, "4.1_firrtl_ast.ipynb": [NOT_IMPLEMENTED], "4.2_firrtl_ast_traversal.ipynb": [NOT_IMPLEMENTED], "4.3_firrtl_common_idioms.ipynb": [NOT_IMPLEMENTED], "4.4_firrtl_add_ops_per_module.ipynb": [NOT_IMPLEMENTED], + "5.1_riscv_isa.ipynb": [NOT_IMPLEMENTED], + "5.2_alu_and_regfile.ipynb": [NOT_IMPLEMENTED] * 2, + "5.3_decoder.ipynb": [NOT_IMPLEMENTED] * 4, + "5.4_single_cycle.ipynb": [NOT_IMPLEMENTED] * 5, + "5.5_compliance.ipynb": [NOT_IMPLEMENTED], + "5.6_pipeline.ipynb": [NOT_IMPLEMENTED] * 5, + "5.7_hazards.ipynb": [NOT_IMPLEMENTED] * 4, + "5.8_bus_and_mmio.ipynb": [NOT_IMPLEMENTED] * 3, + # without Yosys, the formal check of the `Forward` exercise prints a note instead of building it + "5.9_debug_and_verify.ipynb": [NOT_IMPLEMENTED] + * (6 if shutil.which("yosys") or shutil.which("yowasp-yosys") else 5), + "5.10_to_silicon.ipynb": [NOT_IMPLEMENTED] * 6, } if __name__ == "__main__": diff --git a/source/jupyter_server_config.py b/source/jupyter_server_config.py index 4fce8aa..8d2969f 100644 --- a/source/jupyter_server_config.py +++ b/source/jupyter_server_config.py @@ -1,7 +1,7 @@ # Jupyter Server Configuration # Optimized for Docker container use with minimal warnings -c = get_config() #noqa +c = get_config() # noqa # Fix websocket ping timeout warning # Set both to same value to avoid timeout > interval warning @@ -11,8 +11,8 @@ # Disable authentication for local Docker use # This eliminates cookie expiration, 403, and WebSocket auth warnings c.ServerApp.disable_check_xsrf = True -c.IdentityProvider.token = '' -c.ServerApp.allow_origin = '*' +c.IdentityProvider.token = "" +c.ServerApp.allow_origin = "*" c.ServerApp.allow_credentials = True # Disable history manager to suppress Almond kernel history_request errors @@ -25,15 +25,17 @@ # Keep INFO level for essential startup messages (URL, port, etc) # but suppress specific noisy loggers -c.ServerApp.log_level = 'INFO' +c.ServerApp.log_level = "INFO" # Suppress tornado HTTP warnings (403, cookie errors) import logging -logging.getLogger('tornado.access').setLevel(logging.ERROR) -logging.getLogger('tornado.application').setLevel(logging.ERROR) + +logging.getLogger("tornado.access").setLevel(logging.ERROR) +logging.getLogger("tornado.application").setLevel(logging.ERROR) # Suppress LabApp schema validation warnings -logging.getLogger('LabApp').setLevel(logging.ERROR) +logging.getLogger("LabApp").setLevel(logging.ERROR) + # Create a custom filter to suppress specific warning messages class SuppressWarnings(logging.Filter): @@ -44,21 +46,36 @@ def filter(self, record): msg = record.getMessage() # Suppress specific warnings - return not any([ - 'All authentication is disabled' in msg, - 'Clearing invalid/expired login cookie' in msg, - 'is not trusted' in msg, - 'Could not determine jupyterlab build status' in msg - ]) + return not any( + [ + "All authentication is disabled" in msg, + "Clearing invalid/expired login cookie" in msg, + "is not trusted" in msg, + "Could not determine jupyterlab build status" in msg, + ] + ) + # Apply the filter to ServerApp logger -server_logger = logging.getLogger('ServerApp') +server_logger = logging.getLogger("ServerApp") server_logger.addFilter(SuppressWarnings()) # Hide system and build files from file browser # Students only need to see notebook files (*.ipynb) c.ContentsManager.hide_globs = [ - 'almond', 'coursier', 'Dockerfile', 'LICENSE', - 'Install.md', 'README.md', 'runtest.py', - 'binder', 'images', 'source' + "almond", + "coursier", + "Dockerfile", + "LICENSE", + "Install.md", + "README.md", + "runtest.py", + "binder", + "images", + "source", ] + +# The image has the Scala kernel only (it leaves out the Python kernel that JupyterLab installs): +# make it the default, and do not look for the Python one +c.MultiKernelManager.default_kernel_name = "scala" +c.KernelSpecManager.ensure_native_kernel = False diff --git a/source/load-ivy.sc b/source/load-ivy.sc index 0a73c93..75279d0 100644 --- a/source/load-ivy.sc +++ b/source/load-ivy.sc @@ -6,7 +6,12 @@ import $plugin.$ivy.`org.chipsalliance:::chisel-plugin:7.16.0` // only accepts with the reflectiveCalls language feature. // * Chisel 7's dependencies put Scala 3 (TASTy) classes on the classpath; without // -Ytasty-reader, e.g. `import scala.util.Random` fails with "Missing dependency ... TASTy". -interp.configureCompiler(_.settings.processArguments(List("-language:reflectiveCalls", "-Ytasty-reader"), processAll = true)) +// * Deprecations: the kernel prints a warning that names each deprecated call in a cell, and +// runtest.py fails on it. Code in this file only gets a summary line ("1 deprecation ...; +// re-run enabling -deprecation for details"), and adding -deprecation here changes nothing. +interp.configureCompiler( + _.settings.processArguments(List("-language:reflectiveCalls", "-Ytasty-reader"), processAll = true) +) // Uncomment and change to use proxy // System.setProperty("https.proxyHost", "proxy.example.com") @@ -19,64 +24,177 @@ import $ivy.`org.scalatest::scalatest:3.2.19` // firtool automatically (the `llvm-firtool` artifact) on first use. Simulation with // ChiselSim (chisel3.simulator) additionally needs Verilator 5.x and a C++ toolchain. -// Almond 0.14.5 cannot report an exception whose stack trace Ammonite has trimmed to "..." -// frames: the cell then never finishes. That happens to errors raised while Chisel -// elaborates a module (e.g. a `???` exercise inside `new MyModule`). `scrub` drops the +// Almond 0.14.5 cannot report an exception whose stack trace has "..." frames, which Chisel puts +// in the stack traces of errors raised while it elaborates a module (e.g. a `???` exercise inside +// `new MyModule`): the cell then never finishes (see docs/troubleshooting.md). `scrub` drops the // (uninteresting) stack traces of such exceptions so that the error message is shown. def scrub[T](body: => T): T = try body catch { // not the fatal ones (as `scala.util.control.NonFatal`, which this file cannot import before // `-Ytasty-reader` is set): `???` is a NotImplementedError, an `Error`, so it must be caught - case e: Throwable if !(e.isInstanceOf[VirtualMachineError] || e.isInstanceOf[LinkageError] || - e.isInstanceOf[InterruptedException]) => + case e: Throwable + if !(e.isInstanceOf[VirtualMachineError] || e.isInstanceOf[LinkageError] || + e.isInstanceOf[InterruptedException]) => var t: Throwable = e while (t != null) { t.setStackTrace(Array.empty); t = t.getCause } throw e } -// Convenience function to invoke Chisel and grab emitted SystemVerilog. -def getVerilog(dut: => chisel3.RawModule): String = - scrub(circt.stage.ChiselStage.emitSystemVerilog(dut)) +// Convenience function to invoke Chisel and grab emitted SystemVerilog. Chisel 7 puts assertions +// in verification layers, extra files that follow the module (after a `// ----- 8< ----- FILE` +// line each, as firtool 1.160 writes them: recheck when FIRTOOL_VERSION changes); those of a +// module without assertions only hold include guards, and are then left out (all of them; one with +// an assertion keeps them all, as they include each other). +def getVerilog(dut: => chisel3.RawModule): String = { + val sv = scrub(circt.stage.ChiselStage.emitSystemVerilog(dut)) + val marker = "// ----- 8< ----- FILE" + val parts = sv.split(s"(?m)^(?=${java.util.regex.Pattern.quote(marker)})") + def guardsOnly(part: String) = part.linesIterator.drop(1).map(_.trim).forall { l => + l.isEmpty || l.startsWith("`ifndef") || l.startsWith("`define") || l.startsWith("`endif") || + l.startsWith("`include") || l.startsWith("//") + } + val (layers, design) = parts.partition(_.startsWith(marker)) + (if (layers.forall(guardsOnly)) design else parts).mkString.stripTrailing + "\n" +} // Convenience function to invoke Chisel and grab emitted FIRRTL. def getFirrtl(dut: => chisel3.RawModule): String = scrub(circt.stage.ChiselStage.emitCHIRRTL(dut)) // ChiselSim's `EphemeralSimulator.simulate`: elaborates `module`, compiles it with Verilator and -// runs `body` against it. Two differences, so that the notebooks stay short: +// runs `body` against it. Two differences and two options, so that the notebooks stay short: // * errors go through `scrub`; // * a `Module` is reset for one clock cycle before `body` runs, like chiseltest's `test` -// did. (ChiselSim itself leaves the reset to you: until it is asserted, registers hold -// random values.) +// did, and like the `simulate` of ChiselSim's ScalaTest trait. (`simulateRaw`, which this one +// calls, and EphemeralSimulator's `simulate` leave the reset to you: until it is asserted, +// registers hold random values.) +// * the option `randomization` chooses the initial values of registers and memories. ChiselSim's +// default randomizes both; `Randomization.random.copy(memories = false)` leaves memories alone, +// which a memory loaded from a file needs (the random values would overwrite its contents). +// * the option `waves = "name"` dumps a VCD waveform from time zero into build/name/ (kept after +// the simulation, unlike the temporary directory used otherwise) and prints its path. // The `poke`/`peek`/`expect` methods come from `import chisel3.simulator.PeekPokeAPI._`. -def simulate[T <: chisel3.RawModule](module: => T)(body: T => Unit): Unit = { +def simulate[T <: chisel3.RawModule]( + module: => T, + randomization: chisel3.simulator.Randomization = chisel3.simulator.Randomization.random, + waves: String = "" +)(body: T => Unit): Unit = { import chisel3.fromBooleanToLiteral import chisel3.simulator.PeekPokeAPI._ - scrub(chisel3.simulator.EphemeralSimulator.simulate(module) { dut => - dut match { - case m: chisel3.Module => - m.reset.poke(true.B) - m.clock.step(1) - m.reset.poke(false.B) - case _ => - } - body(dut) - }) + import chisel3.simulator.{ChiselSim, LayerControl, Settings} + import svsim.verilator.Backend.CompilationSettings.{TraceKind, TraceStyle} + require(waves.matches("[A-Za-z0-9_-]*"), s"waves: use letters, digits, '_' and '-' only, not '$waves'") + val waveDir = Option.when(waves.nonEmpty)(wavesDir(waves)) + // what EphemeralSimulator.simulate does, with the two options added + implicit val directory: chisel3.testing.HasTestingDirectory = waveDir match { + case Some(dir) => new chisel3.testing.HasTestingDirectory { def getDirectory = dir.toNIO } + case None => chisel3.testing.HasTestingDirectory.temporary(deleteOnExit = true) + } + // VCD support, as ChiselSim's -DemitVcd=1 test option sets it for Verilator + implicit val backendSettings: svsim.BackendSettingsModifications = { + case s: svsim.verilator.Backend.CompilationSettings if waveDir.nonEmpty => + s.withTraceStyle(Some(TraceStyle(TraceKind.Vcd))) + case s => s + } + val settings = + Settings + .defaultRaw[T] + .copy( + verilogLayers = LayerControl.EnableAll, + randomization = randomization, + enableWavesAtTimeZero = waveDir.nonEmpty + ) + try + scrub(new ChiselSim {}.simulateRaw(module, settings = settings) { dut => + dut match { + case m: chisel3.Module => + m.reset.poke(true.B) + m.clock.step(1) + m.reset.poke(false.B) + case _ => + } + body(dut) + }) + finally // also when the test fails, which is when the waves are most useful + if (waves.nonEmpty) wavesFile(waves).foreach(vcd => println(s"Waveform: $vcd")) +} + +// Where `simulate(..., waves = name)` writes its files. +def wavesDir(name: String): os.Path = os.pwd / "build" / name + +// The VCD file written by `simulate(..., waves = name)`, if there is one. +def wavesFile(name: String): Option[os.Path] = { + val dir = wavesDir(name) + if (os.exists(dir)) os.walk(dir).find(_.ext == "vcd") else None } +// Start and stop dumping waves inside a `simulate(..., waves = "name")` body, for example to +// skip an uninteresting start-up phase. (Without `waves`, the simulation has no trace support and +// these fail.) +object waveControl extends chisel3.simulator.ControlAPI // Chisel has no ControlAPI object to import +def enableWaves(): Unit = waveControl.enableWaves() +def disableWaves(): Unit = waveControl.disableWaves() + // Visualization: turn the FIRRTL emitted by Chisel into a Graphviz graph. // FIRRTL (spec 4.x, as emitted by Chisel 7) is line-oriented text, so a few regular // expressions are enough to recover ports, registers, wires, nodes and connections. def firrtlToDot(firrtlString: String): String = { val lines = firrtlString.split("\n").map(_.replaceAll("@\\[.*\\]", "")) - def sanitize(name: String): String = name.replaceAll("\\[([A-Za-z0-9_.]+)\\]", "_$1").replaceAll("[^a-zA-Z0-9_]", "_") - // A (possibly sub-field / sub-index) reference, e.g. `io.in` or `zs[1]`. - // Names directly followed by `(` are primitive operations (`add(a, b)`), not signals. - val ident = "[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*|\\[[A-Za-z_][A-Za-z0-9_.]*\\]|\\[[0-9]+\\])*(?![A-Za-z0-9_(])".r + // The references in an expression: a name, then any `.field` and `[index]`, where an index is a + // number or itself a reference (`io.v[io.idx[0]]`, `w[i][j]`). A name directly followed by `(` is + // a primitive operation (`add(a, b)`), not a signal. + def isNameStart(c: Char) = c.isLetter || c == '_' + def isNamePart(c: Char) = c.isLetterOrDigit || c == '_' + def references(expr: String): Seq[String] = { + val found = scala.collection.mutable.ArrayBuffer[String]() + var i = 0 + def name(): Unit = while (i < expr.length && isNamePart(expr(i))) i += 1 + while (i < expr.length) + if (isNameStart(expr(i)) && (i == 0 || !isNamePart(expr(i - 1)))) { + val start = i + name() + var more = true + while (more && i < expr.length) + if (expr(i) == '.' && i + 1 < expr.length && isNameStart(expr(i + 1))) { i += 1; name() } + else if (expr(i) == '[') { + var depth = 1 // up to the matching `]` + i += 1 + while (depth > 0 && i < expr.length) { + if (expr(i) == '[') depth += 1 else if (expr(i) == ']') depth -= 1 + i += 1 + } + } else more = false + if (i >= expr.length || expr(i) != '(') found += expr.substring(start, i) + } else i += 1 + found.toSeq + } + def isFixed(index: String) = index.forall(_.isDigit) // `v[0]`, not `v[i]` + // A reference without its indices, as it was declared: `io.v.a` of `io.v[io.idx[0]].a` + def unindexed(ref: String): String = { + var depth = 0 + ref.filter { c => + if (c == '[') depth += 1 + val outside = depth == 0 + if (c == ']') depth -= 1 + outside + } + } + // The [start, end] of each outermost `[...]` of a reference: `w[i][j]` has two, `v[idx[0]]` one + def brackets(ref: String): Seq[(Int, Int)] = { + var depth = 0 + var open = 0 + ref.indices.flatMap { i => + ref(i) match { + case '[' => if (depth == 0) open = i; depth += 1; None + case ']' => depth -= 1; if (depth == 0) Some(open -> i) else None + case _ => None + } + } + } val literal = "(?:UInt|SInt)(?:<[0-9]+>)?\\([^)]*\\)".r // e.g. UInt<1>(0h1) - val primOp = "^([a-z0-9_]+)\\(.*".r // e.g. add(a, b) + val primOp = "^([a-z0-9_]+)\\(.*".r // e.g. add(a, b) val declPort = "^(input|output) ([A-Za-z0-9_]+) : (.*)".r val declReg = "^(?:reg|regreset) ([A-Za-z0-9_]+) :.*".r @@ -89,11 +207,13 @@ def firrtlToDot(firrtlString: String): String = { val edges = scala.collection.mutable.LinkedHashSet[(String, String)]() val opLabel = scala.collection.mutable.LinkedHashMap[String, String]() val circuit = "^circuit ([A-Za-z0-9_]+) :.*".r - val module = "^(?:public )?(?:module|extmodule) ([A-Za-z0-9_]+) :.*".r - val top = lines.iterator.map(_.trim).collectFirst { case circuit(n) => n } + val module = "^(?:public )?(?:module|extmodule) ([A-Za-z0-9_]+) :.*".r + val top = lines.iterator + .map(_.trim) + .collectFirst { case circuit(n) => n } .getOrElse(throw new IllegalArgumentException("FIRRTL circuit name is missing")) - val controls = scala.collection.mutable.LinkedHashSet[(String, String)]() - val instance = "^inst ([A-Za-z0-9_]+) of ([A-Za-z0-9_]+).*".r + val controls = scala.collection.mutable.LinkedHashSet[(String, String)]() + val instance = "^inst ([A-Za-z0-9_]+) of ([A-Za-z0-9_]+).*".r val moduleLines = scala.collection.mutable.LinkedHashMap[String, scala.collection.mutable.ArrayBuffer[String]]() var currentModule: Option[String] = None lines.foreach { raw => @@ -107,65 +227,89 @@ def firrtlToDot(firrtlString: String): String = { // Bundle-typed ports look like `output io : { flip in : UInt<8>, bus : { out : UInt<8> } }`. // A field is an input if an even number of `flip`s (its own and its parents') applies to it. - val portToken = "\\{|\\}|(flip )?([A-Za-z0-9_]+) :".r + val portToken = "\\{|\\}|(flip )?([A-Za-z0-9_]+) :".r def addPort(dir: String, name: String, tpe: String): Unit = { - def add(path: String, isInput: Boolean): Unit = (if (isInput) inputs else outputs) += sanitize(path) + def add(path: String, isInput: Boolean): Unit = (if (isInput) inputs else outputs) += path if (!tpe.startsWith("{")) add(name, dir == "input") else { - var scopes = List((name, dir == "input")) - var pending = Option.empty[(String, Boolean)] // the last field, until we know if it is a leaf + var scopes = List((name, dir == "input")) + var pending = Option.empty[(String, Boolean)] // the last field, until we know if it is a leaf def flush(): Unit = { pending.foreach(p => add(p._1, p._2)); pending = None } portToken.findAllMatchIn(tpe).foreach { m => m.matched match { case "{" => pending.foreach(p => scopes ::= p); pending = None case "}" => flush(); scopes = scopes.tail - case _ => + case _ => flush() val (path, isInput) = scopes.head - pending = Some((path + "_" + m.group(2), isInput ^ (m.group(1) != null))) + pending = Some((path + "." + m.group(2), isInput ^ (m.group(1) != null))) } } } } - val dynamic = "\\[([A-Za-z_][A-Za-z0-9_.]*)\\]".r - val index = "\\[([A-Za-z_][A-Za-z0-9_.]*|[0-9]+)\\]".r - val fixedSelections = scala.collection.mutable.LinkedHashSet[(String, String)]() - val dynamicReads = scala.collection.mutable.LinkedHashSet[String]() - val dynamicWrites = scala.collection.mutable.LinkedHashSet[String]() + val fixedSelections = scala.collection.mutable.LinkedHashSet[(String, String)]() + val reads = scala.collection.mutable.LinkedHashSet[String]() // what each expression reads + val writes = scala.collection.mutable.LinkedHashSet[String]() // and drives + val dynamicReads = scala.collection.mutable.LinkedHashSet[String]() + val dynamicWrites = scala.collection.mutable.LinkedHashSet[String]() + val dynamicSelections = scala.collection.mutable.Set[String]() // `w[i]`, and `w[i][0]` of it def visit(moduleName: String, prefix: String, ancestors: Set[String]): Unit = { if (ancestors(moduleName)) throw new IllegalArgumentException("Recursive FIRRTL module: " + moduleName) - val body = moduleLines.getOrElse(moduleName, - throw new IllegalArgumentException("FIRRTL module definition is missing: " + moduleName)) - def scoped(name: String): String = sanitize(prefix + name) + val body = moduleLines.getOrElse( + moduleName, + throw new IllegalArgumentException("FIRRTL module definition is missing: " + moduleName) + ) + // A node is named by its FIRRTL reference, scoped by the instances it is in, the index of a + // dynamic selection too (`a.v[a.i]`); references that differ stay different nodes (#18). + def scoped(ref: String): String = { + val name = new StringBuilder(prefix) + var from = 0 + brackets(ref).foreach { case (open, close) => + val index = ref.substring(open + 1, close) + name ++= ref.substring(from, open) ++= "[" ++= (if (isFixed(index)) index else scoped(index)) ++= "]" + from = close + 1 + } + (name ++= ref.substring(from)).toString + } + + // A selection is drawn from its base (written: to it) and, for a dynamic one, from its index; + // the base and the index are references of their own (`w[i]` of `w[i][j]`). A fixed selection + // (`v[0]`) is joined to its base only if the base is also selected dynamically (see below), or is + // itself a dynamic selection (`w[i][0]`). def reference(ref: String, write: Boolean = false): String = { val selected = scoped(ref) - index.findAllMatchIn(ref).foreach { m => - val base = scoped(ref.substring(0, m.start)) - if (m.group(1).forall(_.isDigit)) fixedSelections += (base -> selected) - else if (write) dynamicWrites += base - else dynamicReads += base - } - dynamic.findAllMatchIn(ref).foreach { m => - val base = ref.substring(0, m.start) - if (write) edges += (selected -> scoped(base)) - else edges += (scoped(base) -> selected) - edges += (scoped(m.group(1)) -> selected) + brackets(ref).lastOption.foreach { case (open, close) => + val base = reference(ref.substring(0, open), write) + val index = ref.substring(open + 1, close) + if (isFixed(index) && !dynamicSelections(base)) fixedSelections += (base -> selected) + else { + if (write) edges += (selected -> base) else edges += (base -> selected) + if (!isFixed(index)) { + (if (write) dynamicWrites else dynamicReads) += base + sources(index).foreach(s => edges += (s -> selected)) + } + dynamicSelections += selected + } } selected } - def sources(expr: String): Seq[String] = - ident.findAllIn(literal.replaceAllIn(expr, "")).filterNot(Set("clock", "reset")).map(ref => reference(ref)).toSeq + def sources(expr: String): Seq[String] = { + val read = references(literal.replaceAllIn(expr, "")).filterNot(Set("clock", "reset")).map(ref => reference(ref)) + reads ++= read + read + } - var conditions = List.empty[(Int, Seq[String])] + var conditions = List.empty[(Int, Seq[String])] var previousConditions = Map.empty[Int, Seq[String]] // `expr` drives `target`, as does every enclosing `when` condition (the dashed edges) def drive(expr: String, target: String): Unit = { sources(expr).foreach(s => edges += (s -> target)) + writes += target conditions.flatMap(_._2).foreach(s => controls += (s -> target)) } body.foreach { raw => - val line = raw.trim + val line = raw.trim val indent = raw.takeWhile(_ == ' ').length if (line.nonEmpty) { while (conditions.nonEmpty && conditions.head._1 >= indent) { @@ -179,48 +323,81 @@ def firrtlToDot(firrtlString: String): String = { previousConditions -= indent } else if (line == "else :") { conditions = (indent -> previousConditions.getOrElse(indent, Seq.empty)) :: conditions - } else line match { - case instance(n, child) => visit(child, prefix + n + ".", ancestors + moduleName) - case declPort(dir, n, tpe) => - if (prefix.isEmpty && n != "clock" && n != "reset") addPort(dir, n, tpe) - case declReg(n) => regs += scoped(n) - case declNode(n, expr) => - expr match { case primOp(op) => opLabel(scoped(n)) = op; case _ => } - drive(expr, scoped(n)) - case connect(dst, src) => - val target = reference(dst.trim, write = true) - drive(src, target) - case _ => - } + } else + line match { + case instance(n, child) => visit(child, prefix + n + ".", ancestors + moduleName) + case declPort(dir, n, tpe) => + if (prefix.isEmpty && n != "clock" && n != "reset") addPort(dir, n, tpe) + case declReg(n) => regs += scoped(n) + case declNode(n, expr) => + expr match { case primOp(op) => opLabel(scoped(n)) = op; case _ => } + drive(expr, scoped(n)) + case connect(dst, src) => + val target = reference(dst.trim, write = true) + drive(src, target) + case _ => + } } } } visit(top, "", Set.empty) + // A whole vector or bundle and its parts (`w` and `w[0]`, `io` and `io.a`) are the same wires: what + // is written to one reaches what reads the other (`connect w[0], a` then `connect out, w`). An input + // port's fields are written from outside, and an output port's are read there (`connect o, r`). + // A dynamic selection is already joined to its base (`w` of `w[i]`), so the wholes stop at it. + def wholes(part: String): Seq[String] = { // `w` and `w[0]` of `w[0].a`; not inside an index + val from = brackets(part).filterNot { case (o, c) => isFixed(part.substring(o + 1, c)) }.lastOption.fold(-1)(_._1) + var depth = 0 + part.indices.flatMap { i => + val cut = depth == 0 && i > from && (part(i) == '.' || part(i) == '[') + if (part(i) == '[') depth += 1 else if (part(i) == ']') depth -= 1 + if (cut) Some(part.substring(0, i)) else None + } + } + val written = writes ++ inputs + val read = reads ++ outputs + val used = written ++ read + for (part <- used; whole <- wholes(part) if used(whole)) { + if (written(part) && read(whole)) edges += (part -> whole) + if (written(whole) && read(part)) edges += (whole -> part) + } + // What is written through a dynamic selection may reach any fixed one of the same base, and the + // other way round; this carries down a nested vector (`w[0][1]` beside `w[i][j]`), as a base is + // recorded before its selections. fixedSelections.foreach { case (base, selected) => - if (dynamicWrites(base)) edges += (base -> selected) - if (dynamicReads(base)) edges += (selected -> base) + if (dynamicWrites(base)) { edges += (base -> selected); dynamicWrites += selected } + if (dynamicReads(base)) { edges += (selected -> base); dynamicReads += selected } } - // Sub-fields and indices (`zs[1]`) are sanitized into `zs_1`, so they are matched with - // their declaration by prefix. - def declaredAs(node: String, set: scala.collection.Set[String]): Boolean = - set.exists(d => node == d || node.startsWith(d + "_")) + // A node is what was declared, or a sub-field or element of it: `zs[1]` of `zs`, `io.v[0].a` of the + // port field `io.v.a` (the declaration has no indices). A node whose name merely starts with a + // declared one (`foo_tmp` beside a port `foo`) is not (#19). + def declaredAs(path: String, set: scala.collection.Set[String]): Boolean = + set.exists(d => path == d || path.startsWith(d + ".")) + // Every id is quoted, so that any reference, and names such as `node` or `edge`, are valid DOT + def quote(id: String): String = "\"" + id + "\"" // Ports and registers are drawn even when only a constant drives them (so they have no edge) val nodes = ((edges ++ controls).flatMap { case (a, b) => Seq(a, b) }.toSeq ++ inputs ++ outputs ++ regs).distinct - val dot = new StringBuilder + val dot = new StringBuilder dot ++= s"digraph circuit {\n label=\"Module: $top\";\n rankdir=LR;\n node [shape=box, style=\"rounded,filled\", fillcolor=lightgray];\n" + // Fill colors from the Okabe-Ito palette, lightened (sky blue, orange, reddish purple), which + // color-blind readers tell apart; the shapes alone also tell inputs (circle), outputs (double + // circle) and registers (3D box) apart nodes.foreach { n => + val path = unindexed(n) val attrs = - if (declaredAs(n, inputs)) "shape=circle, fillcolor=lightgreen" - else if (declaredAs(n, outputs)) "shape=doublecircle, fillcolor=lightcoral" - else if (declaredAs(n, regs)) "shape=box, fillcolor=gold" - else if (opLabel.contains(n)) s"""shape=ellipse, fillcolor=white, label="${opLabel(n)}${if (n.startsWith("_")) "" else "\\n" + n}"""" - else "shape=box, fillcolor=lightgray" - dot ++= s" $n [$attrs];\n" + if (declaredAs(path, inputs)) "shape=circle, fillcolor=\"#9ccfee\"" + else if (declaredAs(path, outputs)) "shape=doublecircle, fillcolor=\"#f3c766\"" + else if (declaredAs(path, regs)) "shape=box3d, fillcolor=\"#e3b3cf\"" + else if (opLabel.contains(n)) { + val name = if (n.split('.').last.startsWith("_")) "" else "\\n" + n // temporaries show only the operation + s"""shape=ellipse, fillcolor=white, label="${opLabel(n)}$name"""" + } else "shape=box, fillcolor=lightgray" + dot ++= s" ${quote(n)} [$attrs];\n" } def emit(es: Iterable[(String, String)], style: String): Unit = - es.foreach { case (a, b) => if (a != b) dot ++= s" $a -> $b$style;\n" } + es.foreach { case (a, b) => if (a != b) dot ++= s" ${quote(a)} -> ${quote(b)}$style;\n" } emit(edges, "") emit(controls, " [style=dashed, label=\"condition\"]") dot ++= "}\n" @@ -229,15 +406,16 @@ def firrtlToDot(firrtlString: String): String = { // Draw the circuit with Graphviz (`dot`). Falls back to printing the FIRRTL without Graphviz. def visualize(gen: () => chisel3.RawModule): Unit = { - import almond.api.helpers.Display - val firrtlString = getFirrtl(gen()) - val svg = - try Some(os.proc("dot", "-Tsvg").call(stdin = firrtlToDot(firrtlString), check = false)).filter(_.exitCode == 0).map(_.out.text()) + val svg = + try + Some(os.proc("dot", "-Tsvg").call(stdin = firrtlToDot(firrtlString), check = false)) + .filter(_.exitCode == 0) + .map(_.out.text()) catch { case _: java.io.IOException => None } svg.filter(_.nonEmpty) match { - case Some(html) => Display.html(html) - case None => + case Some(html) => almond.display.Html(html).display() + case None => println("Graphviz (`dot`) is not available; showing the FIRRTL instead.") println(firrtlString) } diff --git a/source/load-riscv.sc b/source/load-riscv.sc new file mode 100644 index 0000000..c804382 --- /dev/null +++ b/source/load-riscv.sc @@ -0,0 +1,48 @@ +// Makes the classes of the riscv/ sbt project (Module 5) available in a notebook. Load it after +// source/load-ivy.sc: +// +// interp.load.module(os.pwd / "source" / "load-ivy.sc") +// interp.load.module(os.pwd / "source" / "load-riscv.sc") +// +// and then `import riscv._` in a later cell. The project is compiled with sbt when its sources +// changed since the last compilation (the first time this takes about half a minute). +// A running kernel keeps the classes it has already loaded: after editing riscv/src, restart the +// kernel and load the two files again. + +val riscvDir = os.pwd / "riscv" +val riscvClasses = riscvDir / "target" / "scala-2.13" / "classes" + +// What the compiled classes depend on: the build definition and the main sources. Comparing a +// list of (path, size, time) also notices deleted and renamed files. +def riscvFingerprint: String = { + val project = os.walk(riscvDir / "project", skip = _.last == "target").filter(os.isFile) + val files = Seq(riscvDir / "build.sbt") ++ project ++ os.walk(riscvDir / "src" / "main").filter(os.isFile) + files.sorted.map(f => s"${f.relativeTo(riscvDir)} ${os.size(f)} ${os.mtime(f)}").mkString("\n") +} + +os.makeDir.all(riscvDir / "target") +// Two notebooks that start at the same time must not run sbt in the same directory at once +scala.util + .Using( + java.nio.channels.FileChannel.open( + (riscvDir / "target" / ".load-riscv.lock").toNIO, + java.nio.file.StandardOpenOption.CREATE, + java.nio.file.StandardOpenOption.WRITE + ) + ) { lockFile => + lockFile.lock() // released when the channel is closed + val stamp = riscvDir / "target" / ".load-riscv.stamp" + val fingerprint = riscvFingerprint // taken before sbt runs: an edit during the compile counts next time + if (!os.exists(riscvClasses) || !os.exists(stamp) || os.read(stamp) != fingerprint) { + println("Compiling riscv/ with sbt ...") + val sbt = os.proc("sbt", "-batch", "compile").call(cwd = riscvDir, check = false, mergeErrIntoOut = true) + if (sbt.exitCode != 0) { + println(sbt.out.text()) + throw new RuntimeException("sbt could not compile riscv/ (see the output above)") + } + os.write.over(stamp, fingerprint) + } + } + .get + +interp.load.cp(riscvClasses) diff --git a/tests/kernel.py b/tests/kernel.py new file mode 100644 index 0000000..96c1aa3 --- /dev/null +++ b/tests/kernel.py @@ -0,0 +1,49 @@ +"""A Scala kernel for the tests in this directory, which run from the repository root.""" + +import contextlib +import queue +import subprocess +import time + +from jupyter_client.manager import start_new_kernel + + +@contextlib.contextmanager +def scala_kernel(timeout=600): + """Yields `run(code)`, which executes `code`, echoes and returns its text output, and raises on + an error or when `code` runs longer than `timeout` seconds. The kernel is shut down afterwards.""" + km, kc = start_new_kernel( + kernel_name="scala", + startup_timeout=300, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + def run(code): + mid = kc.execute(code) + out = [] + deadline = time.monotonic() + timeout # for the whole cell, however chatty it is + while True: + try: + m = kc.get_iopub_msg(timeout=max(0.0, deadline - time.monotonic())) + except queue.Empty: + raise TimeoutError(f"no result after {timeout} s:\n{code}") from None + if m["parent_header"].get("msg_id") != mid: + continue + if m["msg_type"] == "stream": + print(m["content"]["text"], end="") + out.append(m["content"]["text"]) + if m["msg_type"] == "error": + # the kernel's stderr, which also has the stack trace, is discarded + raise RuntimeError( + "\n".join(m["content"].get("traceback", [])) + or m["content"]["ename"] + ": " + m["content"]["evalue"] + ) + if m["msg_type"] == "status" and m["content"]["execution_state"] == "idle": + return "".join(out) + + try: + yield run + finally: + kc.stop_channels() + km.shutdown_kernel(now=True) diff --git a/tests/lint-allowlist.txt b/tests/lint-allowlist.txt new file mode 100644 index 0000000..592f776 --- /dev/null +++ b/tests/lint-allowlist.txt @@ -0,0 +1,5 @@ +# Deliberate mentions of removed Chisel 3 APIs in markdown cells, checked by +# tests/test_notebooks.py (see REMOVED_APIS there). Format: +2.6_chiselsim.ipynb chiseltest # migration note and the compatibility package +2.6_chiselsim.ipynb iotesters # migration table +4.4_firrtl_add_ops_per_module.ipynb firrtl.Transform # custom transforms became CIRCT passes diff --git a/tests/test_chiseltest_compat.py b/tests/test_chiseltest_compat.py new file mode 100644 index 0000000..5eccf64 --- /dev/null +++ b/tests/test_chiseltest_compat.py @@ -0,0 +1,42 @@ +"""Run from the repository root: python3 tests/test_chiseltest_compat.py. + +Checks what 2.6_chiselsim.ipynb says about the `chiseltest` compatibility package of Chisel 7, in +the kernel the notebooks use: it runs a ChiselTest-style test on ChiselSim, it resets the module for +one cycle first (as ChiselSim's `simulate` does), and its `fork` runs its body at once instead of +concurrently. +""" + +from kernel import scala_kernel + +with scala_kernel() as run: + run('interp.load.module(os.pwd / "source" / "load-ivy.sc")') + run("import chisel3._\nimport chisel3.Input // avoid a name clash with almond.input.Input") # as the notebooks do + run(""" +class Delayed extends Module { + val io = IO(new Bundle { + val in = Input(UInt(32.W)) + val out = Output(UInt(32.W)) + }) + io.out := RegNext(io.in, "hdeadbeef".U(32.W)) +} +""") + # only what the test needs, as the notebooks import only chisel3 and its simulator + out = run(""" +import chiseltest.{fork, ChiselScalatestTester, testableClock, testableUInt} + +object Compat extends ChiselScalatestTester +var order = Vector.empty[String] +Compat.test(new Delayed) { c => + // registers start random, so the reset value shows that the module was reset + c.io.out.expect("hdeadbeef".U) + c.io.in.poke(7.U) + val h = fork { c.clock.step(); order :+= "fork" } + order :+= "main" + h.join() + c.io.out.expect(7.U) +} +println(s"ran; order: ${order.mkString(",")}") +""") + # a concurrent fork would block on its step and let the main thread run first + assert "ran; order: fork,main" in out, out + print("chiseltest compatibility package: OK") diff --git a/tests/test_notebooks.py b/tests/test_notebooks.py new file mode 100644 index 0000000..ffeb980 --- /dev/null +++ b/tests/test_notebooks.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""Static checks on the notebooks (no kernel needed). + +Rules: + links relative links (Prev/Next and others) point to existing files + images local images exist + alt-text every image has non-empty alt text + removed-api no removed Chisel 3 APIs, except deliberate mentions in markdown cells listed + in tests/lint-allowlist.txt + registered every notebook is in `notebooks` of runtest.py, and every entry there exists + outline every notebook is in the README's outline table, with an estimated time + troubleshooting every notebook with a Setup section links docs/troubleshooting.md + +Usage: tests/test_notebooks.py [--self-test] + --self-test seeds one violation per rule into a copy of the notebooks and checks that each + rule reports it, then checks the real notebooks. +""" + +import glob +import importlib.util +import json +import os +import re +import shutil +import sys +import tempfile +import urllib.parse + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +ALLOWLIST = os.path.join("tests", "lint-allowlist.txt") +# Removed Chisel 3 APIs, and legacy ones that new code should not use (chiseltest): name -> pattern. +# A mention counts even inside an import such as `import firrtl.{Transform, ...}`. +REMOVED_APIS = { + "chiseltest": r"(?]*)>?(?:\s+\"[^\"]*\")?\s*\)") +MD_LINK = re.compile(r"(?]+)>?(?:\s+\"[^\"]*\")?\s*\)") +HTML_IMG = re.compile(r"]*>", re.IGNORECASE) +HTML_ATTR = re.compile(r"""\b(src|alt|href)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))""", re.IGNORECASE) +HTML_LINK = re.compile(r"]*>", re.IGNORECASE) +# Text that only looks like a link, e.g. `Vec[UInt](n)` in prose, is not a path. +PATH_LIKE = re.compile(r"^[\w./%-]+(?:[#?].*)?$") +CODE = re.compile(r"```.*?```|`[^`\n]*`", re.DOTALL) + + +def attrs(tag): + return {m.group(1).lower(): next(g for g in m.groups()[1:] if g is not None) for m in HTML_ATTR.finditer(tag)} + + +def is_remote(target): + """True for a URL with a scheme (http:, mailto:, ...) or an anchor in the same page.""" + return bool(urllib.parse.urlsplit(target).scheme) or target.startswith("#") + + +def local_path(root, target): + path = urllib.parse.unquote(urllib.parse.urlsplit(target).path) + return os.path.join(root, path.lstrip("/")) # a leading / means the repository root + + +def cells(root): + """Yields (notebook file name, cell index, cell type, source) for every cell.""" + for path in sorted(glob.glob(os.path.join(root, "*.ipynb"))): + with open(path, encoding="utf-8") as f: + nb = json.load(f) + for index, cell in enumerate(nb["cells"]): + yield os.path.basename(path), index, cell["cell_type"], "".join(cell["source"]) + + +def markdown_cells(root): + """Like `cells`, for markdown cells only and without code spans (whose links are not rendered).""" + for name, index, kind, source in cells(root): + if kind == "markdown": + yield name, index, CODE.sub("", source) + + +def link_targets(source): + """The targets of the markdown and HTML links in `source`.""" + return [m.group(1) for m in MD_LINK.finditer(source)] + [ + attrs(t).get("href", "") for t in HTML_LINK.findall(source) + ] + + +def check_links(root): + errors = [] + for name, index, source in markdown_cells(root): + for target in link_targets(source): + if PATH_LIKE.match(target) and not is_remote(target) and not os.path.exists(local_path(root, target)): + errors.append(f"{name} cell {index}: link to missing file {target}") + return errors + + +def images(root): + """Yields (notebook, cell index, src, alt) for every image of a markdown cell.""" + for name, index, source in markdown_cells(root): + for m in MD_IMAGE.finditer(source): + yield name, index, m.group(2), m.group(1) + for a in map(attrs, HTML_IMG.findall(source)): + yield name, index, a.get("src", ""), a.get("alt") + + +def check_images(root): + return [ + f"{name} cell {index}: " + (f"missing image {src}" if src else "image without src") + for name, index, src, _ in images(root) + if not src or (not is_remote(src) and not os.path.exists(local_path(root, src))) + ] + + +def check_alt_text(root): + return [ + f"{name} cell {index}: image {src} has no alt text" + for name, index, src, alt in images(root) + if not (alt or "").strip() + ] + + +def read_allowlist(root): + """:returns the set of (notebook, API) whose mention in markdown cells is deliberate.""" + allowed = set() + path = os.path.join(root, ALLOWLIST) + if os.path.exists(path): + with open(path, encoding="utf-8") as f: + for n, line in enumerate(f, 1): + fields = line.split("#", 1)[0].split() + if not fields: + continue + if len(fields) != 2 or not fields[0].endswith(".ipynb") or fields[1] not in REMOVED_APIS: + raise SystemExit( + f"{ALLOWLIST}:{n}: expected ' ', API one of " + ", ".join(REMOVED_APIS) + ) + allowed.add(tuple(fields)) + return allowed + + +def check_removed_apis(root): + allowed = read_allowlist(root) + errors, used = [], set() + for name, index, kind, source in cells(root): + for api, pattern in REMOVED_APIS.items(): + if not re.search(pattern, source): + continue + if kind == "markdown" and (name, api) in allowed: # code cells are never allowed + used.add((name, api)) + else: + errors.append( + f"{name} cell {index}: removed API {api} (if the mention in a markdown " + f"cell is deliberate, add '{name} {api}' to {ALLOWLIST})" + ) + errors += [ + f"{ALLOWLIST}: stale entry '{n} {a}' (the notebook does not mention it)" for n, a in sorted(allowed - used) + ] + return errors + + +def notebook_names(root): + return sorted(os.path.basename(p) for p in glob.glob(os.path.join(root, "*.ipynb"))) + + +def check_registered(root): + spec = importlib.util.spec_from_file_location("runtest", os.path.join(root, "runtest.py")) + runtest = importlib.util.module_from_spec(spec) + spec.loader.exec_module(runtest) + registered = set(runtest.notebooks) + present = set(notebook_names(root)) + return [f"{n}: not registered in `notebooks` of runtest.py" for n in sorted(present - registered)] + [ + f"runtest.py: {n} is registered but does not exist" for n in sorted(registered - present) + ] + + +# a row of the outline table: | [name](name.ipynb) | topic | N min | +OUTLINE_ROW = re.compile(r"\| \[[^]]+\]\(([^)]+\.ipynb)\) \|.*\| \d+ min \|\s*$") + + +def check_outline(root): + with open(os.path.join(root, "README.md"), encoding="utf-8") as f: + readme = f.read() + outline = readme.partition("\n## Outline\n")[2].partition("\n## ")[0] + timed = {m.group(1) for m in map(OUTLINE_ROW.match, outline.splitlines()) if m} + present = notebook_names(root) + return [ + f"README.md: {n} is not in the outline table as '| [{n[:-6]}]({n}) | topic | N min |'" + for n in present + if n not in timed + ] + [f"README.md: the outline table lists {n}, which does not exist" for n in sorted(timed - set(present))] + + +TROUBLESHOOTING = "docs/troubleshooting.md" + + +def check_troubleshooting(root): + setup, linked = set(), set() + for name, _, source in markdown_cells(root): + if "## Setup" in source: + setup.add(name) + if any(urllib.parse.urlsplit(t).path == TROUBLESHOOTING for t in link_targets(source)): # anchors too + linked.add(name) + return [f"{n}: no link to docs/troubleshooting.md (put it under ## Setup)" for n in sorted(setup - linked)] + + +RULES = { + "links": check_links, + "images": check_images, + "alt-text": check_alt_text, + "removed-api": check_removed_apis, + "registered": check_registered, + "outline": check_outline, + "troubleshooting": check_troubleshooting, +} + + +def run(root): + return [e for rule in RULES.values() for e in rule(root)] + + +def _edit_cell(root, notebook, index, transform): + path = os.path.join(root, notebook) + with open(path, encoding="utf-8") as f: + nb = json.load(f) + cell = nb["cells"][index] + cell["source"] = transform("".join(cell["source"])) + with open(path, "w", encoding="utf-8") as f: + json.dump(nb, f, indent=1) + + +def _append(text): + """:returns a seed that appends `text` to a markdown cell (cell 1 holds the Prev/Next links).""" + return lambda r: _edit_cell(r, "2.1_first_module.ipynb", 1, lambda s: s + "\n" + text + "\n") + + +# One synthetic violation per rule, or a list of them (each is seeded and checked on its own) +SEEDS = { + "links": _append("[Next](2.2_missing.ipynb)"), + "images": [_append("![A missing figure](images/missing.png)"), _append("![An empty source]()")], + "alt-text": _append("![](images/chisel_1024.png)"), + "removed-api": _append("`import chisel3.iotesters.{PeekPokeTester, Driver}`"), + "registered": lambda r: shutil.copy(os.path.join(r, "0_demo.ipynb"), os.path.join(r, "9_unregistered.ipynb")), + "outline": lambda r: shutil.copy(os.path.join(r, "0_demo.ipynb"), os.path.join(r, "9_not_outlined.ipynb")), + "troubleshooting": lambda r: _edit_cell( + r, + "2.1_first_module.ipynb", + 2, + lambda s: s.replace("[Troubleshooting](docs/troubleshooting.md)", "Troubleshooting"), + ), +} + + +def self_test(): + ok = True + for rule, seed in ((r, s) for r, seeds in SEEDS.items() for s in (seeds if isinstance(seeds, list) else [seeds])): + with tempfile.TemporaryDirectory() as tmp: + for p in glob.glob(os.path.join(ROOT, "*.ipynb")) + [ + os.path.join(ROOT, f) for f in ("runtest.py", "README.md") + ]: + shutil.copy(p, tmp) + for d in ("images", "docs"): # targets of the notebooks' local links + shutil.copytree(os.path.join(ROOT, d), os.path.join(tmp, d)) + os.makedirs(os.path.join(tmp, "tests")) + shutil.copy(os.path.join(ROOT, ALLOWLIST), os.path.join(tmp, ALLOWLIST)) + if RULES[rule](tmp): # the copy already fails: the real run below shows why + print(f"self-test: rule {rule} fails before seeding", file=sys.stderr) + ok = False + continue + seed(tmp) + caught = RULES[rule](tmp) + if not caught: + print(f"self-test: rule {rule} did not catch its seeded violation", file=sys.stderr) + ok = False + else: + print(f"self-test: rule {rule} caught: {caught[0]}") + return ok + + +if __name__ == "__main__": + if len(sys.argv) > 1 and sys.argv[1] in ("-h", "--help"): + print(__doc__) + sys.exit(0) + ok = self_test() if "--self-test" in sys.argv[1:] else True + errors = run(ROOT) + for e in errors: + print(e, file=sys.stderr) + if not errors: + print(f"notebook lint: {len(RULES)} rules passed") + sys.exit(0 if ok and not errors else 1) diff --git a/tests/test_riscv_import.py b/tests/test_riscv_import.py new file mode 100644 index 0000000..f26ce4f --- /dev/null +++ b/tests/test_riscv_import.py @@ -0,0 +1,21 @@ +"""Run from the repository root: python3 tests/test_riscv_import.py. + +Checks that a fresh Scala kernel can use the riscv/ project through source/load-riscv.sc. +""" + +from kernel import scala_kernel + +with scala_kernel() as run: + run('interp.load.module(os.pwd / "source" / "load-ivy.sc")') + run('interp.load.module(os.pwd / "source" / "load-riscv.sc")') + out = run(""" +import chisel3._ +import riscv._ +println(AluOp.all.map(_.toString).mkString(" ")) +println(classOf[Alu].getName) +""") + assert "Add" in out and "riscv.Alu" in out, out + # unchanged sources: the second load must reuse the classes instead of running sbt again + out = run('interp.load.module(os.pwd / "source" / "load-riscv.sc")') + assert "Compiling riscv/" not in out, out + print("load-riscv.sc: OK") diff --git a/tests/test_visualizer.py b/tests/test_visualizer.py index 9b63357..bcc43d6 100644 --- a/tests/test_visualizer.py +++ b/tests/test_visualizer.py @@ -1,16 +1,13 @@ """Run from the repository root: python3 tests/test_visualizer.py.""" -from jupyter_client.manager import start_new_kernel -km,kc=start_new_kernel(kernel_name='scala',startup_timeout=300) -def run(code): - mid=kc.execute(code) - while True: - m=kc.get_iopub_msg(timeout=180) - if m['parent_header'].get('msg_id') != mid: continue - if m['msg_type']=='stream': print(m['content']['text'], end='') - if m['msg_type']=='error': raise RuntimeError(m['content']) - if m['msg_type']=='status' and m['content']['execution_state']=='idle': break -try: + +from kernel import scala_kernel + +with scala_kernel(timeout=180) as run: run('interp.load.module(os.pwd / "source" / "load-ivy.sc")') + # The DOT text of an edge and of a node's attributes: every id is a quoted FIRRTL reference + run('''def q(id: String) = "\\"" + id + "\\"" +def edge(a: String, b: String) = q(a) + " -> " + q(b) +def node(n: String) = q(n) + " ["''') run('''val graph = firrtlToDot("""circuit Top : module Child : input other : UInt<1> @@ -27,10 +24,10 @@ def run(code): else : connect elseout, UInt<1>(0) """) -assert(graph.contains("sel -> out [style=dashed")) -assert(graph.contains("nested -> out [style=dashed")) -assert(graph.contains("sel -> elseout [style=dashed")) -assert(graph.contains("data -> out")) +assert(graph.contains(edge("sel", "out") + " [style=dashed")) +assert(graph.contains(edge("nested", "out") + " [style=dashed")) +assert(graph.contains(edge("sel", "elseout") + " [style=dashed")) +assert(graph.contains(edge("data", "out"))) assert(!graph.contains("other")) assert(graph.contains("Module: Top"))''') run('''val constOnly = firrtlToDot("""circuit K : @@ -39,8 +36,8 @@ def run(code): output k : UInt<1> connect k, UInt<1>(1) """) -assert(constOnly.contains("k [")) -assert(!constOnly.contains("clock ["))''') +assert(constOnly.contains(node("k"))) +assert(!constOnly.contains(node("clock")))''') run('''val hierarchy = firrtlToDot("""circuit Top : module Child : input in : UInt<8> @@ -55,11 +52,11 @@ def run(code): connect b.in, a.out connect result, b.out """) -assert(hierarchy.contains("data -> a_in")) -assert(hierarchy.contains("a_in -> a_out")) -assert(hierarchy.contains("a_out -> b_in")) -assert(hierarchy.contains("b_in -> b_out")) -assert(hierarchy.contains("b_out -> result"))''') +assert(hierarchy.contains(edge("data", "a.in"))) +assert(hierarchy.contains(edge("a.in", "a.out"))) +assert(hierarchy.contains(edge("a.out", "b.in"))) +assert(hierarchy.contains(edge("b.in", "b.out"))) +assert(hierarchy.contains(edge("b.out", "result")))''') run('''val indexed = firrtlToDot("""circuit VecTest : public module VecTest : wire values : UInt<8>[4] @@ -71,22 +68,207 @@ def run(code): connect result, storage[0] connect values[1], result """) -assert(indexed.contains("values -> values_index")) -assert(indexed.contains("index -> values_index")) -assert(indexed.contains("values_index -> result")) -assert(indexed.contains("result -> storage_index")) -assert(indexed.contains("index -> storage_index")) -assert(indexed.contains("storage_index -> storage"))''') - run('''assert(indexed.contains("storage -> storage_0")) -assert(indexed.contains("storage_0 -> result")) -assert(indexed.contains("values_1 -> values"))''') +assert(indexed.contains(edge("values", "values[index]"))) +assert(indexed.contains(edge("index", "values[index]"))) +assert(indexed.contains(edge("values[index]", "result"))) +assert(indexed.contains(edge("result", "storage[index]"))) +assert(indexed.contains(edge("index", "storage[index]"))) +assert(indexed.contains(edge("storage[index]", "storage")))''') + run("""assert(indexed.contains(edge("storage", "storage[0]"))) +assert(indexed.contains(edge("storage[0]", "result"))) +assert(indexed.contains(edge("values[1]", "values")))""") run('''val nested = firrtlToDot("""circuit N : public module N : output io : { flip bus : { data : UInt<8> }, out : UInt<8> } connect io.out, io.bus.data """) -assert(nested.contains("io_bus_data [shape=circle")) -assert(nested.contains("io_out [shape=doublecircle"))''') - print('visualizer regression checks passed') -finally: - kc.stop_channels(); km.shutdown_kernel(now=True) +// shapes, and Okabe-Ito fills: inputs blue circles, outputs orange double circles +assert(nested.contains(node("io.bus.data") + "shape=circle, fillcolor=\\"#9ccfee\\"]")) +assert(nested.contains(node("io.out") + "shape=doublecircle, fillcolor=\\"#f3c766\\"]"))''') + run('''val withReg = firrtlToDot("""circuit R : + public module R : + input clock : Clock + input d : UInt<8> + output q : UInt<8> + reg z : UInt<8>[2], clock + reg y : UInt<8>, clock + connect z[0], d + connect y, z[0] + connect q, y +""") +// registers, and their elements: reddish-purple 3D boxes +assert(withReg.contains(node("z[0]") + "shape=box3d, fillcolor=\\"#e3b3cf\\"]")) +assert(withReg.contains(node("y") + "shape=box3d, fillcolor=\\"#e3b3cf\\"]"))''') + # #18: references that sanitizing to `_` made equal stay different nodes + run('''val distinct = firrtlToDot("""circuit Top : + module Child : + input in : UInt<8> + output out : UInt<8> + connect out, in + public module Top : + input data : UInt<8> + input a_in : UInt<8> + input v_0 : UInt<8> + output result : UInt<8> + output other : UInt<8> + output io : { a_b : UInt<8>, a : { b : UInt<8> } } + wire v : UInt<8>[2] + inst a of Child + connect a.in, data + connect result, a_in + connect v[0], v_0 + connect other, v[0] + connect io.a_b, data + connect io.a.b, a_in +""") +assert(distinct.contains(edge("data", "a.in"))) +assert(distinct.contains(edge("a_in", "result"))) +assert(!distinct.contains(edge("data", "a_in"))) // what merging `a.in` with `a_in` drew +assert(distinct.contains(edge("v_0", "v[0]")) && distinct.contains(edge("v[0]", "other"))) +assert(distinct.contains(edge("data", "io.a_b")) && distinct.contains(edge("a_in", "io.a.b")))''') + run('''val vecPort = firrtlToDot("""circuit V : + module Child : + input i : UInt<1> + input v : UInt<8>[2] + output o : UInt<8> + connect o, v[i] + public module V : + input i : UInt<1> + output io : { v : { flip a : UInt<1> }[2] } + output r : UInt<8> + inst c of Child + connect c.v[i], io.v[0].a + connect r, c.o +""") +// an element of a port's vector of bundles is that port's field +assert(vecPort.contains(node("io.v[0].a") + "shape=circle")) +// the child's `v[i]` selects with the child's `i`, not the top's +assert(vecPort.contains(edge("c.i", "c.v[c.i]")) && vecPort.contains(edge("i", "c.v[i]"))) +assert(!vecPort.contains(edge("i", "c.v[c.i]")))''') + # nested and chained dynamic selections, as Chisel 7 emits them + run('''val nestedIndex = firrtlToDot("""circuit Nested : + public module Nested : + input idx : UInt<1>[2] + input v : UInt<8>[2] + input w : UInt<8>[2][2] + input i : UInt<1> + input j : UInt<1> + input x : UInt<8> + output out : UInt<8> + output o2 : UInt<8> + wire s : UInt<8>[2][2] + connect out, v[idx[0]] + connect o2, w[i][j] + connect s[i][j], x +""") +assert(nestedIndex.contains(edge("v", "v[idx[0]]")) && nestedIndex.contains(edge("idx[0]", "v[idx[0]]"))) +assert(nestedIndex.contains(edge("v[idx[0]]", "out"))) +assert(nestedIndex.contains(node("idx[0]") + "shape=circle")) +assert(nestedIndex.contains(edge("w", "w[i]")) && nestedIndex.contains(edge("i", "w[i]"))) +assert(nestedIndex.contains(edge("w[i]", "w[i][j]")) && nestedIndex.contains(edge("j", "w[i][j]"))) +assert(nestedIndex.contains(edge("w[i][j]", "o2")) && !nestedIndex.contains(edge("w", "w[i][j]"))) +assert(nestedIndex.contains(edge("x", "s[i][j]")) && nestedIndex.contains(edge("s[i][j]", "s[i]"))) +assert(nestedIndex.contains(edge("s[i]", "s")))''') + run('''val mixedIndex = firrtlToDot("""circuit Mixed : + module Child : + input idx : UInt<1>[2] + input v : UInt<8>[2] + output o : UInt<8> + connect o, v[idx[0]] + public module Mixed : + input w : UInt<8>[2][2] + input i : UInt<1> + input j : UInt<1> + input x : UInt<8> + output o : UInt<8> + output p : UInt<8> + output q : UInt<8> + wire m : UInt<8>[2][2] + inst c of Child + connect o, w[i][0] + connect m[0][1], x + connect p, m[i][j] + when w[i][j] : + connect q, c.o +""") +// a fixed selection of a dynamic one stays joined to it +assert(mixedIndex.contains(edge("w[i]", "w[i][0]")) && mixedIndex.contains(edge("w[i][0]", "o"))) +// a fixed write reaches a dynamic read of the same nested vector +assert(mixedIndex.contains(edge("m[0][1]", "m[0]")) && mixedIndex.contains(edge("m[0]", "m"))) +assert(mixedIndex.contains(edge("m", "m[i]")) && mixedIndex.contains(edge("m[i][j]", "p"))) +// the prefix reaches nested indices inside an instance +assert(mixedIndex.contains(edge("c.idx[0]", "c.v[c.idx[0]]")) && mixedIndex.contains(edge("c.v", "c.v[c.idx[0]]"))) +// a nested reference as a when condition +assert(mixedIndex.contains(edge("w[i][j]", "q") + " [style=dashed"))''') + # bulk connects: a whole vector or bundle and its elements or fields + run( + '''val bulk = firrtlToDot("""circuit B : + public module B : + input a : UInt<8> + input b : UInt<8> + input x : UInt<8> + input y : UInt<8>[2] + output out : UInt<8>[2] + output o : { a : UInt<8> } + output e : UInt<8> + input next : { valid : UInt<1> } + output f : UInt<8> + input io : { sel : UInt<1> } + output g : UInt<8> + wire w : UInt<8>[2] + wire r : { a : UInt<8> } + wire z : UInt<8>[2] + connect w[0], a + connect w[1], b + connect out, w + connect r.a, x + connect o, r + connect z, y + connect e, z[1] + wire state : { valid : UInt<1> } + connect state, next + when state.valid : + connect f, a + wire s : { sel : UInt<1> } + connect s, io + connect g, y[s.sel] +""") +assert(bulk.contains(edge("w[0]", "w")) && bulk.contains(edge("w[1]", "w")) && bulk.contains(edge("w", "out"))) +assert(bulk.contains(edge("r.a", "r")) && bulk.contains(edge("r", "o"))) +assert(bulk.contains(edge("z", "z[1]")) && bulk.contains(edge("z[1]", "e"))) +// a part read only by a when condition +assert(bulk.contains(edge("next", "state")) && bulk.contains(edge("state", "state.valid"))) +assert(bulk.contains(edge("state.valid", "f") + " [style=dashed")) +// a port's fields: an output read from outside, an input written there +// a part read only as an index +assert(bulk.contains(edge("s", "s.sel")) && bulk.contains(edge("s.sel", "y[s.sel]"))) +assert(bulk.contains(edge("o", "o.a")) && bulk.contains(edge("next.valid", "next"))) +// parts are not joined to each other, nor a part to the whole when nothing flows that way +assert(!bulk.contains(edge("w[0]", "w[1]")) && !bulk.contains(edge("w", "w[0]")) && !bulk.contains(edge("z[1]", "z")))''' + ) + # #18: DOT keywords are valid node names once quoted + run('''val keywords = firrtlToDot("""circuit K : + public module K : + input node : UInt<1> + output edge : UInt<1> + connect edge, node +""") +assert(keywords.contains(edge("node", "edge")))''') + # #19: a name that only starts with a port's name is not that port + run('''val prefixed = firrtlToDot("""circuit P : + public module P : + input foo : UInt<8> + output o : UInt<8> + node foo_tmp = not(foo) + connect o, foo_tmp +""") +assert(prefixed.contains(node("foo") + "shape=circle")) +assert(prefixed.contains(node("foo_tmp") + "shape=ellipse"))''') + # every graph is valid DOT + run( + """Seq(graph, constOnly, hierarchy, indexed, nested, withReg, distinct, vecPort, nestedIndex, mixedIndex, bulk, keywords, prefixed).foreach { g => + val r = os.proc("dot", "-Tsvg").call(stdin = g, check = false, stderr = os.Pipe) + assert(r.exitCode == 0 && r.err.text().isEmpty, r.err.text() + g) +}""" + ) + print("visualizer regression checks passed") diff --git a/tools/check-solutions.sh b/tools/check-solutions.sh new file mode 100755 index 0000000..5219b61 --- /dev/null +++ b/tools/check-solutions.sh @@ -0,0 +1,41 @@ +#!/bin/bash +# Check the riscv/ reference solutions: copy the project, put riscv/solutions/ over its src/ and +# run every test. The student scaffold in riscv/src/ only has to compile, which is checked too. +# +# Usage: tools/check-solutions.sh (from a clone) +# SOLUTIONS=/path tools/check-solutions.sh (e.g. in the Docker image, which has no solutions) +set -euo pipefail + +root=$(cd "$(dirname "$0")/.." && pwd) +solutions=${SOLUTIONS:-$root/riscv/solutions} +[ -d "$solutions" ] || { + echo "no solutions at $solutions" >&2 + exit 1 +} + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +# only what the build reads, not build output or editor files +mkdir -p "$work/project" +cp "$root/riscv/build.sbt" "$work/" +cp "$root/riscv/project/build.properties" "$work/project/" +for f in "$root"/riscv/project/*.sbt "$root"/riscv/project/*.scala; do # plugins and build code, if any + [ -e "$f" ] && cp "$f" "$work/project/" +done +cp -R "$root/riscv/src" "$root/riscv/programs" "$work/" # the tests read programs/ + +# A solution replaces the scaffold file at the same path; one without a scaffold is a mistake +# (checked first: it needs no compile) +(cd "$solutions" && find . -type f | sed 's|^\./||') | while IFS= read -r f; do + [ -f "$work/src/$f" ] || { + echo "solution $f has no scaffold at riscv/src/$f" >&2 + exit 1 + } +done + +echo "== The scaffold compiles" +(cd "$work" && sbt -batch Test/compile) + +echo "== The solutions pass every test" +cp -R "$solutions/." "$work/src/" +(cd "$work" && sbt -batch test) diff --git a/tools/check-versions.py b/tools/check-versions.py new file mode 100755 index 0000000..a0f8aa9 --- /dev/null +++ b/tools/check-versions.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Check that the pinned tool versions agree across the files that repeat them. + +The Dockerfile `ENV`s are the reference. Dependabot cannot bump them and `load-ivy.sc` +needs literal strings, so the versions are repeated; this script fails on any mismatch. +It also checks that FIRTOOL_VERSION is the firtool version Chisel was published against +(`chisel3.BuildInfo.firtoolVersion`), read from the Chisel sources jar. + +Usage: tools/check-versions.py check every version + tools/check-versions.py --print KEY print one version (e.g. chisel) as the Dockerfile has it + +The Chisel sources jar is looked up in the coursier caches, otherwise downloaded from Maven Central. +""" + +import argparse +import io +import os +import re +import sys +import urllib.request +import zipfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +MAVEN = "https://repo1.maven.org/maven2" +CHISEL_SOURCES = "org/chipsalliance/chisel_2.13/{v}/chisel_2.13-{v}-sources.jar" + +# (file, version key, regular expression whose group 1 is the version). A file may list a key +# several times: every occurrence must match. Each pattern must match at least once. +V = r"([0-9]+(?:\.[0-9]+)+)" +VP = r"([0-9]+(?:\.[0-9]+)+(?:\.post[0-9]+)?)" # a PyPI version, which may have a .postN suffix +SHA256 = r"([0-9a-f]{64})" +CHECKS = [ + ("Dockerfile", "scala", rf"^ENV SCALA_VERSION={V}$"), + ("Dockerfile", "almond", rf"^ENV ALMOND_VERSION={V}$"), + ("Dockerfile", "coursier", rf"^ENV COURSIER_VERSION={V}$"), + ("Dockerfile", "chisel", rf"^ENV CHISEL_VERSION={V}$"), + ("Dockerfile", "firtool", rf"^ENV FIRTOOL_VERSION={V}$"), + ("Dockerfile", "scalatest", rf"org\.scalatest:scalatest_2\.13:{V}"), + ("Dockerfile", "sbt", rf"^ENV SBT_VERSION={V}$"), + ("riscv/project/build.properties", "sbt", rf"^sbt\.version={V}$"), + ("riscv/build.sbt", "scala", rf'^scalaVersion := "{V}"'), + ("riscv/build.sbt", "chisel", rf'val chiselVersion = "{V}"'), + ("riscv/build.sbt", "scalatest", rf'"scalatest"\s+%\s+"{V}"'), + ("source/load-ivy.sc", "chisel", rf"chisel-plugin:{V}`"), + ("source/load-ivy.sc", "chisel", rf"org\.chipsalliance::chisel:{V}`"), + ("source/load-ivy.sc", "scalatest", rf"org\.scalatest::scalatest:{V}`"), + ("tools/install.sh", "scala", rf"^SCALA_VERSION={V}$"), + ("tools/install.sh", "almond", rf"^ALMOND_VERSION={V}$"), + ("tools/install.sh", "coursier", rf"^COURSIER_VERSION={V}$"), + ("tools/install.sh", "sbt", rf"^SBT_VERSION={V}$"), + ("Dockerfile", "sbt-sha256", rf"^ENV SBT_SHA256={SHA256}$"), + ("tools/install.sh", "sbt-sha256", rf"^SBT_SHA256={SHA256}$"), + ("Dockerfile", "coursier-sha256", rf"^ENV COURSIER_SHA256={SHA256}$"), + ("tools/install.sh", "coursier-sha256", rf"^COURSIER_SHA256={SHA256}$"), + ("binder/postBuild", "coursier-sha256", rf"^COURSIER_SHA256={SHA256}$"), + ("tools/install.sh", "firtool", rf"^FIRTOOL_VERSION={V}$"), + ("Dockerfile", "firtool-jar-sha256", rf"^ENV FIRTOOL_JAR_SHA256={SHA256}$"), + ("tools/install.sh", "firtool-jar-sha256", rf"^FIRTOOL_JAR_SHA256={SHA256}$"), + ("Dockerfile", "yowasp-yosys", rf"yowasp-yosys=={VP}"), + ("tools/install.sh", "yowasp-yosys", rf"^YOWASP_YOSYS_VERSION={VP}$"), + ("Dockerfile", "yowasp-runtime", rf"yowasp-runtime=={V}"), + ("tools/install.sh", "yowasp-runtime", rf"^YOWASP_RUNTIME_VERSION={V}$"), + ("Dockerfile", "wasmtime", rf"wasmtime=={V}"), + ("tools/install.sh", "wasmtime", rf"^WASMTIME_VERSION={V}$"), + # the oldest Verilator that works with ChiselSim (older ones abort, see docs/troubleshooting.md) + ("Dockerfile", "verilator-min", rf"Verilator {V} or newer"), + ("tools/install.sh", "verilator-min", rf"^VERILATOR_MIN={V}$"), + ("binder/postBuild", "verilator-min", rf"^VERILATOR_MIN={V}$"), + ("binder/environment.yml", "verilator-min", rf"verilator >={V}"), + ("Install.md", "verilator-min", rf"Verilator {V} or newer"), + ("docs/troubleshooting.md", "verilator-min", rf"Verilator {V} or newer"), + ("Install.md", "coursier", rf"coursier/releases/download/v{V}/coursier"), + ("Install.md", "coursier-sha256", rf"^echo \"{SHA256} coursier\" \| sha256sum -c -$"), + ("binder/postBuild", "scala", rf"^SCALA_VERSION={V}$"), + ("binder/postBuild", "almond", rf"^ALMOND_VERSION={V}$"), + ("binder/postBuild", "coursier", rf"^COURSIER_VERSION={V}$"), + ("Install.md", "scala", rf"Scala {V} with Almond"), + ("Install.md", "almond", rf"with Almond {V} kernel"), + ("Install.md", "chisel", rf"Chisel {V} and CIRCT"), + ("Install.md", "firtool", rf"CIRCT firtool {V}"), + ("Install.md", "sbt", rf"^- sbt {V} with"), + ("Install.md", "firtool", rf"contains `firtool` {V}"), + ("Install.md", "scala", rf"use Scala {V}\)"), + ("Install.md", "scala", rf"scala-kernel_{V}:"), + ("Install.md", "almond", r"scala-kernel_[0-9.]+:([0-9.]+[0-9])"), + ("README.md", "chisel", rf"`chisel-{V}`"), + ("docs/jupyterhub/Dockerfile", "chisel", rf"^ARG BOOTCAMP_IMAGE=sysprog21/chisel-bootcamp:chisel-{V}$"), + ("2.8_memories.ipynb", "firtool", rf"firtool {V} builds"), # its read-under-write findings + ("2.8_memories.ipynb", "firtool", rf"version {V} here"), + ("2.8_memories.ipynb", "chisel", rf"In Chisel {V}, `SRAM`"), # its MemoryFile finding +] +REFERENCE_FILE = "Dockerfile" + + +def collect(): + """:returns {key: [(file, line number, version)]} and a list of patterns that matched nothing.""" + found, missing, files = {}, [], {} + for path, key, pattern in CHECKS: + if path not in files: + with open(os.path.join(ROOT, path), encoding="utf-8") as f: + files[path] = f.read().splitlines() + lines = files[path] + hits = [(path, n, m.group(1)) for n, line in enumerate(lines, 1) for m in re.finditer(pattern, line)] + if not hits: + missing.append(f"{path}: no match for {key} ({pattern})") + found.setdefault(key, []).extend(hits) + return found, missing + + +def chisel_firtool_version(chisel_version): + """:returns the firtool version in chisel3.BuildInfo, read from the Chisel sources jar.""" + rel = CHISEL_SOURCES.format(v=chisel_version) + caches = [os.environ.get("COURSIER_CACHE"), os.path.expanduser("~/.cache/coursier/v1"), "/opt/cache/coursier"] + cached = [ + p for p in (os.path.join(d, "https/repo1.maven.org/maven2", rel) for d in caches if d) if os.path.isfile(p) + ] + if cached: + with open(cached[0], "rb") as f: + data = f.read() + else: + with urllib.request.urlopen(f"{MAVEN}/{rel}", timeout=60) as r: + data = r.read() + with zipfile.ZipFile(io.BytesIO(data)) as z: + name = next((n for n in z.namelist() if n.endswith("chisel3/BuildInfo.scala")), None) + source = z.read(name).decode("utf-8") if name else "" + m = re.search(r'firtoolVersion\s*:\s*scala\.Option\[String\]\s*=\s*Some\("([^"]+)"\)', source) + if not m: + sys.exit("error: firtoolVersion not found in chisel3/BuildInfo.scala of the Chisel sources jar") + return m.group(1) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--print", metavar="KEY", help="print one version and exit") + args = parser.parse_args() + + found, errors = collect() + if errors: # a pattern matched nothing: its file changed shape, so update CHECKS + print("\n".join(errors), file=sys.stderr) + return 1 + reference = {k: next((v for f, _, v in hits if f == REFERENCE_FILE), None) for k, hits in found.items()} + if args.print: + if not reference.get(args.print): + sys.exit(f"error: no {args.print} version in {REFERENCE_FILE}") + print(reference[args.print]) + return 0 + for key, hits in found.items(): + errors += [ + f"{path}:{line}: {key} {version}, but {REFERENCE_FILE} has {reference[key]}" + for path, line, version in hits + if version != reference[key] + ] + + expected = chisel_firtool_version(reference["chisel"]) + if expected != reference["firtool"]: + errors.append( + f"{REFERENCE_FILE}: FIRTOOL_VERSION {reference['firtool']}, but Chisel " + f"{reference['chisel']} was published against firtool {expected}" + ) + + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + print("versions agree: " + ", ".join(f"{k} {v}" for k, v in sorted(reference.items()))) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/ci-notebooks.py b/tools/ci-notebooks.py new file mode 100644 index 0000000..649b760 --- /dev/null +++ b/tools/ci-notebooks.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Print, as a JSON list, the notebooks that CI runs. + +Usage: tools/ci-notebooks.py all + git diff --name-only BASE...HEAD | tools/ci-notebooks.py changed + +`all` lists every notebook registered in runtest.py; pushes to dev and the nightly run use it. +`changed` is for pull requests: when every changed file is a notebook or cannot affect how the +notebooks run (documentation, images, tools other than this script, tests), it lists the smoke +subset plus the changed notebooks, plus the notebooks that use riscv/ when what they read from it +changed; otherwise (the Dockerfile, `source/`, `runtest.py`, this script, a workflow, ...) it lists +every notebook, since any of them may break. +""" + +import fnmatch +import json +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +from runtest import notebooks # noqa: E402 + +SELF = os.path.relpath(os.path.abspath(__file__), ROOT).replace(os.sep, "/") # as git names it + +# One notebook per part of the toolchain: the kernel and Chisel (0_demo, 2.1), ChiselSim and +# Verilator (2.6), and the FIRRTL modules (4.1). +SMOKE = ["0_demo.ipynb", "2.1_first_module.ipynb", "2.6_chiselsim.ipynb", "4.1_firrtl_ast.ipynb"] +# Files that cannot change the outcome of runtest.py: they are not in the image, are only +# rendered, or are tested by other jobs (tests/test_visualizer.py always; riscv/ by the riscv job). +INERT = [ + "*.md", + "riscv/*", + "LICENSE", + "images/*", + "binder/*", + "tools/*", + "tests/*", + ".pre-commit-config.yaml", + ".scalafmt.conf", + "pyproject.toml", + ".github/dependabot.yml", + ".github/workflows/checks.yml", +] +# Exceptions to INERT: this script chooses the notebooks, so a change to it may break the choice +NOT_INERT = [SELF] +# What the notebooks that load source/load-riscv.sc use from riscv/: what source/load-riscv.sc compiles, and the program +# images and the sources that 5.4 assembles (the rest of riscv/ is inert) +RISCV_INPUTS = [ + "riscv/build.sbt", + "riscv/project/*", + "riscv/src/main/*", + "riscv/programs/hex/*", + "riscv/programs/src/*", + "riscv/programs/riscv-tests/*", +] + + +def uses_riscv(notebook): + with open(os.path.join(ROOT, notebook), encoding="utf-8") as f: + return "load-riscv.sc" in f.read() + + +def inert(path): + return path not in NOT_INERT and any(fnmatch.fnmatch(path, g) for g in INERT) + + +def select(mode, changed): + unknown = sorted(set(SMOKE) - set(notebooks)) + if unknown: # a renamed notebook would otherwise drop out of the smoke subset unnoticed + sys.exit(f"tools/ci-notebooks.py: SMOKE lists notebooks that runtest.py does not: {unknown}") + if mode == "all" or any(p not in notebooks and not inert(p) for p in changed): + return sorted(notebooks) + selected = set(SMOKE) | set(changed) + if any(fnmatch.fnmatch(p, g) for p in changed for g in RISCV_INPUTS): + selected |= {n for n in notebooks if uses_riscv(n)} + return sorted(selected & set(notebooks)) + + +if __name__ == "__main__": + if sys.argv[1:] not in (["all"], ["changed"]): + sys.exit(__doc__) + # changed files come one per line on stdin: no argument-length limit and no shell quoting + changed = [line.strip() for line in sys.stdin if line.strip()] if sys.argv[1] == "changed" else [] + print(json.dumps(select(sys.argv[1], changed))) diff --git a/tools/format-scala.py b/tools/format-scala.py new file mode 100755 index 0000000..a11bbb0 --- /dev/null +++ b/tools/format-scala.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Format the Scala code with scalafmt (and .scalafmt.conf): source files and the notebooks' code cells. + +Usage: tools/format-scala.py [--check] [--scalafmt PATH] [NOTEBOOK...] + +The source files (source/*.sc, riscv/) are formatted in place (with --check, only checked). Every code cell is +written to a temporary `.sc` file and all of them are formatted by one scalafmt run. A cell that +scalafmt cannot format is left as it is; UNFORMATTABLE lists how many such cells each notebook is +expected to have (cells that show a syntax error on purpose), and a different number is an error. +With --check, nothing is written and the exit status is 1 if a cell would change. +""" + +import argparse +import glob +import json +import os +import re +import subprocess +import sys +import tempfile +from collections import Counter + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +# notebook -> number of code cells that scalafmt cannot format +UNFORMATTABLE = {"3.6_types.ipynb": 1} # `case (0.U) =>`: a pattern cannot be a hardware literal + + +def code_cells(nb): + return [c for c in nb["cells"] if c["cell_type"] == "code" and "".join(c["source"]).strip()] + + +def to_lines(text): + lines = text.split("\n") + return [line + "\n" for line in lines[:-1]] + [lines[-1]] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--check", action="store_true", help="report cells that would change, write nothing") + parser.add_argument("--scalafmt", default="scalafmt", help="scalafmt executable") + parser.add_argument("notebooks", nargs="*", help="notebooks to format (default: all, and the source files)") + args = parser.parse_args() + config = ["--config", os.path.join(ROOT, ".scalafmt.conf"), "--non-interactive"] + + def scalafmt(*argv, **kw): + try: + return subprocess.run([args.scalafmt, *config, *argv], **kw) + except FileNotFoundError: + sys.exit(f"scalafmt not found ({args.scalafmt}); see CONTRIBUTING.md, or pass --scalafmt PATH") + + # The source files (only when formatting everything): the notebooks' setup script and riscv/ + patterns = ["source/*.sc", "riscv/*.sbt", "riscv/src/**/*.scala", "riscv/solutions/**/*.scala"] + scripts = ( + [] if args.notebooks else sorted(f for p in patterns for f in glob.glob(os.path.join(ROOT, p), recursive=True)) + ) + mode = ["--test"] if args.check else [] + scripts_ok = not scripts or scalafmt(*mode, *scripts, cwd=ROOT).returncode == 0 + + paths = sorted({os.path.abspath(p) for p in args.notebooks} or glob.glob(os.path.join(ROOT, "*.ipynb"))) + + notebooks = {} + with tempfile.TemporaryDirectory() as tmp: + files = {} # temporary file name -> (notebook path, cell) + for path in paths: + with open(path, encoding="utf-8") as f: + notebooks[path] = json.load(f) + for cell in code_cells(notebooks[path]): + name = f"{len(files):05d}.sc" + with open(os.path.join(tmp, name), "w", encoding="utf-8", newline="\n") as f: + f.write("".join(cell["source"]) + "\n") + files[name] = (path, cell) + # One run for every cell, from the temporary directory: scalafmt only formats files below + # its working directory. It names each file it fails on (a parse error or a crash). + run = scalafmt(*files, cwd=tmp, capture_output=True, text=True) + # scalafmt names a file it fails on as "FailedToFormat: " (a crash) or ":: error" + failures_found = re.findall( + r"FailedToFormat: \S*?(\d{5}\.sc)\b|(\d{5}\.sc):\d+: error", run.stdout + run.stderr + ) + failed = {a or b for a, b in failures_found} & set(files) + if run.returncode != 0 and not failed: + sys.exit(f"scalafmt failed (exit status {run.returncode}):\n{run.stdout}{run.stderr}") + changed = set() + for name, (path, cell) in files.items(): + if name in failed: + continue + with open(os.path.join(tmp, name), encoding="utf-8") as f: + formatted = f.read().rstrip("\n") + if formatted != "".join(cell["source"]): + changed.add(path) + cell["source"] = to_lines(formatted) + + failures = Counter(os.path.basename(files[f][0]) for f in failed) + unexpected = [ + f"{name}: scalafmt cannot format {failures[name]} cell(s), expected {UNFORMATTABLE.get(name, 0)}" + for name in sorted({os.path.basename(p) for p in paths}) + if failures[name] != UNFORMATTABLE.get(name, 0) + ] + if unexpected: + print("\n".join(unexpected) + "\n" + run.stdout + run.stderr, file=sys.stderr) + for path in sorted(changed): + rel = os.path.relpath(path, ROOT) + if args.check: + print(f"{rel}: Scala cells are not formatted (run tools/format-scala.py)", file=sys.stderr) + else: + with open(path, "w", encoding="utf-8", newline="\n") as f: + json.dump(notebooks[path], f, indent=1, ensure_ascii=False) + f.write("\n") + print(f"formatted {rel}") + return 1 if unexpected or not scripts_ok or (args.check and changed) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/import-riscv-tests.py b/tools/import-riscv-tests.py new file mode 100755 index 0000000..f8f1ede --- /dev/null +++ b/tools/import-riscv-tests.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Import the rv32ui tests of riscv-tests into riscv/programs/riscv-tests/rv32ui/. + +Usage: tools/import-riscv-tests.py write the files + tools/import-riscv-tests.py --check fail if the committed files differ from a new import + +The tests are assembly with C preprocessor macros, and the course has no RISC-V compiler (its +assembler is riscv.Asm), so this script, which needs git and GCC's C preprocessor (cpp; the +committed files come from GCC 13, as on CI's Ubuntu 24.04), expands them once against +riscv/programs/riscv-tests/riscv_test.h, a test environment without CSRs. The expanded files are +committed; riscv.Asm assembles them in the Docker image. +""" + +import os +import shutil +import subprocess +import sys +import tempfile +import time + +REPOSITORY = "https://github.com/riscv-software-src/riscv-tests.git" +REVISION = "3df703cd52d5f0d8224e3c50bf03c6cb70efff98" # 2026-10-19 +# Tests left out, and why +EXCLUDED = { + "fence_i": "FENCE.I belongs to Zifencei, not RV32I", + "ma_data": "misaligned accesses halt the course's cores (no trap handler without CSRs)", +} + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TESTS = os.path.join(ROOT, "riscv", "programs", "riscv-tests") + + +def run(*cmd, **kw): + result = subprocess.run(cmd, capture_output=True, text=True, **kw) + if result.returncode != 0: + sys.exit(f"{' '.join(cmd)} failed:\n{result.stderr}") + return result.stdout + + +def generate(out): + """Write the expanded tests and the license into the directory `out`.""" + with tempfile.TemporaryDirectory() as tmp: + repo = os.path.join(tmp, "riscv-tests") + run("git", "init", "-q", repo) + for attempt in range(3): # the network may hiccup + fetch = subprocess.run(["git", "-C", repo, "fetch", "-q", "--depth", "1", REPOSITORY, REVISION]) + if fetch.returncode == 0: + break + time.sleep(5 * (attempt + 1)) + else: + sys.exit(f"cannot fetch riscv-tests {REVISION}") + run("git", "-C", repo, "checkout", "-q", "FETCH_HEAD") + source = os.path.join(repo, "isa", "rv32ui") + staged = os.path.join(tmp, "rv32ui") # replaces out/rv32ui once every test has expanded + os.makedirs(staged) + for name in sorted(f[:-2] for f in os.listdir(source) if f.endswith(".S")): + if name in EXCLUDED: + continue + expanded = run( + "cpp", + "-P", + "-x", + "assembler-with-cpp", + "-D__riscv_xlen=32", + "-I", + TESTS, + "-I", + os.path.join(repo, "isa", "macros", "scalar"), + f"{name}.S", + cwd=source, + ) + # without the comments of the macro files (they describe other extensions too) + lines = [l.rstrip() for l in expanded.splitlines() if l.strip() and not l.lstrip().startswith("#")] + header = ( + f"# riscv-tests {REVISION[:12]}, isa/rv32ui/{name}.S, expanded by tools/import-riscv-tests.py\n" + "# against riscv/programs/riscv-tests/riscv_test.h. Do not edit; see ../LICENSE.\n" + ) + with open(os.path.join(staged, f"{name}.S"), "w") as f: + f.write(header + "\n".join(lines) + "\n") + shutil.rmtree(os.path.join(out, "rv32ui"), ignore_errors=True) # no stale tests + shutil.move(staged, os.path.join(out, "rv32ui")) + shutil.copy(os.path.join(repo, "LICENSE"), os.path.join(out, "LICENSE")) + with open(os.path.join(out, "EXCLUDED"), "w") as f: + f.writelines(f"{name}: {why}\n" for name, why in sorted(EXCLUDED.items())) + + +if __name__ == "__main__": + if sys.argv[1:] not in ([], ["--check"]): + sys.exit(__doc__) + if sys.argv[1:] == ["--check"]: + with tempfile.TemporaryDirectory() as fresh: + generate(fresh) + diff = subprocess.run(["diff", "-r", "-x", "riscv_test.h", fresh, TESTS], capture_output=True, text=True) + if diff.returncode != 0: + sys.exit(f"riscv/programs/riscv-tests differs from a new import:\n{diff.stdout}") + print("riscv/programs/riscv-tests matches a new import") + else: + generate(TESTS) + print(f"imported riscv-tests {REVISION[:12]} into {os.path.relpath(TESTS, ROOT)}") diff --git a/tools/install.sh b/tools/install.sh new file mode 100755 index 0000000..38a05cf --- /dev/null +++ b/tools/install.sh @@ -0,0 +1,126 @@ +#!/bin/bash +# Install what the bootcamp needs outside Docker, on Ubuntu 24.04 or newer: a C++ compiler, a JDK, +# Graphviz and Python from apt (with sudo); Verilator from apt if it is 5.026 or newer, or else +# built from source; sbt, a Python environment with Jupyter and Yosys, and the Almond Scala kernel +# in the user's home. Run it from a clone of the repository; it can be run again. Install.md +# describes the same steps by hand. +# +# Usage: tools/install.sh +# Then: source ~/.local/share/chisel-bootcamp/venv/bin/activate && jupyter lab +# (the environment also holds the sbt and the Verilator that the script installed) +set -euo pipefail + +# The versions of the Docker image (tools/check-versions.py checks that they agree). +SCALA_VERSION=2.13.18 +ALMOND_VERSION=0.14.5 +COURSIER_VERSION=2.1.24 +COURSIER_SHA256=7aa975f12469726d6bb87852107afe0b8d6f3c82b12a49ef43cc6647c4e057ca +SBT_VERSION=1.13.1 +SBT_SHA256=4a20e36c1642b6d5be34ef641d2ed6c8c0d464e6145283730d5566716e4083be +YOWASP_YOSYS_VERSION=0.71.0.0.post1285 +YOWASP_RUNTIME_VERSION=1.96 +WASMTIME_VERSION=47.0.1 +# Verilator before 5.026 aborts now and then with "Internal Error: attempted to destroy locked +# Thread Pool" when ChiselSim compiles a design (verilator#5040); Ubuntu 24.04 has 5.020. +VERILATOR_MIN=5.026 +VERILATOR_VERSION=5.038 +VERILATOR_SHA256=f8c03105224fa034095ba6c8a06443f61f6f59e1d72f76b718f89060e905a0d4 +# firtool has no Linux/Arm64 build: on aarch64, the x86-64 one runs under qemu, as in the image +FIRTOOL_VERSION=1.160.0 +FIRTOOL_JAR_SHA256=8f66a76dd7e48dd3b5134bafa091e467d90d4aef2f85b0ebcf3659435f9b22e6 + +root=$(cd "$(dirname "$0")/.." && pwd) +prefix=$HOME/.local/share/chisel-bootcamp +venv=$prefix/venv +mkdir -p "$prefix" +download() { curl -fsSL --retry 3 -o "$1" "$2"; } + +sudo="" +[ "$(id -u)" -eq 0 ] || sudo=sudo +apt_install() { $sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends "$@"; } +$sudo apt-get update -qq +apt_install openjdk-17-jdk-headless verilator g++ make graphviz python3-venv curl ca-certificates git + +# Jupyter and Yosys, in a Python environment of their own; the tools below are linked into its bin/ +python3 -m venv "$venv" +"$venv/bin/pip" install -q --upgrade pip +"$venv/bin/pip" install -q jupyter "yowasp-yosys==$YOWASP_YOSYS_VERSION" \ + "yowasp-runtime==$YOWASP_RUNTIME_VERSION" "wasmtime==$WASMTIME_VERSION" + +# Verilator: the system's if it is new enough, or else a release built into the user's home (in a +# directory per version, so that changing VERILATOR_VERSION builds the new one) +system_verilator=$(/usr/bin/verilator --version | awk '{print $2}') +if ! dpkg --compare-versions "$system_verilator" ge "$VERILATOR_MIN"; then + built=$prefix/verilator-$VERILATOR_VERSION + if [ ! -x "$built/bin/verilator" ]; then + echo "Verilator $system_verilator is older than $VERILATOR_MIN: building $VERILATOR_VERSION (a few minutes)" + apt_install autoconf flex bison help2man perl python3 libfl-dev zlib1g-dev + src=$prefix/verilator-src + log=$prefix/verilator-build.log + rm -rf "$src" "$built" && mkdir -p "$src" + download "$prefix/verilator.tgz" "https://github.com/verilator/verilator/archive/refs/tags/v${VERILATOR_VERSION}.tar.gz" + echo "$VERILATOR_SHA256 $prefix/verilator.tgz" | sha256sum -c - + tar -xzf "$prefix/verilator.tgz" -C "$src" --strip-components=1 + rm "$prefix/verilator.tgz" + (cd "$src" && autoconf && ./configure --prefix="$built" && make -j"$(nproc)" && make install) >"$log" 2>&1 || { + tail -n 50 "$log" >&2 + echo "tools/install.sh: building Verilator failed; the whole log is $log" >&2 + exit 1 + } + rm -rf "$src" "$log" + fi + ln -sf "$built/bin/verilator" "$venv/bin/verilator" +else + rm -f "$venv/bin/verilator" # one that an earlier run built, which would hide the system's +fi + +# sbt, for the riscv/ project of Module 5 (in a directory per version, as Verilator) +sbt=$prefix/sbt-$SBT_VERSION +if [ ! -x "$sbt/bin/sbt" ]; then + download "$prefix/sbt.tgz" "https://github.com/sbt/sbt/releases/download/v${SBT_VERSION}/sbt-${SBT_VERSION}.tgz" + echo "$SBT_SHA256 $prefix/sbt.tgz" | sha256sum -c - + mkdir -p "$sbt" && tar -xzf "$prefix/sbt.tgz" -C "$sbt" --strip-components=1 + rm "$prefix/sbt.tgz" +fi +ln -sf "$sbt/bin/sbt" "$venv/bin/sbt" + +# the Almond kernel, for Scala 2.13 (Chisel 7 needs it) +coursier=$prefix/coursier-$COURSIER_VERSION +if [ ! -x "$coursier" ]; then + download "$coursier" "https://github.com/coursier/coursier/releases/download/v${COURSIER_VERSION}/coursier" + echo "$COURSIER_SHA256 $coursier" | sha256sum -c - + chmod +x "$coursier" +fi +"$coursier" bootstrap -r jitpack "sh.almond:scala-kernel_${SCALA_VERSION}:${ALMOND_VERSION}" \ + --default=true -o "$prefix/almond" --force +# in the venv, which its jupyter always searches: the JVM takes its home from the user database, +# not from $HOME, so a per-user install can land where jupyter does not look (as in CI containers) +"$prefix/almond" --install --force --jupyter-path "$venv/share/jupyter/kernels" + +# the bootcamp's notebook customization, unless there is another one already +custom=$HOME/.jupyter/custom/custom.js +mkdir -p "$(dirname "$custom")" +[ -e "$custom" ] || cp "$root/source/custom.js" "$custom" +cmp -s "$root/source/custom.js" "$custom" || echo "Left $custom as it is: append $root/source/custom.js to it by hand" + +# firtool on Linux/Arm64: the x86-64 build under qemu, which the environment's activation points +# Chisel at (elsewhere, Chisel downloads its own firtool on first use) +if [ "$(uname -m)" = aarch64 ]; then + firtool=$prefix/firtool-$FIRTOOL_VERSION + if [ ! -x "$firtool/firtool" ]; then + apt_install qemu-user unzip + mkdir -p "$firtool" + download "$firtool/firtool.jar" \ + "https://repo1.maven.org/maven2/org/chipsalliance/llvm-firtool/${FIRTOOL_VERSION}/llvm-firtool-${FIRTOOL_VERSION}-linux-x64.jar" + echo "$FIRTOOL_JAR_SHA256 $firtool/firtool.jar" | sha256sum -c - + unzip -p "$firtool/firtool.jar" org.chipsalliance/llvm-firtool/linux-x64/bin/firtool >"$firtool/firtool.x86_64" + rm "$firtool/firtool.jar" + printf '#!/bin/sh\nexec qemu-x86_64 "%s/firtool.x86_64" "$@"\n' "$firtool" >"$firtool/firtool" + chmod +x "$firtool/firtool" "$firtool/firtool.x86_64" + fi + grep -q CHISEL_FIRTOOL_PATH "$venv/bin/activate" || echo "export CHISEL_FIRTOOL_PATH=\"$firtool\"" >>"$venv/bin/activate" +fi + +PATH="$venv/bin:$PATH" +echo "Installed: $(verilator --version), sbt $(sbt --script-version), $(dot -V 2>&1)" +echo "Start the bootcamp with: source $venv/bin/activate && cd $root && jupyter lab"