verilator-5.020/0000755000175000017500000000000014544475344013425 5ustar carstencarstenverilator-5.020/.clang-format0000644000175000017500000000722514544475344016006 0ustar carstencarsten--- Language: Cpp # BasedOnStyle: LLVM AccessModifierOffset: -4 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlines: DontAlign AlignOperands: true AlignTrailingComments: false AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: true AllowShortCaseLabelsOnASingleLine: true AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: true AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: true BinPackArguments: true BinPackParameters: true BraceWrapping: AfterClass: false AfterControlStatement: false AfterEnum: false AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false AfterStruct: false AfterUnion: false AfterExternBlock: false BeforeCatch: false BeforeElse: false IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true BreakBeforeBinaryOperators: All BreakBeforeBraces: Attach BreakBeforeInheritanceComma: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeComma BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true ColumnLimit: 99 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: - Q_FOREACH - BOOST_FOREACH # Include grouping/sorting SortIncludes: true IncludeBlocks: Regroup IncludeCategories: - Regex: '"V3Pch.*\.h"' Priority: -2 # Precompiled headers - Regex: '"(config_build|verilated_config|verilatedos)\.h"' Priority: -1 # Sepecials before main header - Regex: '(<|")verilated.*' Priority: 1 # Runtime headers - Regex: '"V3.*__gen.*\.h"' Priority: 3 # Generated internal headers separately - Regex: '"V3.*"' Priority: 2 # Internal header - Regex: '".*"' Priority: 4 # Other non-system headers - Regex: '<[[:alnum:]_.]+>' Priority: 5 # Simple system headers next - Regex: '<.*>' Priority: 6 # Other system headers next IncludeIsMainRegex: '$' IndentCaseLabels: false IndentPPDirectives: None IndentWidth: 4 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBlockIndentWidth: 2 ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Left ReflowComments: true SortUsingDeclarations: true SpaceAfterCStyleCast: false SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true SpaceBeforeParens: ControlStatements SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 2 SpacesInAngles: false SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false SpacesInLineCommentPrefix: Minimum: 0 Maximum: -1 SpacesInParentheses: false SpacesInSquareBrackets: false Standard: Cpp11 TabWidth: 8 UseTab: Never ... verilator-5.020/.github/0000755000175000017500000000000014544475344014765 5ustar carstencarstenverilator-5.020/.github/PULL_REQUEST_TEMPLATE.md0000644000175000017500000000026714544475344020573 0ustar carstencarstenWe appreciate your contributing to Verilator. If this is your first commit, please add your name to docs/CONTRIBUTORS, and read our contributing guidelines in docs/CONTRIBUTING.rst. verilator-5.020/.github/labels.toml0000644000175000017500000001173014544475344017126 0ustar carstencarsten["area: assertions"] color = "ffffe8" name = "area: assertions" description = "Issue involves assertions" ["area: configure/compiling"] color = "ffffe8" name = "area: configure/compiling" description = "Issue involves configuring or compilating Verilator itself" ["area: coverage"] color = "ffffe8" name = "area: coverage" description = "Issue involves coverage generation" ["area: data-types"] color = "ffffe8" name = "area: data-types" description = "Issue involves data-types" ["area: documentation"] color = "ffffe8" name = "area: documentation" description = "Issue involves documentation" ["area: elaboration"] color = "ffffe8" name = "area: elaboration" description = "Issue involves elaboration phase" ["area: invoking/options"] color = "ffffe8" name = "area: invoking/options" description = "Issue involves options passed to Verilator" ["area: lint"] color = "ffffe8" name = "area: lint" description = "Issue involves SystemVerilog lint checking" ["area: parser"] color = "ffffe8" name = "area: parser" description = "Issue involves SystemVerilog parsing" ["area: performance"] color = "ffffe8" name = "area: performance" description = "Issue involves performance issues" ["area: portability"] color = "ffffe8" name = "area: portability" description = "Issue involves operating system/compiler portability" ["area: runtime result"] color = "ffffe8" name = "area: runtime result" description = "Issue involves an incorrect runtine result from Verilated model" ["area: scheduling"] color = "ffffe8" name = "area: scheduling" description = "Issue involves scheduling/ordering of events" ["area: tests"] color = "ffffe8" name = "area: tests" description = "Issue involves the testing system" ["area: usability"] color = "ffffe8" name = "area: usability" description = "Issue involves general usability" ["effort: days"] color = "d0c0b0" name = "effort: days" description = "Expect this issue to require roughly days of invested effort to resolve" ["effort: hours"] color = "f5e6d6" name = "effort: hours" description = "Expect this issue to require roughly hours of invested effort to resolve" ["effort: minutes"] color = "f5e6d6" name = "effort: minutes" description = "Expect this issue to require less than an hour of invested effort to resolve" ["effort: weeks"] color = "d0c0b0" name = "effort: weeks" description = "Expect this issue to require weeks or more of invested effort to resolve" ["good first issue"] color = "7057ff" name = "good first issue" description = "Good for newcomers" ["help wanted"] color = "008672" name = "help wanted" description = "Extra attention is needed" ["new"] color = "ff4400" name = "new" description = "New issue, not yet seen by maintainers" ["resolution: abandoned"] color = "cfd3d7" name = "resolution: abandoned" description = "Closed; not enough information or otherwise never finished" ["resolution: answered"] color = "cfd3d7" name = "resolution: answered" description = "Closed; only applies to questions which were answered" ["resolution: duplicate"] color = "cfd3d7" name = "resolution: duplicate" description = "Closed; issue or pull request already exists" ["resolution: external"] color = "cfd3d7" name = "resolution: external" description = "Closed; passed to another tool's bug tracker" ["resolution: fixed"] color = "cfd3d7" name = "resolution: fixed" description = "Closed; fixed" ["resolution: invalid"] color = "cfd3d7" name = "resolution: invalid" description = "Closed; issue or pull request is no longer relevant" ["resolution: no fix needed"] color = "cfd3d7" name = "resolution: no fix needed" description = "Closed; no fix required (not a bug)" ["resolution: wontfix"] color = "cfd3d7" name = "resolution: wontfix" description = "Closed; work won't continue on an issue or pull request" ["status: asked reporter"] color = "ffffff" name = "status: asked reporter" description = "Bug is waiting for reporter to answer a question" ["status: assigned"] color = "a0f0ff" name = "status: assigned" description = "Issue is assigned to someone to work on" ["status: blocked"] color = "00007f" name = "status: blocked" description = "Issue is waiting for another bug, when other bug is fixed, then goes to 'status: assigned'" ["status: discussion"] color = "d876e3" name = "status: discussion" description = "Issue is waiting for discussions to resolve" ["status: ready"] color = "b6c92a" name = "status: ready" description = "Issue is ready for someone to fix; then goes to 'status: assigned'" ["type: bug"] color = "d73a4a" name = "type: bug" description = "Defect" ["type: feature-IEEE"] color = "cfccff" name = "type: feature-IEEE" description = "Request to add new feature, described in IEEE 1800" ["type: feature-non-IEEE"] color = "cfccff" name = "type: feature-non-IEEE" description = "Request to add new feature, outside IEEE 1800" ["type: maintenance"] color = "cfccff" name = "type: maintenance" description = "Internal maintenance task" ["type: q and a"] color = "84ba34" name = "type: q and a" description = "Question and answer about some feature or user question" verilator-5.020/.github/ISSUE_TEMPLATE/0000755000175000017500000000000014544475344017150 5ustar carstencarstenverilator-5.020/.github/ISSUE_TEMPLATE/questions.md0000644000175000017500000000046214544475344021526 0ustar carstencarsten--- name: Q and A, or Other about: Use this to ask a question, not related to a specific bug nor feature request. (Note our contributor agreement at https://github.com/verilator/verilator/blob/master/docs/CONTRIBUTING.rst) title: '' labels: new assignees: '' --- How may we help - what is your question? verilator-5.020/.github/ISSUE_TEMPLATE/bug_report.md0000644000175000017500000000124314544475344021642 0ustar carstencarsten--- name: Bug report about: Use this to report that something isn't working as expected, and it isn't "Unsupported." (Note our contributor agreement at https://github.com/verilator/verilator/blob/master/docs/CONTRIBUTING.rst) title: '' labels: new assignees: '' --- Thanks for taking the time to report this. Can you attach an example that shows the issue? (Must be openly licensed, ideally in test_regress format.) What 'verilator' command line do we use to run your example? What 'verilator --version' are you using? Did you try it with the git master version? What OS and distribution are you using? May we assist you in trying to fix this in Verilator yourself? verilator-5.020/.github/ISSUE_TEMPLATE/feature.md0000644000175000017500000000101214544475344021117 0ustar carstencarsten--- name: Feature Request about: Use this to request something should be supported, or a new feature added. (Note our contributor agreement at https://github.com/verilator/verilator/blob/master/docs/CONTRIBUTING.rst) title: '' labels: new assignees: '' --- Thanks for taking the time to report this. What would you like added/supported? Can you attach an example that runs on other simulators? (Must be openly licensed, ideally in test_regress format.) May we assist you in trying to fix this in Verilator yourself? verilator-5.020/.github/workflows/0000755000175000017500000000000014544475344017022 5ustar carstencarstenverilator-5.020/.github/workflows/build.yml0000644000175000017500000001503514544475344020650 0ustar carstencarsten# DESCRIPTION: Github actions config # This name is key to badges in README.rst, so we use the name build # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 name: build on: push: pull_request: workflow_dispatch: schedule: - cron: '0 0 * * 0' # weekly env: CI_OS_NAME: linux CI_COMMIT: ${{ github.sha }} CCACHE_COMPRESS: 1 CCACHE_DIR: ${{ github.workspace }}/.ccache CCACHE_LIMIT_MULTIPLE: 0.95 defaults: run: shell: bash working-directory: repo concurrency: group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} cancel-in-progress: true jobs: build: strategy: fail-fast: false matrix: os: [ubuntu-22.04, ubuntu-20.04] compiler: - { cc: clang, cxx: clang++ } - { cc: gcc, cxx: g++ } # m32 1 is deprecated, not here to speed up regressions m32: [0] exclude: # Build pull requests only with ubuntu-22.04 and without m32 # - os: ${{ github.event_name == 'pull_request' && 'ubuntu-18.04' || 'do-not-exclude' }} # - os: ${{ github.event_name == 'pull_request' && 'ubuntu-20.04' || 'do-not-exclude' }} # - m32: ${{ github.event_name == 'pull_request' && 1 || 'do-not-exclude' }} # Build -m32 only on ubuntu-22.04 clang++ - {os: ubuntu-18.04, m32: 1} - {os: ubuntu-20.04, m32: 1} - compiler: { cc: gcc, cxx: g++ } m32: 1 include: # Build GCC 10 on ubuntu-20.04 - os: ubuntu-20.04 compiler: { cc: gcc-10, cxx: g++-10 } m32: 0 runs-on: ${{ matrix.os }} name: Build | ${{ matrix.os }} | ${{ matrix.compiler.cc }} ${{ matrix.m32 && '| -m32' || '' }} env: CI_BUILD_STAGE_NAME: build CI_RUNS_ON: ${{ matrix.os }} CI_M32: ${{ matrix.m32 }} CC: ${{ matrix.compiler.cc }} CXX: ${{ matrix.compiler.cxx }} CACHE_BASE_KEY: build-${{ matrix.os }}-${{ matrix.compiler.cc }}-m32=${{ matrix.m32 }} CCACHE_MAXSIZE: 1000M # Per build matrix entry (* 5 = 5000M in total) VERILATOR_ARCHIVE: verilator-${{ github.sha }}-${{ matrix.os }}-${{ matrix.compiler.cc }}${{ matrix.m32 && '-m32' || '' }}.tar.gz steps: - name: Checkout uses: actions/checkout@v3 with: path: repo - name: Cache $CCACHE_DIR uses: actions/cache@v3 env: CACHE_KEY: ${{ env.CACHE_BASE_KEY }}-ccache with: path: ${{ env.CCACHE_DIR }} key: ${{ env.CACHE_KEY }}-${{ github.sha }} restore-keys: | ${{ env.CACHE_KEY }}- - name: Install packages for build run: ./ci/ci-install.bash - name: Build run: ./ci/ci-script.bash - name: Tar up repository working-directory: ${{ github.workspace }} run: tar --posix -c -z -f ${{ env.VERILATOR_ARCHIVE }} repo - name: Upload tar archive uses: actions/upload-artifact@v3 with: path: ${{ github.workspace }}/${{ env.VERILATOR_ARCHIVE }} name: ${{ env.VERILATOR_ARCHIVE }} test: needs: build strategy: fail-fast: false matrix: os: [ubuntu-22.04, ubuntu-20.04] compiler: - { cc: clang, cxx: clang++ } - { cc: gcc, cxx: g++ } m32: [0] suite: [dist-vlt-0, dist-vlt-1, dist-vlt-2, vltmt-0, vltmt-1] exclude: # Build pull requests only with ubuntu-22.04 and without m32 # - os: ${{ github.event_name == 'pull_request' && 'ubuntu-18.04' || 'do-not-exclude' }} # - os: ${{ github.event_name == 'pull_request' && 'ubuntu-20.04' || 'do-not-exclude' }} # - m32: ${{ github.event_name == 'pull_request' && 1 || 'do-not-exclude' }} # Build -m32 only on ubuntu-22.04 - {os: ubuntu-18.04, m32: 1} - {os: ubuntu-20.04, m32: 1} - compiler: { cc: gcc, cxx: g++ } m32: 1 include: # Test with GCC 10 on ubuntu-20.04 without m32 - {os: ubuntu-20.04, compiler: { cc: gcc-10, cxx: g++-10 }, m32: 0, suite: dist-vlt-0} - {os: ubuntu-20.04, compiler: { cc: gcc-10, cxx: g++-10 }, m32: 0, suite: dist-vlt-1} - {os: ubuntu-20.04, compiler: { cc: gcc-10, cxx: g++-10 }, m32: 0, suite: dist-vlt-2} - {os: ubuntu-20.04, compiler: { cc: gcc-10, cxx: g++-10 }, m32: 0, suite: vltmt-0} - {os: ubuntu-20.04, compiler: { cc: gcc-10, cxx: g++-10 }, m32: 0, suite: vltmt-1} runs-on: ${{ matrix.os }} name: Test | ${{ matrix.os }} | ${{ matrix.compiler.cc }} | ${{ matrix.suite }} ${{ matrix.m32 && '| -m32' || '' }} env: CI_BUILD_STAGE_NAME: test CI_RUNS_ON: ${{ matrix.os }} CI_M32: ${{ matrix.m32 }} CC: ${{ matrix.compiler.cc }} CXX: ${{ matrix.compiler.cxx }} CACHE_BASE_KEY: test-${{ matrix.os }}-${{ matrix.compiler.cc }}-m32=${{ matrix.m32 }}-${{ matrix.suite }} CCACHE_MAXSIZE: 100M # Per build per suite (* 5 * 5 = 2500M in total) VERILATOR_ARCHIVE: verilator-${{ github.sha }}-${{ matrix.os }}-${{ matrix.compiler.cc }}${{ matrix.m32 && '-m32' || '' }}.tar.gz steps: - name: Download tar archive uses: actions/download-artifact@v3 with: name: ${{ env.VERILATOR_ARCHIVE }} path: ${{ github.workspace }} - name: Unpack tar archive working-directory: ${{ github.workspace }} run: tar -x -z -f ${{ env.VERILATOR_ARCHIVE }} - name: Cache $CCACHE_DIR uses: actions/cache@v3 env: CACHE_KEY: ${{ env.CACHE_BASE_KEY }}-ccache with: path: ${{ env.CCACHE_DIR }} key: ${{ env.CACHE_KEY }}-${{ github.sha }} restore-keys: | ${{ env.CACHE_KEY }}- - name: Install test dependencies run: ./ci/ci-install.bash - name: Test env: TESTS: ${{ matrix.suite }} run: ./ci/ci-script.bash lint-py: runs-on: ubuntu-22.04 name: Lint Python env: CI_BUILD_STAGE_NAME: build CI_RUNS_ON: ubuntu-22.04 CI_M32: 0 steps: - name: Checkout uses: actions/checkout@v3 with: path: repo - name: Install packages for build run: ./ci/ci-install.bash # We use specific version numbers, otherwise a Python package # update may add a warning and break our build - name: Install packages for lint run: sudo pip3 install pylint==3.0.2 ruff==0.1.3 clang sphinx sphinx_rtd_theme sphinxcontrib-spelling breathe ruff - name: Configure run: autoconf && ./configure --enable-longtests --enable-ccwarn - name: Lint run: make -k lint-py verilator-5.020/.github/workflows/docker.yml0000644000175000017500000000524214544475344021017 0ustar carstencarsten# Build and push verilator docker image when tags are pushed to the repository. # The following variable(s) must be configured in the github repository: # DOCKER_HUB_NAMESPACE: docker hub namespace. # The following secrets must be configured in the github repository: # DOCKER_HUB_USER: user name for logging into docker hub # DOCKER_HUB_ACCESS_TOKEN: docker hub access token. name: Build Verilator Container on: push: tags: [ 'v*' ] workflow_dispatch: inputs: manual_tag: description: 'Git tag to use for image build' required: true type: string add_latest_tag: description: 'Tag workflow_dispatch docker image as "latest"' required: true type: boolean default: false jobs: build: runs-on: ubuntu-22.04 strategy: matrix: contexts: - "ci/docker/run:verilator" # - "ci/docker/buildenv:verilator-buildenv" steps: - name: Checkout uses: actions/checkout@v3 - name: Extract context variables run: | echo "${{ matrix.contexts }}" | sed -r 's/(.*):.*/build_context=\1/' >> "$GITHUB_ENV" echo "${{ matrix.contexts }}" | sed -r 's/.*:(.*)/image_name=\1/' >> "$GITHUB_ENV" echo "git_tag=${GITHUB_REF#refs/*/}" >> "$GITHUB_ENV" - name: Use manual tag if: ${{ inputs.manual_tag }} run: | echo "git_tag=${{ inputs.manual_tag }}" >> "$GITHUB_ENV" - name: Docker meta id: docker_meta uses: docker/metadata-action@v4 with: images: | ${{ vars.DOCKER_HUB_NAMESPACE }}/${{ env.image_name }} tags: | type=match,pattern=(v.*),group=1,enable=${{ startsWith(github.ref, 'refs/tags/v') }} type=raw,value=${{ inputs.manual_tag }},enable=${{ inputs.manual_tag != '' }} type=raw,value=latest,enable=${{ inputs.add_latest_tag == true }} - name: Set up QEMU uses: docker/setup-qemu-action@v2 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v2 with: buildkitd-flags: --debug - name: Login to Docker Hub uses: docker/login-action@v2 with: username: ${{ secrets.DOCKER_HUB_USER }} password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} - name: Build and Push to Docker uses: docker/build-push-action@v4 if: startsWith(github.ref, 'refs/tags/v') with: context: ${{ env.build_context }} build-args: SOURCE_COMMIT=${{ env.git_tag }} platforms: linux/arm64,linux/amd64 push: ${{ !env.ACT && startsWith(github.ref, 'refs/tags/v') }} tags: ${{ steps.docker_meta.outputs.tags }} labels: ${{ steps.docker_meta.outputs.labels }} verilator-5.020/.github/workflows/contributor.yml0000644000175000017500000000053514544475344022122 0ustar carstencarsten# DESCRIPTION: Github actions config # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 name: Contributor Agreement on: push: pull_request: workflow_dispatch: jobs: Test: name: "'docs/CONTRIBUTORS' was signed" runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v3 - run: test_regress/t/t_dist_contributors.pl verilator-5.020/.github/workflows/msbuild.yml0000644000175000017500000000252014544475344021203 0ustar carstencarsten# DESCRIPTION: Github actions config # This name is key to badges in README.rst, so we use the name build # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 name: msbuild on: push: pull_request: workflow_dispatch: schedule: - cron: '0 0 * * 0' # weekly env: CI_OS_NAME: win CI_COMMIT: ${{ github.sha }} CCACHE_COMPRESS: 1 CCACHE_DIR: ${{ github.workspace }}/.ccache CCACHE_LIMIT_MULTIPLE: 0.95 defaults: run: working-directory: repo concurrency: group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} cancel-in-progress: true jobs: windows: name: run on windows runs-on: windows-latest steps: - uses: actions/checkout@v3 with: path: repo - name: Cache $CCACHE_DIR uses: actions/cache@v3 with: path: ${{ env.CCACHE_DIR }} key: msbuild-msvc-cmake - name: compile env: WIN_FLEX_BISON: ${{ github.workspace }}/.ccache run: ./ci/ci-win-compile.ps1 - name: test build run: ./ci/ci-win-test.ps1 - name: Zip up repository run: Compress-Archive -LiteralPath install -DestinationPath verilator.zip - name: Upload zip archive uses: actions/upload-artifact@v3 with: path: ${{ github.workspace }}/repo/verilator.zip name: verilator-win.zip verilator-5.020/.github/workflows/format.yml0000644000175000017500000000217714544475344021044 0ustar carstencarsten# DESCRIPTION: Github actions config # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 name: format on: push: pull_request_target: workflow_dispatch: jobs: format: runs-on: ubuntu-22.04 name: Ubuntu 22.04 | format env: CI_OS_NAME: linux CI_RUNS_ON: ubuntu-22.04 CI_COMMIT: ${{ github.sha }} CI_M32: 0 steps: - name: Checkout uses: actions/checkout@v3 with: token: ${{ secrets.GITHUB_TOKEN }} - name: Install packages for build env: CI_BUILD_STAGE_NAME: build run: | bash ci/ci-install.bash && sudo apt-get install clang-format-14 yapf3 && git config --global user.email "action@example.com" && git config --global user.name "github action" - name: Format code run: | autoconf && ./configure && make -j 2 format CLANGFORMAT=clang-format-14 && git status - name: Push run: | if [ -n "$(git status --porcelain)" ]; then git commit . -m "Apply 'make format'" && git push origin fi verilator-5.020/.github/workflows/coverage.yml0000644000175000017500000000375014544475344021345 0ustar carstencarsten# DESCRIPTION: Github actions config # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 name: coverage on: workflow_dispatch: schedule: - cron: '0 0 * * 0' # weekly env: CI_OS_NAME: linux CI_COMMIT: ${{ github.sha }} CI_M32: 0 COVERAGE: 1 VERILATOR_ARCHIVE: verilator-coverage-${{ github.sha }}.tar.gz defaults: run: shell: bash working-directory: repo jobs: Build: runs-on: ubuntu-22.04 env: CI_BUILD_STAGE_NAME: build CI_RUNS_ON: ubuntu-22.04 steps: - name: Checkout uses: actions/checkout@v3 with: path: repo - name: Install packages for build run: ./ci/ci-install.bash - name: Build run: ./ci/ci-script.bash - name: Tar up repository working-directory: ${{ github.workspace }} run: tar --posix -c -z -f ${{ env.VERILATOR_ARCHIVE }} repo - name: Upload tar archive uses: actions/upload-artifact@v3 with: path: ${{ github.workspace }}/${{ env.VERILATOR_ARCHIVE }} name: ${{ env.VERILATOR_ARCHIVE }} Test: needs: Build strategy: fail-fast: false matrix: test: - vlt- - vltmt- num: - 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 include: - { test: dist, num: '' } runs-on: ubuntu-22.04 name: test-${{ matrix.test }}${{ matrix.num }} env: CI_BUILD_STAGE_NAME: test CI_RUNS_ON: ubuntu-22.04 steps: - name: Download tar archive uses: actions/download-artifact@v3 with: name: ${{ env.VERILATOR_ARCHIVE }} path: ${{ github.workspace }} - name: Unpack tar archive working-directory: ${{ github.workspace }} run: tar -x -z -f ${{ env.VERILATOR_ARCHIVE }} - name: Install test dependencies run: ./ci/ci-install.bash - name: Test env: TESTS: coverage-${{ matrix.test }}${{ matrix.num }} run: ./ci/ci-script.bash verilator-5.020/Changes0000644000175000017500000053646014544475344014736 0ustar carstencarsten.. for github, vim: syntax=reStructuredText =============================== Revision History and Change Log =============================== The changes in each Verilator version are described below. The contributors that suggested a given feature are shown in []. Thanks! Verilator 5.020 2024-01-01 ========================== **Major:** * Support compilation with precompiled headers with Make and GCC or CLang. * Change include to systemc instead of systemc.h (#4622) (#4623). [Chih-Mao Chen] This may require that SystemC programs add 'using namespace sc_core', 'using namespace sc_dt'. **Minor:** * Add devcontainer support (#4748). [Stefan Wallentowitz] * Support `iff` in sensitivity list (#1482) (#4626). [Krzysztof Bieganski, Antmicro Ltd.] * Support parameterized virtual interfaces (#4047) (#4743). [Ryszard Rozak, Antmicro Ltd.] * Support --timing triggers for virtual interfaces (#4673). [Krzysztof Bieganski, Antmicro Ltd.] * Support ccache when compiling Verilator with CMake (#4678). [Anthony Donlon] * Support passing constraints to --xml-only output (still otherwise unsupported) (#4683). [Shahid Ikram] * Support node memory usage information in --stats (#4684). [Geza Lore] * Support vpiConstType in vpi_get() (#4761). [Todd Strader] * Support vpi_iterate on packages with vpiInstance (#4726). [Todd Strader] * Support multiple parameters in virtual interfaces (#4745). [Ryszard Rozak, Antmicro Ltd.] * Support user C/C++ code in final archive, and make a lib{model}.a (#4749) (#4754). [Fan Shupei] * Support inside operator on unpacked arrays and queues (#4751). [Ryszard Rozak, Antmicro Ltd.] * Support VPI parameter iteration (#4765). [Todd Strader] * Support packages in vpi_handle_by_name() (#4768). [Todd Strader] * Support invoking interface methods on virtual interface variables (#4774) (#4775). [Jordan McConnon] * Remove deprecated options (#4663). [Geza Lore] * Remove older compiler support; require C++14 or newer (#4784) (#4786). * Optimize timing-delayed queue (#4584). [qrqiuren] * Optimize substitute optimization memory usage (#4687). [Geza Lore] * Optimize wide primitive operations with -Oz (#4733). [Geza Lore] * Optimize V3Premit performance etc. (#4736). [Geza Lore] * Fix VPI TOP level variable iteration (#3919) (#4618). [Marlon James] * Fix display with no % printing assoc array (#4376). [Alex Solomatnikov] * Fix scheduling of external force signals (#4577) (#4668). [Geza Lore] * Fix a memory leak in V3Fork (#4628). [Krzysztof Boroński] * Fix linking parameterized hierarchical blocks and recursive hierarchical blocks (#4654). [Anthony Donlon] * Fix identifiers that end with '_' on Windows (#4655). [Anthony Donlon] * Fix 'for' loop with outside variable reference (#4660). [David Harris] * Fix tracing FST enums (#4661) (#4756). [Todd Strader] * Fix interface parameters used in loop generate constructs (#4664) (#4665). [Anthony Donlon] * Fix C++20 compilation errors (#4670). * Fix deadlocks in error handler (#4672). [Mariusz Glebocki, Antmicro Ltd.] * Fix MingW compilation (#4675). [David Ledger] * Fix trace when using SystemC with certain configurations (#4676). [Anthony Donlon] * Fix range access to classes depending on parameter resolution (#4681). [Krzysztof Boroński] * Fix select into constant And/Or/Xor pattern (#4689). [Geza Lore] * Fix access type of function arguments (#4692) (#4694). [Ryszard Rozak, Antmicro Ltd.] * Fix dynamic NBAs with automatic vars (#4696). [Krzysztof Bieganski, Antmicro Ltd.] * Fix # 0 delays for process resumption, etc. (#4697). [Krzysztof Boroński] * Fix conflicted namespace for coroutines (#4701) (#4707). [Jinyan Xu] * Fix compilers seeing empty input due to file system races (#4708). [Flavien Solt] * Fix shift of > 32-bit number (#4719). [Flavien Solt] * Fix Windows include gates in filesystem Flush implementation. (#4720). [William D. Jones] * Fix power operator with wide numbers and constants (#4721) (#4763). [Flavien Solt] * Fix parameter passing to ports (#4723). [Ryszard Rozak, Antmicro Ltd.] * Fix block names of nested do..while loops (#4728). [Ryszard Rozak, Antmicro Ltd.] * Fix class name in error on 'new' on virtual class (#4739). [Ryszard Rozak, Antmicro Ltd.] * Fix typedefs pointing to parameterized classes (#4747). [Ryszard Rozak, Antmicro Ltd.] * Fix $finish twice to no longer exit (#4757). [Tim Hutt] * Fix dynamic NBA conditions (#4773). [Krzysztof Bieganski, Antmicro Ltd.] * Fix `V3Fork` stage to run only if `--timing` is set (#4778). [Krzysztof Bieganski, Antmicro Ltd.] * Fix max multiply width and add runtime assertions if too small. (#4781) Verilator 5.018 2023-10-30 ========================== **Major:** * Support compilation with precompiled headers with Make and GCC or CLang. * Change include of systemc instead of systemc.h (#4622) (#4623). [Chih-Mao Chen] This may require that SystemC programs add 'using namespace sc_core', 'using namespace sc_dt'. **Minor:** * Add SIDEEFFECT warning on mishandled side effect cases. * Add trace() API even when Verilated without --trace (#4462). [phelter] * Add warning on interface instantiation without parens (#4094). [Gökçe Aydos] * Add sv_vpi_user.h from IEEE 1800-2017 Annex M (#4606). [Marlon James] * Support 'disable fork' (#4125) (#4569). [Aleksander Kiryk, Antmicro Ltd.] * Support 'wait fork' (#4586). [Aleksander Kiryk, Antmicro Ltd.] * Support 'randc' (#4349). * Support assigning events (#4403). [Krzysztof Boroński] * Support resizing function call inout arguments (#4467). * Support NBAs in non-inlined functions/tasks (#4496) (#4572). [Krzysztof Bieganski, Antmicro Ltd.] * Support converting parameters inside modules to localparams (#4511). [Anthony Donlon] * Support concatenation of unpacked arrays (#4558). [Yutetsu TAKATSUKASA] * Support Clang 16 (#4592). [Mariusz Glebocki] * Support VPI variables of real and string data types (#4594). [Marlon James] * Support making VL_LOCK_SPINS configurable (#4599). [Geza Lore] * Change code --stats output (#4597). [Geza Lore] * Change --prof-exec infrastructure and report (#4602). [Geza Lore] * Change lint_off to not propagate upwards to files including where the lint_off is. * Optimize empty expression statements (#4544). * Optimize trace internals (#4610) (#4612). [Geza Lore] * Optimize internal performance issues (#4638). [Geza Lore] * Fix conversion of impure logical expressions to bit expressions (#487 partial) (#4437). [Ryszard Rozak, Antmicro Ltd.] * Fix enum functions in localparams (#3999). [Andrew Nolte] * Fix passing arguments by reference (#3385 partial) (#4489). [Ryszard Rozak, Antmicro Ltd.] * Fix multithreading handling to separate by code units that use/never use it (#4228). [Mariusz Glebocki, Antmicro Ltd.] * Fix usage of annotation options (#4486) (#4504). [Michal Czyz] * Fix detecting local vars in nested forks (#4493) (#4506). [Kamil Rakoczy] * Fix handling input file path separator (#4515) (#4516). [Anthony Donlon] * Fix mis-support for parameterized UDPs (#4518). [Anthony Donlon] * Fix constant conversion of $realtobits, $bitstoreal (#4522). [Andrew Nolte] * Fix conversion of integers in $display '%e' (#4528). [muzafferkal] * Fix non-inlined interface tracing (#3984) (#4530). [Todd Strader] * Fix stream operations with operands of struct type (#4531) (#4532). [Ryszard Rozak, Antmicro Ltd.] * Fix 'this' in a constructor (#4533). [Ryszard Rozak, Antmicro Ltd.] * Fix stream shift operator of 32 bits (#4536). [Julien Faucher] * Fix object destruction after a copy constructor (#4540) (#4541). [Ryszard Rozak, Antmicro Ltd.] * Fix inlining of real functions miscasting (#4543). [Andrew Nolte] * Fix broken link error for enum references (#4551). [Anthony Donlon] * Fix logical expressions with class objects - caching in v3Const (#4552). [Ryszard Rozak, Antmicro Ltd.] * Fix using functions/tasks following class definition inside module (#4553). [Anthony Donlon] * Fix large constant buffer overflow (#4556). [Varun Koyyalagunta] * Fix instance arrays connecting to array of structs (#4557). [raphmaster] * Fix error message for invalid parameter overrides (#4559). [Anthony Donlon] * Fix shift to remove operation side effects (#4563). * Fix compile warning on unused member function variable (#4567). * Fix method narrowing conversion compiler error (#4568). * Fix interface comparison (#4570). [Krzysztof Bieganski, Antmicro Ltd.] * Fix dynamic triggers for named events (#4571). [Krzysztof Bieganski, Antmicro Ltd.] * Fix dictionaries with keys of class types (#4576). [Ryszard Rozak, Antmicro Ltd.] * Fix to not remap local assign intervals in forks (#4583). [Krzysztof Bieganski, Antmicro Ltd.] * Fix display optimization ignoring side effects (#4585). * Fix PLI/DPI user defined system task/function grammar (#4587) (#4588). [Quentin Corradi] * Fix fault on empty clocking block (#4593). [Alex Mykyta] * Fix creating implicit nets for inputs of gate primitives (#4603). [Geza Lore] * Fix try_put method of unbounded mailbox (#4608). [Ryszard Rozak, Antmicro Ltd.] * Fix stable name generation in V3Fork (#4615) (#4624). [Krzysztof Boroński] * Fix virtual methods (#4616). [Ryszard Rozak, Antmicro Ltd.] * Fix insertion at queue end (#4619). [Krzysztof Boroński] * Fix rand fields of reference types (#4627). [Ryszard Rozak, Antmicro Ltd.] * Fix dynamic casts of null values (#4631). [Ryszard Rozak, Antmicro Ltd.] * Fix signals read via virtual interfaces being misoptimized (#4645). [Krzysztof Bieganski, Antmicro Ltd.] * Fix handling of static keyword in methods (#4649). [Ryszard Rozak, Antmicro Ltd.] * Fix preprocessor to show `line 2 on resumed file. Verilator 5.016 2023-09-16 ========================== **Minor:** * Add prepareClone and atClone APIs for Verilated models (#3503) (#4444). [Yinan Xu] * Add check for conflicting options e.g. binary and lint-only (#4409). [Ethan Sifferman] * Add --no-trace-top to not trace top signals (#4412) (#4422). [Frans Skarman] * Support recursive function calls (#3267). * Support assignments of packed values to stream expressions on queues (#4401). [Ryszard Rozak, Antmicro Ltd] * Support no-parentheses calls to static methods (#4432). [Krzysztof Boroński] * Support block_item_declaration in forks (#4455). [Krzysztof Boroński] * Support assignments of stream expressions on queues to packed values (#4458). [Ryszard Rozak, Antmicro Ltd] * Support function non-constant default arguments (#4470). * Support 'let'. * Optimize Verilator executable size by refactoring error reporting routines (#4446). [Anthony Donlon] * Optimize Verilation runtime pointers and graphs (#4396) (#4397) (#4398). [Krzysztof Bieganski, Antmicro Ltd] * Optimize preparations towards multithreaded Verilation (#4291) (#4463) (#4476) (#4477) (#4479). [Kamil Rakoczy, Antmicro Ltd] * Fix Windows filename format, etc (#3873) (#4421). [Anthony Donlon]. * Fix t_dist_cppstyle Perl performance issue (#4085). [Srinivasan Venkataramanan] * Fix using type in parameterized classes without #() (#4281) (#4440). [Anthony Donlon] * Fix false INFINITELOOP on forever..mailbox.get() (#4323). [Srinivasan Venkataramanan] * Fix data type of condition operation on class objects (#4345) (#4352). [Ryszard Rozak, Antmicro Ltd] * Fix variables mutated under fork..join_none/join_any blocks into anonymous objects (#4356). [Krzysztof Boroński] * Fix V3CUse, do not consider implementations (.cpp) at all (#4386). [Krzysztof Boroński] * Fix ++/-- under statements (#4399). [Aleksander Kiryk, Antmicro Ltd] * Fix detection of mixed blocking and nonblocking assignment in nested assignments (#4404). [Ryszard Rozak, Antmicro Ltd] * Fix jumping over object initialization (#4411). [Krzysztof Boroński] * Fix multiple issues towards short circuit support (#4413) (#4460). [Ryszard Rozak, Antmicro Ltd] * Fix variable lifetimes in extern methods (#4414). [Krzysztof Boroński] * Fix multiple function definitions in V3Sched (#4416). [Hennadii Chernyshchyk] * Fix false UNUSEDPARAM on generate localparam (#4427). [Bill Pringlemeir] * Fix checking for parameter and port connections in the wrong place (#4428). [Anthony Donlon] * Fix coroutine handle movement during queue manipulation (#4431). [Aleksander Kiryk, Antmicro Ltd] * Fix nested assignments on the LHS (#4435). [Ryszard Rozak, Antmicro Ltd] * Fix false MULTITOP on bound interfaces (#4438). [Alex Solomatnikov] * Fix internal error on real conversion (#4447). [vdhotre-ventana] * Fix lifetime unknown error on enum.name (#4448). [jwoutersymatra] * Fix unstable output of VHashSha256 (#4453). [Anthony Donlon] * Fix static cast from a stream type (#4469) (#4485). [Ryszard Rozak, Antmicro Ltd] * Fix error on enum with VARHIDDEN of cell (#4482). [Michail Rontionov] * Fix lint of case statements with enum and wildcard bits (#4464) (#4487). [Anthony Donlon] * Fix reference to extended class in parameterized class (#4466). * Fix recursive display causing segfault (#4480). [Kuoping Hsu] * Fix the error message when the type of ref argument is wrong (#4490). [Ryszard Rozak, Antmicro Ltd] * Fix display %x formatting of real. * Fix mis-warning on #() in classes' own functions. * Fix IGNOREDRETURN to not warn on void-cast static function calls. * Fix ZERODLY to not warn on 'wait(0)'. Verilator 5.014 2023-08-06 ========================== **Minor:** * Deprecation planned for 32-bit pointer -m32 mode (#4268). * Deprecate CMake config below version 3.13 (#4389) (#4390). [Vito Gamberini] * Support some stream operations on queues (#4292). [Ryszard Rozak, Antmicro Ltd] * Support property declaration with empty parentheses (#4313) (#4317). [Anthony Donlon] * Support locator methods with "with" on assoc arrays (#4335). [Ryszard Rozak, Antmicro Ltd] * Support string replication with variable (#4341). [Aleksander Kiryk, Antmicro Ltd] * Support more types in wait (#4374). [Aleksander Kiryk, Antmicro Ltd] * Support static method calls as default values of function arguments (#4378). [Ryszard Rozak, Antmicro Ltd] * Add GENUNNAMED lint warning. [Srinivasan Venkataramanan, Deepa Palaniappan] * Add MISINDENT lint warning for misleading indentation. * Fix 'VlForkSync' redeclaration (#4277). [Krzysztof Bieganski, Antmicro Ltd] * Fix processes that can outlive their parents (#4253). [Krzysztof Boronski, Antmicro Ltd] * Fix duplicate fork names (#4295). [Ryszard Rozak, Antmicro Ltd] * Fix splitting coroutines (#4297) (#4307). [Jiamin Zhu] * Fix error when multiple duplicate DPI exports (#4301). * Fix class reference assignment checking (#4296). [Ryszard Rozak, Antmicro Ltd] * Fix handling of ref types in initial values of type parameters (#4304). [Ryszard Rozak, Antmicro Ltd] * Fix comparison of string parameters (#4308). [Ryszard Rozak, Antmicro Ltd] * Fix state update for always processes (#4311). [Aleksander Kiryk, Antmicro Ltd] * Fix multiple edge timing controls in class methods (#4318) (#4320) (#4344). [Krzysztof Bieganski, Antmicro Ltd] * Fix implicit calls of base class constructors with optional arguments (#4319). [Ryszard Rozak, Antmicro Ltd] * Fix propagation of process requirement (#4321). [Krzysztof Boroński] * Fix unhandled overloads in V3InstrCount (#4324). [Krzysztof Boroński] * Fix selects of static members (#4326). [Ryszard Rozak, Antmicro Ltd] * Fix references to members of results of static methods (#4327). [Ryszard Rozak, Antmicro Ltd] * Fix unique..with method on queues of class objects (#4328). [Ryszard Rozak, Antmicro Ltd] * Fix queue slicing (#4329). [Aleksander Kiryk, Antmicro Ltd] * Fix wildcard referring types (#4336) (#4342). [Aleksander Kiryk, Antmicro Ltd] * Fix comparison of class objects (#4346). [Ryszard Rozak, Antmicro Ltd] * Fix unexpected RefDType on assoc arrays (#4337). [Aleksander Kiryk, Antmicro Ltd] * Fix cmake astgen for Rocky Linux 8.7 (#4343). [Julian Daube] * Fix class timescale in class packages (#4348). [Krzysztof Bieganski, Antmicro Ltd] * Fix string concatenations (#4354). [Ryszard Rozak, Antmicro Ltd] * Fix unlinked task error from broken context (#4355) (#4402). [Aleksander Kiryk, Antmicro Ltd] * Fix selects on unpacked structs (#4359). [Ryszard Rozak, Antmicro Ltd] * Fix select operation on assoc array with wide keys (#4360). [Ryszard Rozak, Antmicro Ltd] * Fix non-public methods with wide output (#4364). [Ryszard Rozak, Antmicro Ltd] * Fix handling of super.new calls (#4366). [Ryszard Rozak, Antmicro Ltd] * Fix assign to input var in methods (#4367). [Aleksander Kiryk, Antmicro Ltd] * Fix VlProcess not found (#4368). [Aleksander Kiryk, Antmicro Ltd] * Fix order of evaluation of function calls in statements (#4375). [Ryszard Rozak, Antmicro Ltd] * Fix config_build.h issues (#4380) (#4381). [Andrew Miloradovsky] Verilator 5.012 2023-06-13 ========================== **Major:** * With -j or --build-jobs, multithread Verilator's emit phase of Verilation. [Kamil Rakoczy, Antmicro Ltd] Additional Verilator-internal stages will become multithreaded over time. **Minor:** * Add --main-top-name option for C main TOP name (#4235) (#4249). [Don Williamson] * Add creating __inputs.vpp file with --debug (#4177). [Tudor Timi] * Add NEWERSTD warning when using feature in newer language standard (#4168) (#4172). [Ethan Sifferman] * Add warning that timing controls in DPI exports are unsupported (#4238). [Krzysztof Bieganski, Antmicro Ltd] * Support std::process class (#4212). [Aleksander Kiryk, Antmicro Ltd] * Support inside expressions with strings and doubles (#4138) (#4139). [Krzysztof Boroński] * Support get_randstate/set_randstate class method functions. * Support for condition operator on class objects (#4214). [Ryszard Rozak, Antmicro Ltd] * Support array max (#4275). [Aleksander Kiryk, Antmicro Ltd] * Optimize VPI callValueCbs (#4155). [Hennadii Chernyshchyk] * Configure for faster C++ linking using 'mold', if it is installed. * Fix crash on duplicate imported modules (#3231). [Robert Balas] * Fix false WIDTHEXPAND on array declarations (#3959). [JOTEGO] * Fix marking overridden methods as coroutines (#4120) (#4169). [Krzysztof Bieganski, Antmicro Ltd] * Fix SystemC signal copy macro use (#4135). [Josep Sans] * Fix duplicate static names in blocks in functions (#4144) (#4160). [Stefan Wallentowitz] * Fix initialization order of initial static after function/task (#4159). [Kamil Rakoczy, Antmicro Ltd] * Fix linking AstRefDType if it has parameterized class ref (#4164) (#4170). [Ryszard Rozak, Antmicro Ltd] * Fix crash caused by $display() optimization (#4165) (#4166). [Tudor Timi] * Fix arrays of unpacked structs (#4173). [Risto Pejašinović] * Fix $fscanf of decimals overflowing variables (#4174). [Ahmed El-Mahmoudy] * Fix super.new missing data type (#4147). [Tudor Timi] * Fix missing class forward declarations (#4151). [Krzysztof Boroński] * Fix hashes of instances of parameterized classes (#4182). [Ryszard Rozak, Antmicro Ltd] * Fix forced assignments that override non-continuous assignments (#4183) (#4192). [Krzysztof Bieganski, Antmicro Ltd] * Fix wide structure VL_TOSTRING_W generation (#4188) (#4189). [Aylon Chaim Porat] * Fix references to members of parameterized base classes (#4196). [Ryszard Rozak, Antmicro Ltd] * Fix tracing undefined alignment (#4201) (#4288) [John Wehle] * Fix class specific same methods for AstVarScope, AstVar, and AstScope (#4203) (#4250). [John Wehle] * Fix dotted references in parameterized classes (#4206). [Ryszard Rozak, Antmicro Ltd] * Fix bit selections under parameterized classes (#4210). [Ryszard Rozak, Antmicro Ltd] * Fix duplicate std:: declaration with -I (#4215). [Harald Pretl] * Fix deep traversal of class inheritance timing (#4216). [Krzysztof Boroński] * Fix class parameters of enum types (#4219). [Ryszard Rozak, Antmicro Ltd] * Fix static methods with prototypes (#4220). [Ryszard Rozak, Antmicro Ltd] * Fix LATCH warning on function local variables (#4221) (#4284) [Julien Margetts] * Fix VCD scope types (#4227) (#4282). [Àlex Torregrosa] * Fix incorrect multi-driven lint warning (#4231) (#4248). [Adrien Le Masle] * Fix missing assignment for wide unpacked structs (#4233). [Jiamin Zhu] * Fix unpacked struct == and != operators (#4234) (#4240). [Risto Pejašinović] * Fix AstStructSel clean when data type is structure (#4241) (#4244). [Risto Pejašinović] * Fix function calls in with statements (#4245). [Ryszard Rozak, Antmicro Ltd] * Fix operator == for unpacked struct, if elements are VlUnpacked arrays (#4247). [Risto Pejašinović] * Fix STATIC lifetime for variables created from clocking items (#4262). [Krzysztof Boroński] * Fix names of foreach blocks (#4264). [Ryszard Rozak, Antmicro Ltd] * Fix iterated variables in foreach loops to have VAUTOM lifetimes (#4265). [Krzysztof Boroński] * Fix missing assignment for wide class members (#4267). [Jiamin Zhu] * Fix the global uses timing flag when forks exist (#4274). [Krzysztof Bieganski, Antmicro Ltd] * Fix struct redefinition (#4276). [Aleksander Kiryk, Antmicro Ltd] * Fix detection of wire/reg duplicates. * Fix false IMPLICITSTATIC on package functions. * Fix method calls on function return values. Verilator 5.010 2023-04-30 ========================== **Minor:** * Add --public-depth to force public to a certain instance depth (#3952). [Andrew Nolte] * Add --public-params flag (#3990). [Andrew Nolte] * Add CONSTRAINTIGN warning when constraint ignored. * Add STATICVAR warning and convert to automatic (#4018) (#4027) (#4030). [Ryszard Rozak, Antmicro Ltd] * Add error if class types don't match (#4064). [Ryszard Rozak, Antmicro Ltd] * Support class extends of package::class. * Support class srandom and class random stability. * Support class method calls without parenthesis (#3902) (#4082). [Srinivasan Venkataramanan] * Support method calls without parenthesis (#4034). [Ryszard Rozak, Antmicro Ltd] * Support parameterized return types of methods (#4122). [Ryszard Rozak, Antmicro Ltd] * Support parameterized class references in extends statement (#4146). [Ryszard Rozak, Antmicro Ltd] * Support complicated IEEE 'for' assignments. * Support $fopen as an expression. * Support ++/-- on dotted member variables. * Optimize static trigger evaluation (#4142). [Geza Lore, X-EPIC] * Optimize more xor trees (#4071). [Yutetsu TAKATSUKASA] * Change range order warning from LITENDIAN to ASCRANGE (#4010). [Iztok Jeras] * Change ZERODLY to a warning. * Fix random internal crashes (#666). [Dag Lem] * Fix install, standardization in cmake CMakeLists.txt (#3974). [Yu-Sheng Lin] * Fix UNDRIVEN warning seg fault (#3989). [Felix Neumärker] * Fix symbol entries when inheriting classes (#3995) (#3996). [Krzysztof Boroński] * Fix event controls reusing same variable (#4014). Kamil Rakoczy * Fix push to dynamic queue in struct (#4015). [ezchi] * Fix names for blocks in do..while loop (#4019). [Ryszard Rozak, Antmicro Ltd] * Fix randomize on null field (#4023). [Ryszard Rozak, Antmicro Ltd] * Fix rand fields in base classes (#4025). [Ryszard Rozak, Antmicro Ltd] * Fix large return blocks with --comp-limit-blocks (#4028). [tenghtt] * Fix clocking block scope internal error (#4032). [Srinivasan Venkataramanan] * Fix false LATCH warning on --assert 'unique else if' (#4033) ($4054). [Jesse Taube] * Fix characters from DEFENV literals for Conda (#4035) (#4044). [Tim Snyder] * Fix info message prints under --assert (#4036) (#4053). [Srinivasan Venkataramanan] * Fix C++ compile errors when passing class refs as task argument (#4063). [Krzysztof Bieganski, Antmicro Ltd] * Fix NBAs inside fork-joins (#4050). [Aleksander Kiryk, Antmicro Ltd] * Fix task calls as fork statements (#4055). [Krzysztof Bieganski, Antmicro Ltd] * Fix _Vilp used before declaration (#4057) (#4062). [Josep Sans] * Fix incorrect optimization of bit op tree (#4059) (#4070). [Yutetsu TAKATSUKASA] * Fix parameters in a class body to be localparam (#4061). [Ryszard Rozak, Antmicro Ltd] * Fix interface generate begin (#4065). [Srinivasan Venkataramanan] * Fix tracing with awaits at end of block (#4075) (#4076). [Krzysztof Bieganski, Antmicro Ltd] * Fix sense expression variable naming (#4081). [Kamil Rakoczy] * Fix importing symbols from base class (#4084). [Ryszard Rozak, Antmicro Ltd] * Fix false error on new const assignment (#4098). [Tudor Timi] * Fix unpacked structs under classes (#4102). [Tudor Timi] * Fix variables in class methods to be automatic (#4111) (#4137). [Peter Monsson] * Fix to use parallel build for projects with a lot of files (#4116). [Krzysztof Boroński] * Fix including __Syms header in generated C++ files (#4123). [Krzysztof Boroński] * Fix systemc namespace issues (#4126) (#4127). [Eyck Jentzsch] * Fix class param extends A=B (#4128). [Ryszard Rozak, Antmicro Ltd] * Fix missing begin block hierarchy in --xml-only cells section (#4129) (#4133). [Risto Pejašinović] * Fix resolution of class lvalues after parameterization (#4131). [Krzysztof Boroński] * Fix DFG error on $countbits (#4101) (#4143). [Paul Donahue] * Fix duplicating parameter class types (#4115). [Ryszard Rozak, Antmicro Ltd] * Fix class extend param references (#4136). [Ryszard Rozak, Antmicro Ltd] * Fix -CFLAGS to allow overriding optimization levels (#4140). [Peter Monsson] * Fix DPI function type alias (#4148) (#4149). [Toru Niina] * Fix deleting unused parameterized classes (#4150). [Ryszard Rozak, Antmicro Ltd] * Fix false ENUMVALUE on expressions and arrays. * Fix unnecessary verilated_std.sv waivers in --waiver-output. Verilator 5.008 2023-03-04 ========================== **Minor:** * Add --annotate-points option, change multipoint on line reporting (#3876). [Nassim Corteggiani] * Add --verilate-jobs option (#3889). [Kamil Rakoczy, Antmicro Ltd] * Add WIDTHEXPAND and WIDTHTRUNC warnings to replace WIDTH (#3900). [Andrew Nolte] * Add SOURCE_DATE_EPOCH for docs/guide/conf.py (#3918). [Larry Doolittle] * Add /*verilator public[flat|flat_rd|flat_rw| ]*/ metacomments (#3894). [Joseph Nwabueze] * Add lint warning on always_comb multidriven (#3888) (#3939). [Adam Bagley] * Add warning on ++/-- over expressions with potential side effects (#3976). [Krzysztof Boroński] * Add error on mixing .name and by-port instantiations. * Removed deprecated --cdc option. * Support unpacked unions. * Support interface classes and class implements. * Support global clocking and $global_clock. * Support class parameters without initial values. * Support cast to numbers from strings. * Support struct I/O in --lib-create (#3378) (#3892). [Varun Koyyalagunta] * Support function calls without parenthesis (#3903) (#3902). [Ryszard Rozak, Antmicro Ltd] * Support class extending its parameter (#3904). [Ryszard Rozak, Antmicro Ltd] * Support static function variables (#3830). [Ryszard Rozak, Antmicro Ltd] * Support recursive methods (#3987). [Ryszard Rozak, Antmicro Ltd] * Fix real parameters of infinity and NaN. * Fix pattern assignment to unpacked structs (#3510). [Mostafa Garnal] * Fix single-element replication to dynarray/unpacked/queue (#3548). [Gustav Svensk] * Fix constant enum methods (#3621). [Todd Strader] * Fix inconsistent naming of generate scope arrays (#3840). [Andrew Nolte] * Fix namespace fallback resolution (#3863) (#3942). [Aleksander Kiryk, Antmicro Ltd] * Fix std:: to be parsed first (#3864) (#3928). [Aleksander Kiryk, Antmicro Ltd] * Fix cmake warning if multiple SOURCES w/o PREFIX (#3916) (#3927). [Yoda Lee] * Fix parameterized class function linkage (#3917). [Ryszard Rozak] * Fix static members of type aliases of a parameterized class (#3922). [Ryszard Rozak, Antmicro Ltd] * Fix class extend parameter dot case (#3926). [Ryszard Rozak, Antmicro Ltd] * Fix MsWin missing directory exception, and ::std (#3928) (#3933) (#3935). [Kritik Bhimani] * Fix very long VPI signal names (#3929). [Marlon James] * Fix VPI upper interface scopes not found (#3937). [David Stanford] * Fix virus detection false positive (#3944). [Stuart Morris] * Fix constant string function assignment (#3945). [Todd Strader] * Fix constant format field widths (#3946). [Todd Strader] * Fix class field linking when a super classes is a param (#3949). [Ryszard Rozak, Antmicro Ltd] * Fix CMake bad C identifiers (#3948) (#3951). [Zixi Li] * Fix build on HP PA architecture (#3954). [John David Anglin] * Fix date on the front page of verilator.pdf (#3956) (#3957). [Larry Doolittle] * Fix associative arrays declared with ref type (#3960). [Ryszard Rozak, Antmicro Ltd] * Fix missing error on negative replicate (#3963). [Benjamin Menküc] * Fix self references to parameterized classes (#3962). [Ryszard Rozak, Antmicro Ltd] * Fix LITENDIAN warning is backwards (#3966) (#3967). [Cameron Kirk] * Fix subsequent parameter declarations (#3969). [Ryszard Rozak, Antmicro Ltd] * Fix timing delays to not truncate below 64 bits (#3973) (#3982). [Felix Neumärker] * Fix cmake on MacOS to mark weak symbols with -U linker flag (#3978) (#3979). [Peter Debacker] * Fix UNDRIVEN warning seg fault (#3989). [Felix Neumärker] * Fix coverage of class methods (#3998). [Tim Paine] * Fix packed array structure replication. * Fix enum.next(0) and enum.prev(0). Verilator 5.006 2023-01-22 ========================== **Minor:** * Support clocking blocks (#3674). [Krzysztof Bieganski, Antmicro Ltd] * Support packed structs (#3802). [Aleksander Kiryk, Antmicro Ltd] * Support Windows-native builds using cmake (#3814). [Kritik Bhimani] * Support p format for UnpackArray (#3877). [Aleksander Kiryk, Antmicro Ltd] * Support property calls without parenthesis (#3879) (#3893). [Ryszard Rozak, Antmicro Ltd] * Support import/export lists in modport (#3886). [Gökçe Aydos] * Support class queue equality (#3895). [Ilya Barkov] * Support type case and type equality comparisons. * Add IMPLICITSTATIC warning when a task/function is implicitly static (#3839). [Ryszard Rozak, Antmicro Ltd] * Add VL_VALUE_STRING_MAX_WORDS override (#3869). [Andrew Nolte] * Optimize expansion of extend operators. * Internal multithreading tests. [Mariusz Glebocki, et al, Antmicro Ltd] * Fix VPI one-time timed callbacks (#2778). [Marlon James, et al] * Fix initiation of function variables (#3815). [Dan Gisselquist] * Fix to zero possibly uninitialized bits in replications (#3815). * Fix crash in DFT due to width use after free (#3817) (#3820). [Jevin Sweval] * Fix signed/unsigned comparison compile warning (#3822). [Kamil Rakoczy] * Fix OS-X weak symbols with -U linker flag (#3823). [Jevin Sweval] * Fix wrong bit op tree optimization (#3824) (#3825). [Yutetsu TAKATSUKASA] * Fix self references when param class instantiated (#3833). [Ryszard Rozak, Antmicro Ltd] * Fix memory leak in V3Sched, etc. (#3834). [Geza Lore] * Fix compatibility with musl libc / Alpine Linux (#3845). [Sören Tempel] * Fix empty case items crash (#3851). [Rich Porter] * Fix VL_CPU_RELAX on MIPS/Armel/s390/sparc (#3843) (#3891). [Kamil Rakoczy] * Fix module parameter name collision (#3854) (#3855). [James Shi] * Fix unpacked array expansion (#3861). [Joey Liu] * Fix signed/unsigned parameter types (#3866). [James Shi] * Fix chain call of abstract class constructor (#3868) (#3883). [Ilya Barkov] * Fix to use same std in Verilator and Verilated compile (#3881). [Kamil Rakoczy, Antmicro Ltd] * Fix foreach unnamedblk duplicate error (#3885). [Ilya Barkov] * Fix elaboration of member selected classes (#3890). [Ilya Barkov] * Fix mismatched widths in DFG (#3872). [Geza Lore, Yike Zhou] * Fix lint for non-integral types in packed structs. * Fix generate case with empty body statements. Verilator 5.004 2022-12-14 ========================== **Major:** * Support named properties (#3667). [Ryszard Rozak, Antmicro Ltd] * Add ENUMVALUE warning when value misused for enum (#726) (#3777) (#3783). * Deprecate --no-threads; use --threads 1 for single threaded (#3703). [Kamil Rakoczy, Antmicro Ltd] **Minor:** * Support std::semaphore and typed std::mailbox (#3708). [Krzysztof Bieganski, Antmicro Ltd] * Support 'with' in unique, unique_index, min, max in queues (#3772). [Ryszard Rozak, Antmicro Ltd] * Support events in VCD/FST traces (#3759). [Yves Mathieu] * Support foreach loops on strings (#3760). [Ryszard Rozak, Antmicro Ltd] * Support member selects in with clauses (#3775). [Ryszard Rozak, Antmicro Ltd] * Support super.new calls (#3789). [Ryszard Rozak, Antmicro Ltd] * Support randcase. * Support pre_randomize and post_randomize. * Support $timeunit and $timeprecision. * Support assignment expressions. * Change ENDLABEL from warning into an error. * Internal AST improvements, also affect XML format (#3721). [Geza Lore] * Deprecate verilated_fst_sc.cpp and verilated_vcd_sc.cpp. * Disable stack size limit (#3706) (#3751). [Mariusz Glebocki] * Add error when use --exe with --lib-create (#3785). [Yinan Xu] * Fix jump handling in do while loops (#3731). [Ryszard Rozak, Antmicro Ltd] * Fix 'with' clause handling in functions (#3739). [Ryszard Rozak, Antmicro Ltd] * Fix CONTEXT compile error on MingW (#3741). [William D. Jones] * Fix MSVC compiler errors (#3742) (#3746). [Kritik Bhimani] * Fix CASEINCOMPLETE when covers all enum values (#3745) (#3782). [Guy-Armand Kamendje] * Fix return type of $countbits functions to int (#3725). [Ryszard Rozak, Antmicro Ltd] * Fix timing control in while-break loops (#3733) (#3769). [Ryszard Rozak, Antmicro Ltd] * Fix return in constructors (#3734). [Ryszard Rozak, Antmicro Ltd] * Fix missing UNUSED warnings with --coverage (#3736). [alejandro-castro-ortegon] * Fix tracing parameters overridden with -G (#3723). [Iztok Jeras] * Fix folding of LogAnd with non-bool operands (#3726). [Geza Lore] * Fix DFG optimization issues (#3740) (#3771). [Geza Lore] * Fix pre/postincrement operations (#3744) (#3756). [Ryszard Rozak, Antmicro Ltd] * Fix cross-compile for MingW, Arm and RISC-V (#3752). [Miodrag Milanović] * Fix $unit as base package for other packages (#3755). [Ryszard Rozak, Antmicro Ltd] * Fix make jobserver with submakes (#3758). [Gus Smith] * Fix to escape VERILATOR_ROOT file paths (#3764) (#3765). [Jiacheng Qian] * Fix empty string literals converting to string types (#3774). [miree] * Fix to remove $date from .vcd files (#3779). [Larry Doolittle] * Fix missing user objects in --lib-create mode (#3780) (#3784). [Yinan Xu] * Fix non-blocking assignments in forks (#3781) (#3800). [Krzysztof Bieganski, Antmicro Ltd] * Fix forks without any delayed statements (#3792) (#3801). [Krzysztof Bieganski, Antmicro Ltd] * Fix internal error in bit op tree optimization (#3793). [Yutetsu TAKATSUKASA] * Fix lint_off EOFNEWLINE in .vlt files (#3796). [Andrew Nolte] * Fix wait 0. * Fix comparing ranged slices of unpacked arrays. Verilator 5.002 2022-10-29 ========================== **Major:** * This is a major new release. * Require C++20 for the new --timing features. Upgrading to a C++20 or newer compiler is strongly recommended. * Support the Active and NBA scheduling regions as defined by the SystemVerilog standard (IEEE 1800-2017 chapter 4). This means all generated clocks are now simulated correctly (#3278, #3384). [Geza Lore, Shunyao CAD] * Support timing controls (delays, event controls in any location, wait statements) and forks. [Krzysztof Bieganski, Antmicro Ltd] This may require adding --timing or --no-timing. See docs for details. * Introduce a new combinational logic optimizer (DFG), that can yield significant performance improvements on some designs. [Geza Lore, Shunyao CAD] * Add --binary option as alias of --main --exe --build --timing (#3625). For designs where C++ was only used to make a simple no-I/O testbench, we recommend abandoning that C++, and instead letting Verilator build it with --binary (or --main). **Minor:** * Split UNUSED warning into genvar, param, and signal warnings (#3607). [Topa Topino] * Support standalone 'this' in classes (#2594) (#3248) (#3675). [Arkadiusz Kozdra, Antmicro Ltd] * Support tristate select/extend (#3604). [Ryszard Rozak, Antmicro Ltd> * Support linting for top module interfaces (#3635). [Kanad Kanhere] * Support virtual interfaces (#3654). [Arkadiusz Kozdra, Antmicro Ltd] * Support class type params without defaults (#3693). [Krzysztof Bieganski, Antmicro Ltd] * Support empty generate_regions (#3695). [mpb27] * Support access to constructs inside type parameters (#3702). [Arkadiusz Kozdra, Antmicro Ltd] * Add --dump-tree-dot to enable dumping Ast Tree .dot files (#3636). [Marcel Chang] * Add --get-supported to determine what features are in Verilator. * Add error on real edge event control. * Fix false LATCH warning on 'unique if' (#3088). [Rachit Nigam] * Fix cell assigning integer array parameters (#3299). [Michael Platzer] * Fix LSB error on --hierarchical submodules (#3539). [danbone] * Fix $display of fixed-width numbers (#3565). [Iztok Jeras] * Fix foreach and pre/post increment in functions (#3613). [Nandu Raj] * Fix linker errors in user-facing timing functions (#3657). [Krzysztof Bieganski, Antmicro Ltd] * Fix null access on optimized-out fork statements (#3658). [Krzysztof Bieganski, Antmicro Ltd] * Fix VPI inline module naming mismatch (#3690) (#3694). [Jiuyang Liu] * Fix deadlock in timeprecision when using SystemC (#3707). [Kamil Rakoczy, Antmicro Ltd] * Fix width mismatch on inside operator (#3714). [Àlex Torregrosa] Verilator 4.228 2022-10-01 ========================== **Announcement:** * The next release is anticipated to premiere Verilator Version 5. Please consider beta-testing the github 'develop-v5' branch, which will soon merge into the github 'master' branch (#3383). **Minor:** * Support some IEEE signal strengths (#3601) (#3629). [Ryszard Rozak, Antmicro Ltd] * Add --main to generate main() C++ (previously was experimental only). * Add --build-jobs, and rework arguments for -j (#3623). [Kamil Rakoczy] * Rename --bin to --build-dep-bin. * Rename debug flags --dumpi-tree, --dumpi-graph, etc. [Geza Lore] * Fix thread safety in SystemC VL_ASSIGN_SBW/WSB (#3494) (#3513). [Mladen Slijepcevic] * Fix crash in gate optimization of circular logic (#3543). [Bill Flynn] * Fix arguments in non-static method call (#3547) (#3582). [Gustav Svensk] * Fix default --mod-prefix when --prefix is repeated (#3603). [Geza Lore] * Fix calling trace() after open() segfault (#3610) (#3627). [Yu-Sheng Lin] * Fix typedef'ed class conversion to Boolean (#3616). [Aleksander Kiryk] * Fix Verilation speed when disabled warnings (#3632). [Kamil Rakoczy, Antmicro Ltd] Verilator 4.226 2022-08-31 ========================== **Minor:** * Add --future0 and --future1 options. * Support class parameters (#2231) (#3541). [Arkadiusz Kozdra, Antmicro Ltd] * Support wildcard index associative arrays (#3501). [Arkadiusz Kozdra, Antmicro Ltd] * Support negated properties (#3572). [Aleksander Kiryk] * Support $test$plusargs(expr) (#3489). * Rename trace rolloverSize() (#3570). * Improve Verilation speed with --threads on large designs. [Geza Lore] * Improve Verilation memory by reducing V3Number (#3521). [Mariusz Glebocki, Antmicro Ltd] * Fix struct pattern assignment (#2328) (#3517). [Mostafa Gamal] * Fix public combo propagation issues (#2905). [Todd Strader] * Fix incorrect tristate logic (#3399) [shareefj, Vighnesh Iyer] * Fix incorrect bit op tree optimization (#3470). [algrobman] * Fix bisonpre for MSYS2 (#3471). * Fix max memory usage (#3483). [Kamil Rakoczy, Antmicro Ltd] * Fix empty string arguments to display (#3484). [Grulfen] * Fix table optimizing away display (#3488). [Stefan Post] * Fix unique_ptr memory header for MinGW64 (#3493). * Fix $dump system task with --output-split-cfuncs (#3495) (#3497). [Varun Koyyalagunta] * Fix wrong bit op tree optimization (#3509). [Nathan Graybeal] * Fix nested default assignment for struct pattern (#3511) (#3524). [Mostafa Gamal] * Fix sformat string incorrectly cleared (#3515) (#3519). [Gustav Svensk] * Fix segfault exporting non-existent package (#3535). * Fix void-cast queue pop_front or pop_back (#3542) (#3364). [Drew Ranck] * Fix case statement comparing string literal (#3544). [Gustav Svensk] * Fix === with some tristate constants (#3551). [Ryszard Rozak, Antmicro Ltd] * Fix converting classes to string (#3552). [Arkadiusz Kozdra, Antmicro Ltd] * Fix --hierarchical with order-based pin connections (#3583) (#3585). [Kelin9298] Verilator 4.224 2022-06-19 ========================== **Major:** * VCD tracing is now parallelized with --threads (#3449). [Geza Lore, Shunyao CAD] **Minor:** * Add -f options to replace -O options (#3436). * Changed --no-merge-const-pool to -fno-merge-const-pool (#3436). * Changed --no-decoration to remove output whitespace (#3460). [Kamil Rakoczy] * Support compile time trace signal selection with tracing_on/off (#3323). [Shunyao CAD] * Support non-ANSI interface port declarations (#3439). [Geza Lore, Shunyao CAD] * Support concat assignment to packed array (#3446). * Improve conditional merging optimization (#3125). [Geza Lore, Shunyao CAD] * Define VM_TRACE_VCD when tracing in VCD format. [Geza Lore, Shunyao CAD] * Add assert when VerilatedContext is mis-deleted (#3121). [Rupert Swarbrick] * Internal prep work towards timing control. [Krzysztof Bieganski, Antmicro Ltd] * Fix hang with large case statement optimization (#3405). [Mike Urbach] * Fix UNOPTFLAT warning from initial static var (#3406). [Kamil Rakoczy] * Fix compile error when enable VL_LEAK_CHECKS (#3411). [HungMingWu] * Fix cmake rules to support higher-level targets (#3377) (#3386). [Martin Stadler] * Fix BLKANDNBLK on $readmem/$writemem (#3379). [Alex Solomatnikov] * Fix 'with' operator with type casting (#3387). [xiak95] * Fix incorrect conditional merging (#3409). [Raynard Qiao] * Fix passing VL_TRACE_FST_WRITER_THREAD in CMake build. [Geza Lore, Shunyao CAD] * Fix compile error under strict C++11 mode (#3463). [Kevin Kiningham] * Fix public unpacked input ports (#3465). [Todd Strader] Verilator 4.222 2022-05-02 ========================== **Minor:** * Split --prof-threads into --prof-exec and --prof-pgo (#3365). [Geza Lore, Shunyao CAD] * Deprecate 'vluint64_t' and similar types (#3255). * Raise error on assignment to const in initial blocks. [Geza Lore, Shunyao CAD] * Issue INITIALDLY/COMBDLY/BLKSEQ warnings consistent with Verilator execution. [Geza Lore, Shunyao CAD] * Support LoongArch ISA multithreading (#3353) (#3354). [Xi Zhang] * Fix MSVC localtime_s (#3124). * Fix Bison 3.8.2 error (#3366). [elike-ypq] * Fix rare bug in -Oz (V3Localize) (#3286). [Geza Lore, Shunyao CAD] * Fix tracing interfaces inside interfaces (#3309). [Kevin Millis] * Fix filenames with dots overwriting debug .vpp files (#3373). * Fix including VK_USER_OBJS in make library (#3370) (#3382). [Julien Margetts] * Fix hang in generate symbol references (#3391) (#3398). [Yoda Lee] * Fix missing #include (#3392). [Aliaksei Chapyzhenka] * Fix crash in recursive module inlining (#3393). [david-sawatzke] * Fix --protect-ids mangling names of library methods. [Geza Lore, Shunyao CAD] * Fix foreach segmentation fault (#3400). [Kamil Rakoczy] Verilator 4.220 2022-03-12 ========================== **Minor:** * Removed the deprecated lint_off flag -msg; use -rule instead. * Removed the deprecated "fl" attribute in XML output; use "loc" attribute instead. * Suppress WIDTH warning on negate using carry bit (#3295). [Peter Monsson] * Add trace dumpvars() call for selective runtime tracing (#3322). [Shunyao CAD] * Add VERILATOR_VERSION_INTEGER for determining API (#3343). [Larry Doolittle] * Improve various V3Combine algorithm details (#3328). [Yutetsu TAKATSUKASA] * Improve various V3Order algorithm details. [Geza Lore] * Fix MacOS arm64 build (#3285) (#3291). [Guokai Chen] * Fix signed number operation (#3294) (#3308). [Raynard Qiao] * Fix FST traces to include vector range (#3296) (#3297). [Jamie Iles] * Fix skipping public enum values with four-state values (#3303). * Fix $readmem file not found to be warning not error (#3310). [Alexander Grobman] * Fix class stringification on wide arrays (#3312). [Iru Cai] * Fix $fscanf etc to return -1 on EOF (#3313). [Jose Tejada] * Fix public function arguments that are arrayed (#3316). [pawel256] * Fix unnamedblk error on foreach (#3321). [Aliaksei Chapyzhenka] * Fix crash in recursive module inlining (#3324). [Larry Doolittle] * Fix VL_RESTORER behavior on passing a lvalue reference (#3326). [HungMingWu] * Fix compile error with --trace-fst --sc (#3332). [leavinel] * Fix cast to array types (#3333). [Todd Strader] * Fix Vdeeptemp error with --threads and --compiler clang (#3338). [Per Karlsson] Verilator 4.218 2022-01-17 ========================== **Major:** * Primary inputs and outputs (VL_INW/VL_OUTW) now use VlWide type. In general this should be backward compatible, but may lead to some wrapper code needing changes. * Option --cdc is deprecated and is planned for removal, file a bug if this is still being used. **Minor:** * Support class static members (#2233). * Support force/release (#2431) (#2593). [Shunyao CAD] * Add 'forceable' attribute to allow forcing from C++. (#3272). [Geza Lore, Shunyao CAD] * Support lower dimension looping in foreach loops (#3172). [Ehab Ibrahim] * Support up to 64 bit enums for .next/.prev/.name (#3244). [Alexander Grobman] * Reduce .rodata footprint of trace initialization (#3250). [Geza Lore, Shunyao CAD] * Support FST tracing in hierarchical Verilation (#3251). [Yutetsu TAKATSUKASA] * Use C++11 standard types for MacOS portability (#3254) (#3257). [Adrien Le Masle] * Fix make support for BSD ar (#2999) (#3256). [Julie Schwartz] * Fix bad ending address on $readmem (#3205). [Julie Schwartz] * Fix MSWIN compile error (#2681). [Unai Martinez-Corral] * Fix break under foreach loop (#3230). * Fix VL_STREAML_FAST_QQI with 64 bit left-hand-side (#3232) (#3235). [Adrien Le Masle] * Fix $sformat of inputs/outputs (#3236). [Adrien Le Masle] * Fix associative array first method as statement (#3228). [Adrien Le Masle] * Fix associative array foreach loop (#3229). * Fix $fclose not accepting expressions (#3237). [Julie Schwartz] * Fix $random not updating seed (#3238). [Julie Schwartz] * Fix top level param overwrite when package has same param (#3241) (#3247). [Adrien Le Masle] * Fix spurious UNUSED by ignoring inout pin connections (#3242). [Julie Schwartz] * Fix splitting of _eval and other top level functions. [Geza Lore, Shunyao CAD] * Fix internal error by inout port (#3258). [Yutetsu TAKATSUKASA] * Fix GCC 11 compile error (#3273). [HungMingWu] Verilator 4.216 2021-12-05 ========================== **Major:** * Add --lib-create, similar to --protect-lib but without protections. * Support tracing through --hierarchical/--lib-create libraries (#3200). **Minor:** * Internal code cleanups and improvements. [Geza Lore] * Improve --thread Verilation-time performance. * Support task name in $display %m (#3211). [Julie Schwartz] * Make 'bit', 'logic' and 'time' types unsigned by default. [Geza Lore] * Optimize $random concatenates/selects (#3114). * Fix array method names with parenthesis (#3181) (#3183). [Teng Huang] * Fix split_var assign merging (#3177) (#3179). [Yutetsu TAKATSUKASA] * Fix wrong bit op tree optimization (#3185). [Yutetsu TAKATSUKASA] * Fix some SliceSels not being constants (#3186) (#3218). [Michaël Lefebvre] * Fix nested generate if genblk naming (#3189). [yanx21] * Fix hang on recursive definition error (#3199). [Jonathan Kimmitt] * Fix display of signed without format (#3204). [Julie Schwartz] * Fix display of empty string constant (#3207) (#3215). [Julie Schwartz] * Fix incorrect width after and-or optimization (#3208). [Julie Schwartz] * Fix $fopen etc on integer arrays (#3214). [adrienlemasle] * Fix $size on dynamic strings (#3216). * Fix %0 format on $value$plusargs (#3217). * Fix timescale portability on Arm64 (#3222). Verilator 4.214 2021-10-17 ========================== **Major:** * Add profile-guided optimization of mtasks (#3150). **Minor:** * Verilator_gantt has removed the ASCII graphics, use the VCD output instead. * Verilator_gantt now shows the predicted mtask times, eval times, and additional statistics. * Verilator_gantt data files now include processor information, to allow later processing. * Support displaying x and z in $display task (#3107) (#3109). [Iru Cai] * Fix verilator_profcfunc profile accounting (#3115). * Fix display has no time units on class function (#3116). [Damien Pretet] * Fix removing if statement with side effect in condition (#3131). [Alexander Grobman] * Fix --waiver-output for multiline warnings (#2429) (#3141). [Keith Colbert] * Fix internal error on bad widths (#3140) (#3145). [Zhanglei Wang] * Fix crash on clang 12/13 (#3148). [Kuoping Hsu] * Fix cygwin compile error due to missing -std=gnu++14 (#3149). [Sun Kim] * Fix $urandom_range when the range is 0 ... UINT_MAX (#3161). [Iru Cai] * Fix constructor-parameter argument comma-separation in C++ (#3162). [Matthew Ballance] * Fix missing install of vl_file_copy/vl_hier_graph (#3165). [Popolon] * Fix calling new with arguments in same class (#3166). [Matthew Ballance] * Fix false EOFNEWLINE warning when DOS carriage returns present (#3171). Verilator 4.212 2021-09-01 ========================== **Minor:** * Fix re-evaluation of logic dependent on state set in DPI exports (#3091). [Geza Lore] * Support unpacked array localparams in tasks/functions (#3078). [Geza Lore] * Support timeunit/timeprecision in $unit. * Support assignment patterns as children of pins (#3041). [Krzysztof Bieganski, Antmicro Ltd] * Add --instr-count-dpi to tune assumed DPI import cost for multithreaded model scheduling. Default value changed to 200 (#3068). [Yinan Xu] * Output files are split based on the set of headers required in order to aid incremental compilation via ccache (#3071). [Geza Lore] * Parameter values are now emitted as 'static constexpr' instead of enum. C++ direct references to parameters might require updating (#3077). [Geza Lore] * Refactored Verilated include files; include verilated.h not verilated_heavy.h. * Add header guards on Dpi.h generated files (#2979). [Tood Strader] * Add XML ccall, constpool, initarray, and if/while begins (#3080). [Steven Hugg] * Add error when constant function under a generate (#3103). [Don Owen] * Fix -G to treat simple integer literals as signed (#3060). [Anikin1610] * Fix emitted string array initializers (#2895). [Iztok Jeras] * Fix bitop tree optimization dropping necessary & operator (#3096). [Flavien Solt] * Fix internal error on wide -x-initial unique (#3106). [Alexandre Joannou] * Fix traces to show array instances with brackets (#3092) (#3095). [Pieter Kapsenberg] Verilator 4.210 2021-07-07 ========================== **Major:** * Generated code is now emitted as global functions rather than methods. '$c' contents might need to be updated, see the docs (#3006). [Geza Lore] * The generated model class instantiated by the user is now an interface object and no longer the TOP module instance. User code with direct C++ member access to model internals, including verilator public_flat items will likely need to be updated. See the manual for instructions: https://verilator.org/guide/latest/connecting.html#porting-from-pre-4-210 (#3036). [Geza Lore] **Minor:** * Add --prof-c to pass profiling to compiler (#3059). [Alexander Grobman] * Optimize a lot more model variables into function locals (#3027). [Geza Lore] * Support middle-of-design nested top modules (#3026). [Dan Petrisko] * Remove deprecated --no-relative-cfuncs option (#3024). [Geza Lore] * Remove deprecated --inhibit-sim option (#3035). [Geza Lore] * Merge const static data globally into a new constant pool (#3013). [Geza Lore] * Allow configure override of AR program (#2999). [ahouska] * In XML, show pinIndex information (#2877). [errae233] * Fix error on unsupported recursive functions (#2957). [Trefor Southwell] * Fix type parameter specialization when struct names are same (#3055). [7FM] * Improve speed of table optimization (-OA) pass. [Geza Lore] Verilator 4.204 2021-06-12 ========================== **Minor:** * Add 'make ccache-report' (#3011). [Geza Lore] * Add --reloop-limit argument (#2943) (#2960). [Geza Lore] * Add --expand-limit argument (#3005). [Julien Margetts] * Add TRACE_THREADS to CMake (#2934). [Jonathan Drolet] * Optimize large lookup tables to static data (#2925). [Geza Lore] * Optimize reloop to accept constant index offsets (#2939). [Geza Lore] * Split always blocks to better respect --output-split-cfuncs. [Geza Lore] * Support ignoring "`pragma protect ..." (#2886). [Udi Finkelstein] * Support --trace-fst for SystemC with CMake (#2927). [Jonathan Drolet] * Update cmake latest C++ Standard Compilation flag (#2951). [Ameya Vikram Singh] * Prep work towards better ccache hashing/performance. [Geza Lore] * Fix assertion failure in bitOpTree optimization (#2891) (#2899). [Raynard Qiao] * Fix DPI functions not seen as vpiModule (#2893). [Todd Strader] * Fix bounds check in VL_SEL_IWII (#2910). [Krzysztof Bieganski, Antmicro Ltd] * Fix slowdown in elaboration (#2911). [Nathan Graybeal] * Fix initialization of assoc in assoc array (#2914). [myftptoyman] * Fix make support for gmake 3.x (#2920) (#2921). [Philipp Wagner] * Fix VPI memory access for packed arrays (#2922). [Todd Strader] * Fix MCD close also closing stdout (#2931). [Alexander Grobman] * Fix split procedures to better respect --output-split-cfuncs (#2942). [Geza Lore] * Fix to emit 'else if' without nesting (#2944). [Geza Lore] * Fix part select issues in LATCH warning (#2948) (#2938). [Julien Margetts] * Fix to not emit empty files with low split limits (#2961). [Geza Lore] * Fix merging of assignments in C++ code (#2970). [Rupert Swarbrick] * Fix unused variable warnings (#2991). [Pieter Kapsenberg] * Fix --protect-ids when using SV classes (#2994). [Geza Lore] * Fix constant function calls with uninitialized value (#2995). [yanx21] * Fix Makefiles to support Windows EXEEXT usage (#3008). [Miodrag Milanovic] Verilator 4.202 2021-04-24 ========================== **Major:** * Documentation has been rewritten into a book format. * Verilated signals now use VlWide and VlPacked in place of C arrays. **Minor:** * Add an URL on warnings to point to the manual's description. * Add EOFNEWLINE warning when missing a newline at EOF. * Changed TIMESCALEMOD from error into a warning. * Mark --no-relative-cfuncs as scheduled for deprecation. * Add --coverage-max-width (#2853). [xuejiazidi] * Add VerilatedCovContext::forcePerInstance (#2793). [Kevin Laeufer] * Add FST SystemC tracing (#2806). [Àlex Torregrosa] * Add PINNOTFOUND warning in place of error (#2868). [Udi Finkelstein] * Support overlaps in priority case statements (#2864). [Rupert Swarbrick] * Support for null ports (#2875). [Udi Finkelstein] * Fix class unpacked-array compile error (#2774). [Iru Cai] * Fix scope types in FST and VCD traces (#2805). [Àlex Torregrosa] * Fix exceeding command-line ar limit (#2834). [Yinan Xu] * Fix false $dumpfile warning on model save (#2834). [Yinan Xu] * Fix --timescale-override not suppressing TIMESCALEMOD (#2838). [Kaleb Barrett] * Fix false TIMESCALEMOD on generate-ignored instances (#2838). [Kaleb Barrett] * Fix --output-split with class extends (#2839). [Iru Cai] * Fix false WIDTHCONCAT on casted constant (#2849). [Rupert Swarbrick] * Fix tracing of long hashed names (#2854). [Graham Rushton] * Fix --public-flat-rw / DPI issue (#2858). [Todd Strader] * Fix interface localparam access (#2859). [Todd Strader] * Fix Cygwin example compile issues (#2856). [Mark Shaw] * Fix select of with index variable (#2880). [Alexander Grobman] * Fix cmake version number to be numeric (#2881). [Yuri Victorovich] * Fix MinGW not supporting 'localtime_r' (#2882). [HyungKi Jeong] * Fix cast from packed, typedef'ed interface signal (#2884). [Todd Strader] * Fix VPI package reported as vpiModule (#2885). [Todd Strader] * Fix dumping waveforms to multiple FST files (#2889). [David Metz] * Fix assertion failure in bitOpTree (#2892). [Yutetsu TAKATSUKASA] * Fix V3Premit infinite loop on always read-and-write (#2898). [Raynard Qiao] * Fix VPI packed vectors (#2900). [Todd Strader] * Fix VPI public interface parameters (#2901). [Todd Strader] Verilator 4.200 2021-03-12 ========================== **Announcement:** * --inhibit-sim is planned for deprecation, file a bug if this is still being used. **Major:** * Add simulation context (VerilatedContext) to allow multiple fully independent models to be in the same process. Please see the updated examples. (#2660) * Add context->time() and context->timeInc() API calls, to set simulation time. These now are recommended in place of the legacy sc_time_stamp(). **Minor:** * Converted Asciidoc documentation into reStructuredText (RST) format. * Fix range inheritance on port without data type (#2753). [Embedded Go] * Fix slice-assign overflow (#2803) (#2811). [David Turner] * Fix interface array connection ordering broken in v4.110 (#2827). [Don Owen] * Fix or-reduction on different scopes broken in 4.110 (#2828). [Yinan Xu] * Fix MSVC++ compile error. (#2831) (#2833) [Drew Taussig] Verilator 4.110 2021-02-25 ========================== **Major:** * Optimize bit operations and others (#2186) (#2632) (#2633) (#2751) (#2800) [Yutetsu TAKATSUKASA] **Minor:** * Support concat selection (#2721). * Support struct scopes when dumping structs to VCD (#2776) [Àlex Torregrosa] * Generate SELRANGE for potentially unreachable code (#2625) (#2754) [Pierre-Henri Horrein] * For --flatten, override inlining of public and no_inline modules (#2761) [James Hanlon] * Fix little endian interface pin swizzling (#2475). [Don Owen] * Fix range inheritance on port without data type (#2753). [Embedded Go] * Fix TIMESCALE warnings on primitives (#2763). [Xuanqi] * Fix to exclude strings from toggle coverage (#2766) (#2767) [Paul Wright] * Fix $fread extra semicolon inside statements. [Leendert van Doorn] * Fix class extends with VM_PARALLEL_BUILDS (#2775). [Iru Cai] * Fix shifts by > 32 bit values (#2785). [qrq992] * Fix examples not flushing vcd (#2787). [Richard E George] * Fix little endian packed array pattern assignment (#2795). [Àlex Torregrosa] Verilator 4.108 2021-01-10 ========================== **Major:** * Many VPI changes for IEEE compatibility, which may alter behavior from previous releases. * Support randomize() class method and rand (#2607). [Krzysztof Bieganski, Antmicro Ltd] **Minor:** * Support $cast and new CASTCONST warning. * Add --top option as alias of --top-module. * Add LATCH and NOLATCH warnings (#1609) (#2740). [Julien Margetts] * Remove Unix::Processors internal test dependency. * Report UNUSED on parameters, localparam and genvars (#2627). [Charles Eric LaForest] * Add error on real to non-real output pins (#2690). [Peter Monsson] * Support package imports before parameters in interfaces (#2714). [James Hanlon] * Support --sanitize in internal tests (#2705). [Yutetsu TAKATSUKASA] * Fix passing parameter type instantiations by position number. * Fix DPI open array handling issues. * Fix error when dotted refers to missing module (#2095). [Alexander Grobman] * Fix little endian packed array counting (#2499). [phantom-killua] * Fix showing reference locations for BLKANDNBLK (#2170). [Yuri Victorovich] * Fix genblk naming to match IEEE (#2686). [tinshark] * Fix VPI memory word indexing (#2695). [Marlon James] * Fix vpiLeftRange on little-endian memories (#2696). [Marlon James] * Fix VPI module tree (#2704). [Todd Strader] * Fix vpi_release_handle to be called implicitly per IEEE (#2706). * Fix to allow inheriting 'VerilatedVcdFile' class. (#2720) [HyungKi Jeong] * Fix $urandom_range maximum value (#2723). [Nandu Raj] * Fix tracing empty sc module (#2729). * Fix generate for unrolling to be signed (#2730). [yanx21] * Fix to emit timescale in hierarchical blocks (#2735). [Yutetsu TAKATSUKASA] * Fix to ignore coverage on real ports (#2741) (#2745). [Paul Wright] Verilator 4.106 2020-12-02 ========================== **Major:** * Change -sv option to select 1800-2017 instead of 1800-2005. **Minor:** * Check for proper 'local' and 'protected' (#2228). * Support $random and $urandom seeds. * Support $monitor and $strobe. * Support complex function arguments. * Support 'super'. * Support 'with item.index'. * Fix the default GNU Make executable name on FreeBSD (#2553). [Yuri Victorovich] * Fix trace signal names getting hashed (#2643). [Barbara Gigerl] * Fix unpacked array parameters near functions (#2639). [Anderson Ignacio da Silva] * Fix access to non-overridden base class variable (#2654). [Tobias Rosenkranz] Verilator 4.104 2020-11-14 ========================== **Minor:** * Support queue and associative array 'with' statements (#2616). * Support queue slicing (#2326). * Support associative array pattern assignments and defaults. * Support static methods and typedefs in classes (#2615). [Krzysztof Bieganski, Antmicro Ltd] * Add error on typedef referencing self (#2539). [Cody Piersall] * With --debug, turn off address space layout randomization. * Fix iteration over mutating list bug in VPI (#2588). [Kaleb Barrett] * Fix cast width propagation (#2597). [flex-liu] * Fix return from callValueCbs (#2589) (#2605). [Marlon James] * Fix WIDTH warnings on comparisons with nullptr (#2602). [Rupert Swarbrick] * Fix fault when $fgets, $sscanf, etc used with string (#2604). [Yutetsu TAKATSUKASA] * Fix WIFEXITED missing from MinGW/MSYS2 (#2609). [Jean Berniolles] * Fix queue poping wrong value when otherwise unused (#2512). [nanduraj1] * Fix arrays of modport interfaces (#2614). [Thierry Tambe] * Fix split_var internal error (#2640) (#2641). [Yutetsu TAKATSUKASA] Verilator 4.102 2020-10-15 ========================== **Minor:** * Support const object new() assignments. * Support # as a comment in -f files (#2497). [phantom-killua] * Support 'this' (#2585). [Rafal Kapuscik] * Support defines for FST tracing (#2592). [Markus Krause] * Support non-overlapping implication inside properties (#1292). [Peter Monsson] * Fix timescale with --hierarchical (#2554). [Yutetsu TAKATSUKASA] * Fix cmake build with --hierarchical (#2560). [Yutetsu TAKATSUKASA] * Fix -G dropping public indication (#2561). [Andrew Goessling] * Fix $urandom_range passed variable (#2563). [nanduraj1] * Fix method calls to package class functions (#2565). [Peter Monsson] * Fix class wide member display (#2567). [Nandu Raj P] * Fix hierarchical references inside function (#2267) (#2572). [James Pallister] * Fix flushCall for backward compatibility (#2580). [chenguokai] * Fix preprocessor stringify of undefined macro. [Martin Whitaker] Verilator 4.100 2020-09-07 ========================== **Major:** * C++11 or newer compilers are now required. * SystemC 2.3.0 or newer (SYSTEMC_VERSION >= 20111121) is now required. * Support hierarchical Verilation (#2206). [Yutetsu TAKATSUKASA] **Minor:** * Support (with limitations) class extern, class extends, virtual class. * Support $urandom, $urandom_range without stability. * Support assume property. [Peter Monsson] * Support non-overlapping implication inside properties (#1292). [Peter Monsson] * Fix false DECLFILENAME on black-boxed modules (#2430). [Philipp Wagner] * Fix naming of "id : begin" blocks. * Fix class constructor error on assignments to const. * Fix splitting eval functions with --output-split-cfuncs (#2368). [Geza Lore] * Fix queues as class members (#2525). [nanduraj1] Verilator 4.040 2020-08-15 ========================== **Announcement:** * Version 4.040 is planned to be the final version that will support pre-C++11 compilers. Please move to C++11 or newer compilers. **Minor:** * Fix arrayed interfaces, broke in 4.038 (#2468). [Josh Redford] * Support $stable, $rose and $fell. (#2148) (#2501) [Peter Monsson] * Support simple function localparams (#2461). [James Hanlon] * Miscellaneous parsing error changes towards UVM support. * Fix arrayed interfaces (#2469). [Josh Redford] * Fix protect lib VCS warning. (#2479) [Julien Margetts] * Fix combining different-width parameters (#2484). [abirkmanis] * Fix protect-lib without sequential logic (#2492). [Yutetsu TAKATSUKASA] * Fix V3Unknown from running with flat XML output (#2494). [James Hanlon] * Fix non-32 bit conversion to float (#2495). [dsvf] * Fix casting non-self-determined subexpressions (#2493). [phantom-killua] * Fix SystemC net names (#2500). [Edgar E. Iglesias] * Fix build with Bison 3.7 and newer (#2505). [Rupert Swarbrick] * Fix slice of unpacked array (#2506) (#2507). [Yutetsu TAKATSUKASA] Verilator 4.038 2020-07-11 ========================== **Announcement:** * Versions 4.038 and 4.040 are planned to be the final versions that will support pre-C++11 compilers. Please move to C++11 or newer compilers. **Minor:** * Support VPI access to parameters and localparam. [Ludwig Rogiers] * Support parsing (not elaboration, yet) of UVM. * Add new UNSUPPORTED error code to replace most previous Unsupported: messages. * With --bbox-unsup continue parsing on many (not all) UVM constructs. * Support for-loop increments with commas. * Support $swrite with arbitrary arguments. * Support $writememb (#2450). [Fan Shupei] * Fix OS X, Free BSD, and -m32 portability issues. [Geza Lore] * Fix to flush FST trace on termination due to $stop or assertion failure. * Fix part select error when multipling by power-of-two (#2413). [Conor McCullough] * Fix division exception (#2460) [Kuoping Hsu] Verilator 4.036 2020-06-06 ========================== **Major:** * OPT_FAST is now -Os by default. See the BENCHMARKING & OPTIMIZATION part of the manual if you experience issues with compilation speed. * --output-split is now on by default. VM_PARALLEL_BUILDS is set by default iff the --output-split caused an actual file split to occur. --output-split-cfuncs and --output-split-ctrace now default to the value of --output-split. These changes should improve build times of medium and large designs with default options. User makefiles may require changes. **Minor:** * Configure now enables SystemC if it is installed as a system headers, e.g. with 'apt-get install systemc-dev'. * Add --waiver-output flag that writes a verilator config file (.vlt) with waivers to the warnings emitted during a Verilator run. * Support verilator_coverage --write-info for lcov HTML reports. * Line Coverage now tracks all statement lines, not just branch lines. * The run-time library is now compiled with -Os by default. (#2369, #2373) * Support multi channel descriptor I/O (#2190) [Stephen Henry] * Support $countbits. (#2287) [Yossi Nivin] * Support $isunbounded and parameter $. (#2104) * Support unpacked array .sum and .product. * Support prefix/postfix increment/decrement. (#2223) [Maciej Sobkowski] * Fix FST tracing of little bit endian signals. [Geza Lore] * Fix +: and -: on unpacked arrays. (#2304) [engr248] * Fix $isunknown with constant Z's. * Fix queues and dynamic array wide ops. (#2352) [Vassilis Papaefstathiou] Verilator 4.034 2020-05-03 ========================== **Major:** * Support simplistic classes with many restrictions, see manual. (#377) * Support IEEE time units and time precisions. (#234) Includes `timescale, $printtimescale, $timeformat. VL_TIME_MULTIPLIER, VL_TIME_PRECISION, VL_TIME_UNIT have been removed and the time precision must now match the SystemC time precision. To get closer behavior to older versions, use e.g. --timescale-override "1ps/1ps". * Add --build to call make automatically. (#2249) [Yutetsu TAKATSUKASA] * Configuring with ccache present now defaults to using it; see OBJCACHE. * Fix DPI import/export to be standard compliant. (#2236) [Geza Lore] * Add --trace-threads for general multithreaded tracing. (#2269) [Geza Lore] **Minor:** * Add --flatten for use with --xml-only. (#2270) [James Hanlon] * Greatly improve FST/VCD dump performance (#2244) (#2246) (#2250) (#2257) [Geza Lore] * Support $ferror, and $fflush without arguments. (#1638) * Support event data type (with some restrictions). * Support $root. (#2150) [Keyi Zhang] * Add error if use SystemC 2.2 and earlier (pre-2011) as is deprecated. * Add support of --trace-structs for CMake (#2986). [Martin Schmidt] * Fix arrayed instances connecting to slices. (#2263) [Don/engr248] * Fix error on unpacked connecting to packed. (#2288) [Joseph Shaker] * Fix logical not optimization with empty begin. (#2291) [Baltazar Ortiz] * Fix reduction OR on wide data, broke in v4.026. (#2300) [Jack Koenig] * Fix clock enables with bit-extends. (#2299) [Marco Widmer] * Fix MacOs Homebrew by removing default LIBS. (#2298) [Ryan Clarke] Verilator 4.032 2020-04-04 ========================== **Minor:** * Add column numbers to errors and warnings. * Add GCC 9-style line number prefix when showing source text for errors. * Add setting VM_PARALLEL_BUILDS=1 when using --output-split. (#2185) * Change --quiet-exit to also suppress 'Exiting due to N errors'. * Suppress REALCVT for whole real numbers. * Support split_var in vlt files. (#2219) [Marco Widmer] * Fix parameter type redeclaring a type. (#2195) [hdzhangdoc] * Fix VCD open with empty filename. (#2198) [Julius Baxter] * Fix packages as enum base types. (#2202) [Driss Hafdi] * Fix duplicate typedefs in generate for. (#2205) [hdzhangdoc] * Fix MinW portability. (#2114) [Sean Cross] * Fix assertions with unique case inside. (#2199) [hdzhangdoc] * Fix implicit conversion of floats to wide integers. Verilator 4.030 2020-03-08 ========================== **Major:** * Add split_var metacomment to assist UNOPTFLAT fixes. (#2066) [Yutetsu TAKATSUKASA] * Support $dumpfile and $dumpvars. (#2126) [Alexander Grobman] * Support dynamic arrays. (#379) **Minor:** * Add +verilator+noassert flag to disable assertion checking. [Tobias Wölfel] * Add check for assertOn for asserts. (#2162) [Tobias Wölfel] * Add --structs-packed for forward compatibility. * Support $displayb/o/h, $writeb/o/h, etc. (#1637) * Use gcc -Os in examples instead of -O2 for better average performance. * Fix genblk naming with directly nested generate blocks. (#2176) [Alexander Grobman] * Fix undeclared VL_SHIFTR_WWQ. (#2114) [Alex Solomatnikov] Verilator 4.028 2020-02-08 ========================== **Major:** * Support attributes (public, isolate_assignments, etc.) in configuration files. * Add -match to lint_off to waive warnings. [Philipp Wagner] **Minor:** * Link Verilator binary partially statically. (#2146) [Geza Lore] * Verilation speed improvements (#2133) (#2138) [Geza Lore] * Support libgoogle-perftools-dev's libtcmalloc if available. (#2137) [Geza Lore] * Support $readmem/$writemem with assoc arrarys. (#2100) [agrobman] * Support type(expression) operator and $typename. (#1650) * Support left justified $display. (#2101) [Pieter Kapsenberg] * Support string character access via indexing. * Support enum.next(k) with constant k > 1. (#2125) [Tobias Rosenkranz] * Support parameter access from arrays of interfaces. (#2155) [Todd Strader] * Add parameter values in XML. #2110. [Pieter Kapsenberg] * Add loc column location in XML (replaces fl). (#2122) [Pieter Kapsenberg] * Add error on misused define. [Topa Tota] * Add parameter to set maximum signal width. (#2082) [Øyvind Harboe] * Add warning on genvar in normal for loop. (#2143) [Yuri Victorovich] * Fix VPI scope naming for public modules. [Nandu Raj] * Fix FST tracing of enums inside structs. [fsiegle] * Fix WIDTH warning on . * Support VerilatedFstC set_time_unit. (#1433) [Pieter Kapsenberg] * Support deferred assertions. (#1449) [Charles Eddleston] * Mark infrequently called functions with GCC cold attribute. * Fix sign-compare warning in verilated.cpp. (#1437) [Sergey Kvachonok] * Fix fault on $realtime with %t. (#1443) [Julien Margetts] * Fix $display with string without %s. (#1441) [Denis Rystsov] * Fix parameter function string returns. (#1441) [Denis Rystsov] * Fix invalid XML output due to special chars. (#1444) [Kanad Kanhere] * Fix performance when mulithreaded on 1 CPU. (#1455) [Stefan Wallentowitz] * Fix type and real parameter issues (#1427) (#1456) (#1458) [Todd Strader] * Fix build error on MinGW. (#1460) [Richard Myers] * Fix not reporting some duplicate signals. (#1462) [Peter Gerst] * Fix --savable invalid C++ on packed arrays. (#1465) [Alex Chadwick] * Fix constant function return of function var. (#1467) [Roman Popov] Verilator 4.014 2019-05-08 ========================== **Minor:** * Add --trace-fst-thread. * Support '#' comments in $readmem. (#1411) [Frédéric Requin] * Support "'dx" constants. (#1423) [Udi Finkelstein] * For FST tracing use LZ4 compression. [Tony Bybell] * Add error when use parameters without value. (#1424) [Peter Gerst] * Auto-extend and WIDTH warn on unsized X/Zs. (#1423) [Udi Finkelstein] * Fix missing VL_SHIFTL errors. (#1412) (#1415) [Larry Lee] * Fix MinGW GCC 6 printf formats. (#1413) [Sergey Kvachonok] * Fix test problems when missing fst2vcd. (#1417) [Todd Strader] * Fix GTKWave register warning. (#1421) [Pieter Kapsenberg] * Fix FST enums not displaying. (#1426) [Danilo Ramos] * Fix table compile error with multiinterfaces. (#1431) [Bogdan Vukobratovic] Verilator 4.012 2019-03-23 ========================== **Minor:** * Add +verilator+seed. (#1396) [Stan Sokorac] * Support $fread. [Leendert van Doorn] * Support void' cast on functions called as tasks. (#1383) [Al Grant] * Add IGNOREDRETURN warning. (#1383) * Report PORTSHORT errors on concat constants. (#1400) [Will Korteland] * Fix VERILATOR_GDB being ignored. (#2017) [Yu Sheng Lin] * Fix $value$plus$args missing verilated_heavy.h. [Yi-Chung Chen] * Fix MSVC compile error. (#1406) [Benjamin Gartner] * Fix maintainer test when no Parallel::Forker. (#1977) [Enzo Chi] * Fix +1364-1995ext flags applying too late. (#1384) [Al Grant] Verilator 4.010 2019-01-27 ========================== **Minor:** * Removed --trace-lxt2, use --trace-fst instead. * For --xml, add additional information. (#1372) [Jonathan Kimmitt] * Add circular typedef error. (#1388) [Al Grant] * Add unsupported for loops error. (#1986) [Yu Sheng Lin] * Fix FST tracing of wide arrays. (#1376) [Aleksander Osman] * Fix error when pattern assignment has too few elements. (#1378) [Viktor Tomov] * Fix error when no modules in $unit. (#1381) [Al Grant] * Fix missing too many digits warning. (#1380) [Jonathan Kimmitt] * Fix uninitialized data in verFiles and unroller. (#1385) (#1386) [Al Grant] * Fix internal error on xrefs into unrolled functions. (#1387) [Al Grant] * Fix DPI export void compiler error. (#1391) [Stan Sokorac] Verilator 4.008 2018-12-01 ========================== **Minor:** * Support "ref" and "const ref" pins and functions. (#1360) [Jake Longo] * In --xml-only show the original unmodified names, and add module_files and cells similar to Verilog-Perl, msg2719. [Kanad Kanhere] * Add CONTASSREG error on continuous assignments to regs. (#1369) [Peter Gerst] * Add PROCASSWIRE error on behavioral assignments to wires, msg2737. [Neil Turton] * Add IMPORTSTAR warning on import::* inside $unit scope. * Fix --trace-lxt2 compile error on MinGW. (#1990) [HyungKi Jeong] * Fix hang on bad pattern keys. (#1364) [Matt Myers] * Fix crash due to cygwin bug in getline. (#1349) [Affe Mao] * Fix __Slow files getting compiled with OPT_FAST. (#1370) [Thomas Watts] Verilator 4.006 2018-10-27 ========================== **Minor:** * Add --pp-comments. (#1988) [Robert Henry] * Add --dump-defines. * For --trace-fst, save enum decoding information. (#1358) [Sergi Granell] (To visualize enumeration data you must use GTKwave 3.3.95 or newer.) * For --trace-fst, combine hier information into FST. [Tony Bybell] * Fix --trace-lxt2 compile error on MinGW, msg2667. [HyungKi Jeong] * Fix Windows .exe not found. (#1361) [Patrick Stewart] Verilator 4.004 2018-10-06 ========================== **Major:** * Add GTKWave FST native tracing. (#1356) [Sergi Granell] (Verilator developers need to pull the latest vcddiff.) **Minor:** * Support $past. [Dan Gisselquist] * Support restrict. (#1350) [Clifford Wolf] * Rename include/lxt2 to include/gtkwave. * Fix replication of 64-bit signal change detects. * Fix Mac OSX 10.13.6 / LLVM 9.1 compile issues. (#1348) [Kevin Kiningham] * Fix MinGW compile issues. (#1979) [HyungKi Jeong] Verilator 4.002 2018-09-16 ========================== **Major:** * This is a major release. Any patches may require major rework to apply. [Thanks everyone] * Add multithreaded model generation. * Add runtime arguments. * Add GTKWave LXT2 native tracing. (#1333) [Yu Sheng Lin] * Note $random has new algorithm; results may vary vs. previous versions. **Minor:** * Better optimize large always block splitting. (#1244) [John Coiner] * Add new reloop optimization for repetitive assignment compression. * Support string.atoi and similar methods. (#1289) [Joel Holdsworth] * Fix internals to be C++ null-pointer-check clean. * Fix internals to avoid 'using namespace std'. * Fix Verilation performance issues. (#1316) [John Coiner] * Fix clocker attributes to not propagate on concats. [John Coiner] * Fix first clock edge and --x-initial-edge. (#1327) [Rupert Swarbrick] * Fix compile error on tracing of string arrays. (#1338) [Iztok Jeras] * Fix number parsing with newline after radix. (#1340) [George Cuan] * Fix string ?: conditional type resolution. (#1345) [Iztok Jeras] * Fix duplicate symbol error on generate tri. (#1347) [Tomas Dzetkulic] Verilator 3.926 2018-08-22 ========================== **Minor:** * Add OBJCACHE envvar support to examples and generated Makefiles. * Change MODDUP errors to warnings. (#1969) [Marshal Qiao] * Fix define argument stringification (`"), broke since 3.914. [Joe DErrico] * Fix to ignore Unicode UTF-8 BOM sequences. (#1967) [HyungKi Jeong] * Fix std:: build error. (#1322) * Fix function inlining inside certain while loops. (#1330) [Julien Margetts] Verilator 3.924 2018-06-12 ========================== **Minor:** * Renamed --profile-cfuncs to --prof-cfuncs. * Report interface ports connected to wrong interface. (#1294) [Todd Strader] * When tracing, use scalars on single bit arrays to appease vcddiff. * Fix parsing "output signed" in V2K port list, msg2540. [James Jung] * Fix parsing error on bad missing #. (#1308) [Dan Kirkham] * Fix $clog2 to be in verilog 2005. (#1319) [James Hutchinson] Verilator 3.922 2018-03-17 ========================== **Major:** * Support IEEE 1800-2017 as default language. **Minor:** * Support trig functions ($sin() etc). (#1281) [Patrick Stewart] * Support calling system functions as tasks. (#1285) [Joel Holdsworth] * Support assert properties. (#785) (#1290) [John Coiner, et al] * Support $writememh. [John Coiner] * Add --no-debug-leak to reduce memory use under debug. [John Coiner] * Fix severe runtime performance bug in certain foreach loops. [John Coiner] * On convergence errors, show activity. [John Coiner] * Fix GCC 8.0 issues. (#1273) * Fix pullup/pulldowns on bit selects. (#1274) [Rob Stoddard] * Fix verilator_coverage --annotate-min. (#1284) [Tymoteusz Blazejczyk] * Fix quoting of quoted arguments. [John Coiner] Verilator 3.920 2018-02-01 ========================== **Announcement:** * Moving forward, use the git "stable" branch to track the latest release, and git "v#.###" tags for specific releases. **Minor:** * Support 'assume' similar to 'assert'. (#1269) [Dan Gisselquist] * Remove c++filt. (#1265) [Stefan Wallentowitz] * Fix tracing example file output. (#1268) [Enzo Chi] * Fix gate optimization out of memory, add --gate-stmts. (#1260) [Alex Solomatnikov] * Fix compile error on public real parameters by suppressing. (#1261) [Alex Solomatnikov] * Fix input-only tristate comparisons. (#1267) [Alexis G] * Fix missing edge type in xml output. (#1955) [Alexis G] * Fix compile error with --public and interface bind. (#1264) [Alexis G] Verilator 3.918 2018-01-02 ========================== **Minor:** * Workaround GCC/clang bug with huge compile times. (#1248) * Support DPI open arrays. (#909) (#1245) [David Pierce, Victor Besyakov] * Add INFINITELOOP warning. (#1254) [Alex Solomatnikov] * Support > 64 bit decimal $display. * Support DPI time and svLogicVal. [Victor Besyakov] Note older version incorrectly assumed svBitVal even for logicals. * Support string len() method. [Victor Besyakov] * Add error if always_comb has sensitivity list. [Arjen Roodselaar] * Fix SystemC 2.3.2 compile error. (#1251) [Tymoteusz Blazejczyk] * Fix modport outputs being treated as inputs. (#1246) [Jeff Bush] * Fix false ALWCOMBORDER on interface references. (#1247) [Josh Redford] * Fix constant propagation across DPI imports of inout strings. [Victor Besyakov] * Fix resolving inline nested interface names. (#1250) [Arjen Roodselaar] * Fix GCC false warning on array bounds. (#2386) Verilator 3.916 2017-11-25 ========================== **Minor:** * Support self-recursive modules. (#659) [Sean Moore, et al] * Support $error/$warning in elaboration time blocks. * Support $size/$bits/etc on type references. * Add error when driving input-only modport. (#1110) [Trevor Elbourne] * Add BSSPACE and COLONPLUS lint warnings. * Detect MSB overflow when under VL_DEBUG. (#1238) [Junyi Xi] * Add data types to --xml. [Rui Terra] * Fix partial slicing with pattern assignments. (#991) [Johan Bjork] * Fix false unused warning on interfaces. (#1241) [Laurens van Dam] * Fix error on "unique case" with no cases. * Fix MacOS portability. (#1232) [Jeff Bush] Verilator 3.914 2017-10-14 ========================== **Major:** * Add new examples/ directory with appropriate examples. This replaces the old test_c and test_sc directories. **Minor:** * Add --getenv option for simplifying Makefiles. * Add --x-initial option for specifying initial value assignment behavior. * Add --no-relative-cfuncs and related default optimization. (#1224) [John Coiner] * Add /*verilator tag*/ for XML extraction applications. [Chris Randall] * The internal test_verilated test directory is moved to be part of test_regress. * The experimental VL_THREADED setting (only, not normal mode) now requires C++11. * Fix over-aggressive inlining. (#1223) [John Coiner] * Fix Ubuntu 17.10 issues. (#1223 partial). [John Coiner] * Fix compiler warning when WIDTH warning ignored on large compare. * Fix memory leak in VerilatedVcd dumps. (#1222 partial) [Shareef Jalloq] * Fix unnecessary Vdly variables. (#1224 partial) [John Coiner] * Fix conditional slices and add related optimizations. * Fix \`\` expansion of `defines. (#1225) (#1227) (#1228) [Odd Magne Reitan] * Fix -E duplicating output. (#1226) [Odd Magne Reitan] * Fix float-conversion warning. (#1229) [Robert Henry] * Fix MacOS portability. (#1230) (#1231) [Jeff Bush] Verilator 3.912 2017-09-23 ========================== **Major:** * Verilated headers no longer "use namespace std;" User's code without "std::" prefixes may need "use namespace std;" to compile. **Minor:** * Support or/and/xor array intrinsic methods. (#1210) [Michael Popoloski] * Support package export. (#1217) [Usuario Eda] * Support module port parameters without defaults. (#1213) [Michael Popoloski] * Add performance information to --stats file. * Simplify VL_CONST_W macro generation for faster compiles. * Optimize improvements for Shift-And, and replication constructs. * Fix ordering of arrayed cell wide connections. (#1202 partial) [Michael Popoloski] * Fix LITENDIAN warning on arrayed cells. (#1202) [Michael Popoloski] * Fix enum ranges without colons. (#1204) [Michael Popoloski] * Fix GCC noreturn compile error. (#1209) [Michael Popoloski] * Fix constant function default parameters. (#1211) [Michael Popoloski] * Fix non-colon array of interface modports. (#1212) [Michael Popoloski] * Fix .name connections on interfaces. (#1214) [Michael Popoloski] * Fix wide array indices causing compile error. Verilator 3.910 2017-09-07 ========================== **Major:** * SystemPerl mode (-sp-deprecated) has been removed. **Minor:** * Update keyword warnings to include C++11 and others. Verilator 3.908 2017-08-28 ========================== **Minor:** * Support x in $readmem. (#1180) [Arthur Kahlich] * Support packed struct DPI imports. (#1190) [Rob Stoddard] * Fix GCC 6 warnings. * Fix compile error on unused VL_VALUEPLUSARGS_IW. (#1181) [Thomas J Whatson] * Fix undefined VL_POW_WWI. [Clifford Wolf] * Fix internal error on unconnected inouts. (#1187) [Rob Stoddard] Verilator 3.906 2017-06-22 ========================== **Minor:** * Support set_time_unit/set_time_precision in C traces. (#1937) * Fix extract of packed array with non-zero LSB. (#1172) [James Pallister] * Fix shifts by more than 32-bit numbers. (#1174) [Clifford Wolf] * Fix power operator on wide constants. (#761) [Clifford Wolf] * Fix .* on interface pins. (#1176) [Maciej Piechotka] Verilator 3.904 2017-05-30 ========================== **Minor:** * Fix non-cutable ordering loops on clock arrays. (#1009) [Todd Strader] * Support ports of array of reals. (#1154) [J Briquet] * Support arrayed parameter overrides. (#1153) [John Stevenson] * Support $value$plusargs with variables. (#1165) [Wesley Terpstra] * Support modport access to un-modport objects. (#1161) [Todd Strader] * Add stack trace when can't optimize function. (#1158) [Todd Strader] * Add warning on mis-sized literal. (#1156) [Todd Strader] * Fix interface functions returning wrong parameters. (#996) [Todd Strader] * Fix non-arrayed cells with interface arrays. (#1153) [John Stevenson] * Fix --assert with complex case statements. (#1164) [Enzo Chi] Verilator 3.902 2017-04-02 ========================== **Major:** * Add -FI option to force includes. (#1916) [Amir Gonnen] * Add --relative-includes. [Rob Stoddard] **Minor:** * Add error on duplicate pattern assignments. (#1145) [Johan Bjork] * Fix error on improperly widthed default function. (#984) [Todd Strader] * Fix 2009 localparam syntax, msg2139. [Galen Seitz] * Fix ugly interface-to-non-interface errors. (#1112) [Johan Bjork] * Fix LDFLAGS and CFLAGS not preserving order. (#1130) [Olof Kindgren] * Fix internal error on initializing parameter array. (#1131) [Jie Xu] * Fix internal error on interface arrays. (#1135) [John Stevenson] * Fix calling sformatf to display, and elab $displays. (#1139) [Johan Bjork] * Fix realpath compile issue on MSVC++. (#1141) [Miodrag Milanovic] * Fix missing error on interface size mismatch. (#1143) [Johan Bjork] * Fix error on parameters with dotted references. (#1146) [Johan Bjork] * Fix wreal not handling continuous assign. (#1150) [J Briquet] * Fix nested structure parameter selects. (#1150) [J Briquet] Verilator 3.900 2017-01-15 ========================== **Major:** * Internal code changes for improved compatibility and performance. **Minor:** * Support old-style $display($time). (#467) [John Demme] * With --bbox-unsup, suppress desassign and mixed edges. (#1120) [Galen Seitz] * Fix parsing sensitivity with &&. (#934) [Luke Yang] * Fix internal error on double-for loop unrolling. (#1044) [Jan Egil Ruud] * Fix internal error on unique casez with --assert. (#1117) [Enzo Chi] * Fix bad code when tracing array of structs. (#1122) [Andrew Bardsley] Verilator 3.890 2016-11-25 ========================== **Minor:** * Honor --output-split on coverage constructors. (#1098) [Johan Bjork] * Fix various issues when making outside of the kit. * Fix flex 2.6.2 bug. (#1103) [Sergey Kvachonok] * Fix error on bad interface name. (#1097) [Todd Strader] * Fix error on referencing variable in parent. (#1099) [Ian Thompson] * Fix type parameters with low optimization. (#1101) [Stefan Wallentowitz] Verilator 3.888 2016-10-14 ========================== **Major:** * Support foreach. (#1078) [Xuan Guo] **Minor:** * Add --no-decoration to remove output comments, msg2015. [Frédéric Requin] * If VM_PARALLEL_BUILDS=1, use OPT_FAST and OPT_SLOW. [Frédéric Requin] Set VM_DEFAULT_RULES=0 for old behavior. * Add error on DPI functions > 32 bits. (#1898) [Elliot Mednick] * Improve Verilation performance on internal strings. (#1896) [Johan Bjork] * Improve Verilation performance on trace duplicates. (#1090) [Johan Bjork] * Fix SystemC compiles with VPI. (#1081) [Arthur Kahlich] * Fix error on wide numbers that represent shifts, msg1991. (#1088) [Mandy Xu] Verilator 3.886 2016-07-30 ========================== **Minor:** * Fix enum values of 11-16 bits wide using .next/.prev. (#1062) [Brian Flachs] * Fix false warnings on non-power-2 enums using .next/.prev. * Fix comparison of unpacked arrays. (#1071) [Andrew Bardsley] * Fix compiler warning in GCC 6. [David Horton] Verilator 3.884 2016-05-18 ========================== **Major:** * Support parameter type. (#376) [Alan Hunter, et al] * Support command-line -G/+pvalue param overrides. (#1045) [Stefan Wallentowitz] * Add --l2-name option for controlling "v" naming. * The default l2 scope name is now the same as the top-level module. (#1050) Use "--l2-name v" for the historical behavior. **Minor:** * Fix --output-split of constructors. (#1035) [Johan Bjork] * Fix removal of empty packages, modules and cells. (#1034) [Johan Bjork] * Fix core dump on Arch Linux/GCC 6.1.1. (#1058) [Jannis Harder] * Fix $value$plusargs to string. (#1880) [Frédéric Requin] Verilator 3.882 2016-03-01 ========================== **Minor:** * Internal Verilation-time performance enhancements. (#1021) [Johan Bjork] * Support inlining interfaces. (#1018) [Johan Bjork] * Support SV strings to readmemh. (#1040) [Stefan Wallentowitz] * Fix unrolling complicated for-loop bounds. (#677) [Johan Bjork] * Fix stats file containing multiple unroll entries. (#1020) [Johan Bjork] * Fix using short parameter names on negative params. (#1022) [Duraid Madina] * Fix read-after-free error. (#1031) [Johan Bjork] * Fix elaboration-time display warnings. (#1032) [Johan Bjork] * Fix crash on very deep function trees. (#1028) [Jonathan Kimmitt] * Fix slicing mix of big and little-endian. (#1033) [Geoff Barrett] * Fix pattern assignment width propagation. (#1037) [Johan Bjork] Verilator 3.880 2015-12-19 ========================== **Minor:** * Support display %u, %v, %p, %z. (#989) [Johan Bjork] * Fix real parameters causing bad module names. (#992) [Johan Bjork] * Fix size-changing cast on packed struct. (#993) [Johan Bjork] * Fix function calls on arrayed interface. (#994) [Johan Bjork] * Fix arrayed interfaces. (#879) (#1001) [Todd Strader] * Fix constant function assigned to packed structs. (#997) [Johan Bjork] * Fix interface inside generate. (#998) [Johan Bjork] * Fix $signed casts under generates. (#999) [Clifford Wolf] * Fix genvar constant propagation. (#1003) [Johan Bjork] * Fix parameter constant propagation from package. (#1004) [Johan Bjork] * Fix array slicing of non-const indexes. (#1006) [Johan Bjork] * Fix dotted generated array error. (#1005) [Jeff Bush, Johan Bjork] * Fix error instead of warning on large concat. (#1865) [Paul Rolfe] * Fix $bitstoreal constant propagation. (#1012) [Jonathan Kimmitt] * Fix model restore crash. (#1013) [Jason McMullan] * Fix arrayed instances to unpacked of same size. (#1015) [Varun Koyyalagunta] * Fix slices of unpacked arrays with non-zero LSBs. * Fix ternary operation with unpacked array. (#1017) [Varun Koyyalagunta]. Verilator 3.878 2015-11-01 ========================== **Major:** * Add --vpi flag, and fix VPI linkage. (#969) [Arthur Kahlich] * Support genvar indexes into arrayed cells. (#517) [Todd Strader] * Support $sformatf. (#977) [Johan Bjork] * Support elaboration assertions. (#973) [Johan Bjork] * Support $display with non-format arguments. (#467) [Jamey Hicks] **Minor:** * Add VerilatedScopeNameMap for introspection. (#966) [Todd Strader] * Ignore %l in $display. (#983) [Todd Strader] * Fix very long module names. (#937) [Todd Strader] * Fix internal error on dotted refs into generates. (#958) [Jie Xu] * Fix structure parameter constant propagation. (#968) [Todd Strader] * Fix enum constant propagation. (#970) [Todd Strader] * Fix mis-optimizing public DPI functions. (#963) [Wei Song] * Fix package:scope.scope variable references. * Fix $fwrite to constant stderr/stdout. (#961) [Wei Song] * Fix struct.enum.name method calls. (#855) [Jonathon Donaldson] * Fix dot indexing into arrayed inferfaces. (#978) [Johan Bjork] * Fix crash in commandArgsPlusMatch. (#987) [Jamie Iles] * Fix error message on missing interface. (#985) [Todd Strader] Verilator 3.876 2015-08-12 ========================== **Minor:** * Add tracing_on, etc to vlt files. (#932) [Frédéric Requin] * Support extraction of enum bits. (#951) [Jonathon Donaldson] * Fix MinGW compiler error. (#927) (#929) [Hans Tichelaar] * Fix .c files to be treated as .cpp. (#930) [Jonathon Donaldson] * Fix string-to-int space conversion. (#931) [Fabrizio Ferrandi] * Fix dpi imports inside generates. [Michael Tresidder] * Fix rounding in trace $timescale. (#946) [Frédéric Requin] * Fix $fopen with SV string. (#947) [Sven Stucki] * Fix hashed error with typedef inside block. (#948) [Sven Stucki] * Fix makefile with --coverage. (#953) [Eivind Liland] * Fix coverage documentation. (#954) [Thomas J Whatson] * Fix parameters with function parameter arguments. (#952) [Jie Xu] * Fix size casts as second argument of cast item. (#950) [Jonathon Donaldson] Verilator 3.874 2015-06-06 ========================== **Minor:** * Add pkg-config .pc file. (#919) [Stefan Wallentowitz] * Fix installing missing manpages. (#908) [Ahmed El-Mahmoudy] * Fix sign extension in large localparams. (#910) [Mike Thyer] * Fix core dump in sync-async warnings. (#911) [Sebastian Dressler] * Fix truncation warning with -pins-bv. (#912) [Alfonso Martinez] * Fix Cygwin uint32 compile. (#914) [Matthew Barr] * Fix preprocessing stringified newline escapes. (#915) [Anton Rapp] * Fix part-select in constant function. (#916) [Andrew Bardsley] * Fix width extension on mis-width ports. (#918) [Patrick Maupin] * Fix width propagation on sized casts. (#925) [Jonathon Donaldson] * Fix MSVC++ compiler error. (#927) [Hans Tichelaar] Verilator 3.872 2015-04-05 ========================== **Minor:** * Add VerilatedVcdFile to allow real-time waveforms. (#890) [HyungKi Jeong] * Add --clk and related optimizations. (#1840) [Jie Xu] * Fix order of C style arrays. [Duraid Madina] * Add --dump-treei-. (#894) [Jie Xu] * Fix comma-instantiations with parameters. (#884) [Franck Jullien] * Fix SystemC arrayed bit vectors. (#886) [David Poole] * Fix compile error on MinGW. (#887) [HyungKi Jeong] Verilator 3.870 2015-02-12 ========================== **Minor:** * Suppress COMBDLY when inside always_latch. (#864) [Iztok Jeras] * Support cast operator with expression size. (#865) [Iztok Jeras] * Add warning on slice selection out of bounds. (#875) [Cong Van Nguyen]. * Fix member select error broke in 3.868. (#867) [Iztok Jeras] * Fix $sccanf from string. (#866) [David Pierce] * Fix VM_PARALLEL_BUILDS broke in 3.868. (#870) [Hiroki Honda] * Fix non-ANSI modport instantiations. (#868) [Kevin Thompson] * Fix UNOPTFLAT change detect on multidim arrays. (#872) [Andrew Bardsley] * Fix slice connections of arrays to ports. (#880) [Varun Koyyalagunta] * Fix mis-optimizing gate assignments in unopt blocks. (#881) [Mike Thyer] * Fix sign extension of pattern members. (#882) [Iztok Jeras] * Fix clang compile warnings. Verilator 3.868 2014-12-20 ========================== **Major:** * New verilator_coverage program added to replace SystemPerl's vcoverage. * PSL support was removed, please use System Verilog assertions. * SystemPerl mode is deprecated and now untested. **Minor:** * Support enum.first/name and similar methods. (#460) (#848) * Add 'string' printing and comparisons. (#746) (#747) etc. * Inline C functions that are used only once. (#1838) [Jie Xu] * Fix tracing SystemC signals with structures. (#858) [Eivind Liland] Note that SystemC traces will no longer show the signals in the wrapper, they can be seen one level further down. * Add --stats-vars. (#851) [Jeremy Bennett] * Fix bare generates in interfaces. (#789) [Bob Newgard] * Fix underscores in real literals. (#863) [Jonathon Donaldson] Verilator 3.866 2014-11-15 ========================== **Minor:** * Fix +define+A+B to define A and B to match other simulators. (#847) [Adam Krolnik] * Add optimization of wires from arrayed cells. (#1831) [Jie Xu] * Add optimization of operators between concats. (#1831) [Jie Xu] * Add public enums. (#833) [Jonathon Donaldson] * Trace_off now operates on cells. (#826) [Lane Brooks] * Fix public parameters in unused packages. (#804) [Jonathon Donaldson] * Fix select when partially out-of-bound. (#823) [Clifford Wolf] * Fix generate unrolling with function call. (#830) [Steven Slatter] * Fix cast-to-size context-determined sizing. (#828) [Geoff Barrett] * Fix not tracing modules following primitives. (#837) [Jie Xu] * Fix trace overflow on huge arrays. (#834) [Geoff Barrett] * Fix quoted comment slashes in defines. (#845) [Adam Krolnik] Verilator 3.864 2014-09-21 ========================== **Minor:** * Support power operator with real. (#809) [Jonathon Donaldson] * Improve verilator_profcfunc time attributions. [Jonathon Donaldson] * Fix duplicate anonymous structures in $root. (#788) [Bob Newgard] * Fix mis-optimization of bit-swap in wide signal. (#800) [Jie Xu] * Fix error when tracing public parameters. (#722) [Jonathon Donaldson] * Fix dpiGetContext in dotted scopes. (#740) [Geoff Barrett] * Fix over-shift structure optimization error. (#803) [Jeff Bush] * Fix optional parameter keyword in module #(). (#810) [Iztok Jeras] * Fix $warning/$error multi-argument ordering. (#816) [Jonathon Donaldson] * Fix clang warnings. (#818) [Iztok Jeras] * Fix string formats under deep expressions. (#820) [Iztok Jeras] Verilator 3.862 2014-06-10 ========================== **Minor:** * Using command line -Wno-{WARNING} now overrides file-local lint_on. * Add -P to suppress `line and blanks with preprocessing. (#781) [Derek Lockhart] * Support SV 2012 package import before port list. * Change SYMRSVDWORD to print as warning rather than error. * Fix seg-fault with variable of parameterized interface. (#692) [Jie Xu] * Fix false name conflict on cells in generate blocks. (#749) [Igor Lesik] * Fix pattern assignment to basic types. (#767) [Jie Xu] * Fix pattern assignment to conditionals. (#769) [Jie Xu] * Fix shift corner-cases. (#765) (#766) (#768) (#772) (#774) (#776) [Clifford Wolf] * Fix C compiler interpreting signing. (#773) [Clifford Wolf] * Fix late constant division by zero giving X error. (#775) [Clifford Wolf] * Fix gate primitives with arrays and non-arrayed pins. * Fix DETECTARRAY error on packed arrays. (#770) [Jie Xu] * Fix ENDLABEL warnings on escaped identifiers. * Fix string corruption. (#780) [Derek Lockhart] Verilator 3.860 2014-05-11 ========================== **Major:** * PSL is no longer supported, please use System Verilog assertions. * Support '{} assignment pattern on arrays. (#355) * Support streaming operators. (#649) [Glen Gibb] * Fix expression problems with -Wno-WIDTH. (#729) (#736) (#737) (#759) Where WIDTH warnings were ignored this might result in different warning messages and results, though it should better match the spec. [Clifford Wolf] **Minor:** * Add --no-trace-params. * Add assertions on 'unique if'. (#725) [Jeff Bush] * Add PINCONNECTEMPTY warning. [Holger Waechtler] * Support parameter arrays. (#683) [Jeremy Bennett] * Documentation fixes. (#723) [Glen Gibb] * Support {} in always sensitivity lists. (#745) [Igor Lesik] * Fix begin_keywords "1800+VAMS". (#1806) * Fix tracing of package variables and real arrays. * Fix tracing of packed arrays without --trace-structs. (#742) [Jie Xu] * Fix missing coverage line on else-if. (#727) [Sharad Bagri] * Fix modport function import not-found error. * Fix power operator calculation. (#730) (#735) [Clifford Wolf] * Fix reporting struct members as reserved words. (#741) [Chris Randall] * Fix change detection error on unions. (#758) [Jie Xu] * Fix -Wno-UNOPTFLAT change detection with 64-bits. (#762) [Clifford Wolf] * Fix shift-right optimization. (#763) [Clifford Wolf] * Fix Mac OS-X test issues. [Holger Waechtler] * Fix C++-2011 warnings. Verilator 3.856 2014-03-11 ========================== **Minor:** * Support case inside. (#708) [Jan Egil Ruud] * Add parameters into trace files. (#706) [Alex Solomatnikov] * Fix parsing "#0 'b0". (#256) * Fix array bound checks on real variables. * Fix --skip-identical mis-detecting on OS-X. (#707) * Fix missing VL_SHIFTRS_IQI with WIDTH warning. (#714) [Fabrizio Ferrandi] * Fix signed shift right optimization. (#715) [Fabrizio Ferrandi] * Fix internal error on "input x =" syntax error. (#716) [Lane Brooks] * Fix slice extraction from packed array. (#717) [Jan Egil Ruud] * Fix inside statement EQWILD error. (#718) [Jan Egil Ruud] Verilator 3.855 2014-01-18 ========================== **Minor:** * Support modport import. (#696) [Jeremy Bennett] * Add --trace-structs to show struct names. (#673) [Chris Randall] * Fix tracing of packed structs. (#705) [Jie Xu] * Fix --lint-only with MinGW. (#1813) [HyungKi Jeong] * Fix some delayed assignments of typedefed unpacked arrays. * Fix wire declarations with size and not range. (#466) [Alex Solomatnikov] * Fix parameter pin vs. normal pin error. (#704) [Alex Solomatnikov] Verilator 3.854 2013-11-26 ========================== **Minor:** * Add UNPACKED warning to convert unpacked structs. [Jeremy Bennett] * Add --compiler clang to work around compiler bug. (#694) [Stefan Ludwig] * Support vpi_get of vpiSuppressVal. (#687) [Varun Koyyalagunta] * Support vpi_get_time. (#688) [Varun Koyyalagunta] * Fix evaluation of chained parameter functions. (#684) [Ted Campbell] * Fix enum value extension of '1. * Fix multiple VPI variable callbacks. (#679) [Rich Porter] * Fix vpi_get of vpiSize. (#680) [Rich Porter] * Fix vpi_remove_cb inside callback. (#689) [Varun Koyyalagunta] * Fix crash with coverage of structures. (#691) [Eivind Liland] * Fix array assignment from const var. (#693) [Jie Xu] Verilator 3.853 2013-09-30 ========================== **Minor:** * Add --no-order-clock-delay to work around #613. [Charlie Brej] Verilator 3.852 2013-09-29 ========================== **Minor:** * Support named function and task arguments. [Chris Randall] * Report SELRANGE warning for non-generate if. (#675) [Roland Kruse] * Fix ordering of $fgetc. (#1808) [Frédéric Requin] * Fix --output-split-cfunc to count internal functions. [Chris Randall] * Fix crash on 32-bit Ubuntu. (#670) [Mark Jackson Pulver] Verilator 3.851 2013-08-15 ========================== **Minor:** * Fix ordering of clock enables with delayed assigns. (#613) [Jeremy Bennett] * Fix vpi_iterate on memory words. (#655) [Rich Porter] * Fix final duplicate declarations when non-inlined. (#661) [Charlie Brej] * Fix interface ports with comma lists. (#1779) [Ed Lander] * Fix parameter real conversion from integer. * Fix clang warnings. (#668) [Yutetsu Takatsukasa] Verilator 3.850 2013-06-02 ========================== **Major:** * Support interfaces and modports. (#102) [Byron Bradley, Jeremy Bennett] **Minor:** * Duplicate clock gate optimization on by default. (#621) * Fix arrayed input compile error. (#645) [Krzysztof Jankowski] * Fix GCC version runtime changes. (#651) [Jeremy Bennett] * Fix packed array select internal error. (#652) [Krzysztof Jankowski] Verilator 3.847 2013-05-11 ========================== **Minor:** * Add ALWCOMBORDER warning. [KC Buckenmaier] * Add --pins-sc-uint and --pins-sc-biguint. (#638) [Alex Hornung] * Support "signal[vec]++". * Fix simulation error when inputs and MULTIDRIVEN. (#634) [Ted Campbell] * Fix module resolution with __. (#631) [Jason McMullan] * Fix packed array non-zero right index select crash. (#642) [Krzysztof Jankowski] * Fix nested union crash. (#643) [Krzysztof Jankowski] Verilator 3.846 2013-03-09 ========================== **Major:** * IEEE 1800-2012 is now the default language. This adds 4 new keywords and updates the svdpi.h and vpi_user.h header files. * Add --report-unoptflat. (#611) [Jeremy Bennett] **Minor:** * Add duplicate clock gate optimization. (#1772) [Varun Koyyalagunta] Disabled unless -OD or -O3 used, please try it as may get some significant speedups. * Support pattern assignment features. (#616) (#617) (#618) [Ed Lander] * Support bind in $unit. (#602) [Ed Lander] * Support '() sized casts. (#628) [Ed Lander] * Fix wrong dot resolution under inlining. [Art Stamness] * Fix DETECTARRAY on packed structures. (#610) [Jeremy Bennett] * Fix LITENDIAN on unpacked structures. (#614) [Wai Sum Mong] * Fix 32-bit OS VPI scan issue. (#615) [Jeremy Bennett, Rich Porter] * Fix opening a VerilatedVcdC file multiple times. (#1774) [Frédéric Requin] * Fix UNOPTFLAT circular array bounds crossing. (#630) [Jie Xu] Verilator 3.845 2013-02-04 ========================== **Minor:** * Fix nested packed arrays and struct. (#600) [Jeremy Bennett] Packed arrays are now represented as a single linear vector in Verilated models. This may affect packed arrays that are public or accessed via the VPI. * Support wires with data types. (#608) [Ed Lander] * Support bind, to module names only. (#602) [Ed Lander] * Support VPI product info, warning calls, etc. (#588) [Rick Porter] * Support $left, $right and related functions. (#448) [Iztok Jeras] * Support inside expressions. * Define SYSTEMVERILOG, SV_COV_START and other IEEE mandated predefines. * Fix pin width mismatch error. (#595) [Alex Solomatnikov] * Fix implicit one bit parameter selection. (#603) [Jeremy Bennett] * Fix signed/unsigned parameter misconversion. (#606) [Jeremy Bennett] * Fix segfault on multidimensional dotted arrays. (#607) [Jie Xu] * Fix per-bit array output connection error. (#414) [Jan Egil Ruud] * Fix package logic var compile error. * Fix enums with X values. Verilator 3.844 2013-01-09 ========================== **Minor:** * Support "unsigned int" DPI import functions. (#1770) [Alex Lee] * Fix package resolution of parameters. (#586) [Jeremy Bennett] * Fix non-integer vpi_get_value. (#587) [Rich Porter] * Fix task inlining under $display and case. (#589) (#598) [Holger Waechtler] * Fix package import of non-localparam parameter. (#474) (#591) [Jeremy Bennett] * Fix package import of package imports, partial #592. [Jeremy Bennett] * Fix package import preventing local var. (#599) [Jeremy Bennett] * Fix array extraction of implicit vars. (#601) [Joe Eiler] Verilator 3.843 2012-12-01 ========================== **Minor:** * Add +1364-1995ext and similar language options. (#532) [Jeremy Bennett] * Fix mis-optimized identical submodule subtract. (#581) [Charlie Brej] * Fix crash on dotted references into dead modules. (#583) [Jeremy Bennett] * Fix compile issues on MSVCC. (#571) (#577) [Amir Gonnen] * Fix --debug overriding preceding --dump-treei. (#580) [Jeremy Bennett] Verilator 3.842 2012-11-03 ========================== **Minor:** * Add -x-initial-edge. (#570) [Jeremy Bennett] * Fix parameter pins interspersed with cells broke in 3.840. [Bernard Deadman] * Fix large shift error on large shift constants. [David Welch] * Fix $display mangling on GCC 4.7 and speed up. (#1765) (#373) (#574) [R Diez] * Fix array of struct references giving false error. (#566) [Julius Baxter] * Fix missing var access functions when no DPI. (#572) [Amir Gonnen] * Fix name collision on unnamed blocks. (#567) [Chandan Egbert] * Fix name collision on task inputs. (#569) [Chandan Egbert] Verilator 3.841 2012-09-03 ========================== **Major:** * Add --savable to support model save/restore. [Jeremy Bennett] **Minor:** * Support '{} assignment pattern on structures, part of #355. * Fix double-deep parameter cell WIDTHs. (#541) [Hiroki Honda] * Fix imports under multiple instantiated cells. (#542) [Alex Solomatnikov] * Fix defparam in generate broke in 3.840. (#543) [Alex Solomatnikov] * Fix duplicate begin error broke in 3.840. (#548) [Alex Solomatnikov] * Fix triangle symbol resolution error broke in 3.840. (#550) [Ted Campbell] Verilator 3.840 2012-07-31 Beta =============================== **Major:** * Rewrote tristate handling; supports tri0, tri1, tristate bit selects, concatenates and pullup/pulldowns. (#395) (#56) (#54) (#51) [Alex Solomatnikov, Lane Brooks, et al] * Support packed structures and unions. (#181) Note this was a major internal change that may lead to some instability. **Minor:** * Support tri0 and tri1. (#462) [Alex Solomatnikov] * Support nmos and pmos. (#488) [Alex Solomatnikov] * Add INITIALDLY warning on initial assignments. (#478) [Alex Solomatnikov] * Add PINMISSING and PINNOCONNECT lint checks. * Add --converge-limit option. * Fix generate operators not short circuiting. (#413) [by Jeremy Bennett] * Fix parameters not supported in constant functions. (#474) [Alex Solomatnikov] * Fix duplicate warnings/errors. (#516) [Alex Solomatnikov] * Fix signed extending biops with WIDTH warning off. (#511) [Junji Hashimoto] * Fix ITOD internal error on real conversions. (#491) [Alex Solomatnikov] * Fix input and real loosing real data type. (#501) [Alex Solomatnikov] * Fix imports causing symbol table error. (#490) [Alex Solomatnikov] * Fix newlines in radix values. (#507) [Walter Lavino] * Fix loop error message to report line. (#513) [Jeremy Bennett] * Fix false UNUSED warning on file system calls. * Fix GCC 4.7.0 compile warnings. (#530) [Jeremy Bennett] * Fix svdpi.h compile error on Apple OS. * Fix compile error under git submodules. (#534) [Aurelien Francillon] Verilator 3.833 2012-04-15 ========================== **Minor:** * Support += and -= in standard for loops. (#463) [Alex Solomatnikov] * Fix processing unused parameterized modules. (#469) (#470) [Alex Solomatnikov] * Add SELRANGE as warning instead of error. (#477) [Alex Solomatnikov] * Add readme.pdf and internal.pdf and doxygen. (#483) [by Jeremy Bennett] * Fix change detections on arrays. (#364) [John Stevenson, Alex Solomatnikov] * Fix signed array warning. (#456) [Alex Solomatnikov] * Fix genvar and begin under generate. (#461) [Alex Solomatnikov] * Fix real constant parameter functions. (#475) [Alex Solomatnikov] * Fix and document --gdb option. (#454) [Jeremy Bennett] * Fix OpenSolaris compile error. [Sanjay Singh] Verilator 3.832 2012-03-07 ========================== **Minor:** * Fix memory delayed assignments from multiple clock domains. [Andrew Ling] * Support arrayed SystemC I/O pins. [Christophe Joly] * Report MULTIDRIVEN on memories set in multiple clock domains. * Report ENDLABEL on mismatching end labels. (#450) [Iztok Jeras] * Fix expansion of back-slashed escaped macros. (#441) [Alberto Del Rio] * Fix inheriting real and signed type across untyped parameters. * Fix core dump with over 100 deep UNOPTFLAT. (#432) [Joe Eiler] * Fix false command not found warning in makefiles. [Ruben Diez] * Fix hang when functions inside begin block. [David Welch] * Fix hang on recursive substitution `defines. (#443) [Alex Solomatnikov] Verilator 3.831 2012-01-20 ========================== **Major:** * Support SystemC 2.3.0 prerelease. This requires setting the new SYSTEMC_INCLUDE and SYSTEMC_LIBDIR variables in place of now deprecated SYSTEMC and SYSTEMC_ARCH. [Iztok Jeras] **Minor:** * Suppress VARHIDDEN on dpi import arguments. [Ruben Diez] * Support "generate for (genvar i=0; ...". [David Kravitz] * Fix dpi exports with > 32 bit but < 64 bit args. (#423) [Chandan Egbert] * Fix array of instantiations with sub-range output. (#414) [Jeremy Bennett] * Fix BLKSEQ warnings on variables declared inside always. [Ruben Diez] Verilator 3.830 2011-11-27 ========================== **Major:** * With "--language VAMS" support a touch of Verilog AMS. [Holger Waechtler] **Minor:** * Add sc_bv attribute to force bit vectors. (#402) [by Stefan Wallentowitz] * Search for user -y paths before default current directory. [Ruben Diez] * Support constants in sensitivity lists. (#412) [Jeremy Bennett] * Support $system. [Ruben Diez] * Support $sscanf with %g. [Holger Waechtler] * Indicate 'exiting due to errors' if errors, not warnings. [Ruben Diez] * Fix bad result with if-else-return optimization. (#420) [Alex Solomatnikov] * Fix reporting not found modules if generate-off. (#403) [Jeremy Bennett] * Fix $display with %d following %g. [Holger Waechtler] Verilator 3.824 2011-10-25 ========================== **Minor:** * Fix "always @ (* )". (#403) (#404) [Walter Lavino] * Add ASSIGNIN as suppressible error. [Jeremy Bennett] * Fix 3.823 constructor core dump on Debian. (#401) [Ahmed El-Mahmoudy] Verilator 3.823 2011-10-20 ========================== **Minor:** * Support $ceil, $floor, etc. [Alex Solomatnikov] * Add configure options for cc warnings and extended tests. [Ruben Diez] * Add -Wall reporting ASSIGNDLY on assignment delays. [Ruben Diez] * Fix UNDRIVEN warnings inside DPI import functions. [Ruben Diez] * Fix --help output to go to stderr, not stdout. (#397) [Ruben Diez] * Fix DPI import output of 64 bits. (#398) [Mike Denio] * Fix DPI import false BLKSEQ warnings. [Alex Solomatnikov] * Fix MSVC compile warning with trunc/round. (#394) [Amir Gonnen] * Fix autoconf and Makefile warnings. (#396) [Ruben Diez] Verilator 3.821 2011-09-14 ========================== **Minor:** * Fix PowerPC runtime error. (#288) [Ahmed El-Mahmoudy] * Fix internal error on integer casts. (#374) [Chandan Egbert] Verilator 3.820 2011-07-28 ========================== **Minor:** * Support 'real' numbers and related functions. * Support 'const' variables in limited cases; similar to enums. [Alex Solomatnikov] * Support disable for loop escapes. * Support $fopen and I/O with integer instead of `verilator_file_descriptor. * Support coverage in -cc and -sc output modes. [John Li] Note this requires SystemPerl 1.338 or newer. * Use 'vluint64_t' for SystemC instead of (same sized) 'uint64' for MSVC++. * Fix vpi_register_cb using bad s_cb_data. (#370) [by Thomas Watts] * Fix $display missing leading zeros in %0d. (#367) [Alex Solomatnikov] Verilator 3.813 2011-06-28 ========================== **Minor:** * Support bit vectors > 64 bits wide in DPI import and exports. * Fix out of memory on slice syntax error. (#354) [Alex Solomatnikov] * Fix error on enum references to other packages. (#339) [Alex Solomatnikov] * Fix DPI undeclared svBitVecVal compile error. (#346) [Chandan Egbert] * Fix DPI bit vector compile errors. (#347) (#359) [Chandan Egbert] * Fix CDCRSTLOGIC report showing endpoint flops without resets. * Fix compiler warnings on SPARC. (#288) [Ahmed El-Mahmoudy] Verilator 3.812 2011-04-06 ========================== **Minor:** * Add --trace-max-width and --trace-max-array. (#319) [Alex Solomatnikov] * Add --Wno-fatal to turn off abort on warnings. [by Stefan Wallentowitz] * Support ${...} and $(...) env vars in .vc files. [by Stefan Wallentowitz] * Support $bits(data_type). (#327) [Alex Solomatnikov] * Support loop unrolling on width mismatches. (#333) [Joe Eiler] * Support simple cast operators. (#335) [Alex Solomatnikov] * Accelerate bit-selected inversions. * Add error on circular parameter definitions. (#329) [Alex Solomatnikov] * Fix concatenates and vectored bufif1. (#326) [Iztok Jeras] Verilator 3.811 2011-02-14 ========================== **Minor:** * Report error on duplicated or empty pins. (#321) [Christian Leber] * Report error on function call output tied to constant. [Bernard Deadman] * Throw UNUSED/UNDRIVEN only once per net in a parameterized module. * Fix internal error on functions called as SV tasks. [Bernard Deadman] * Fix internal error on non-inlined inout pins. [Jeff Winston] * Fix false BLKSEQ on non-unrolled for loop indexes. [Jeff Winston] * Fix block comment not separating identifiers. (#311) [Gene Sullivan] * Fix warnings to point to lowest net usage, not upper level ports. * Fix error on constants connected to outputs. (#323) [Christian Leber] Verilator 3.810 2011-01-03 ========================== **Major:** * Add limited support for VPI access to public signals, see docs. * Add -F option to read relative option files. (#297) [Neil Hamilton] * Support ++,--,+= etc as standalone statements. [Alex Solomatnikov] * Add -Wall, -Wwarn-style, -Wno-style to enable code style warnings that have been added to this release, and disabled by default: * With --Wall, add BLKSEQ warning on blocking assignments in seq blocks. * With --Wall, add DECLFILENAME warning on modules not matching filename. * With --Wall, add DEFPARAM warning on deprecated defparam statements. * With --Wall, add IFDEPTH warning on deep if statements. * With --Wall, add INCABSPATH warning on `include with absolute paths. * With --Wall, add SYNCASYNCNET warning on mixed sync/async reset nets. * With --Wall, add UNDRIVEN warning on undriven nets. * With --Wall, add UNUSED warning on unused nets. **Minor:** * When running with VERILATOR_ROOT, optionally find binaries under bin. * Suppress WIDTH warnings when adding/subtracting 1'b1. * The VARHIDDEN warning is now disabled by default, use -Wall to enable. Verilator 3.805 2010-11-02 ========================== **Minor:** * Add warning when directory contains spaces. (#1705) [Salman Sheikh] * Fix wrong filename on include file errors. (#289) [Brad Parker] * Fix segfault on SystemVerilog "output wire foo=0". (#291) [Joshua Wise] * Fix DPI export name not found. (#1703) [Terry Chen] Verilator 3.804 2010-09-20 ========================== **Minor:** * Support tracing/coverage of underscore signals. (#280) [by Jason McMullan] * Increase define recursions before error. [Paul Liu] * On core dump, print debug suggestions. * Fix preprocessor \`\` of existing base define. (#283) [Usha Priyadharshini] Verilator 3.803 2010-07-10 ========================== **Minor:** * Fix preprocessor preservation of newlines across macro substitutions. * Fix preprocessor stringification of nested macros. * Fix some constant parameter functions causing crash. (#253) [Nick Bowler] * Fix do {...} while() not requiring final semicolon. Verilator 3.802 2010-05-01 ========================== **Minor:** * Support runtime access to public signal names. * Add /*verilator public_flat_rw*/ for timing-specific public access. * Fix word size to match uint64_t on -m64 systems. (#238) [Joe Eiler] * Improve error handling on slices of arrays. (#226) [by Byron Bradley] * Report errors when extra underscores used in meta-comments. * Fix bit reductions on multi-packed dimensions. (#227) [by Byron Bradley] * Fix removing $fscanf if assigned to unused var. (#248) [Ashutosh Das] * Fix "make install" with configure outside srcdir. [Stefan Wallentowitz] * Fix loop unroller out of memory; change --unroll-stmts. [Ashutosh Das] * Fix trace files with empty modules crashing some viewers. * Fix parsing single files > 2GB. [Jeffrey Short] * Fix installing data files as non-executable. (#168) [by Ahmed El-Mahmoudy] Verilator 3.801 2010-03-17 ========================== **Minor:** * Support "break", "continue", "return". * Support "`default_nettype none|wire". [Dominic Plunkett] * Skip SystemC tests if not installed. [Iztok Jeras] * Fix clock-gates with non-AND complex logic. (#220) [Ashutosh Das] * Fix flushing VCD buffers on $stop. [Ashutosh Das] * Fix Mac OS-X compile issues. (#217) [Joshua Wise, Trevor Williams] * Fix make uninstall. (#216) [Iztok Jeras] * Fix parameterized defines with empty arguments. Verilator 3.800 2010-02-07 ========================== **Major application visible changes:** * SystemPerl is no longer required for tracing. Applications must use VerilatedVcdC class in place of SpTraceVcdC. * SystemVerilog 1800-2009 is now the default language. Thus "global" etc are now keywords. See the --language option. **Major new features:** * Support SystemVerilog types "byte", "chandle", "int", "longint", "shortint", "time", "var" and "void" in variables and functions. * Support "program", "package", "import" and $unit. * Support typedef and enum. [by Donal Casey] * Support direct programming interface (DPI) "import" and "export". Includes an extension to map user $system PLI calls to the DPI. * Support assignments of multidimensional slices. (#170) [by Byron Bradley] * Support multidimensional inputs/outputs. (#171) [by Byron Bradley] * Support "reg [1:0][1:0][1:0]" and "reg x [3][2]". (#176) [Byron Bradley] * Support declarations in loop initializers. (#172) [by Byron Bradley] * Support $test$plusargs and $value$plusargs, but see the docs! * Support $sformat and $swrite. * Support 1800-2009 define defaults and `undefineall. * Add -CFLAGS, -LDFLAGS, .a, .o, and .so options. * Speed compiles by avoiding including the STL iostream header. Application programs may need to include it themselves to avoid errors. * Add experimental clock domain crossing checks. * Add experimental --pipe-filter to filter all Verilog input. * Add experimental config files to filter warnings outside of the source. * Add VARHIDDEN warning when signal name hides module name. * Support optional cell parenthesis. (#179) [by Byron Bradley] * Support for-loop i++, ++i, i--, --i. (#175) [by Byron Bradley] * Support 1800-2009 /*comments*/ in define values. * Add Makefile VM_GLOBAL_FAST, listing objects needed to link executables. * Add --bbox-unsup option to black-box unsupported UDP tables. * Add -Wno-MODDUP option to allow duplicate modules. **Bug fixes:** * Fix implicit variable issues. (#196) (#201) [Byron Bradley] * Fix 'for' variable typing. (#205) [by Byron Bradley] * Fix tracing with --pins-bv 1. (#195) [Michael S] * Fix MSVC++ 2008 compile issues. (#209) [Amir Gonnen] * Fix MinGW compilation. (#184) (#214) [by Shankar Giri, Amir Gonnen] * Fix Cygwin 1.7.x compiler error with uint32_t. (#204) [Ivan Djordjevic] * Fix `define argument mis-replacing system task of same name. (#191) * Fix Verilator core dump on wide integer divides. (#178) [Byron Bradley] * Fix lint_off/lint_on meta comments on same line as warning. Verilator 3.720 2009-10-26 ========================== **Major:** * Support little endian bit vectors ("reg [0:2] x;"). * Support division and modulus of > 64 bit vectors. [Gary Thomas] **Minor:** * Fix writing to out-of-bounds arrays writing element 0. * Fix core dump with SystemVerilog var declarations under unnamed begins. * Fix VCD files showing internal flattened hierarchy, broke in 3.714. * Fix cell port connection to unsized integer causing false width warning. * Fix erroring on strings with backslashed newlines. (#168) [Pete Nixon] Verilator 3.714 2009-09-18 ========================== **Major:** * Add --bbox-sys option to blackbox $system calls. **Minor:** * Support generate for var++, var--, ++var, --var. * Improved warning when "do" used as identifier. * Don't require SYSTEMPERL_INCLUDE if SYSTEMPERL/src exists. [Gary Thomas] * Fix deep defines causing flex scanner overflows. [Brad Dobbie] * Fix preprocessing commas in deep parameterized macros. [Brad Dobbie] * Fix tracing escaped dotted identifiers. (#107) * Fix $display with uppercase %M. * Fix --error-limit option being ignored. Verilator 3.713 2009-08-04 ========================== **Minor:** * Support constant function calls for parameters. [many!] * Support SystemVerilog "logic". (#101) [by Alex Duller] * Name SYMRSVDWORD error, and allow disabling it. (#103) [Gary Thomas] * Fix escaped preprocessor identifiers. (#106) [Nimrod Gileadi] Verilator 3.712 2009-07-14 ========================== **Major:** * Patching SystemC is no longer required to trace sc_bvs. **Minor:** * Add verilator --pins-uint8 option to use sc_in. * Add verilator -V option, to show verbose version. * Add BLKLOOPINIT error code, and describe --unroll-count. [Jeff Winston] * Support zero-width constants in concatenations. [Jeff Winston] * On WIDTH warnings, show variable name causing error. [Jeff Winston] Verilator 3.711 2009-06-23 ========================== **Minor:** * Support decimal constants of arbitrary widths. [Mark Marshall] * Fix error on case statement with all duplicate items. (#99) [Gary Thomas] * Fix segfault on unrolling for's with bad inits. (#90) [Andreas Olofsson] * Fix tristates causing "Assigned pin is neither...". [by Lane Brooks] * Fix compiler errors under Fedora release candidate 11. [Chitlesh Goorah] Verilator 3.710 2009-05-19 ========================== **Major:** * Verilator is now licensed under LGPL v3 and/or Artistic v2.0. **Minor:** * `__FILE__ now expands to a string, per draft SystemVerilog 2010(ish). * The front end parser has been re-factored to enable more SV parsing. Code should parse the same, but minor parsing bugs may pop up. * Verilator_includer is no longer installed twice. (#48) [Lane Brooks] * Fix escaped identifiers with '.' causing conflicts. (#83) [J Baxter] * Fix define formal arguments that contain newlines. (#84) [David A] Verilator 3.703 2009-05-02 ========================== **Minor:** * Fix $clog2 calculation error with powers-of-2. (#81) [Patricio Kaplan] * Fix error with tasks that have output first. (#78) [Andrea Foletto] * Fix "cloning" error with -y/--top-module. (#76) [Dimitris Nalbantis] * Fix segfault with error on bad --top-module. (#79) [Dimitris Nalbantis] * Fix "redefining I" error with complex includes. [Duraid Madina] * Fix GCC 4.3.2 compile warnings. Verilator 3.702 2009-03-28 ========================== **Minor:** * Add --pins-bv option to use sc_bv for all ports. [Brian Small] * Add SYSTEMPERL_INCLUDE envvar to assist RPM builds. [Chitlesh Goorah] * Report errors when duplicate labels are used. (#72) [Vasu Kandadi] * Fix the SC_MODULE name() to not include __PVT__. [Bob Fredieu] Verilator 3.701 2009-02-26 ========================== **Minor:** * Support repeat and forever statements. [Jeremy Bennett] * Add --debugi- option, for internal debugging. [Dennis Muhlestein] * Fix compile issues with GCC 4.3. (#47) [Lane Brooks] * Fix VL_RANDom to better randomize bits. [Art Stamness] * Fix error messages to consistently go to stderr. [Jeremy Bennett] * Fix left associativity for ?: operators. Verilator 3.700 2009-01-08 ========================== **Major:** * Support limited tristate inouts. Written by Lane Brooks, under support by Ubixum Inc. This allows common pad ring and tristate-mux structures to be Verilated. See the documentation for more information on supported constructs. * Add --coverage_toggle for toggle coverage analysis. Running coverage now requires SystemPerl 1.301 or newer. * Add coverage_on/_off metacomments to bracket coverage regions. **Minor:** * Support posedge of bit-selected signals. (#45) [Rodney Sinclair] * Optimize two-level shift and and/or trees, +23% on one test. * Line coverage now aggregates by hierarchy automatically. Previously this would be done inside SystemPerl, which was slower. * Minor performance improvements of Verilator compiler runtime. * Coverage of each parameterized module is counted separately. [Bob Fredieu] * Fix creating parameterized modules when no parameter values are changed. * Fix certain generate-if cells causing "clone" error. [Stephane Laurent] * Fix line coverage of public functions. [Soon Koh] * Fix SystemC 2.2 deprecated warnings about sensitive() and sc_start(). * Fix arrayed variables under function not compiling. (#44) [Ralf Karge] * Fix --output-split-cfuncs to also split trace code. [Niranjan Prabhu] * Fix 'bad select range' warning missing some cases. (#43) [Lane Brooks] * Fix internal signal names containing control characters (broke in 3.680). * Fix compile error on Ubuntu 8.10. [Christopher Boumenot] * Fix internal error on "output x; reg x = y;". * Fix wrong result for read of delayed FSM signal. (#46) [Rodney Sinclair] Verilator 3.681 2008-11-12 ========================== **Minor:** * Support SystemVerilog unique and priority case. * Include Verilog file's directory name in coverage reports. * Fix 'for' under 'generate-for' causing error. (#38) [Rafael Shirakawa] * Fix coverage hierarchy being backwards with inlining. [Vasu Arasanipalai] * Fix GCC 4.3 compile error. (#35) [Lane Brooks] * Fix MSVC compile error. (#42) [John Stroebel] Verilator 3.680 2008-10-08 ========================== **Major:** * Support negative bit indexes. [Stephane Laurent] Tracing negative indexes requires latest Verilog-Perl and SystemPerl. **Minor:** * Suppress width warnings between constant strings and wider vectors. [Rodney Sinclair] * Ignore SystemVerilog timeunit and timeprecision. * Expand environment variables in -f input files. [Lawrence Butcher] * Report error if port declaration is missing. (#32) [Guy-Armand Kamendje] * Fix genvars causing link error when using --public. [Chris Candler] Verilator 3.671 2008-09-19 ========================== **Major:** * SystemC uint64_t pins are now the default instead of sc_bv<64>. Use --no-pins64 for backward compatibility. * Support SystemVerilog "cover property" statements. **Minor:** * When warnings are disabled on signals that are flattened out, disable the warnings on the signal(s) that replace it. * Add by-design and by-module subtotals to verilator_profcfunc. * Add IMPERFECTSCH warning, disabled by default. * Support coverage under SystemPerl 1.285 and newer. * Support arbitrary characters in identifiers. [Stephane Laurent] * Fix extra evaluation of pure combo blocks in SystemC output. * Fix stack overflow on large ? : trees. [John Sanguinetti] Verilator 3.670 2008-07-23 ========================== **Major:** * Add --x-assign=fast option, and make it the default. This chooses performance over reset debugging. See the manual. * Add --autoflush, for flushing streams after $display. [Steve Tong] * Add CASEWITHX lint warning and if disabled fix handling of casez with Xs. **Minor:** * Add $feof, $fgetc, $fgets, $fflush, $fscanf, $sscanf. [Holger Waechtler] * Add $stime. [Holger Waechtler] * Add $random. * Add --Wfuture-, for improving forward compatibility. * Add WIDTH warning to $fopen etc file descriptors. * Fix verilator_includer not being installed properly. [Holger Waechtler] * Fix IMPURE errors due to X-assignment temporary variables. [Steve Tong] * Fix "lvalue" errors with public functions. (#25) [CY Wang] Verilator 3.665 2008-06-25 ========================== **Minor:** * Ignore "// verilator" comments alone on endif lines. [Rodney Sinclair] * "Make install" now installs verilator_includer and verilator_profcfunc. * Fix tracing missing changes on undriven public wires. [Rodney Sinclair] * Fix syntax error when "`include `defname" is ifdefed. [John Dickol] * Fix error when macro call has commas in concatenate. [John Dickol] * Fix compile errors under Fedora 9, GCC 4.3.0. [by Jeremy Bennett] * Fix Makefile to find headers/libraries under prefix. [by Holger Waechtler] Verilator 3.664 2008-05-08 ========================== **Minor:** * Fix missing file in kit. Verilator 3.663 2008-05-07 ========================== **Minor:** * Add DESTDIR to Makefiles to assist RPM construction. [Gunter Dannoritzer] * Fix compiler warnings under GCC 4.2.1. * Fix preprocessor `else after series of `elsif. [Mark Nodine] * Fix parameterized defines calling define with comma. [Joshua Wise] * Fix comma separated list of primitives. [by Bryan Brady] Verilator 3.662 2008-04-25 ========================== **Minor:** * Add Verilog 2005 $clog2() function. This is useful in calculating bus-widths from parameters. * Support C-style comments in -f option files. [Stefan Thiede] * Add error message when modules have duplicate names. [Stefan Thiede] * Support defines terminated in EOF, though against spec. [Stefan Thiede] * Support optional argument to $finish and $stop. [by Stefan Thiede] * Support ranges on gate primitive instantiations. [Stefan Thiede] * Ignore old standard(ish) Verilog-XL defines. [by Stefan Thiede] * Fix "always @ ((a) or (b))" syntax error. [by Niranjan Prabhu] * Fix "output reg name=expr;" syntax error. [Martin Scharrer] * Fix multiple .v files being read in random order. [Stefan Thiede] * Fix internal error when params get non-constants. [Johan Wouters] * Fix bug introduced in 3.661 with parameterized defines. Verilator 3.661 2008-04-04 ========================== **Major:** * The --enable-defenv configure option added in 3.660 is now the default. This hard-codes a default for VERILATOR_ROOT etc in the executables. * Add --language option for supporting older code. [Stefan Thiede] * Add --top-module option to select between multiple tops. [Stefan Thiede] **Minor:** * Unsized concatenates now give WIDTHCONCAT warnings. [Jonathan Kimmitt] Previously they threw fatal errors, which in most cases is correct according to spec, but can be incorrect in presence of parameter values. * Support functions with "input integer". [Johan Wouters] * Ignore delays attached to gate UDPs. [Stefan Thiede] * Fix SystemVerilog parameterized defines with \`\` expansion, and fix extra whitespace inserted on substitution. [Vladimir Matveyenko] * Fix no-module include files on command line. [Stefan Thiede] * Fix dropping of backslash quoted-quote at end of $display. * Fix task output pin connected to non-variables. [Jonathan Kimmitt] * Fix missing test_v in install datadir. [Holger Waechtler] * Fix internal error after MSB < LSB error reported to user. [Stefan Thiede] Verilator 3.660 2008-03-23 ========================== **Minor:** * Support hard-coding VERILATOR_ROOT etc in the executables, to enable easier use of Verilator RPMs. [Gunter Dannoritzer] * Allow multiple .v files on command line. [Stefan Thiede] * Convert re-defining macro error to warning. [Stefan Thiede] * Add --error-limit option. [Stefan Thiede] * Allow __ in cell names by quoting them in C. [Stefan Thiede] * Fix genvar to be signed, so "< 0" works properly. [Niranjan Prabhu] * Fix assignments to inputs inside functions/tasks. [Patricio Kaplan] * Fix definitions in main file.v, referenced in library. [Stefan Thiede] * Fix undefined assigns to be implicit warnings. [Stefan Thiede] Verilator 3.658 2008-02-25 ========================== **Minor:** * Fix unistd compile error in 3.657. [Patricio Kaplan, Jonathan Kimmitt] Verilator 3.657 2008-02-20 ========================== **Minor:** * Fix assignments of {a,b,c} = {c,b,a}. [Jonathan Kimmitt] * Fix Perl warning with --lint-only. [by Ding Xiaoliang] * Fix to avoid creating obj_dir with --lint-only. [Ding Xiaoliang] * Fix parsing of always @(*). [Patricio Kaplan] Verilator 3.656 2008-01-18 ========================== **Minor:** * Wide VL_CONST_W_#X functions are now made automatically. [Bernard Deadman] In such cases, a new {prefix}__Inlines.h file will be built and included. * Fix sign error when extracting from signed memory. [Peter Debacker] * Fix tracing of SystemC w/o SystemPerl. [Bernard Deadman, Johan Wouters] Verilator 3.655 2007-11-27 ========================== **Minor:** * Support "#delay ;" with associated STMTDLY warning. * Fix generate for loops with constant zero conditions. [Rodney Sinclair] * Fix divide-by-zero errors in constant propagator. [Rodney Sinclair] * Fix wrong result with obscure signed-shift underneath a "? :". * Fix many internal memory leaks, and added leak detector. Verilator 3.654 2007-10-18 ========================== **Minor:** * Don't exit early if many warnings but no errors are found. [Stan Mayer] * Fix parsing module #(parameter x,y) declarations. [Oleg Rodionov] * Fix parsing system functions with empty parens. [Oleg Rodionov] Verilator 3.653 2007-08-01 ========================== **Minor:** * Support SystemVerilog ==? and !=? operators. * Fix SC_LIBS missing from generated makefiles. [Ding Xiaoliang] Verilator 3.652 2007-06-21 ========================== **Minor:** * Report as many warning types as possible before exiting. * Support V2K portlists with "input a,b,...". [Mark Nodine] * Support V2K function/task argument lists. * Optimize constant $display arguments. * Fix preprocessor dropping some `line directives. [Mark Nodine] Verilator 3.651 2007-05-22 ========================== **Major:** * Add verilator_profcfunc utility. [Gene Weber] **Minor:** * Treat modules within `celldefine and `endcelldefine as if in library. * Support functions which return integers. [Mark Nodine] * Warn if flex is not installed. [Ralf Karge] * Ignore `protect and `endprotect. * Fix empty case/endcase blocks. Verilator 3.650 2007-04-20 ========================== **Major:** * Add --compiler msvc option. This is now required when Verilated code is to be run through MSVC++. This also enables fixing MSVC++ error C1061, blocks nested too deeply. [Ralf Karge] * Add --lint-only option, to lint without creating other output. **Minor:** * Add /*verilator lint_save*/ and /*verilator lint_restore*/ to allow friendly control over re-enabling lint messages. [Gerald Williams] * Support SystemVerilog .name and .* interconnect. * Support while and do-while loops. * Use $(LINK) instead of $(CXX) for Makefile link rules. [Gerald Williams] * Add USER_CPPFLAGS and USER_LDFLAGS to Makefiles. [Gerald Williams] * Fix compile errors under Windows MINGW compiler. [Gerald Williams] * Fix dotted bit reference to local memory. [Eugene Weber] * Fix 3.640 `verilog forcing IEEE 1364-1995 only. [David Hewson] Verilator 3.640 2007-03-12 ========================== **Minor:** * Support Verilog 2005 `begin_keywords and `end_keywords. * Updated list of SystemVerilog keywords to correspond to IEEE 1800-2005. * Add /*verilator public_flat*/. [Eugene Weber] * Try all +libext's in the exact order given. [Michael Shinkarovsky] * Fix elimination of public signals assigned to constants. [Eugene Weber] * Fix internal error when public for loop has empty body. [David Addison] * Fix "Loops detected" assertion when model exceeds 4GB. [David Hewson] * Fix display %m names inside named blocks. Verilator 3.633 2007-02-07 ========================== **Minor:** * Add --trace-depth option for minimizing VCD file size. [Emerson Suguimoto] * With VL_DEBUG, show wires causing convergence errors. [Mike Shinkarovsky] * Fix isolate_assignments when many signals per always. [Mike Shinkarovsky] * Fix isolate_assignments across task/func temporaries. [Mike Shinkarovsky] * Fix $display's with array select followed by wide AND. [David Hewson] Verilator 3.632 2007-01-17 ========================== **Minor:** * Add /*verilator isolate_assignments*/ attribute. [Mike Shinkarovsky] Verilator 3.631 2007-01-02 ========================== **Major:** * Support standard NAME[#] for cells created by arraying or generate for. This replaces the non-standard name__# syntax used in earlier versions. **Minor:** * Fix again dotted references into generate cells. [David Hewson] Verilator no longer accepts duplicated variables inside unique generate blocks as this is illegal according to the specification. * Fix $readmem* with filenames < 8 characters. [Emerson Suguimoto] Verilator 3.630 2006-12-19 ========================== **Major:** * Support $readmemb and $readmemh. [Eugene Weber, Arthur Kahlich] **Minor:** * When dotted signal lookup fails, help the user by showing known scopes. * Fix to reduce depth of priority encoded case statements. [Eugene Weber] * Fix configure and compiling under Solaris. [Bob Farrell] * Fix dotted references inside generated cells. [David Hewson] * Fix missed split optimization points underneath other re-split blocks. Verilator 3.623 2006-12-05 ========================== **Major:** * Add --output-split-cfuncs for accelerating GCC compile. [Eugene Weber] **Minor:** * Add M32 make variable to support -m32 compiles. [Eugene Weber] * Fix $signed mis-extending when input has a WIDTH violation. [Eugene Weber] Verilator 3.622 2006-10-17 Stable ================================= **Minor:** * Fix --skip-identical without --debug, broken in 3.621. [Andy Meier] Verilator 3.621 2006-10-11 Beta =============================== **Major:** * Add /*verilator no_inline_task*/ to prevent over-expansion. [Eugene Weber] **Minor:** * Public functions now allow > 64 bit arguments. * Remove .vpp intermediate files when not under --debug. * Fix link error when using --exe with --trace. [Eugene Weber] * Fix mis-optimization of wide concats with constants. * Fix core dump on printing error when not under --debug. [Allan Cochrane] Verilator 3.620 2006-10-04 Stable ================================= **Minor:** * Support simple inout task ports. [Eugene Weber] * Allow overriding Perl, Flex and Bison versions. [by Robert Farrell] * Optimize variables set to constants within basic blocks for ~3%. * Default make no longer makes the docs; if you edit the documentation. sources, run "make info" to get them. * Optimize additional Boolean identities (a|a = a, etc.) * Fix coredump when dotted cross-ref inside task call. [Eugene Weber] * Fix dotted variables in always sensitivity lists. [Allan Cochrane] Verilator 3.610 2006-09-20 Stable ================================= **Minor:** * Verilator now works under DJGPP (Pentium GCC). [John Stroebel] * Add default define for VL_PRINTF. [John Stroebel] * Removed coverage request variable; see Coverage limitations in docs. * Fix DOS carriage returns in multiline defines. [Ralf Karge] * Fix printf format warnings on 64-bit linux. Verilator 3.602 2006-09-11 Stable ================================= **Minor:** * Fix function references under top inlined module. [David Hewson] Verilator 3.601 2006-09-06 Beta =============================== **Major:** * Add --inhibit-sim flag for environments using old __Vm_inhibitSim. * Add `systemc_dtor for destructor extensions. [Allan Cochrane] * Add -MP to make phony dependencies, ala GCC's. **Minor:** * Changed how internal functions are invoked to reduce aliasing. Useful when using GCC's -O2 or -fstrict-aliasing, to gain another ~4%. * Declare optimized lookup tables as 'static', to reduce D-Cache miss rate. * Fix memory leak when destroying modules. [John Stroebel] * Fix coredump when unused modules have unused cells. [David Hewson] * Fix 3.600 internal error with arrayed instances. [David Hewson] * Fix 3.600 internal error with non-unrolled function loops. [David Hewson] * Fix $display %m name not matching Verilog name inside SystemC modules. Verilator 3.600 2006-08-28 Beta =============================== **Major:** * Support dotted cross-hierarchy variable and task references. **Minor:** * Lint for x's in generate case statements. * Fix line numbers being off by one when first file starts with newline. * Fix naming of generate for blocks to prevent non-inline name conflict. * Fix redundant statements remaining after table optimization. Verilator 3.542 2006-08-11 Stable ================================= **Minor:** * vl_finish and vl_fatal now print via VL_PRINTF rather then cerr/cout. * Fix extraneous UNSIGNED warning when comparing genvars. [David Hewson] * Fix extra white space in $display %c. [by David Addison] * Fix missing VL_CONST_W_24X macro. [Bernard Deadman] Verilator 3.541 2006-07-05 Beta =============================== **Minor:** * Add warning on changeDetect to arrayed structures. [David Hewson] * Fix "// verilator lint_on" not re-enabling warnings. [David Hewson] * Fix 3.540's multiple memory assignments to same block. [David Hewson] * Fix non-zero start number for arrayed instantiations. [Jae Hossell] * Fix GCC 4.0 header file warnings. Verilator 3.540 2006-06-27 Beta =============================== **Minor:** * Optimize combo assignments that are used only once, ~5-25% faster. * Optimize delayed assignments to memories inside loops, ~0-5% faster. * Fix mis-width warning on bit selects of memories. [David Hewson] * Fix mis-width warning on dead generate-if branches. [Jae Hossell] Verilator 3.533 2006-06-05 Stable ================================= **Minor:** * Add PDF user manual, verilator.pdf. * Fix delayed bit-selected arrayed assignments. [David Hewson] * Fix execution path to Perl. [Shanshan Xu] * Fix Bison compile errors in verilog.y. [by Ben Jackson] Verilator 3.531 2006-05-10 Stable ================================= **Minor:** * Support $c routines which return 64 bit values. * Fix `include `DEFINE. * Fix Verilator core dump when have empty public function. [David.Hewson] Verilator 3.530 2006-04-24 Stable ================================= **Major:** * $time is now 64 bits. The macro VL_TIME_I is now VL_TIME_Q, but calls the same sc_time_stamp() function to get the current time. Verilator 3.523 2006-03-06 Stable ================================= **Minor:** * Fix error line numbers being off due to multi-line defines. [Mat Zeno] * Fix GCC sign extending (uint64_t)(a>>, $signed, $unsigned. [MANY!] * Support multi-dimensional arrays. [Eugen Fekete] * Support very limited Property Specification Language (aka PSL or Sugar). The format and keywords are now very limited, but will grow with future releases. The --assert switch enables this feature. * With --assert, generate assertions for synthesis parallel_case and full_case. **Minor:** * Fix generate if's with empty if/else blocks. [Mat Zeno] * Fix generate for cell instantiations with same name. [Mat Zeno] Verilator 3.481 2005-10-12 Stable ================================= **Minor:** * Add /*verilator tracing_on/off*/ for waveform control. * Fix split optimization reordering $display statements. Verilator 3.480 2005-09-27 Beta =============================== **Major:** * Allow coverage of flattened modules, and multiple points per line. Coverage analysis requires SystemPerl 1.230 or newer. **Minor:** * Add preprocessor changes to support meta-comments. * Optimize sequential assignments of different bits of same bus; ~5% faster. * Optimize away duplicate lookup tables. * Optimize wide concatenates into individual words. [Ralf Karge] * Optimize local variables from delayed array assignments. Verilator 3.470 2005-09-06 Stable ================================= **Minor:** * Optimize staging flops under reset blocks. * Add '-Werror-...' to upgrade specific warnings to errors. * Add GCC branch prediction hints on generated if statements. * Fix bad simulation when same function called twice in same expression. * Fix preprocessor substitution of quoted parameterized defines. Verilator 3.464 2005-08-24 Stable ================================= **Major:** * Add `systemc_imp_header, for use when using --output-split. * Add --stats option to dump design statistics. **Minor:** * Fix core dump with clock inversion optimizations. Verilator 3.463 2005-08-05 Stable ================================= **Minor:** * Fix case defaults when not last statement in case list. [Wim Michiels] Verilator 3.462 2005-08-03 Stable ================================= **Minor:** * Fix reordering of delayed assignments to same memory index. [Wim Michiels] * Fix compile error with Flex 2.5.1. [Jens Arm] * Fix multiply-instantiated public tasks generating non-compilable code. Verilator 3.461 2005-07-28 Beta =============================== **Minor:** * Fix compile error with older versions of bison. [Jeff Dutton] Verilator 3.460 2005-07-27 Beta =============================== **Major:** * Add -output-split option to enable faster parallel GCC compiles. To support --output-split, the makefiles now split VM_CLASSES into VM_CLASSES_FAST and VM_CLASSES_SLOW. This may require a change to local makefiles. * Support -v argument to read library files. **Minor:** * When issuing unoptimizable warning, show an example path. * Internal tree dumps now indicate edit number that changed the node. * Fix false warning when a clock is constant. * Fix X/Z in decimal numbers. [Wim Michiels] * Fix genvar statements in non-named generate blocks. * Fix core dump when missing newline in `define. [David van der Bokke] Verilator 3.450 2005-07-12 ========================== **Major:** * $finish will no longer exit, but set Verilated::gotFinish(). This enables support for final statements, and for other cleanup code. If this is undesired, redefine the vl_user_finish routine. Top level loops should use Verilated::gotFinish() as an exit condition for their loop, and then call top->final(). To prevent an infinite loop, a double $finish will still exit; this may be removed in future releases. * Support SystemVerilog keywords $bits, $countones, $isunknown, $onehot, $onehot0, always_comb, always_ff, always_latch, finish. **Minor:** * Fix "=== 1'bx" to always be false, instead of random. Verilator 3.440 2005-06-28 Stable ================================= **Major:** * Add Verilog 2001 generate for/if/case statements. Verilator 3.431 2005-06-24 Stable ================================= **Minor:** * Fix selection bugs introduced in 3.430 beta. Verilator 3.430 2005-06-22 Beta =============================== **Minor:** * Add Verilog 2001 variable part selects [n+:m] and [n-:m]. [Wim Michiels] Verilator 3.422 2005-06-10 Stable ================================= **Minor:** * Add Verilog 2001 power (**) operator. [Danny Ding] * Fix crash and added error message when assigning to inputs. [Ralf Karge] * Fix tracing of modules with public functions. Verilator 3.421 2005-06-02 Beta =============================== **Minor:** * Fix error about reserved word on non-public signals. * Fix missing initialization compile errors in 3.420 beta. [Ralf Karge] Verilator 3.420 2005-06-02 Beta =============================== **Minor:** * Performance improvements worth ~20% * Add -x-assign options; ~5% faster if use -x-assign=0. * Add error message when multiple defaults in case statement. * Optimize shifts out of conditionals and if statements. * Optimize local 'short' wires. * Fix case defaults when not last statement in case list. [Ralf Karge] * Fix crash when wire self-assigns x=x. * Fix gate optimization with top-flattened modules. [Mahesh Kumashikar] Verilator 3.411 2005-05-30 Stable ================================= **Minor:** * Fix compile error in GCC 2.96. [Jeff Dutton] Verilator 3.410 2005-05-25 Beta =============================== **Major:** * Allow functions and tasks to be declared public. They will become public C++ functions, with appropriate C++ types. This allows users to make public accessor functions/tasks, instead of having to use public variables and `systemc_header hacks. **Minor:** * Skip producing output files if all inputs are identical This uses timestamps, similar to make. Disable with --no-skip-identical. * Improved compile performance with large case statements. * Fix internal error in V3Table. [Jeff Dutton] * Fix compile error in GCC 2.96, and with SystemC 1.2. [Jeff Dutton] Verilator 3.400 2005-04-29 Beta =============================== **Major:** * Internal changes to support future clocking features. * Verilog-Perl and SystemPerl are no longer required for C++ or SystemC output. If you want tracing or coverage analysis, they are still needed. * Add --sc to create pure SystemC output not requiring SystemPerl. * Add --pins64 to create 64 bit SystemC outputs instead of sc_bv<64>. * The --exe flag is now required to produce executables inside the makefile. This was previously the case any time .cpp files were passed on the command line. * Add -O3 and --inline-mult for performance tuning. [Ralf Karge] One experiment regained 5% performance, at a cost of 300% in compile time. **Minor:** * Improved performance of large case/always statements with low fanin by converting to internal lookup tables (ROMs). * Initialize SystemC port names. [S Shuba] * Add Doxygen comments to Verilated includes. * Fix -cc pins 8 bits wide and less to be uint8_t instead of uint16_t. * Fix crash when Mdir has same name as .v file. [Gernot Koch] * Fix crash with size mismatches on case items. [Gernot Koch] Verilator 3.340 2005-02-18 Stable ================================= **Minor:** * Report misconnected pins across all modules, instead of just first error. * Improved large netlist compile times. * Fix over-active inlining, resulting in compile slowness. Verilator 3.332 2005-01-27 ========================== **Major:** * Add -E preprocess only flag, similar to GCC. * Add CMPCONSTLR when comparison is constant due to > or < with all ones. **Minor:** * Fix loss of first -f file argument, introduced in 3.331. Verilator 3.331 2005-01-18 ========================== **Major:** * The Verilog::Perl preprocessor is now C++ code inside of Verilator. This improves performance, makes compilation easier, and enables some future features. **Minor:** * Support arrays of instantiations (non-primitives only). [Wim Michiels] * Fix unlinked error with defparam. [Shawn Wang] Verilator 3.320 2004-12-10 ========================== **Major:** * NEWS is now renamed Changes, to support CPAN indexing. * If Verilator is passed a C file, create a makefile link rule. This saves several user steps when compiling small projects. **Minor:** * Add new COMBDLY warning in place of fatal error. [Shawn Wang] * Fix mis-simulation with wide-arrays under bit selects. [Ralf Karge] * Add NC Verilog as alternative to VCS for reference tests. * Support implicit wire declarations on input-only signals. (Dangerous, as leads to wires without drivers, but allowed by spec.) * Fix compile warnings on Suse 9.1 Verilator 3.311 2004-11-29 ========================== **Major:** * Support implicit wire declarations (as a warning). [Shawn Wang] **Minor:** * Fix over-shift difference in Verilog vs C++. [Ralf Karge] Verilator 3.310 2004-11-15 ========================== **Major:** * Support defparam. * Support gate primitives: buf, not, and, nand, or, nor, xor, xnor. **Minor:** * Ignore all specify blocks. Verilator 3.302 2004-11-12 ========================== **Minor:** * Support NAND and NOR operators. * Better warnings when port widths don't match. * Fix internal error due to some port width mismatches. [Ralf Karge] * Fix WIDTH warnings on modules that are only used parameterized, not in 'default' state. * Fix selection of SystemC library on cygwin systems. [Shawn Wang] * Fix runtime bit-selection of parameter constants. Verilator 3.301 2004-11-04 ========================== **Minor:** * Fix 64 bit [31:0] = {#{}} mis-simulation. [Ralf Karge] * Fix shifts greater then word width mis-simulation. [Ralf Karge] * Fix to work around GCC 2.96 negation bug. Verilator 3.300 2004-10-21 ========================== **Major:** * New backend that eliminates most VL macros. Improves performance 20%-50%, depending on frequency of use of signals over 64 bits. GCC compile times with -O2 shrink by a factor of 10. **Minor:** * Fix "setting unsigned int from signed value" warning. Verilator 3.271 2004-10-21 ========================== **Minor:** * Fix "loops detected" error with some negedge clocks. * Fix some output code spacing issues. Verilator 3.270 2004-10-15 ========================== **Minor:** * Support Verilog 2001 parameters in module headers. [Ralf Karge] * Faster code to support compilers not inlining all Verilated functions. * Fix numeric fault when dividing by zero. Verilator 3.260 2004-10-07 ========================== **Major:** * Support Verilog 2001 named parameter instantiation. [Ralf Karge] **Minor:** * Return 1's when one bit wide extract indexes outside array bounds. * Fix compile warnings on 64-bit operating systems. * Fix incorrect dependency in .d file when setting VERILATOR_BIN. Verilator 3.251 2004-09-09 ========================== **Minor:** * Fix parenthesis overflow in Microsoft Visual C++ [Renga Sundararajan] Verilator 3.250 2004-08-30 ========================== **Major:** * Support Microsoft Visual C++ [Renga Sundararajan] **Minor:** * SystemPerl 1.161+ is required. Verilator 3.241 2004-08-17 ========================== **Minor:** * Support ,'s to separate multiple assignments. [Paul Nitza] * Fix shift sign extension problem using non-GCC compilers. Verilator 3.240 2004-08-13 ========================== **Major:** * Verilator now uses 64 bit math where appropriate. Inputs and outputs of 33-64 bits wide to the C++ Verilated model must now be uint64_t's; SystemC has not changed, they will remain sc_bv's. This increases performance by ~ 9% on x86 machines, varying with how frequently 33-64 bit signals occur. Signals 9-16 bits wide are now stored as 16 bit shorts instead of longs, this aids cache packing. **Minor:** * Fix SystemC compile error with feedthrus. [Paul Nitza] * Fix concat value error introduced in 3.230. Verilator 3.230 2004-08-10 ========================== **Minor:** * Add coverage output to test_sp example, SystemPerl 1.160+ is required. * Fix time 0 value of signals. [Hans Van Antwerpen] Earlier versions would not evaluate some combinatorial signals until posedge/negedge blocks had been activated. * Fix wide constant inputs to public submodules [Hans Van Antwerpen] * Fix wide signal width extension bug. Only applies when width mismatch warnings were overridden. Verilator 3.220 2004-06-22 ========================== **Major:** * Many waveform tracing changes: * Tracing is now supported on C++ standalone simulations. [John Brownlee] **Minor:** * When tracing, SystemPerl 1.150 or newer is required. * When tracing, Verilator must be called with the --trace switch. * Add SystemPerl example to documentation. [John Brownlee] * Various Cygwin compilation fixes. [John Brownlee] Verilator 3.210 2004-04-01 ========================== **Major:** * Compiler optimization switches have changed See the BENCHMARKING section of the documentation. * With Verilog-Perl 2.3 or newer, Verilator supports SystemVerilog preprocessor extensions. **Minor:** * Add localparam. [Thomas Hawkins] * Add warnings for SystemVerilog reserved words. Verilator 3.203 2004-03-10 ========================== **Minor:** * Notes and repairs for Solaris. [Fred Ma] Verilator 3.202 2004-01-27 ========================== **Major:** * The beta version is now the primary release. See below for many changes. If you have many problems, you may wish to try release 3.125. * Verilated::traceEverOn(true) must be called at time 0 if you will ever turn on tracing (waveform dumping) of signals. Future versions will need this switch to disable trace incompatible optimizations. **Minor:** * Optimize common replication operations. * Fix several tracing bugs Verilator 3.201-beta 2003-12-10 =============================== **Major:** * BETA VERSION, USE 3.124 for stable release! * Version 3.2XX includes an all new back-end. This includes automatic inlining, flattening of signals between hierarchy, and complete ordering of statements. This results in 60-300% execution speedups, though less pretty C++ output. Even better results are possible using GCC 3.2.2 (part of Redhat 9.1), as GCC has fixed some optimization problems which Verilator exposes. If you are using `systemc_ctor, beware pointers to submodules are now initialized after the constructor is called for a module, to avoid segfaults, move statements that reference subcells into initial statements. * C++ Constructor that creates a verilog module may take a char* name. This name will be used to prefix any $display %m arguments, so users may distinguish between multiple Verilated modules in a single executable. Verilator 3.125 2004-01-27 ========================== **Minor:** * Optimize bit replications Verilator 3.124 2003-12-05 ========================== **Major:** * An optimized executable will be made by default, in addition to a debug executable. Invoking Verilator with --debug will pick the debug version. **Minor:** * Many minor invisible changes to support the next version. Verilator 3.123 2003-11-10 ========================== **Minor:** * Wide bus performance enhancements. * Fix function call bug when width warning suppressed. [Leon Wildman] * Fix __DOT__ compile problem with funcs in last revision. [Leon Wildman] Verilator 3.122 2003-10-29 ========================== **Major:** * Modules which are accessed from external code now must be marked with /*verilator public_module*/ unless they already contain public signals. To enforce this, private cell names now have a string prepended. **Minor:** * Fix replicated function calls in one statement. [Robert A. Clark] * Fix function call bug when width warning suppressed. [Leon Wildman] Verilator 3.121 2003-09-29 ========================== **Minor:** * Support multiplication over 32 bits. [Chris Boumenot] Also improved speed of addition and subtraction over 32 bits. * Detect bit selection out of range errors. * Detect integer width errors. * Fix width problems on function arguments. [Robert A. Clark] Verilator 3.120 2003-09-24 ========================== **Minor:** * $finish now exits the model (via vl_finish function). * Support inputs/outputs in tasks. * Support V2K "integer int = {INITIAL_VALUE};" * Ignore floating point delay values. [Robert A. Clark] * Ignore `celldefine, `endcelldefine, etc. [Robert A. Clark] * Optimize reduction operators. * Fix converting "\ooo" into octal values. * Fix $display("%x"); Verilator 3.112 2003-09-16 ========================== **Minor:** * Fix functions in continuous assignments. [Robert A. Clark] * Fix inlining of modules with 2-level deep outputs. Verilator 3.111 2003-09-15 ========================== **Minor:** * Fix declaration of functions before using that module. [Robert A. Clark] * Fix module inlining bug with outputs. Verilator 3.110 2003-09-12 ========================== **Major:** * Support Verilog 2001 style input/output declarations. [Robert A. Clark] * Support local vars in headers of function/tasks. [Leon Wildman] Verilator 3.109 2003-08-28 ========================== **Major:** * Support local variables in named begin blocks. [Leon Wildman] Verilator 3.108 2003-08-11 ========================== **Major:** * Support functions. **Minor:** * Signals 8 bits and shorter are now stored as chars instead of uint32_t's. This improves Dcache packing and improves performance by ~7%. * $display now usually results in a single VL_PRINT rather then many. * Optimize conditionals (?:) Verilator 3.107 2003-07-15 ========================== **Major:** * --private and --l2name are now the default, as this enables additional optimizations. Use --noprivate or --nol2name to get the older behavior. **Minor:** * Now support $display of binary and wide format data. * Add detection of incomplete case statements, and added related optimizations worth ~4%. * Work around flex bug in Redhat 8.0. [Eugene Weber] * Add some additional C++ reserved words. * Additional constant optimizations, ~5% speed improvement. Verilator 3.106 2003-06-17 ========================== **Major:** * $c can now take multiple expressions as arguments. For example $c("foo","bar(",32+1,");") will insert "foobar(33);" This makes it easier to pass the values of signals. * Several changes to support future versions that may have signal-eliminating optimizations. Users should try to use these switch on designs, they will become the default in later versions. * Add --private switch and /*verilator public*/ metacomment. This renames all signals so that compile errors will result if any signals referenced by C++ code are missing a /*verilator public*/ metacomment. * With --l2name, the second level cell C++ cell is now named "v". Previously it was named based on the name of the verilog code. This means to get to signals, scope to "{topcell} ->v ->{mysignal}" instead of "{topcell} ->{verilogmod}. {mysignal}". This allows different modules to be substituted for the cell without requiring source changes. **Minor:** * Several cleanups for Redhat 8.0. Verilator 3.105 2003-05-08 ========================== **Minor:** * Fix more GCC 3.2 errors. [David Black] Verilator 3.104 2003-04-30 ========================== **Major:** * Indicate direction of ports with VL_IN and VL_OUT. * Allow $c32, etc, to specify width of the $c statement for VCS. * Numerous performance improvements, worth about 25% **Minor:** * Fix false "indent underflow" error inside `systemc_ctor sections. * Fix missing ordering optimizations when outputs also used internally. * Assign constant cell pins in initial blocks rather then every cycle. * Promote subcell's combo logic to sequential evaluation when possible. * Fix GCC 3.2 compile errors. [Narayan Bhagavatula] Verilator 3.103 2003-01-28 ========================== **Minor:** * Fix missing model evaluation when clock generated several levels of hierarchy across from where it is used as a clock. [Richard Myers] * Fix sign-extension bug introduced in 3.102. Verilator 3.102 2003-01-24 ========================== **Minor:** * Fix sign-extension of X/Z's ("32'hx") Verilator 3.101 2003-01-13 ========================== **Minor:** * Fix 'parameter FOO=#'bXXXX' [Richard Myers] * Allow spaces inside numbers ("32'h 1234") [Sam Gladstone] Verilator 3.100 2002-12-23 ========================== **Major:** * Support for simple tasks w/o vars or I/O. [Richard Myers] **Minor:** * Ignore DOS carriage returns in Linux files. [Richard Myers] Verilator 3.012 2002-12-18 ========================== **Minor:** * Fix parsing bug with casex statements containing case items with bit extracts of parameters. [Richard Myers] * Fix bug which could cause writes of non-power-of-2 sized arrays to corrupt memory beyond the size of the array. [Dan Lussier] * Fix bug which did not detect UNOPT problems caused by submodules. See the description in the verilator man page. [John Deroo] * Fix compile with threaded Perl. [Ami Keren] Verilator 3.010 2002-11-03 ========================== **Major:** * Support SystemC 2.0.1. SystemPerl version 1.130 or newer is required. **Minor:** * Fix bug with inlined modules under other inlined modules. [Scott Bleiweiss] Verilator 3.005 2002-10-21 ========================== **Minor:** * Fix X's in case (not casex/z) to constant propagate correctly. * Fix missing include. [Kurachi] Verilator 3.004 2002-10-10 ========================== **Minor:** * Add module_inline metacomment and associated optimizations. * Allow coverage_block_off metacomment in place of `coverage_block_off. This prevents problems with Emacs AUTORESET. [Ray Strouble] * Fix `coverage_block_off also disabling subsequent blocks. * Fix unrolling of loops with multiple simple statements. * Fix compile warnings on newer GCC. [Kurachi] * Additional concatenation optimizations. Verilator 3.003 2002-09-13 ========================== **Minor:** * Now compiles on Windows 2000 with Cygwin. * Fix bug with pin assignments to wide memories. * Optimize wire assignments to constants. Verilator 3.002 2002-08-19 ========================== **Major:** * First public release of version 3. Verilator 3.000 2002-08-03 ========================== **Major:** * All new code base. Many changes too numerous to mention. **Minor:** * Approximately 4 times faster then Verilator 2. * Support initial statements * Support correct blocking/nonblocking assignments * Support `defines across multiple modules * Optimize call ordering, constant propagation, and dead code elimination. Verilator 2.1.8 2002-04-03 ========================== **Major:** * All applications must now link against include/verilated.cpp **Minor:** * Paths specified to verilator_make should be absolute, or be formed to allow for execution in the object directory (prepend ../ to each path.) This allows relative filenames for makes which hash and cache dependencies. * Add warning when parameter constants are too large. [John Deroo] * Add warning when x/?'s used in non-casez statements. * Add warning when blocking assignments used in posedge blocks. [Dan Lussier] * Split evaluation function into clocked and non-clocked, 20% perf gain. Verilator 2.1.5 2001-12-01 ========================== **Major:** * Add coverage analysis. In conjunction with SystemC provide line coverage reports, without SystemC, provide a hook to user written accumulation function. See --coverage option of verilator_make. **Minor:** * Relaxed multiply range checking * Support for constants up to 128 bits * Randomize values used when assigning to X's. * Add -guard option of internal testing. * Changed indentation in emitted code to be automatically generated. * Fix corruption of assignments of signal over 32 bits with non-0 lsb. Verilator 2.1.4 2001-11-16 ========================== **Major:** * Add $c("c_commands();"); for embedding arbitrary C code in Verilog. Verilator 2.1.3 2001-11-03 ========================== **Major:** * Support for parameters. Verilator 2.1.2 2001-10-25 ========================== **Major:** * Verilog Errors now reference the .v file rather then the .vpp file. **Minor:** * Support strings in assignments: reg [31:0] foo = "STRG"; * Support %m in format strings. Ripped out old $info support, use Verilog-Perl's vpm program instead. * Convert $stop to call of v_stop() which user can define. * Fix bug where a==b==c would have wrong precedence rule. * Fix bug where XNOR on odd-bit-widths (~^ or ^~) had bad value. Verilator 2.1.1 2001-05-17 ========================== **Major:** * New test_sp directory for System-Perl (SystemC) top level instantiation of the Verilated code, lower modules are still C++ code. (Experimental). * New test_spp directory for Pure System-Perl (SystemC) where every module is true SystemC code. (Experimental) **Minor:** * Input ports are now loaded by pointer reference into the sub-cell. This is faster on I-386 machines, as the stack must be used when there are a large number of parameters. Also, this simplifies debugging as the value of input ports exists for tracing. * Many code cleanups towards standard C++ style conventions. Verilator 2.1.0 2001-05-08 ========================== **Minor:** * Many code cleanups towards standard C++ style conventions. Version history lost ==================== Verilator 1.8 1996-07-08 ======================== [Versions 0 to 1.8 were by Paul Wasson] * Fix single bit in concat from instance output incorrect offset bug. Verilator 1.7 1996-05-20 ======================== * Mask unused bits of DONTCAREs. Verilator 1.6 1996-05-13 ======================== * Add fasttrace script Verilator 1.5 1996-01-09 ======================== * Pass structure pointer into translated code, so multiple instances can use same functions. * Fix static value concat on casex items. Verilator 1.1 1995-03-30 ======================== * Bug fixes, added verimake_partial script, performance improvements. Verilator 1.0c 1994-09-30 ========================= * Initial release of Verilator Verilator 0.0 1994-07-08 ======================== * First code written. .. ---------------------------------------------------------------------- Copyright ========= Copyright 2001-2024 by Wilson Snyder. This program is free software; you can redistribute it and/or modify it under the terms of either the GNU Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 verilator-5.020/configure.ac0000644000175000017500000005561214544475344015724 0ustar carstencarsten# DESCRIPTION: Process this file with autoconf to produce a configure script. # # Copyright 2003-2024 by Wilson Snyder. Verilator is free software; you # can redistribute it and/or modify it under the terms of either the GNU Lesser # General Public License Version 3 or the Perl Artistic License Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 # When releasing, also update header of Changes file, and CmakeLists.txt, # and commit using "devel release" or "Version bump" message # Then 'make maintainer-dist' #AC_INIT([Verilator],[#.### YYYY-MM-DD]) #AC_INIT([Verilator],[#.### devel]) AC_INIT([Verilator],[5.020 2024-01-01], [https://verilator.org], [verilator],[https://verilator.org]) AC_CONFIG_HEADERS(src/config_package.h) AC_CONFIG_FILES(Makefile src/Makefile src/Makefile_obj include/verilated.mk include/verilated_config.h verilator.pc verilator-config.cmake verilator-config-version.cmake) # Version AC_MSG_RESULT([configuring for $PACKAGE_STRING]) PACKAGE_VERSION_NUMBER=`AS_ECHO("$PACKAGE_VERSION") | sed 's/ .*//g'` AC_SUBST(PACKAGE_VERSION_NUMBER) AC_DEFINE_UNQUOTED([PACKAGE_VERSION_NUMBER_STRING],["$PACKAGE_VERSION_NUMBER"],[Package version as a number]) VERILATOR_VERSION_INTEGER=`AS_ECHO("$PACKAGE_VERSION") | [sed 's/\([0-9]\)\.\([0-9][0-9][0-9]\) .*/\1\2000/g']` AC_SUBST(VERILATOR_VERSION_INTEGER) AC_DEFINE_UNQUOTED([PACKAGE_VERSION_STRING_CHAR], [static const char* const PACKAGE_STRING_UNUSED = "$PACKAGE_STRING";], [Package version as a number]) AC_SUBST(PACKAGE_VERSION_STRING_CHAR) # Ignore automake flags passed by Ubuntu builds AC_ARG_ENABLE([dependency-tracking], [AS_HELP_STRING([--disable-dependency-tracking], [ignored])]) AC_ARG_ENABLE([maintainer-mode], [AS_HELP_STRING([--enable-maintainer-mode], [ignored])]) AC_ARG_ENABLE([silent-rules], [AS_HELP_STRING([--disable-silent-rules], [ignored])]) # Flag to enable linking specific libraries statically AC_MSG_CHECKING(whether to perform partial static linking of Verilator binary) AC_ARG_ENABLE([partial-static], [AS_HELP_STRING([--disable-partial-static], [By default, for Verilation performance, Verilator is linked against some of its dependencies statically. Use this to link the Verilator binary fully dynamically.])], [case "${enableval}" in yes) CFG_ENABLE_PARTIAL_STATIC=yes ;; no) CFG_ENABLE_PARTIAL_STATIC=no ;; *) AC_MSG_ERROR([bad value '${enableval}' for --disable-partial-static]) ;; esac], CFG_ENABLE_PARTIAL_STATIC=yes) AC_MSG_RESULT($CFG_ENABLE_PARTIAL_STATIC) # Flag to enable linking Verilator with tcmalloc if available AC_MSG_CHECKING(whether to use tcmalloc) AC_ARG_ENABLE([tcmalloc], [AS_HELP_STRING([--enable-tcmalloc], [Use libtcmalloc_minimal for faster dynamic memory management in Verilator binary @<:@default=check@:>@])], [case "${enableval}" in yes) CFG_WITH_TCMALLOC=yes ;; no) CFG_WITH_TCMALLOC=no ;; *) AC_MSG_ERROR([bad value '${enableval}' for --enable-tcmalloc]) ;; esac], [CFG_WITH_TCMALLOC=check;]) AC_MSG_RESULT($CFG_WITH_TCMALLOC) # Flag to enable -m32 build AC_MSG_CHECKING(whether to use -m32) AC_ARG_ENABLE([m32], [AS_HELP_STRING([--enable-m32], [Use -m32 for all compilation and link, including Verilator and generated models.])], [case "${enableval}" in yes) CFG_ENABLE_M32=yes ;; no) CFG_ENABLE_M32=no ;; *) AC_MSG_ERROR([bad value '${enableval}' for --enable-m32]) ;; esac], CFG_ENABLE_M32=no) AC_MSG_RESULT($CFG_ENABLE_M32) # Flag to enable coverage build AC_MSG_CHECKING(whether to build for coverage collection) AC_ARG_ENABLE([coverage], [AS_HELP_STRING([--enable-coverage], [Build Verilator for code coverage collection. For developers only.])], [case "${enableval}" in yes) CFG_ENABLE_COVERAGE=yes ;; no) CFG_ENABLE_COVERAGE=no ;; *) AC_MSG_ERROR([bad value '${enableval}' for --enable-coverage]) ;; esac], CFG_ENABLE_COVERAGE=no) AC_MSG_RESULT($CFG_ENABLE_COVERAGE) # Special Substitutions - CFG_WITH_DEFENV AC_MSG_CHECKING(whether to use hardcoded paths) AC_ARG_ENABLE([defenv], [AS_HELP_STRING([--disable-defenv], [disable using some hardcoded data paths extracted from some default environment variables (the default is to use hardcoded paths) in Verilator binary])], [case "${enableval}" in yes) CFG_WITH_DEFENV=yes ;; no) CFG_WITH_DEFENV=no ;; *) AC_MSG_ERROR([bad value ${enableval} for --disable-defenv]) ;; esac], CFG_WITH_DEFENV=yes) AC_SUBST(CFG_WITH_DEFENV) AC_MSG_RESULT($CFG_WITH_DEFENV) # Special Substitutions - CFG_WITH_CCWARN AC_MSG_CHECKING(whether to show and stop on compilation warnings) AC_ARG_ENABLE([ccwarn], [AS_HELP_STRING([--enable-ccwarn], [enable showing and stopping on compilation warnings in Verilator binary and Verilated makefiles])], [case "${enableval}" in yes) CFG_WITH_CCWARN=yes ;; no) CFG_WITH_CCWARN=no ;; *) AC_MSG_ERROR([bad value ${enableval} for --enable-ccwarn]) ;; esac], [case "x${VERILATOR_AUTHOR_SITE}" in x) CFG_WITH_CCWARN=no ;; *) CFG_WITH_CCWARN=yes ;; esac] ) AC_SUBST(CFG_WITH_CCWARN) AC_MSG_RESULT($CFG_WITH_CCWARN) # Special Substitutions - CFG_WITH_LONGTESTS AC_MSG_CHECKING(whether to run long tests) AC_ARG_ENABLE([longtests], [AS_HELP_STRING([--enable-longtests], [enable running long developer tests])], [case "${enableval}" in yes) CFG_WITH_LONGTESTS=yes ;; no) CFG_WITH_LONGTESTS=no ;; *) AC_MSG_ERROR([bad value ${enableval} for --enable-longtests]) ;; esac], [case "x${VERILATOR_AUTHOR_SITE}" in x) CFG_WITH_LONGTESTS=no ;; *) CFG_WITH_LONGTESTS=yes ;; esac] ) AC_SUBST(CFG_WITH_LONGTESTS) AC_MSG_RESULT($CFG_WITH_LONGTESTS) # Compiler flags (ensure they are not empty to avoid configure defaults) CFLAGS="$CFLAGS " CPPFLAGS="$CPPFLAGS " CXXFLAGS="$CXXFLAGS " LDFLAGS="$LDFLAGS " # Checks for programs. AC_PROG_CC AC_PROG_CXX AC_PROG_INSTALL AC_LANG_PUSH(C++) cxx_version=$($CXX --version | head -1) AC_MSG_RESULT([compiler is $CXX --version = $cxx_version]) AC_MSG_CHECKING([that C++ compiler can compile simple program]) AC_RUN_IFELSE( [AC_LANG_SOURCE([int main() { return 0; }])], AC_MSG_RESULT(yes), AC_MSG_RESULT(no);AC_MSG_ERROR([a working C++ compiler is required]), AC_MSG_RESULT(yes)) AC_CHECK_PROG(AR,ar,ar) if test "x$AR" = "x" ; then AC_MSG_ERROR([Cannot find "ar" in your PATH, please install it]) fi AC_PATH_PROG(PERL,perl) if test "x$PERL" = "x" ; then AC_MSG_ERROR([Cannot find "perl" in your PATH, please install it]) fi AC_PATH_PROG(PYTHON3,python3) if test "x$PYTHON3" = "x" ; then AC_MSG_ERROR([Cannot find "python3" in your PATH, please install it]) fi AC_PATH_PROG(LEX,flex) if test "x$LEX" = "x" ; then AC_MSG_ERROR([Cannot find "flex" in your PATH, please install it]) fi flex_version=$($LEX --version | head -1) AC_MSG_RESULT([$LEX --version = $flex_version]) AC_PATH_PROG(YACC,bison) if test "x$YACC" = "x" ; then AC_MSG_ERROR([Cannot find "bison" in your PATH, please install it]) fi bison_version=$($YACC --version | head -1) AC_MSG_RESULT([$YACC --version = $bison_version]) AC_CHECK_PROG(OBJCACHE,ccache,ccache) if test "x$OBJCACHE" != "x" ; then objcache_version=$($OBJCACHE --version | head -1) AC_MSG_RESULT([objcache is $OBJCACHE --version = $objcache_version]) fi # Checks for libraries. # Checks for typedefs, structures AC_CHECK_TYPE(size_t,unsigned int) AC_TYPE_SIZE_T # Checks for compiler characteristics. AC_C_INLINE AC_LINK_IFELSE( [AC_LANG_PROGRAM([#include ], [[int* a=new int; delete a; ]])], [], [AC_MSG_ERROR([$CXX does not seem to successfully compile a simple C++ program])]) AC_DEFUN([_MY_CXX_CHECK_FLAG], [# _MY_CXX_CHECK_FLAG(flag) -- Check if compiler supports specific options # Set $_my_result appropriately ACO_SAVE_CXXFLAGS="$CXXFLAGS" # -Werror needed otherwise unknown -Wno-div-by-zero won't report problems # new/delete is needed to find -faligned-new link problem on Darwin CXXFLAGS="$CXXFLAGS $1 -Werror" AC_MSG_CHECKING([whether $CXX accepts $1]) AC_LINK_IFELSE( [AC_LANG_PROGRAM([#include ], [[int* a=new int; delete a; ]])], [_my_result=yes if test -s conftest.err; then if grep -e "$1" conftest.err >/dev/null; then _my_result=no fi fi], [_my_result=no]) # GCC is annoying, trying to be helpful, it postpones unknown -Wno- # options if there's no error We want to see them regardless, so try # forcing an error and see if we get a gcc warning AC_COMPILE_IFELSE( [AC_LANG_PROGRAM([[an_error "intentional-error-for-test.h" ]],[])], [], # Ignore ok exit [if test -s conftest.err; then if grep -e "$1" conftest.err >/dev/null; then _my_result=no fi fi]) AC_MSG_RESULT($_my_result) CXXFLAGS="$ACO_SAVE_CXXFLAGS" ]) AC_DEFUN([_MY_CXX_CHECK_IFELSE], [# _MY_CXX_CHECK_IFELSE(option,action-if-supported,action-if-not-supported) # Check if compiler supports specific option. If it does, # do action-if-supported, otherwise do action-if-not-supported _MY_CXX_CHECK_FLAG($1) if test "$_my_result" = "yes" ; then true $2 else true $3 fi ]) AC_DEFUN([_MY_CXX_CHECK_SET], [# _MY_CXX_CHECK_SET(variable,option) # Check if compiler supports specific option. If it does, # set variable to option, only if not previously set. if test "$$1" = ""; then _MY_CXX_CHECK_IFELSE($2, $1="$2") fi ]) AC_DEFUN([_MY_CXX_CHECK_OPT], [# _MY_CXX_CHECK_OPT(variable,option) # Check if compiler supports specific option. If it does, # append option to variable _MY_CXX_CHECK_IFELSE($2, $1="$$1 $2") ]) AC_DEFUN([_MY_LDLIBS_CHECK_FLAG], [# _MY_LDLIBS_CHECK_FLAG(flag) -- Check if linker supports specific options # Set $_my_result appropriately ACO_SAVE_LIBS="$LIBS" LIBS="$LIBS $1" AC_MSG_CHECKING([whether $CXX linker accepts $1]) AC_LINK_IFELSE( [AC_LANG_PROGRAM([[]])], [_my_result=yes if test -s conftest.err; then if grep -e "$1" conftest.err >/dev/null; then _my_result=no fi fi], [_my_result=no]) AC_MSG_RESULT($_my_result) LIBS="$ACO_SAVE_LIBS" ]) AC_DEFUN([_MY_LDLIBS_CHECK_IFELSE], [# _MY_LDLIBS_CHECK_IFELSE(flag,action-if-supported,action-if-not-supported) # Check if linker supports specific flag, if it does do action-if-supported # otherwise do action-if-not-supported _MY_LDLIBS_CHECK_FLAG($1) if test "$_my_result" = "yes" ; then true $2 else true $3 fi ]) AC_DEFUN([_MY_LDLIBS_CHECK_OPT], [# _MY_LDLIBS_CHECK_OPT(variable, flag) -- Check if linker supports specific # options. If it does, append flag to variable. _MY_LDLIBS_CHECK_IFELSE($2, $1="$$1 $2") ]) # When using -m32. Check this first as later checks may fail with the -m32 flag. if test "$CFG_ENABLE_M32" = "yes"; then _MY_CXX_CHECK_IFELSE( -m32, [CXX="$CXX -m32"], [AC_MSG_ERROR([--enable-m32 was given but compiler does not support -m32])]) fi # Similarly, add the coverage flags early as they influence later checks. if test "$CFG_ENABLE_COVERAGE" = "yes"; then _MY_CXX_CHECK_OPT(CXX,--coverage) # Otherwise inline may not show as uncovered # If we use this then e.g. verilated.h functions properly show up # if unused. # However, VerilatedSerialize::write then changes from covered # to uncovered (in G++ 9.3.0) even with all inlining turned off. # Having false negative coverage is more effort then missing negatives. # Also this seems to explode the runtime (since a lot more data). # _MY_CXX_CHECK_OPT(CXX,-fkeep-inline-functions) # Otherwise static may not show as uncovered _MY_CXX_CHECK_OPT(CXX,-fkeep-static-functions) # Exceptions can pollute the branch coverage data _MY_CXX_CHECK_OPT(CXX,-fno-exceptions) # Define-out some impossible stuff _MY_CXX_CHECK_OPT(CXX,-DVL_GCOV) fi # Compiler flags to enable profiling _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_PROFILE,-pg) AC_SUBST(CFG_CXXFLAGS_PROFILE) # Flag to select newest language standard supported # Macros work such that first option that passes is the one we take # Currently enable c++17/c++14 due to packaged SystemC dependency # c++17 is the newest that Verilator is regularly tested to support # c++14 is the oldest that Verilator supports # gnu is required for Cygwin to compile verilated.h successfully #_MY_CXX_CHECK_SET(CFG_CXXFLAGS_STD_NEWEST,-std=gnu++20) #_MY_CXX_CHECK_SET(CFG_CXXFLAGS_STD_NEWEST,-std=c++20) _MY_CXX_CHECK_SET(CFG_CXXFLAGS_STD_NEWEST,-std=gnu++17) _MY_CXX_CHECK_SET(CFG_CXXFLAGS_STD_NEWEST,-std=c++17) _MY_CXX_CHECK_SET(CFG_CXXFLAGS_STD_NEWEST,-std=gnu++14) _MY_CXX_CHECK_SET(CFG_CXXFLAGS_STD_NEWEST,-std=c++14) AC_SUBST(CFG_CXXFLAGS_STD_NEWEST) # Flags for compiling Verilator internals including parser, and Verilated files # These turn on extra warnings and are only used with 'configure --enable-ccwarn' _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_WEXTRA,-Wextra) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_WEXTRA,-Wfloat-conversion) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_WEXTRA,-Wlogical-op) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_WEXTRA,-Wthread-safety) AC_SUBST(CFG_CXXFLAGS_WEXTRA) # Flags for coroutine support for dynamic scheduling _MY_CXX_CHECK_SET(CFG_CXXFLAGS_COROUTINES,-fcoroutines-ts) _MY_CXX_CHECK_SET(CFG_CXXFLAGS_COROUTINES,-fcoroutines) _MY_CXX_CHECK_SET(CFG_CXXFLAGS_COROUTINES,-fcoroutines-ts -Wno-deprecated-experimental-coroutine) AC_SUBST(CFG_CXXFLAGS_COROUTINES) # HAVE_COROUTINES # Check if coroutines are supported at all AC_MSG_CHECKING([whether coroutines are supported by $CXX]) ACO_SAVE_CXXFLAGS="$CXXFLAGS" CXXFLAGS="$CXXFLAGS $CFG_CXXFLAGS_COROUTINES" AC_LINK_IFELSE( [AC_LANG_PROGRAM([ #ifdef __clang__ #define __cpp_impl_coroutine 1 #endif #include ],[[]])], [_my_result=yes AC_DEFINE([HAVE_COROUTINES],[1],[Defined if coroutines are supported by $CXX])], [AC_LINK_IFELSE( [AC_LANG_PROGRAM([#include ],[[]])], [_my_result=yes AC_DEFINE([HAVE_COROUTINES],[1],[Defined if coroutines are supported by $CXX])], [_my_result=no])]) AC_MSG_RESULT($_my_result) CXXFLAGS="$ACO_SAVE_CXXFLAGS" AC_SUBST(HAVE_COROUTINES) # Flags for compiling Verilator internals including parser always _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_SRC,-Qunused-arguments) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_SRC,-faligned-new) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_SRC,-Wno-unused-parameter) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_SRC,-Wno-shadow) AC_SUBST(CFG_CXXFLAGS_SRC) # Flags for compiling Verilator parser always (in addition to above CFG_CXXFLAGS_SRC) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_PARSER,-Wno-char-subscripts) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_PARSER,-Wno-null-conversion) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_PARSER,-Wno-parentheses-equality) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_PARSER,-Wno-unused) AC_SUBST(CFG_CXXFLAGS_PARSER) # Flags for compiling the debug version of Verilator (in addition to above CFG_CXXFLAGS_SRC) if test "$CFG_ENABLE_COVERAGE" = "no"; then # Do not optimize for the coverage build _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_DEBUG,-Og) fi _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_DEBUG,-ggdb) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_DEBUG,-gz) AC_SUBST(CFG_CXXFLAGS_DEBUG) # Flags for linking the debug version of Verilator (in addition to above CFG_LDFLAGS_SRC) _MY_LDLIBS_CHECK_OPT(CFG_LDFLAGS_DEBUG,-gz) AC_SUBST(CFG_LDFLAGS_DEBUG) # Flags for Verilated makefile # For example, -Wno-div-by-zero isn't in 4.1.2 # Random code often does / 0. Unfortunately VL_DIV_I(0,0) will warn # without this flag, even though there's a conditional to prevent the divide. # We still don't add no-div-by-zero as it throws message to stdout, though doesn't die. #_MY_CXX_CHECK_OPT(-Wno-div-by-zero) # For some reason -faligned-new does not work under Travis w/ clang but the # configure test doesn't catch this either AS_IF([test "x$TRAVIS_COMPILER" != xclang], [_MY_CXX_CHECK_OPT(CFG_CXXFLAGS_NO_UNUSED,-faligned-new)]) CFG_CXX_FLAGS_CMAKE="-faligned-new" m4_foreach([cflag],[ [-fbracket-depth=4096], [-fcf-protection=none], [-mno-cet], [-Qunused-arguments], [-Wno-bool-operation], [-Wno-c++11-narrowing], [-Wno-constant-logical-operand], [-Wno-non-pod-varargs], [-Wno-overloaded-virtual], [-Wno-parentheses-equality], [-Wno-shadow], [-Wno-sign-compare], [-Wno-tautological-bitwise-compare], [-Wno-uninitialized], [-Wno-unused-but-set-parameter], [-Wno-unused-but-set-variable], [-Wno-unused-parameter], [-Wno-unused-variable]],[ _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_NO_UNUSED,cflag) # CMake will test what flags work itself, so pass all flags through to it CFG_CXX_FLAGS_CMAKE="$CFG_CXX_FLAGS_CMAKE cflag" ]) AC_SUBST(CFG_CXXFLAGS_NO_UNUSED) AC_SUBST(CFG_CXX_FLAGS_CMAKE) # Find multithread linker flags m4_foreach([ldflag], [ [-mt], [-pthread], [-lpthread], [-latomic]],[ _MY_LDLIBS_CHECK_OPT(CFG_LDLIBS_THREADS,ldflag) # CMake will test what flags work itself, so pass all flags through to it CFG_LDFLAGS_THREADS_CMAKE="$CFG_LDFLAGS_THREADS_CMAKE ldflag" ]) AC_SUBST(CFG_LDLIBS_THREADS) AC_SUBST(CFG_LDFLAGS_THREADS_CMAKE) # If 'mold' is installed, use it to link for faster buildtimes _MY_LDLIBS_CHECK_OPT(CFG_LDFLAGS_SRC, -fuse-ld=mold) _MY_LDLIBS_CHECK_OPT(CFG_LDFLAGS_VERILATED, -fuse-ld=mold) # When linking partially statically if test "$CFG_ENABLE_PARTIAL_STATIC" = "yes"; then _MY_LDLIBS_CHECK_OPT(CFG_LDFLAGS_SRC, -static-libgcc) _MY_LDLIBS_CHECK_OPT(CFG_LDFLAGS_SRC, -static-libstdc++) _MY_LDLIBS_CHECK_OPT(CFG_LDFLAGS_SRC, -Xlinker -gc-sections) LTCMALLOC=-l:libtcmalloc_minimal.a else LTCMALLOC=-ltcmalloc_minimal fi AC_SUBST(CFG_LDFLAGS_SRC) AC_SUBST(CFG_LDFLAGS_VERILATED) # The pthread library is required by tcmalloc, so add it if it exists. If it # does not, the tcmalloc check below will fail anyway, and linking against # pthreads is harmless otherwise. CFG_LIBS="$LIBS $CFG_LIBS" _MY_LDLIBS_CHECK_OPT(CFG_LIBS, -lpthread) # Check libraries for MingW _MY_LDLIBS_CHECK_OPT(CFG_LIBS, -lbcrypt) _MY_LDLIBS_CHECK_OPT(CFG_LIBS, -lpsapi) # Check if tcmalloc is available based on --enable-tcmalloc _MY_LDLIBS_CHECK_IFELSE( $LTCMALLOC, [if test "$CFG_WITH_TCMALLOC" != "no"; then CFG_LIBS="$LTCMALLOC $CFG_LIBS"; # If using tcmalloc, add some extra options to make the compiler not assume # it is using it's own versions of the standard library functions _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_SRC,-fno-builtin-malloc) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_SRC,-fno-builtin-calloc) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_SRC,-fno-builtin-realloc) _MY_CXX_CHECK_OPT(CFG_CXXFLAGS_SRC,-fno-builtin-free) fi], [if test "$CFG_WITH_TCMALLOC" = "yes"; then AC_MSG_ERROR([--enable-tcmalloc was given but test for ${LTCMALLOC} failed]) fi]) AC_SUBST(CFG_LIBS) # Need C++14 at least #Alternative: AX_CXX_COMPILE_STDCXX([14]) AC_DEFUN([_MY_CXX_CHECK_CXX_VER], [# _MY_CXX_CHECK_CXX_VER(flag) -- Check if compiler runs C++14 # Set $_my_result AC_LINK_IFELSE( [AC_LANG_PROGRAM([#include #if (__cplusplus < 201402L) # error "Too old" #endif ], [[ ]])], [_my_result=yes if test -s conftest.err; then if grep -e "$1" conftest.err >/dev/null; then _my_result=no fi fi], [_my_result=no]) ]) # Add $CFG_CXXFLAGS_STD only if can't compile correctly otherwise, # as adding std= when not needed can cause errors with the C++ std library. CFG_CXXFLAGS_STD=$CFG_CXXFLAGS_STD_NEWEST AC_MSG_CHECKING(whether $CXX supports C++14) _MY_CXX_CHECK_CXX_VER() AC_MSG_RESULT($_my_result) if test "$_my_result" = "no" ; then CXXFLAGS="$CXXFLAGS $CFG_CXXFLAGS_STD" CFG_CXX_FLAGS_CMAKE="$CFG_CXX_FLAGS_CMAKE $CFG_CXXFLAGS_STD" AC_MSG_CHECKING(whether $CXX supports C++14 with $CFG_CXXFLAGS_STD) _MY_CXX_CHECK_CXX_VER() AC_MSG_RESULT($_my_result) else # CFG_CXXFLAGS_STD is also propagated to include/verilated.mk.in # make sure we use the same std flag while compiling verilator and verilated design CFG_CXXFLAGS_STD="" fi if test "$_my_result" = "no" ; then AC_MSG_NOTICE([[]]) AC_MSG_ERROR([[the $CXX compiler appears to not support C++14. Verilator requires a C++14 or newer compiler.]]) fi AC_SUBST(CFG_CXXFLAGS_STD) # Compiler precompiled header options (assumes either gcc or clang++) AC_MSG_CHECKING([for $CXX precompile header include option]) if $CXX --help | grep include-pch >/dev/null 2>/dev/null ; then # clang CFG_CXXFLAGS_PCH_I=-include-pch CFG_GCH_IF_CLANG=.gch else # GCC CFG_CXXFLAGS_PCH_I=-include CFG_GCH_IF_CLANG= fi AC_MSG_RESULT($CFG_CXXFLAGS_PCH_I) AC_SUBST(CFG_CXXFLAGS_PCH_I) AC_SUBST(CFG_GCH_IF_CLANG) # Checks for library functions. AC_CHECK_MEMBER([struct stat.st_mtim.tv_nsec], [AC_DEFINE([HAVE_STAT_NSEC],[1],[Defined if struct stat has st_mtim.tv_nsec])], [], [#include ]) # HAVE_SYSTEMC # - If found the default search path has it, so support is always enabled. # - If not found or not system-wide, user can set SYSTEMC_INCLUDE. # AC_CHECK_HEADERS seems to not locate on Travis-CI but include does work. AC_MSG_CHECKING([whether SystemC is found (in system path)]) ACO_SAVE_LIBS="$LIBS" LIBS="$LIBS -lsystemc" AC_LINK_IFELSE( [AC_LANG_PROGRAM([[#include extern "C" int sc_main(int argc, char* argv[]) { return 0; } ]],[[sc_version()]])], [_my_result=yes AC_DEFINE([HAVE_SYSTEMC],[1],[Defined if have SystemC library])], [_my_result=no]) AC_MSG_RESULT($_my_result) LIBS="$ACO_SAVE_LIBS" AC_SUBST(HAVE_SYSTEMC) # Checks for system services # Other install directories pkgdatadir=${datadir}/verilator AC_SUBST(pkgdatadir) pkgconfigdir=${datadir}/pkgconfig AC_SUBST(pkgconfigdir) AC_OUTPUT AC_MSG_RESULT([]) AC_MSG_RESULT([Now type 'make' (or sometimes 'gmake') to build Verilator.]) AC_MSG_RESULT([]) verilator-5.020/nodist/0000755000175000017500000000000014544475344014725 5ustar carstencarstenverilator-5.020/nodist/clang_check_attributes0000755000175000017500000013675014544475344021356 0ustar carstencarsten#!/usr/bin/env python3 # pylint: disable=C0114,C0115,C0116,C0209,C0302,R0902,R0911,R0912,R0914,R0915,E1101 # # Copyright 2022-2024 by Wilson Snyder. Verilator is free software; you # can redistribute it and/or modify it under the terms of either the GNU Lesser # General Public License Version 3 or the Apache License 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Apache-2.0 import argparse import os import sys import shlex from typing import Callable, Iterable, Optional, Union, TYPE_CHECKING import dataclasses from dataclasses import dataclass import enum from enum import Enum import multiprocessing import re import tempfile import clang.cindex from clang.cindex import ( Index, TranslationUnitSaveError, TranslationUnitLoadError, CompilationDatabase, ) if not TYPE_CHECKING: from clang.cindex import CursorKind else: # Workaround for missing support for members defined out-of-class in Pylance: # https://github.com/microsoft/pylance-release/issues/2365#issuecomment-1035803067 class CursorKindMeta(type): def __getattr__(cls, name: str) -> clang.cindex.CursorKind: return getattr(clang.cindex.CursorKind, name) class CursorKind(clang.cindex.CursorKind, metaclass=CursorKindMeta): pass def fully_qualified_name(node): if node is None: return [] if node.kind == CursorKind.TRANSLATION_UNIT: return [] res = fully_qualified_name(node.semantic_parent) if res: return res + ([node.displayname] if node.displayname else []) return [node.displayname] if node.displayname else [] # Returns True, if `class_node` contains node # that matches `member` spelling def check_class_member_exists(class_node, member): for child in class_node.get_children(): if member.spelling == child.spelling: return True return False # Returns Base class (if found) of `class_node` # that is of type `base_type` def get_base_class(class_node, base_type): for child in class_node.get_children(): if child.kind is CursorKind.CXX_BASE_SPECIFIER: base_class = child.type if base_type.spelling == base_class.spelling: return base_class return None @dataclass class VlAnnotations: mt_start: bool = False mt_safe: bool = False stable_tree: bool = False mt_safe_postinit: bool = False mt_unsafe: bool = False mt_disabled: bool = False mt_unsafe_one: bool = False pure: bool = False guarded: bool = False requires: bool = False excludes: bool = False acquire: bool = False release: bool = False def is_mt_safe_context(self): return self.mt_safe and not (self.mt_unsafe or self.mt_unsafe_one) def is_pure_context(self): return self.pure def is_stabe_tree_context(self): # stable tree context requires calls to be marked # as MT_SAFE or MT_STABLE # Functions in MT_START needs to be MT_SAFE or MT_STABLE return self.stable_tree or self.mt_start def is_mt_unsafe_call(self): return self.mt_unsafe or self.mt_unsafe_one or self.mt_disabled def is_mt_safe_call(self): return (not self.is_mt_unsafe_call() and (self.mt_safe or self.mt_safe_postinit or self.pure or self.requires or self.excludes or self.acquire or self.release)) def is_pure_call(self): return self.pure def is_stabe_tree_call(self): return self.stable_tree def __or__(self, other: "VlAnnotations"): result = VlAnnotations() for key, value in dataclasses.asdict(self).items(): setattr(result, key, value | getattr(other, key)) return result def is_empty(self): for value in dataclasses.asdict(self).values(): if value: return False return True def __str__(self): result = [] for field, value in dataclasses.asdict(self).items(): if value: result.append(field) return ", ".join(result) @staticmethod def from_nodes_list(nodes: Iterable): result = VlAnnotations() for node in nodes: if node.kind == CursorKind.ANNOTATE_ATTR: if node.displayname == "MT_START": result.mt_start = True elif node.displayname == "MT_SAFE": result.mt_safe = True elif node.displayname == "MT_STABLE": result.stable_tree = True elif node.displayname == "MT_SAFE_POSTINIT": result.mt_safe_postinit = True elif node.displayname == "MT_UNSAFE": result.mt_unsafe = True elif node.displayname == "MT_UNSAFE_ONE": result.mt_unsafe_one = True elif node.displayname == "MT_DISABLED": result.mt_disabled = True elif node.displayname == "PURE": result.pure = True elif node.displayname in ["ACQUIRE", "ACQUIRE_SHARED"]: result.acquire = True elif node.displayname in ["RELEASE", "RELEASE_SHARED"]: result.release = True elif node.displayname == "REQUIRES": result.requires = True elif node.displayname in ["EXCLUDES", "MT_SAFE_EXCLUDES"]: result.excludes = True elif node.displayname == "GUARDED_BY": result.guarded = True # Attributes are always at the beginning elif not node.kind.is_attribute(): break return result class FunctionType(Enum): UNKNOWN = enum.auto() FUNCTION = enum.auto() METHOD = enum.auto() STATIC_METHOD = enum.auto() CONSTRUCTOR = enum.auto() @staticmethod def from_node(node: clang.cindex.Cursor): if node is None: return FunctionType.UNKNOWN if node.kind == CursorKind.FUNCTION_DECL: return FunctionType.FUNCTION if node.kind == CursorKind.CXX_METHOD and node.is_static_method(): return FunctionType.STATIC_METHOD if node.kind == CursorKind.CXX_METHOD: return FunctionType.METHOD if node.kind == CursorKind.CONSTRUCTOR: return FunctionType.CONSTRUCTOR return FunctionType.UNKNOWN @dataclass(eq=False) class FunctionInfo: name_parts: list[str] usr: str file: str line: int annotations: VlAnnotations ftype: FunctionType _hash: Optional[int] = dataclasses.field(default=None, init=False, repr=False) @property def name(self): return "::".join(self.name_parts) def __str__(self): return f"[{self.name}@{self.file}:{self.line}]" def __hash__(self): if not self._hash: self._hash = hash(f"{self.usr}:{self.file}:{self.line}") return self._hash def __eq__(self, other): return (self.usr == other.usr and self.file == other.file and self.line == other.line) def copy(self, /, **changes): return dataclasses.replace(self, **changes) @staticmethod def from_decl_file_line_and_refd_node(file: str, line: int, refd: clang.cindex.Cursor, annotations: VlAnnotations): file = os.path.abspath(file) refd = refd.canonical assert refd is not None name_parts = fully_qualified_name(refd) usr = refd.get_usr() ftype = FunctionType.from_node(refd) return FunctionInfo(name_parts, usr, file, line, annotations, ftype) @staticmethod def from_node(node: clang.cindex.Cursor, refd: Optional[clang.cindex.Cursor] = None, annotations: Optional[VlAnnotations] = None): file = os.path.abspath(node.location.file.name) line = node.location.line if annotations is None: annotations = VlAnnotations.from_nodes_list(node.get_children()) if refd is None: refd = node.referenced if refd is not None: refd = refd.canonical assert refd is not None name_parts = fully_qualified_name(refd) usr = refd.get_usr() ftype = FunctionType.from_node(refd) return FunctionInfo(name_parts, usr, file, line, annotations, ftype) class DiagnosticKind(Enum): ANNOTATIONS_DEF_DECL_MISMATCH = enum.auto() NON_PURE_CALL_IN_PURE_CTX = enum.auto() NON_MT_SAFE_CALL_IN_MT_SAFE_CTX = enum.auto() NON_STABLE_TREE_CALL_IN_STABLE_TREE_CTX = enum.auto() MISSING_MT_DISABLED_ANNOTATION = enum.auto() def __lt__(self, other): return self.value < other.value @dataclass class Diagnostic: target: FunctionInfo source: FunctionInfo source_ctx: FunctionInfo kind: DiagnosticKind _hash: Optional[int] = dataclasses.field(default=None, init=False, repr=False) def __hash__(self): if not self._hash: self._hash = hash( hash(self.target) ^ hash(self.source_ctx) ^ hash(self.kind)) return self._hash class CallAnnotationsValidator: def __init__(self, diagnostic_cb: Callable[[Diagnostic], None], is_ignored_top_level: Callable[[clang.cindex.Cursor], bool], is_ignored_def: Callable[ [clang.cindex.Cursor, clang.cindex.Cursor], bool], is_ignored_call: Callable[[clang.cindex.Cursor], bool]): self._diagnostic_cb = diagnostic_cb self._is_ignored_top_level = is_ignored_top_level self._is_ignored_call = is_ignored_call self._is_ignored_def = is_ignored_def self._index = Index.create() # Map key represents translation unit initial defines # (from command line and source's lines before any include) self._processed_headers: dict[str, set[str]] = {} self._external_decls: dict[str, set[tuple[str, int]]] = {} # Current context self._main_source_file: str = "" self._defines: dict[str, str] = {} self._call_location: Optional[FunctionInfo] = None self._caller: Optional[FunctionInfo] = None self._constructor_context: list[clang.cindex.Cursor] = [] self._level: int = 0 def is_mt_disabled_code_unit(self): return "VL_MT_DISABLED_CODE_UNIT" in self._defines def is_constructor_context(self): return len(self._constructor_context) > 0 # Parses all lines in a form: `#define KEY VALUE` located before any `#include` line. # The parsing is very simple, there is no support for line breaks, etc. @staticmethod def parse_initial_defines(source_file: str) -> dict[str, str]: defs: dict[str, str] = {} with open(source_file, "r", encoding="utf-8") as file: for line in file: line = line.strip() match = re.fullmatch( r"^#\s*(define\s+(\w+)(?:\s+(.*))?|include\s+.*)$", line) if match: if match.group(1).startswith("define"): key = match.group(2) value = match.groups("1")[2] defs[key] = value elif match.group(1).startswith("include"): break return defs @staticmethod def filter_out_unsupported_compiler_args( args: list[str]) -> tuple[list[str], dict[str, str]]: filtered_args = [] defines = {} args_iter = iter(args) try: while arg := next(args_iter): # Skip positional arguments (input file name). if not arg.startswith("-") and (arg.endswith(".cpp") or arg.endswith(".c") or arg.endswith(".h")): continue # Skipped options with separate value argument. if arg in ["-o", "-T", "-MT", "-MQ", "-MF" "-L"]: next(args_iter) continue # Skipped options without separate value argument. if arg == "-c" or arg.startswith("-W") or arg.startswith("-L"): continue # Preserved options with separate value argument. if arg in [ "-x" "-Xclang", "-I", "-isystem", "-iquote", "-include", "-include-pch" ]: filtered_args += [arg, next(args_iter)] continue kv_str = None d_or_u = None # Preserve define/undefine with separate value argument. if arg in ["-D", "-U"]: filtered_args.append(arg) d_or_u = arg[1] kv_str = next(args_iter) filtered_args.append(kv_str) # Preserve define/undefine without separate value argument. elif arg[0:2] in ["-D", "-U"]: filtered_args.append(arg) kv_str = arg[2:] d_or_u = arg[1] # Preserve everything else. else: filtered_args.append(arg) continue # Keep track of defines for class' internal purposes. key_value = kv_str.split("=", 1) key = key_value[0] val = "1" if len(key_value) == 1 else key_value[1] if d_or_u == "D": defines[key] = val elif d_or_u == "U" and key in defines: del defines[key] except StopIteration: pass return (filtered_args, defines) def compile_and_analyze_file(self, source_file: str, compiler_args: list[str], build_dir: Optional[str]): filename = os.path.abspath(source_file) initial_cwd = "." filtered_args, defines = self.filter_out_unsupported_compiler_args( compiler_args) defines.update(self.parse_initial_defines(source_file)) if build_dir: initial_cwd = os.getcwd() os.chdir(build_dir) try: translation_unit = self._index.parse(filename, filtered_args) except TranslationUnitLoadError: translation_unit = None errors = [] if translation_unit: for diag in translation_unit.diagnostics: if diag.severity >= clang.cindex.Diagnostic.Error: errors.append(str(diag)) if translation_unit and len(errors) == 0: self._defines = defines self._main_source_file = filename self.process_translation_unit(translation_unit) self._main_source_file = "" self._defines = {} else: print(f"%Error: parsing failed: {filename}", file=sys.stderr) for error in errors: print(f" {error}", file=sys.stderr) if build_dir: os.chdir(initial_cwd) def emit_diagnostic(self, target: Union[FunctionInfo, clang.cindex.Cursor], kind: DiagnosticKind): assert self._caller is not None assert self._call_location is not None source = self._caller source_ctx = self._call_location if isinstance(target, FunctionInfo): self._diagnostic_cb(Diagnostic(target, source, source_ctx, kind)) else: self._diagnostic_cb( Diagnostic(FunctionInfo.from_node(target), source, source_ctx, kind)) def iterate_children(self, children: Iterable[clang.cindex.Cursor], handler: Callable[[clang.cindex.Cursor], None]): if children: self._level += 1 for child in children: handler(child) self._level -= 1 @staticmethod def get_referenced_node_info( node: clang.cindex.Cursor ) -> tuple[bool, Optional[clang.cindex.Cursor], VlAnnotations, Iterable[clang.cindex.Cursor]]: if not node.spelling and not node.displayname: return (False, None, VlAnnotations(), []) refd = node.referenced if refd is None: raise ValueError("The node does not specify referenced node.") refd = refd.canonical children = list(refd.get_children()) annotations = VlAnnotations.from_nodes_list(children) return (True, refd, annotations, children) def check_mt_safe_call(self, node: clang.cindex.Cursor, refd: clang.cindex.Cursor, annotations: VlAnnotations): is_mt_safe = False if annotations.is_mt_safe_call(): is_mt_safe = True elif not annotations.is_mt_unsafe_call(): # Check whether the object the method is called on is mt-safe def find_object_ref(node): try: node = next(node.get_children()) if node.kind == CursorKind.DECL_REF_EXPR: # Operator on an argument or local object return node if node.kind != CursorKind.MEMBER_REF_EXPR: return None if node.referenced and node.referenced.kind == CursorKind.FIELD_DECL: # Operator on a member object return node node = next(node.get_children()) if node.kind == CursorKind.UNEXPOSED_EXPR: node = next(node.get_children()) return node except StopIteration: return None refn = find_object_ref(node) if self.is_constructor_context() and not refn: # we are in constructor and no object reference means # we are calling local method. It is MT safe # only if this method is also only calling local methods or # MT-safe methods self.iterate_children(refd.get_children(), self.dispatch_node_inside_definition) is_mt_safe = True # class/struct member elif refn and refn.kind == CursorKind.MEMBER_REF_EXPR and refn.referenced: refn = refn.referenced refna = VlAnnotations.from_nodes_list(refn.get_children()) if refna.guarded: is_mt_safe = True if self.is_constructor_context() and refn.semantic_parent: # we are in constructor, so calling local members is MT_SAFE, # make sure object that we are calling is local to the constructor constructor_class = self._constructor_context[ -1].semantic_parent if refn.semantic_parent.spelling == constructor_class.spelling: if check_class_member_exists(constructor_class, refn): is_mt_safe = True else: # check if this class inherits from some base class base_class = get_base_class(constructor_class, refn.semantic_parent) if base_class: if check_class_member_exists( base_class.get_declaration(), refn): is_mt_safe = True # variable elif refn and refn.kind == CursorKind.DECL_REF_EXPR and refn.referenced: if refn.get_definition(): if refn.referenced.semantic_parent: if refn.referenced.semantic_parent.kind in [ CursorKind.FUNCTION_DECL, CursorKind.CXX_METHOD ]: # This is a local or an argument. # Calling methods on local pointers or references is MT-safe, # but on argument pointers or references is not. if "*" not in refn.type.spelling and "&" not in refn.type.spelling: is_mt_safe = True # local variable if refn.referenced.kind == CursorKind.VAR_DECL: is_mt_safe = True else: # Global variable in different translation unit, unsafe pass elif refn and refn.kind == CursorKind.CALL_EXPR: if self.is_constructor_context(): # call to local function from constructor context # safe if this function also calling local methods or # MT-safe methods self.dispatch_call_node(refn) is_mt_safe = True return is_mt_safe # Call handling def process_method_call(self, node: clang.cindex.Cursor, refd: clang.cindex.Cursor, annotations: VlAnnotations): assert self._call_location ctx = self._call_location.annotations # MT-safe context if ctx.is_mt_safe_context(): if not self.check_mt_safe_call(node, refd, annotations): self.emit_diagnostic( FunctionInfo.from_node(refd, refd, annotations), DiagnosticKind.NON_MT_SAFE_CALL_IN_MT_SAFE_CTX) # stable tree context if ctx.is_stabe_tree_context(): if annotations.is_mt_unsafe_call() or not ( annotations.is_stabe_tree_call() or annotations.is_pure_call() or self.check_mt_safe_call(node, refd, annotations)): self.emit_diagnostic( FunctionInfo.from_node(refd, refd, annotations), DiagnosticKind.NON_STABLE_TREE_CALL_IN_STABLE_TREE_CTX) # pure context if ctx.is_pure_context(): if not annotations.is_pure_call(): self.emit_diagnostic( FunctionInfo.from_node(refd, refd, annotations), DiagnosticKind.NON_PURE_CALL_IN_PURE_CTX) def process_function_call(self, refd: clang.cindex.Cursor, annotations: VlAnnotations): assert self._call_location ctx = self._call_location.annotations # MT-safe context if ctx.is_mt_safe_context(): if not annotations.is_mt_safe_call(): self.emit_diagnostic( FunctionInfo.from_node(refd, refd, annotations), DiagnosticKind.NON_MT_SAFE_CALL_IN_MT_SAFE_CTX) # stable tree context if ctx.is_stabe_tree_context(): if annotations.is_mt_unsafe_call() or not ( annotations.is_pure_call() or annotations.is_mt_safe_call() or annotations.is_stabe_tree_call()): self.emit_diagnostic( FunctionInfo.from_node(refd, refd, annotations), DiagnosticKind.NON_STABLE_TREE_CALL_IN_STABLE_TREE_CTX) # pure context if ctx.is_pure_context(): if not annotations.is_pure_call(): self.emit_diagnostic( FunctionInfo.from_node(refd, refd, annotations), DiagnosticKind.NON_PURE_CALL_IN_PURE_CTX) def process_constructor_call(self, refd: clang.cindex.Cursor, annotations: VlAnnotations): assert self._call_location ctx = self._call_location.annotations # Constructors are OK in MT-safe context # only if they call local methods or MT-safe functions. if ctx.is_mt_safe_context() or self.is_constructor_context(): self._constructor_context.append(refd) self.iterate_children(refd.get_children(), self.dispatch_node_inside_definition) self._constructor_context.pop() # stable tree context if ctx.is_stabe_tree_context(): self._constructor_context.append(refd) self.iterate_children(refd.get_children(), self.dispatch_node_inside_definition) self._constructor_context.pop() # pure context if ctx.is_pure_context(): if not annotations.is_pure_call( ) and not refd.is_default_constructor(): self.emit_diagnostic( FunctionInfo.from_node(refd, refd, annotations), DiagnosticKind.NON_PURE_CALL_IN_PURE_CTX) def dispatch_call_node(self, node: clang.cindex.Cursor): [supported, refd, annotations, _] = self.get_referenced_node_info(node) if not supported: self.iterate_children(node.get_children(), self.dispatch_node_inside_definition) return True assert refd is not None if self._is_ignored_call(refd): return True if "std::function" in refd.displayname: # Workaroud for missing support for lambda annotations # in c++11. # If function takes std::function as argument, # assume, that this std::function will be called inside it. self.process_function_definition(node) return False assert self._call_location is not None node_file = os.path.abspath(node.location.file.name) self._call_location = self._call_location.copy(file=node_file, line=node.location.line) # Standalone functions and static class methods if (refd.kind == CursorKind.FUNCTION_DECL or refd.kind == CursorKind.CXX_METHOD and refd.is_static_method()): self.process_function_call(refd, annotations) # Function pointer elif refd.kind in [ CursorKind.VAR_DECL, CursorKind.FIELD_DECL, CursorKind.PARM_DECL ]: self.process_function_call(refd, annotations) # Non-static class methods elif refd.kind == CursorKind.CXX_METHOD: self.process_method_call(node, refd, annotations) # Conversion method (e.g. `operator int()`) elif refd.kind == CursorKind.CONVERSION_FUNCTION: self.process_method_call(node, refd, annotations) # Constructors elif refd.kind == CursorKind.CONSTRUCTOR: self.process_constructor_call(refd, annotations) else: # Ignore other callables, but report them print("Unknown callable: " f"{refd.location.file.name}:{refd.location.line}: " f"{refd.displayname} {refd.kind}\n" f" from: {node.location.file.name}:{node.location.line}") return True def process_function_declaration(self, node: clang.cindex.Cursor): # Ignore declarations in main .cpp file if node.location.file.name != self._main_source_file: children = list(node.get_children()) annotations = VlAnnotations.from_nodes_list(children) if not annotations.mt_disabled: self._external_decls.setdefault(node.get_usr(), set()).add( (str(node.location.file.name), int(node.location.line))) return self.iterate_children(children, self.dispatch_node) return self.iterate_children(node.get_children(), self.dispatch_node) # Definition handling def dispatch_node_inside_definition(self, node: clang.cindex.Cursor): if node.kind == CursorKind.CALL_EXPR: if self.dispatch_call_node(node) is False: return None elif node.is_definition() and node.kind in [ CursorKind.CXX_METHOD, CursorKind.FUNCTION_DECL, CursorKind.CONSTRUCTOR, CursorKind.CONVERSION_FUNCTION ]: self.process_function_definition(node) return None return self.iterate_children(node.get_children(), self.dispatch_node_inside_definition) def process_function_definition(self, node: clang.cindex.Cursor): [supported, refd, annotations, _] = self.get_referenced_node_info(node) if refd and self._is_ignored_def(node, refd): return None node_children = list(node.get_children()) if not supported: return self.iterate_children(node_children, self.dispatch_node) assert refd is not None def_annotations = VlAnnotations.from_nodes_list(node_children) # Implicitly mark definitions in VL_MT_DISABLED_CODE_UNIT .cpp files as # VL_MT_DISABLED. Existence of the annotation on declarations in .h # files is verified below. # Also sets VL_REQUIRES, as this annotation is added together with # explicit VL_MT_DISABLED. if self.is_mt_disabled_code_unit(): if node.location.file.name == self._main_source_file: annotations.mt_disabled = True annotations.requires = True if refd.location.file.name == self._main_source_file: def_annotations.mt_disabled = True def_annotations.requires = True if not (def_annotations.is_empty() or def_annotations == annotations): # Use definition's annotations for the diagnostic # source (i.e. the definition) self._caller = FunctionInfo.from_node(node, refd, def_annotations) self._call_location = self._caller self.emit_diagnostic( FunctionInfo.from_node(refd, refd, annotations), DiagnosticKind.ANNOTATIONS_DEF_DECL_MISMATCH) # Use concatenation of definition and declaration annotations # for calls validation. self._caller = FunctionInfo.from_node(node, refd, def_annotations | annotations) prev_call_location = self._call_location self._call_location = self._caller if self.is_mt_disabled_code_unit(): # Report declarations of this functions that don't have MT_DISABLED annotation # and are located in headers. if node.location.file.name == self._main_source_file: usr = node.get_usr() declarations = self._external_decls.get(usr, set()) for file, line in declarations: self.emit_diagnostic( FunctionInfo.from_decl_file_line_and_refd_node( file, line, refd, def_annotations), DiagnosticKind.MISSING_MT_DISABLED_ANNOTATION) if declarations: del self._external_decls[usr] self.iterate_children(node_children, self.dispatch_node_inside_definition) self._call_location = prev_call_location self._caller = prev_call_location return None # Nodes not located inside definition def dispatch_node(self, node: clang.cindex.Cursor): if node.kind in [ CursorKind.CXX_METHOD, CursorKind.FUNCTION_DECL, CursorKind.CONSTRUCTOR, CursorKind.CONVERSION_FUNCTION ]: if node.is_definition(): return self.process_function_definition(node) # else: return self.process_function_declaration(node) return self.iterate_children(node.get_children(), self.dispatch_node) def process_translation_unit( self, translation_unit: clang.cindex.TranslationUnit): self._level += 1 kv_defines = sorted([f"{k}={v}" for k, v in self._defines.items()]) concat_defines = '\n'.join(kv_defines) # List of headers already processed in a TU with specified set of defines. tu_processed_headers = self._processed_headers.setdefault( concat_defines, set()) for child in translation_unit.cursor.get_children(): if self._is_ignored_top_level(child): continue if tu_processed_headers: filename = os.path.abspath(child.location.file.name) if filename in tu_processed_headers: continue self.dispatch_node(child) self._level -= 1 tu_processed_headers.update([ os.path.abspath(str(hdr.source)) for hdr in translation_unit.get_includes() ]) @dataclass class CompileCommand: refid: int filename: str args: list[str] directory: str = dataclasses.field(default_factory=os.getcwd) def get_filter_funcs(verilator_root: str): verilator_root = os.path.abspath(verilator_root) + "/" def is_ignored_top_level(node: clang.cindex.Cursor) -> bool: # Anything defined in a header outside Verilator root if not node.location.file: return True filename = os.path.abspath(node.location.file.name) return not filename.startswith(verilator_root) def is_ignored_def(node: clang.cindex.Cursor, refd: clang.cindex.Cursor) -> bool: # __* if str(refd.spelling).startswith("__"): return True # Anything defined in a header outside Verilator root if not node.location.file: return True filename = os.path.abspath(node.location.file.name) if not filename.startswith(verilator_root): return True return False def is_ignored_call(refd: clang.cindex.Cursor) -> bool: # __* if str(refd.spelling).startswith("__"): return True # std::* fqn = fully_qualified_name(refd) if fqn and fqn[0] == "std": return True # Anything declared in a header outside Verilator root if not refd.location.file: return True filename = os.path.abspath(refd.location.file.name) if not filename.startswith(verilator_root): return True return False return (is_ignored_top_level, is_ignored_def, is_ignored_call) def precompile_header(compile_command: CompileCommand, tmp_dir: str) -> str: initial_cwd = os.getcwd() errors = [] try: os.chdir(compile_command.directory) index = Index.create() translation_unit = index.parse(compile_command.filename, compile_command.args) for diag in translation_unit.diagnostics: if diag.severity >= clang.cindex.Diagnostic.Error: errors.append(str(diag)) if len(errors) == 0: pch_file = os.path.join( tmp_dir, f"{compile_command.refid:02}_{os.path.basename(compile_command.filename)}.pch" ) translation_unit.save(pch_file) if pch_file: return pch_file except (TranslationUnitSaveError, TranslationUnitLoadError, OSError) as exception: print(f"%Warning: {exception}", file=sys.stderr) finally: os.chdir(initial_cwd) print( f"%Warning: Precompilation failed, skipping: {compile_command.filename}", file=sys.stderr) for error in errors: print(f" {error}", file=sys.stderr) return "" # Compile and analyze inputs in a single process. def run_analysis(ccl: Iterable[CompileCommand], pccl: Iterable[CompileCommand], diagnostic_cb: Callable[[Diagnostic], None], verilator_root: str): (is_ignored_top_level, is_ignored_def, is_ignored_call) = get_filter_funcs(verilator_root) prefix = "verilator_clang_check_attributes_" with tempfile.TemporaryDirectory(prefix=prefix) as tmp_dir: extra_args = [] for pcc in pccl: pch_file = precompile_header(pcc, tmp_dir) if pch_file: extra_args += ["-include-pch", pch_file] cav = CallAnnotationsValidator(diagnostic_cb, is_ignored_top_level, is_ignored_def, is_ignored_call) for compile_command in ccl: cav.compile_and_analyze_file(compile_command.filename, extra_args + compile_command.args, compile_command.directory) @dataclass class ParallelAnalysisProcess: cav: Optional[CallAnnotationsValidator] = None diags: set[Diagnostic] = dataclasses.field(default_factory=set) tmp_dir: str = "" @staticmethod def init_data(verilator_root: str, tmp_dir: str): (is_ignored_top_level, is_ignored_def, is_ignored_call) = get_filter_funcs(verilator_root) ParallelAnalysisProcess.cav = CallAnnotationsValidator( ParallelAnalysisProcess._diagnostic_handler, is_ignored_top_level, is_ignored_def, is_ignored_call) ParallelAnalysisProcess.tmp_dir = tmp_dir @staticmethod def _diagnostic_handler(diag: Diagnostic): ParallelAnalysisProcess.diags.add(diag) @staticmethod def analyze_cpp_file(compile_command: CompileCommand) -> set[Diagnostic]: ParallelAnalysisProcess.diags = set() assert ParallelAnalysisProcess.cav is not None ParallelAnalysisProcess.cav.compile_and_analyze_file( compile_command.filename, compile_command.args, compile_command.directory) return ParallelAnalysisProcess.diags @staticmethod def precompile_header(compile_command: CompileCommand) -> str: return precompile_header(compile_command, ParallelAnalysisProcess.tmp_dir) # Compile and analyze inputs in multiple processes. def run_parallel_analysis(ccl: Iterable[CompileCommand], pccl: Iterable[CompileCommand], diagnostic_cb: Callable[[Diagnostic], None], jobs_count: int, verilator_root: str): prefix = "verilator_clang_check_attributes_" with tempfile.TemporaryDirectory(prefix=prefix) as tmp_dir: with multiprocessing.Pool( processes=jobs_count, initializer=ParallelAnalysisProcess.init_data, initargs=[verilator_root, tmp_dir]) as pool: extra_args = [] for pch_file in pool.imap_unordered( ParallelAnalysisProcess.precompile_header, pccl): if pch_file: extra_args += ["-include-pch", pch_file] if extra_args: for compile_command in ccl: compile_command.args = compile_command.args + extra_args for diags in pool.imap_unordered( ParallelAnalysisProcess.analyze_cpp_file, ccl, 1): for diag in diags: diagnostic_cb(diag) class TopDownSummaryPrinter(): @dataclass class FunctionCallees: info: FunctionInfo calees: set[FunctionInfo] mismatch: Optional[FunctionInfo] = None reason: Optional[DiagnosticKind] = None def __init__(self): self._is_first_group = True self._funcs: dict[str, TopDownSummaryPrinter.FunctionCallees] = {} self._unsafe_in_safe: set[str] = set() def begin_group(self, label): if not self._is_first_group: print() print(f"%Error: {label}") self._is_first_group = False def handle_diagnostic(self, diag: Diagnostic): usr = diag.source.usr func = self._funcs.get(usr, None) if func is None: func = TopDownSummaryPrinter.FunctionCallees(diag.source, set()) self._funcs[usr] = func func.reason = diag.kind if diag.kind == DiagnosticKind.ANNOTATIONS_DEF_DECL_MISMATCH: func.mismatch = diag.target else: func.calees.add(diag.target) self._unsafe_in_safe.add(diag.target.usr) def print_summary(self, root_dir: str): row_groups: dict[str, list[list[str]]] = {} column_widths = [0, 0] for func in sorted(self._funcs.values(), key=lambda func: (func.info.file, func.info.line, func.info.usr)): func_info = func.info relfile = os.path.relpath(func_info.file, root_dir) row_group = [] name = f"\"{func_info.name}\" " if func.reason == DiagnosticKind.ANNOTATIONS_DEF_DECL_MISMATCH: name += "declaration does not match definition" elif func.reason == DiagnosticKind.NON_MT_SAFE_CALL_IN_MT_SAFE_CTX: name += "is mtsafe but calls non-mtsafe function(s)" elif func.reason == DiagnosticKind.NON_PURE_CALL_IN_PURE_CTX: name += "is pure but calls non-pure function(s)" elif func.reason == DiagnosticKind.NON_STABLE_TREE_CALL_IN_STABLE_TREE_CTX: name += "is stable_tree but calls non-stable_tree or non-mtsafe" elif func.reason == DiagnosticKind.MISSING_MT_DISABLED_ANNOTATION: name += ("defined in a file marked as " + "VL_MT_DISABLED_CODE_UNIT has declaration(s) " + "without VL_MT_DISABLED annotation") else: name += "for unknown reason (please add description)" if func.mismatch: mrelfile = os.path.relpath(func.mismatch.file, root_dir) row_group.append([ f"{mrelfile}:{func.mismatch.line}:", f"[{func.mismatch.annotations}]", func.mismatch.name + " [declaration]" ]) row_group.append([ f"{relfile}:{func_info.line}:", f"[{func_info.annotations}]", func_info.name ]) for callee in sorted(func.calees, key=lambda func: (func.file, func.line, func.usr)): crelfile = os.path.relpath(callee.file, root_dir) row_group.append([ f"{crelfile}:{callee.line}:", f"[{callee.annotations}]", " " + callee.name ]) row_groups[name] = row_group for row in row_group: for row_id, value in enumerate(row[0:-1]): column_widths[row_id] = max(column_widths[row_id], len(value)) for label, rows in sorted(row_groups.items(), key=lambda kv: kv[0]): self.begin_group(label) for row in rows: print(f"{row[0]:<{column_widths[0]}} " f"{row[1]:<{column_widths[1]}} " f"{row[2]}") print( f"Number of functions reported unsafe: {len(self._unsafe_in_safe)}" ) def main(): default_verilator_root = os.path.abspath( os.path.join(os.path.dirname(__file__), "..")) parser = argparse.ArgumentParser( allow_abbrev=False, formatter_class=argparse.RawDescriptionHelpFormatter, description="""Check function annotations for correctness""", epilog= """Copyright 2022-2024 by Wilson Snyder. Verilator is free software; you can redistribute it and/or modify it under the terms of either the GNU Lesser General Public License Version 3 or the Apache License 2.0. SPDX-License-Identifier: LGPL-3.0-only OR Apache-2.0""") parser.add_argument("--verilator-root", type=str, default=default_verilator_root, help="Path to Verilator sources root directory.") parser.add_argument("--jobs", "-j", type=int, default=0, help="Number of parallel jobs to use.") parser.add_argument( "--compile-commands-dir", type=str, default=None, help="Path to directory containing compile_commands.json.") parser.add_argument("--cxxflags", type=str, default=None, help="Extra flags passed to clang++.") parser.add_argument( "--compilation-root", type=str, default=os.getcwd(), help="Directory used as CWD when compiling source files.") parser.add_argument( "-c", "--precompile", action="append", help="Header file to be precompiled and cached at the start.") parser.add_argument("file", type=str, nargs="+", help="Source file to analyze.") cmdline = parser.parse_args() if cmdline.jobs == 0: cmdline.jobs = max(1, len(os.sched_getaffinity(0))) if not cmdline.compilation_root: cmdline.compilation_root = cmdline.verilator_root verilator_root = os.path.abspath(cmdline.verilator_root) default_compilation_root = os.path.abspath(cmdline.compilation_root) compdb: Optional[CompilationDatabase] = None if cmdline.compile_commands_dir: compdb = CompilationDatabase.fromDirectory( cmdline.compile_commands_dir) if cmdline.cxxflags is not None: common_cxxflags = shlex.split(cmdline.cxxflags) else: common_cxxflags = [] precompile_commands_list = [] if cmdline.precompile: hdr_cxxflags = ['-xc++-header'] + common_cxxflags for refid, file in enumerate(cmdline.precompile): filename = os.path.abspath(file) compile_command = CompileCommand(refid, filename, hdr_cxxflags, default_compilation_root) precompile_commands_list.append(compile_command) compile_commands_list = [] for refid, file in enumerate(cmdline.file): filename = os.path.abspath(file) root = default_compilation_root cxxflags = [] if compdb: entry = compdb.getCompileCommands(filename) entry_list = list(entry) # Compilation database can contain multiple entries for single file, # e.g. when it has been updated by appending new entries. # Use last entry for the file, if it exists, as it is the newest one. if len(entry_list) > 0: last_entry = entry_list[-1] root = last_entry.directory entry_args = list(last_entry.arguments) # First argument in compile_commands.json arguments list is # compiler executable name/path. CIndex (libclang) always # implicitly prepends executable name, so it shouldn't be passed # here. cxxflags = common_cxxflags + entry_args[1:] else: cxxflags = common_cxxflags[:] compile_command = CompileCommand(refid, filename, cxxflags, root) compile_commands_list.append(compile_command) summary_printer = TopDownSummaryPrinter() if cmdline.jobs == 1: run_analysis(compile_commands_list, precompile_commands_list, summary_printer.handle_diagnostic, verilator_root) else: run_parallel_analysis(compile_commands_list, precompile_commands_list, summary_printer.handle_diagnostic, cmdline.jobs, verilator_root) summary_printer.print_summary(verilator_root) if __name__ == '__main__': main() verilator-5.020/nodist/code_coverage.dat0000644000175000017500000000415414544475344020210 0ustar carstencarsten# -*- Python -*- # DESCRIPTION: Verilator: Internal C++ code lcov control file # # Copyright 2019-2024 by Wilson Snyder. This program is free software; you # can redistribute it and/or modify it under the terms of either the GNU # Lesser General Public License Version 3 or the Perl Artistic License # Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 source_globs("src/*.cpp") source_globs("src/*.h") source_globs("src/*.l") source_globs("src/*.y") source_globs("src/obj_dbg/*.h") source_globs("src/obj_dbg/*.cpp") source_globs("include/*.c") source_globs("include/*.cpp") source_globs("include/*.h") source_globs("include/*/*.h") source_globs("include/*/*.cpp") source_globs("include/*/*.c") # Note *'s are removed when using fastcov remove_source("/usr/*") remove_source("*/include/sysc/*") remove_source("*/V3Lexer_pregen.yy.cpp") remove_source("*/V3PreLex_pregen.yy.cpp") remove_source("*/verilog.c") remove_source("*include/gtkwave/*") # Something wrong in generation, unfortunately as would like this #genhtml: ERROR: cannot read /svaha/wsnyder/SandBox/homecvs/v4/verilator/src/obj_dbg/verilog.y #remove_source("*/src/obj_dbg/verilog.y") remove_source("*test_regress/*") remove_source("*examples/*") # Remove collected coverage on each little test main file # Would just be removed with remove_source in later step remove_gcda_regexp(r'test_regress/.*/(Vt_|Vtop_).*\.gcda') # Exclude line entirely, also excludes from function and branch coverage exclude_line_regexp(r'\bv3fatalSrc\b') exclude_line_regexp(r'\bfatalSrc\b') exclude_line_regexp(r'\bVL_UNCOVERABLE\b') exclude_line_regexp(r'\bVL_UNREACHABLE\b') exclude_line_regexp(r'\bVL_FATAL') exclude_line_regexp(r'\bUASSERT') exclude_line_regexp(r'\bNUM_ASSERT') exclude_line_regexp(r'\bERROR_RSVD_WORD') exclude_line_regexp(r'\bV3ERROR_NA') exclude_line_regexp(r'\bUINFO\b') exclude_line_regexp(r'\bVL_DEFINE_DEBUG_FUNCTIONS\b') # Exclude for branch coverage only exclude_branch_regexp(r'\bdebug\(\)') exclude_branch_regexp(r'\bassert\(') exclude_branch_regexp(r'\bBROKEN_BASE_RTN\(') exclude_branch_regexp(r'\bBROKEN_RTN\(') exclude_branch_regexp(r'\bSELF_CHECK') True verilator-5.020/nodist/dot_importer0000755000175000017500000000731014544475344017363 0ustar carstencarsten#!/usr/bin/env python3 # pylint: disable=C0103,C0114,C0115,C0116,C0209,C0301 ###################################################################### import argparse import re ###################################################################### Header = [] Vertexes = [] Edges = [] ####################################################################### def dotread(filename): with open(filename, "r", encoding="utf8") as fh: header = True vnum = 0 vertex_re = re.compile(r'^\t([a-zA-Z0-9_]+)\t(.*)$') edge_re = re.compile( r'^\t([a-zA-Z0-9_]+)\s+->\s+([a-zA-Z0-9_]+)\s*(.*)$') for line in fh: vertex_match = re.search(vertex_re, line) edge_match = re.search(edge_re, line) if vertex_match: if vertex_match.group(1) != 'nTITLE': header = False Vertexes.append({ 'num': vnum, 'line': line, 'name': vertex_match.group(1) }) vnum += 1 elif edge_match: fromv = edge_match.group(1) tov = edge_match.group(2) w = re.match(r'weight=(\d+)', line) weight = w.group(1) if w else 1 w = re.match(r'style=(\S+)', line) cutable = w.group(1) if w else None edge = { 'num': vnum, 'line': line, 'weight': weight, 'cutable': cutable, 'from': fromv, 'to': tov } vnum += 1 Edges.append(edge) elif header: Header.append(line) print("IGNORE: " + line) ####################################################################### def cwrite(filename): with open(filename, "w", encoding="utf8") as fh: fh.write("void V3GraphTestImport::dotImport() {\n") fh.write(" auto* gp = &m_graph;\n") for ver in sorted(Vertexes, key=lambda ver: ver['num']): fh.write( " auto* %s = new V3GraphTestVertex{gp, \"%s\"}; if (%s) {}\n" % (ver['name'], ver['name'], ver['name'])) fh.write("\n") for edge in Edges: fh.write(" new V3GraphEdge{gp, %s, %s, %s, %s};\n" % (edge['from'], edge['to'], edge['weight'], "true" if edge['cutable'] else "false")) fh.write("}\n") ###################################################################### # main parser = argparse.ArgumentParser( allow_abbrev=False, formatter_class=argparse.RawDescriptionHelpFormatter, description= """dot_importer takes a graphvis .dot file and converts into .cpp file. This x.cpp file is then manually included in V3GraphTest.cpp to verify various xsub-algorithms.""", epilog= """Copyright 2005-2024 by Wilson Snyder. This program is free software; you can redistribute it and/or modify it under the terms of either the GNU Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0""") parser.add_argument('--debug', action='store_const', const=9, help='enable debug') parser.add_argument('filename', help='input .dot filename to process') Args = parser.parse_args() dotread(Args.filename) cwrite("graph_export.cpp") ###################################################################### # Local Variables: # compile-command: "./dot_importer ../test_regress/obj_vlt/t_EXAMPLE/*orderg_o*.dot && cat graph_export.cpp" # End: verilator-5.020/nodist/fastcov.py0000755000175000017500000007773014544475344016765 0ustar carstencarsten#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # Copyright 2018-present, Bryan Gillespie """ Author: Bryan Gillespie https://github.com/RPGillespie6/fastcov A massively parallel gcov wrapper for generating intermediate coverage formats fast The goal of fastcov is to generate code coverage intermediate formats as fast as possible, even for large projects with hundreds of gcda objects. The intermediate formats may then be consumed by a report generator such as lcov's genhtml, or a dedicated frontend such as coveralls. Sample Usage: $ cd build_dir $ ./fastcov.py --zerocounters $ $ ./fastcov.py --exclude /usr/include test/ --lcov -o report.info $ genhtml -o code_coverage report.info """ import re import os import sys import glob import json import time import logging import argparse import threading import subprocess import multiprocessing FASTCOV_VERSION = (1,7) MINIMUM_PYTHON = (3,5) MINIMUM_GCOV = (9,0,0) # Interesting metrics START_TIME = time.monotonic() GCOVS_TOTAL = 0 GCOVS_SKIPPED = 0 # For when things go wrong... # Start error codes at 3 because 1-2 are special # See https://stackoverflow.com/a/1535733/2516916 EXIT_CODE = 0 EXIT_CODES = { "gcov_version": 3, "python_version": 4, "unsupported_coverage_format": 5, "excl_not_found": 6, } # Disable all logging in case developers are using this as a module logging.disable(level=logging.CRITICAL) class FastcovFormatter(logging.Formatter): def format(self, record): record.levelname = record.levelname.lower() log_message = super(FastcovFormatter, self).format(record) return "[{:.3f}s] {}".format(stopwatch(), log_message) def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def setExitCode(key): global EXIT_CODE EXIT_CODE = EXIT_CODES[key] def incrementCounters(total, skipped): global GCOVS_TOTAL global GCOVS_SKIPPED GCOVS_TOTAL += total GCOVS_SKIPPED += skipped def stopwatch(): """Return number of seconds since last time this was called.""" global START_TIME end_time = time.monotonic() delta = end_time - START_TIME START_TIME = end_time return delta def parseVersionFromLine(version_str): """Given a string containing a dotted integer version, parse out integers and return as tuple.""" version = re.search(r'(\d+\.\d+\.\d+)', version_str) if not version: return (0,0,0) return tuple(map(int, version.group(1).split("."))) def getGcovVersion(gcov): p = subprocess.Popen([gcov, "-v"], stdout=subprocess.PIPE) output = p.communicate()[0].decode('UTF-8') p.wait() return parseVersionFromLine(output.split("\n")[0]) def removeFiles(files): for file in files: os.remove(file) def getFilteredCoverageFiles(coverage_files, exclude): def excludeGcda(gcda): for ex in exclude: if ex in gcda: logging.debug("Omitting %s due to '--exclude-gcda %s'", gcda, ex) return False return True return list(filter(excludeGcda, coverage_files)) def findCoverageFiles(cwd, coverage_files, use_gcno): coverage_type = "user provided" if not coverage_files: coverage_type = "gcno" if use_gcno else "gcda" coverage_files = glob.glob(os.path.join(os.path.abspath(cwd), "**/*." + coverage_type), recursive=True) logging.info("Found {} coverage files ({})".format(len(coverage_files), coverage_type)) logging.debug("Coverage files found:\n %s", "\n ".join(coverage_files)) return coverage_files def gcovWorker(data_q, metrics_q, args, chunk, gcov_filter_options): base_report = {"sources": {}} gcovs_total = 0 gcovs_skipped = 0 gcov_args = "-it" if args.branchcoverage or args.xbranchcoverage: gcov_args += "b" p = subprocess.Popen([args.gcov, gcov_args] + chunk, cwd=args.cdirectory, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) for line in iter(p.stdout.readline, b''): intermediate_json = json.loads(line.decode(sys.stdout.encoding)) intermediate_json_files = processGcovs(args.cdirectory, intermediate_json["files"], gcov_filter_options) for f in intermediate_json_files: distillSource(f, base_report["sources"], args.test_name, args.xbranchcoverage) gcovs_total += len(intermediate_json["files"]) gcovs_skipped += len(intermediate_json["files"]) - len(intermediate_json_files) p.wait() data_q.put(base_report) metrics_q.put((gcovs_total, gcovs_skipped)) def processGcdas(args, coverage_files, gcov_filter_options): chunk_size = max(args.minimum_chunk, int(len(coverage_files) / args.jobs) + 1) processes = [] data_q = multiprocessing.Queue() metrics_q = multiprocessing.Queue() for chunk in chunks(coverage_files, chunk_size): p = multiprocessing.Process(target=gcovWorker, args=(data_q, metrics_q, args, chunk, gcov_filter_options)) processes.append(p) p.start() logging.info("Spawned {} gcov processes, each processing at most {} coverage files".format(len(processes), chunk_size)) fastcov_jsons = [] for p in processes: fastcov_jsons.append(data_q.get()) incrementCounters(*metrics_q.get()) for p in processes: p.join() base_fastcov = fastcov_jsons.pop() for fj in fastcov_jsons: combineReports(base_fastcov, fj) return base_fastcov def shouldFilterSource(source, gcov_filter_options): """Returns true if the provided source file should be filtered due to CLI options, otherwise returns false.""" # If explicit sources were passed, check for match if gcov_filter_options["sources"]: if source not in gcov_filter_options["sources"]: logging.debug("Filtering coverage for '%s' due to option '--source-files'", source) return True # Check exclude filter for ex in gcov_filter_options["exclude"]: if ex in source: logging.debug("Filtering coverage for '%s' due to option '--exclude %s'", source, ex) return True # Check include filter if gcov_filter_options["include"]: included = False for inc in gcov_filter_options["include"]: if inc in source: included = True break if not included: logging.debug("Filtering coverage for '%s' due to option '--include %s'", source, " ".join(gcov_filter_options["include"])) return True return False def filterFastcov(fastcov_json, args): logging.info("Performing filtering operations (if applicable)") gcov_filter_options = getGcovFilterOptions(args) for source in list(fastcov_json["sources"].keys()): if shouldFilterSource(source, gcov_filter_options): del fastcov_json["sources"][source] def processGcov(cwd, gcov, files, gcov_filter_options): # Add absolute path gcov["file_abs"] = os.path.abspath(os.path.join(cwd, gcov["file"])) if shouldFilterSource(gcov["file_abs"], gcov_filter_options): return files.append(gcov) logging.debug("Accepted coverage for '%s'", gcov["file_abs"]) def processGcovs(cwd, gcov_files, gcov_filter_options): files = [] for gcov in gcov_files: processGcov(cwd, gcov, files, gcov_filter_options) return files def dumpBranchCoverageToLcovInfo(f, branches): branch_miss = 0 branch_found = 0 brda = [] for line_num, branch_counts in branches.items(): for i, count in enumerate(branch_counts): # Branch (, , , ) brda.append((line_num, int(i/2), i, count)) branch_miss += int(count == 0) branch_found += 1 for v in sorted(brda): f.write("BRDA:{},{},{},{}\n".format(*v)) f.write("BRF:{}\n".format(branch_found)) # Branches Found f.write("BRH:{}\n".format(branch_found - branch_miss)) # Branches Hit def dumpToLcovInfo(fastcov_json, output): with open(output, "w") as f: sources = fastcov_json["sources"] for sf in sorted(sources.keys()): for tn in sorted(sources[sf].keys()): data = sources[sf][tn] f.write("TN:{}\n".format(tn)) #Test Name - used mainly in conjuction with genhtml --show-details f.write("SF:{}\n".format(sf)) #Source File fn_miss = 0 fn = [] fnda = [] for function, fdata in data["functions"].items(): fn.append((fdata["start_line"], function)) # Function Start Line fnda.append((fdata["execution_count"], function)) # Function Hits fn_miss += int(fdata["execution_count"] == 0) # NOTE: lcov sorts FN, but not FNDA. for v in sorted(fn): f.write("FN:{},{}\n".format(*v)) for v in sorted(fnda): f.write("FNDA:{},{}\n".format(*v)) f.write("FNF:{}\n".format(len(data["functions"]))) #Functions Found f.write("FNH:{}\n".format((len(data["functions"]) - fn_miss))) #Functions Hit if data["branches"]: dumpBranchCoverageToLcovInfo(f, data["branches"]) line_miss = 0 da = [] for line_num, count in data["lines"].items(): da.append((line_num, count)) line_miss += int(count == 0) for v in sorted(da): f.write("DA:{},{}\n".format(*v)) # Line f.write("LF:{}\n".format(len(data["lines"]))) #Lines Found f.write("LH:{}\n".format((len(data["lines"]) - line_miss))) #Lines Hit f.write("end_of_record\n") def getSourceLines(source, fallback_encodings=[]): """Return a list of lines from the provided source, trying to decode with fallback encodings if the default fails.""" default_encoding = sys.getdefaultencoding() for encoding in [default_encoding] + fallback_encodings: try: with open(source, encoding=encoding) as f: return f.readlines() except UnicodeDecodeError: pass logging.warning("Could not decode '{}' with {} or fallback encodings ({}); ignoring errors".format(source, default_encoding, ",".join(fallback_encodings))) with open(source, errors="ignore") as f: return f.readlines() def exclProcessSource(fastcov_sources, source, exclude_branches_sw, include_branches_sw, fallback_encodings): start_line = 0 end_line = 0 # Start enumeration at line 1 because the first line of the file is line 1 not 0 for i, line in enumerate(getSourceLines(source, fallback_encodings), 1): # Cycle through test names (likely only 1) for test_name in fastcov_sources[source]: fastcov_data = fastcov_sources[source][test_name] # Build line to function dict so can quickly delete by line number line_to_func = {} for f in fastcov_data["functions"].keys(): l = fastcov_data["functions"][f]["start_line"] if l not in line_to_func: line_to_func[l] = set() line_to_func[l].add(f) if i in fastcov_data["branches"]: del_exclude_br = exclude_branches_sw and any(line.lstrip().startswith(e) for e in exclude_branches_sw) del_include_br = include_branches_sw and all(not line.lstrip().startswith(e) for e in include_branches_sw) if del_exclude_br or del_include_br: del fastcov_data["branches"][i] if "LCOV_EXCL" not in line: continue if "LCOV_EXCL_LINE" in line: for key in ["lines", "branches"]: if i in fastcov_data[key]: del fastcov_data[key][i] if i in line_to_func: for key in line_to_func[i]: if key in fastcov_data["functions"]: del fastcov_data["functions"][key] elif "LCOV_EXCL_START" in line: start_line = i elif "LCOV_EXCL_STOP" in line: end_line = i if not start_line: end_line = 0 continue for key in ["lines", "branches"]: for line_num in list(fastcov_data[key].keys()): if start_line <= line_num <= end_line: del fastcov_data[key][line_num] for line_num in range(start_line, end_line): if line_num in line_to_func: for key in line_to_func[line_num]: if key in fastcov_data["functions"]: del fastcov_data["functions"][key] start_line = end_line = 0 elif "LCOV_EXCL_BR_LINE" in line: if i in fastcov_data["branches"]: del fastcov_data["branches"][i] def exclMarkerWorker(fastcov_sources, chunk, exclude_branches_sw, include_branches_sw, fallback_encodings): for source in chunk: try: exclProcessSource(fastcov_sources, source, exclude_branches_sw, include_branches_sw, fallback_encodings) except FileNotFoundError: logging.error("Could not find '%s' to scan for exclusion markers...", source) setExitCode("excl_not_found") # Set exit code because of error def scanExclusionMarkers(fastcov_json, jobs, exclude_branches_sw, include_branches_sw, min_chunk_size, fallback_encodings): chunk_size = max(min_chunk_size, int(len(fastcov_json["sources"]) / jobs) + 1) threads = [] for chunk in chunks(list(fastcov_json["sources"].keys()), chunk_size): t = threading.Thread(target=exclMarkerWorker, args=(fastcov_json["sources"], chunk, exclude_branches_sw, include_branches_sw, fallback_encodings)) threads.append(t) t.start() logging.info("Spawned {} threads each scanning at most {} source files".format(len(threads), chunk_size)) for t in threads: t.join() def distillFunction(function_raw, functions): function_name = function_raw["name"] # NOTE: need to explicitly cast all counts coming from gcov to int - this is because gcov's json library # will pass as scientific notation (i.e. 12+e45) start_line = int(function_raw["start_line"]) execution_count = int(function_raw["execution_count"]) if function_name not in functions: functions[function_name] = { "start_line": start_line, "execution_count": execution_count } else: functions[function_name]["execution_count"] += execution_count def emptyBranchSet(branch1, branch2): return (branch1["count"] == 0 and branch2["count"] == 0) def matchingBranchSet(branch1, branch2): return (branch1["count"] == branch2["count"]) def filterExceptionalBranches(branches): filtered_branches = [] exception_branch = False for i in range(0, len(branches), 2): if i+1 >= len(branches): filtered_branches.append(branches[i]) break # Filter exceptional branch noise if branches[i+1]["throw"]: exception_branch = True continue # Filter initializer list noise if exception_branch and emptyBranchSet(branches[i], branches[i+1]) and len(filtered_branches) >= 2 and matchingBranchSet(filtered_branches[-1], filtered_branches[-2]): return [] filtered_branches.append(branches[i]) filtered_branches.append(branches[i+1]) return filtered_branches def distillLine(line_raw, lines, branches, include_exceptional_branches): line_number = int(line_raw["line_number"]) count = int(line_raw["count"]) if line_number not in lines: lines[line_number] = count else: lines[line_number] += count # Filter out exceptional branches by default unless requested otherwise if not include_exceptional_branches: line_raw["branches"] = filterExceptionalBranches(line_raw["branches"]) # Increment all branch counts for i, branch in enumerate(line_raw["branches"]): if line_number not in branches: branches[line_number] = [] blen = len(branches[line_number]) glen = len(line_raw["branches"]) if blen < glen: branches[line_number] += [0] * (glen - blen) branches[line_number][i] += int(branch["count"]) def distillSource(source_raw, sources, test_name, include_exceptional_branches): source_name = source_raw["file_abs"] if source_name not in sources: sources[source_name] = { test_name: { "functions": {}, "branches": {}, "lines": {} } } for function in source_raw["functions"]: distillFunction(function, sources[source_name][test_name]["functions"]) for line in source_raw["lines"]: distillLine(line, sources[source_name][test_name]["lines"], sources[source_name][test_name]["branches"], include_exceptional_branches) def dumpToJson(intermediate, output): with open(output, "w") as f: json.dump(intermediate, f) def getGcovFilterOptions(args): return { "sources": set([os.path.abspath(s) for s in args.sources]), #Make paths absolute, use set for fast lookups "include": args.includepost, "exclude": args.excludepost, } def addDicts(dict1, dict2): """Add dicts together by value. i.e. addDicts({"a":1,"b":0}, {"a":2}) == {"a":3,"b":0}.""" result = {k:v for k,v in dict1.items()} for k,v in dict2.items(): if k in result: result[k] += v else: result[k] = v return result def addLists(list1, list2): """Add lists together by value. i.e. addLists([1,1], [2,2]) == [3,3].""" # Find big list and small list blist, slist = list(list2), list(list1) if len(list1) > len(list2): blist, slist = slist, blist # Overlay small list onto big list for i, b in enumerate(slist): blist[i] += b return blist def combineReports(base, overlay): for source, scov in overlay["sources"].items(): # Combine Source Coverage if source not in base["sources"]: base["sources"][source] = scov continue for test_name, tcov in scov.items(): # Combine Source Test Name Coverage if test_name not in base["sources"][source]: base["sources"][source][test_name] = tcov continue # Drill down and create convenience variable base_data = base["sources"][source][test_name] # Combine Line Coverage base_data["lines"] = addDicts(base_data["lines"], tcov["lines"]) # Combine Branch Coverage for branch, cov in tcov["branches"].items(): if branch not in base_data["branches"]: base_data["branches"][branch] = cov else: base_data["branches"][branch] = addLists(base_data["branches"][branch], cov) # Combine Function Coverage for function, cov in tcov["functions"].items(): if function not in base_data["functions"]: base_data["functions"][function] = cov else: base_data["functions"][function]["execution_count"] += cov["execution_count"] def parseInfo(path): """Parse an lcov .info file into fastcov json.""" fastcov_json = { "sources": {} } with open(path) as f: for line in f: if line.startswith("TN:"): current_test_name = line[3:].strip() elif line.startswith("SF:"): current_sf = line[3:].strip() fastcov_json["sources"][current_sf] = { current_test_name: { "functions": {}, "branches": {}, "lines": {}, } } current_data = fastcov_json["sources"][current_sf][current_test_name] elif line.startswith("FN:"): line_num, function_name = line[3:].strip().split(",") current_data["functions"][function_name] = {} current_data["functions"][function_name]["start_line"] = int(line_num) elif line.startswith("FNDA:"): count, function_name = line[5:].strip().split(",") current_data["functions"][function_name]["execution_count"] = int(count) elif line.startswith("DA:"): line_num, count = line[3:].strip().split(",") current_data["lines"][line_num] = int(count) elif line.startswith("BRDA:"): branch_tokens = line[5:].strip().split(",") line_num, count = branch_tokens[0], branch_tokens[-1] if line_num not in current_data["branches"]: current_data["branches"][line_num] = [] current_data["branches"][line_num].append(int(count)) return fastcov_json def convertKeysToInt(report): for source in report["sources"].keys(): for test_name in report["sources"][source].keys(): report_data = report["sources"][source][test_name] report_data["lines"] = {int(k):v for k,v in report_data["lines"].items()} report_data["branches"] = {int(k):v for k,v in report_data["branches"].items()} def parseAndCombine(paths): base_report = {} for path in paths: if path.endswith(".json"): with open(path) as f: report = json.load(f) elif path.endswith(".info"): report = parseInfo(path) else: logging.error("Currently only fastcov .json and lcov .info supported for combine operations, aborting due to %s...\n", path) sys.exit(EXIT_CODES["unsupported_coverage_format"]) # In order for sorting to work later when we serialize, # make sure integer keys are int convertKeysToInt(report) if not base_report: base_report = report logging.info("Setting {} as base report".format(path)) else: combineReports(base_report, report) logging.info("Adding {} to base report".format(path)) return base_report def getCombineCoverage(args): logging.info("Performing combine operation") fastcov_json = parseAndCombine(args.combine) filterFastcov(fastcov_json, args) return fastcov_json def getGcovCoverage(args): # Need at least python 3.5 because of use of recursive glob checkPythonVersion(sys.version_info[0:2]) # Need at least gcov 9.0.0 because that's when gcov JSON and stdout streaming was introduced checkGcovVersion(getGcovVersion(args.gcov)) # Get list of gcda files to process coverage_files = findCoverageFiles(args.directory, args.coverage_files, args.use_gcno) # If gcda/gcno filtering is enabled, filter them out now if args.excludepre: coverage_files = getFilteredCoverageFiles(coverage_files, args.excludepre) logging.info("Found {} coverage files after filtering".format(len(coverage_files))) # We "zero" the "counters" by deleting all gcda files if args.zerocounters: removeFiles(coverage_files) logging.info("Removed {} .gcda files".format(len(coverage_files))) sys.exit() # Fire up one gcov per cpu and start processing gcdas gcov_filter_options = getGcovFilterOptions(args) fastcov_json = processGcdas(args, coverage_files, gcov_filter_options) # Summarize processing results logging.info("Processed {} .gcov files ({} total, {} skipped)".format(GCOVS_TOTAL - GCOVS_SKIPPED, GCOVS_TOTAL, GCOVS_SKIPPED)) logging.debug("Final report will contain coverage for the following %d source files:\n %s", len(fastcov_json["sources"]), "\n ".join(fastcov_json["sources"])) return fastcov_json def dumpFile(fastcov_json, args): if args.lcov: dumpToLcovInfo(fastcov_json, args.output) logging.info("Created lcov info file '{}'".format(args.output)) else: dumpToJson(fastcov_json, args.output) logging.info("Created fastcov json file '{}'".format(args.output)) def tupleToDotted(tup): return ".".join(map(str, tup)) def parseArgs(): parser = argparse.ArgumentParser(description='A parallel gcov wrapper for fast coverage report generation') parser.add_argument('-z', '--zerocounters', dest='zerocounters', action="store_true", help='Recursively delete all gcda files') # Enable Branch Coverage parser.add_argument('-b', '--branch-coverage', dest='branchcoverage', action="store_true", help='Include only the most useful branches in the coverage report.') parser.add_argument('-B', '--exceptional-branch-coverage', dest='xbranchcoverage', action="store_true", help='Include ALL branches in the coverage report (including potentially noisy exceptional branches).') parser.add_argument('-A', '--exclude-br-lines-starting-with', dest='exclude_branches_sw', nargs="+", metavar='', default=[], help='Exclude branches from lines starting with one of the provided strings (i.e. assert, return, etc.)') parser.add_argument('-a', '--include-br-lines-starting-with', dest='include_branches_sw', nargs="+", metavar='', default=[], help='Include only branches from lines starting with one of the provided strings (i.e. if, else, while, etc.)') parser.add_argument('-X', '--skip-exclusion-markers', dest='skip_exclusion_markers', action="store_true", help='Skip reading source files to search for lcov exclusion markers (such as "LCOV_EXCL_LINE")') parser.add_argument('-x', '--scan-exclusion-markers', dest='scan_exclusion_markers', action="store_true", help='(Combine operations) Force reading source files to search for lcov exclusion markers (such as "LCOV_EXCL_LINE")') # Capture untested file coverage as well via gcno parser.add_argument('-n', '--process-gcno', dest='use_gcno', action="store_true", help='Process both gcno and gcda coverage files. This option is useful for capturing untested files in the coverage report.') # Filtering Options parser.add_argument('-s', '--source-files', dest='sources', nargs="+", metavar='', default=[], help='Filter: Specify exactly which source files should be included in the final report. Paths must be either absolute or relative to current directory.') parser.add_argument('-e', '--exclude', dest='excludepost', nargs="+", metavar='', default=[], help='Filter: Exclude source files from final report if they contain one of the provided substrings (i.e. /usr/include test/, etc.)') parser.add_argument('-i', '--include', dest='includepost', nargs="+", metavar='', default=[], help='Filter: Only include source files in final report that contain one of the provided substrings (i.e. src/ etc.)') parser.add_argument('-f', '--gcda-files', dest='coverage_files', nargs="+", metavar='', default=[], help='Filter: Specify exactly which gcda or gcno files should be processed. Note that specifying gcno causes both gcno and gcda to be processed.') parser.add_argument('-E', '--exclude-gcda', dest='excludepre', nargs="+", metavar='', default=[], help='Filter: Exclude gcda or gcno files from being processed via simple find matching (not regex)') parser.add_argument('-g', '--gcov', dest='gcov', default='gcov', help='Which gcov binary to use') parser.add_argument('-d', '--search-directory', dest='directory', default=".", help='Base directory to recursively search for gcda files (default: .)') parser.add_argument('-c', '--compiler-directory', dest='cdirectory', default=".", help='Base directory compiler was invoked from (default: .) \ This needs to be set if invoking fastcov from somewhere other than the base compiler directory.') parser.add_argument('-j', '--jobs', dest='jobs', type=int, default=multiprocessing.cpu_count(), help='Number of parallel gcov to spawn (default: {}).'.format(multiprocessing.cpu_count())) parser.add_argument('-m', '--minimum-chunk-size', dest='minimum_chunk', type=int, default=5, help='Minimum number of files a thread should process (default: 5). \ If you have only 4 gcda files but they are monstrously huge, you could change this value to a 1 so that each thread will only process 1 gcda. Otherwise fastcov will spawn only 1 thread to process all of them.') parser.add_argument('-F', '--fallback-encodings', dest='fallback_encodings', nargs="+", metavar='', default=[], help='List of encodings to try if opening a source file with the default fails (i.e. latin1, etc.). This option is not usually needed.') parser.add_argument('-l', '--lcov', dest='lcov', action="store_true", help='Output in lcov info format instead of fastcov json') parser.add_argument('-o', '--output', dest='output', default="coverage.json", help='Name of output file (default: coverage.json)') parser.add_argument('-q', '--quiet', dest='quiet', action="store_true", help='Suppress output to stdout') parser.add_argument('-t', '--test-name', dest='test_name', default="", help='Specify a test name for the coverage. Equivalent to lcov\'s `-t`.') parser.add_argument('-C', '--add-tracefile', dest='combine', nargs="+", help='Combine multiple coverage files into one. If this flag is specified, fastcov will do a combine operation instead invoking gcov. Equivalent to lcov\'s `-a`.') parser.add_argument('-V', '--verbose', dest="verbose", action="store_true", help="Print more detailed information about what fastcov is doing") parser.add_argument('-v', '--version', action="version", version='%(prog)s {version}'.format(version=__version__), help="Show program's version number and exit") args = parser.parse_args() return args def checkPythonVersion(version): """Exit if the provided python version is less than the supported version.""" if version < MINIMUM_PYTHON: sys.stderr.write("Minimum python version {} required, found {}\n".format(tupleToDotted(MINIMUM_PYTHON), tupleToDotted(version))) sys.exit(EXIT_CODES["python_version"]) def checkGcovVersion(version): """Exit if the provided gcov version is less than the supported version.""" if version < MINIMUM_GCOV: sys.stderr.write("Minimum gcov version {} required, found {}\n".format(tupleToDotted(MINIMUM_GCOV), tupleToDotted(version))) sys.exit(EXIT_CODES["gcov_version"]) def setupLogging(quiet, verbose): handler = logging.StreamHandler() handler.setFormatter(FastcovFormatter("[%(levelname)s]: %(message)s")) root = logging.getLogger() root.setLevel(logging.INFO) root.addHandler(handler) if not quiet: logging.disable(level=logging.NOTSET) # Re-enable logging if verbose: root.setLevel(logging.DEBUG) def main(): args = parseArgs() # Setup logging setupLogging(args.quiet, args.verbose) # Get report from appropriate source if args.combine: fastcov_json = getCombineCoverage(args) skip_exclusion_markers = not args.scan_exclusion_markers else: fastcov_json = getGcovCoverage(args) skip_exclusion_markers = args.skip_exclusion_markers # Scan for exclusion markers if not skip_exclusion_markers: scanExclusionMarkers(fastcov_json, args.jobs, args.exclude_branches_sw, args.include_branches_sw, args.minimum_chunk, args.fallback_encodings) logging.info("Scanned {} source files for exclusion markers".format(len(fastcov_json["sources"]))) # Dump to desired file format dumpFile(fastcov_json, args) # If there was an error along the way, but we still completed the pipeline... if EXIT_CODE: sys.exit(EXIT_CODE) # Set package version... it's way down here so that we can call tupleToDotted __version__ = tupleToDotted(FASTCOV_VERSION) if __name__ == '__main__': main() verilator-5.020/nodist/code_coverage0000755000175000017500000003477514544475344017460 0ustar carstencarsten#!/usr/bin/env python3 # pylint: disable=C0103,C0114,C0115,C0116,C0209,R0912,R0914,R0915,W0125,W0621,exec-used ###################################################################### import argparse import glob import multiprocessing import os import re import subprocess import sys RealPath = os.path.dirname(os.path.realpath(__file__)) Exclude_Branch_Regexps = [] Exclude_Line_Regexps = [] Remove_Gcda_Regexps = [] Remove_Sources = [] Source_Globs = [] if 'VERILATOR_ROOT' not in os.environ: os.environ['VERILATOR_ROOT'] = os.getcwd() ###################################################################### def test(): if not os.path.exists("nodist/code_coverage.dat"): sys.exit("%Error: Run code_coverage from the top of the verilator kit") exec(open("./nodist/code_coverage.dat", "r", encoding="utf8").read()) # pylint: disable=consider-using-with if Args.stage_enabled[0]: ci_fold_start("distclean") print("Stage 0: distclean") run("make distclean || true") ci_fold_end() if Args.stage_enabled[1]: ci_fold_start("configure") print("Stage 1: configure (coverage on)") run("autoconf") run("./configure --enable-longtests --enable-coverage CXX=g++") ci_fold_end() if Args.stage_enabled[2]: ci_fold_start("build") print("Stage 2: build") nproc = multiprocessing.cpu_count() run("make -k -j " + str(nproc) + " VERILATOR_NO_OPT_BUILD=1") # The optimized versions will not collect good coverage, overwrite them run("cp bin/verilator_bin_dbg bin/verilator_bin") run("cp bin/verilator_coverage_bin_dbg bin/verilator_coverage_bin") ci_fold_end() if Args.stage_enabled[3]: ci_fold_start("test") print("Stage 3: make tests (with coverage on)") if not Args.tests: if not Args.scenarios or re.match('dist', Args.scenarios): run("make examples VERILATOR_NO_OPT_BUILD=1") run("make test_regress VERILATOR_NO_OPT_BUILD=1" + (" SCENARIOS='" + Args.scenarios + "'" if Args.scenarios else "") + (" DRIVER_HASHSET='--hashset=" + Args.hashset + "'" if Args.hashset else "") + ('' if Args.stop else ' || true')) else: for test in Args.tests: if not os.path.exists(test) and os.path.exists( "test_regress/t/" + test): test = "test_regress/t/" + test run(test) ci_fold_end() cc_dir = "nodist/obj_dir/coverage" if Args.stage_enabled[4]: ci_fold_start("gcno") print("Stage 4: Create gcno files under " + cc_dir) os.makedirs(cc_dir, exist_ok=True) os.makedirs(cc_dir + "/info", exist_ok=True) with subprocess.Popen("find . -print | grep .gcda", shell=True, stdout=subprocess.PIPE) as sp: datout = sp.stdout.read() dats = {} for dat in datout.splitlines(): dat = dat.decode('utf-8') dats[dat] = 1 for dat in sorted(dats.keys()): gcno = re.sub(r'\.gcda$', '.gcno', dat) for regexp in Remove_Gcda_Regexps: if re.search(regexp, dat): # Remove .gcda/.gcno for files we don't care about before we slowly # read them unlink_ok(dat) unlink_ok(gcno) del dats[dat] break with subprocess.Popen("find . -print | grep .gcno", shell=True, stdout=subprocess.PIPE) as sp: datout = sp.stdout.read() gcnos = {} for gcno in datout.splitlines(): gcno = gcno.decode('utf-8') gbase = re.sub(r'.*/', '', gcno, count=1) gcnos[gbase] = os.path.abspath(gcno) # We need a matching .gcno for every .gcda, try to find a matching file elsewhere for dat in sorted(dats): gcno = re.sub(r'\.gcda$', '.gcno', dat) gbase = re.sub(r'.*/', '', gcno, count=1) if not os.path.exists(gcno): if gbase in gcnos: os.symlink(gcnos[gbase], gcno) else: print("MISSING .gcno for a .gcda: " + gcno, file=sys.stderr) ci_fold_end() if Args.stage_enabled[5]: ci_fold_start("fastcov") # Must run in root directory to find all files os.makedirs(cc_dir, exist_ok=True) run(RealPath + "/fastcov.py -b -c src/obj_dbg -X --lcov" + # " --exclude /usr --exclude test_regress" + " -o " + cc_dir + " -o " + cc_dir + "/app_total.info") # For debug to convert single .gcna/.gcno in a directory to cov.info: # lcov -c -d . -o cov.info ci_fold_end() if Args.stage_enabled[6]: ci_fold_start("clone") # No control file to override single lines, so replicate the sources # Also lets us see the insertion markers in the HTML source res print("Stage 6: Clone sources under " + cc_dir) clone_sources(cc_dir) ci_fold_end() if Args.stage_enabled[11]: ci_fold_start("dirs") print("Stage 11: Cleanup paths") cleanup_abs_paths_info(cc_dir, cc_dir + "/app_total.info", cc_dir + "/app_total.info") ci_fold_end() if Args.stage_enabled[12]: ci_fold_start("filter") print("Stage 12: Filter processed source files") inc = '' for globf in Source_Globs: for infile in glob.glob(globf): inc += " '" + infile + "'" exc = '' for globf in Remove_Sources: # Fastcov does exact match not globbing at present # Lcov requires whole path match so needs the glob globf = re.sub(r'^\*', '', globf) globf = re.sub(r'\*$', '', globf) exc += " '" + globf + "'" if inc != '': inc = "--include " + inc if exc != '': exc = "--exclude " + exc run("cd " + cc_dir + " ; " + RealPath + "/fastcov.py -C app_total.info " + inc + " " + exc + " -x --lcov -o app_total_f.info") ci_fold_end() if Args.stage_enabled[17]: ci_fold_start("report") print("Stage 17: Create HTML") run("cd " + cc_dir + " ; genhtml app_total_f.info --demangle-cpp" + " --rc lcov_branch_coverage=1 --rc genhtml_hi_limit=100 --output-directory html" ) ci_fold_end() if Args.stage_enabled[18]: ci_fold_start("upload") print("Stage 18: Upload") cmd = "bash <(cat ci/coverage-upload.sh) -f " + cc_dir + "/app_total.info" print("print: Not running: export CODECOV_TOKEN=") print("print: Not running: " + cmd) ci_fold_end() if Args.stage_enabled[19]: print("*-* All Finished *-*") print("") print("* See report in " + cc_dir + "/html/index.html") print( "* Remember to make distclean && ./configure before working on non-coverage" ) def clone_sources(cc_dir): excluded_lines = 0 excluded_br_lines = 0 for globf in Source_Globs: for infile in glob.glob(globf): if re.match(r'^/', infile): sys.exit( "%Error: source globs should be relative not absolute filenames, " + infile) outfile = cc_dir + "/" + infile outpath = re.sub(r'/[^/]*$', '', outfile, count=1) os.makedirs(outpath, exist_ok=True) with open(infile, "r", encoding="utf8") as fh: with open(outfile, "w", encoding="utf8") as ofh: lineno = 0 for line in fh: lineno += 1 line = line.rstrip() done = False if re.search(r'LCOV_EXCL_LINE', line): line += " LCOV_EXCL_BR_LINE" done = True elif re.search(r'LCOV_EXCL_START', line): line += " LCOV_EXCL_BR_START" done = True elif re.search(r'LCOV_EXCL_STOP', line): line += " LCOV_EXCL_BR_STOP" done = True for regexp in Exclude_Line_Regexps: if done: break if re.search(regexp, line): # print("%s:%d: %s" % (infile, lineno, line) line += " //code_coverage: // LCOV_EXCL_LINE LCOV_EXCL_BR_LINE" excluded_lines += 1 excluded_br_lines += 1 done = True for regexp in Exclude_Branch_Regexps: if done: break if re.search(regexp, line): # print("%s:%d: %s" % (infile, lineno, line) line += " //code_coverage: // LCOV_EXCL_BR_LINE" excluded_br_lines += 1 done = True ofh.write(line + "\n") print("Number of source lines automatically LCOV_EXCL_LINE'ed: %d" % excluded_lines) print("Number of source lines automatically LCOV_EXCL_BR_LINE'ed: %d" % excluded_br_lines) def cleanup_abs_paths_info(cc_dir, infile, outfile): lines = [] with open(infile, "r", encoding="utf8") as fh: for line in fh: if re.search(r'^SF:', line): line = re.sub(os.environ['VERILATOR_ROOT'] + '/', '', line, count=1) line = re.sub(cc_dir + '/', '', line, count=1) line = re.sub(r'obj_dbg/verilog.y$', 'verilog.y', line) # print("Remaining SF: "+line) lines.append(line) with open(outfile, "w", encoding="utf8") as ofh: for line in lines: ofh.write(line) def cleanup_abs_paths_json(cc_dir, infile, outfile): # Handcrafted cleanup, alternative would be to deserialize/serialize JSON, # but this is much faster lines = [] with open(infile, "r", encoding="utf8") as fh: for line in fh: line = re.sub('"' + os.environ['VERILATOR_ROOT'] + '/', '"', line) line = re.sub('"' + cc_dir + '/', '"', line) line = re.sub(r'obj_dbg/verilog.y$', 'verilog.y', line) lines.append(line) with open(outfile, "w", encoding="utf8") as ofh: for line in lines: ofh.write(line) ###################################################################### # .dat file callbacks def exclude_branch_regexp(*regexps): Exclude_Branch_Regexps.extend(regexps) def exclude_line_regexp(*regexps): Exclude_Line_Regexps.extend(regexps) def remove_gcda_regexp(*regexps): Remove_Gcda_Regexps.extend(regexps) def remove_source(*sources): Remove_Sources.extend(sources) def source_globs(*dirs): Source_Globs.extend(dirs) ####################################################################### def run(command): # run a system command, check errors print("\t%s" % command) status = subprocess.call(command, shell=True) if status < 0: raise RuntimeError("%Error: Command failed " + command + ", stopped") def unlink_ok(filename): try: os.unlink(filename) except OSError: pass def ci_fold_start(action): print("::group::" + action, flush=True) def ci_fold_end(): print("::endgroup::\n", flush=True) ####################################################################### ####################################################################### parser = argparse.ArgumentParser( allow_abbrev=False, formatter_class=argparse.RawDescriptionHelpFormatter, description= """code_coverage builds Verilator with C++ coverage support and runs tests with coverage enabled. This will rebuild the current object files. Run as: cd $VERILATOR_ROOT nodist/code_coverage""", epilog= """Copyright 2019-2024 by Wilson Snyder. This program is free software; you can redistribute it and/or modify it under the terms of either the GNU Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0""") parser.add_argument('--debug', action='store_true', help='enable debug') parser.add_argument('--hashset', action='store', help='pass test hashset onto driver.pl test harness') parser.add_argument('--scenarios', action='store', help='pass test scenarios onto driver.pl test harness') parser.add_argument( '--stages', action='store', help='runs a specific stage or range of stages (see the script)') parser.add_argument( '--test', action='append', dest='tests', default=[], help= 'Instead of normal regressions, run the specified test(s), may be used multiple times' ) parser.add_argument('--no-stop', dest='stop', action='store_false', help='do not stop collecting data if tests fail') parser.set_defaults(stop=True) Args = parser.parse_args() if True: start = 0 end = 99 Args.stage_enabled = {} if Args.stages: match_one = re.match(r'^(\d+)$', Args.stages) match_range = re.match(r'^(\d+)-(\d+)$', Args.stages) match_to = re.match(r'^-(\d+)$', Args.stages) match_from = re.match(r'^(\d+)-$', Args.stages) if match_one: start = end = int(match_one.group(1)) elif match_range: start = int(match_range.group(1)) end = int(match_range.group(2)) elif match_to: end = int(match_to.group(1)) elif match_from: start = int(match_from.group(1)) else: sys.exit("%Error: --stages not understood: " + Args.stages) for n in range(0, 100): Args.stage_enabled[n] = False for n in range(start, end + 1): Args.stage_enabled[n] = True test() ###################################################################### # Local Variables: # compile-command: "cd .. ; nodist/code_coverage " # End: verilator-5.020/nodist/fuzzer/0000755000175000017500000000000014544475344016252 5ustar carstencarstenverilator-5.020/nodist/fuzzer/run0000755000175000017500000000125114544475344017003 0ustar carstencarsten#!/bin/bash ###################################################################### # DESCRIPTION: Fuzzer run script # # Copyright 2019-2019 by Eric Rippey. This program is free software; you # can redistribute it and/or modify it under the terms of either the GNU # Lesser General Public License Version 3 or the Perl Artistic License # Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 ###################################################################### # Actually do the fuzzing. Note that this will not terminate in any reasonable # amount of time. However, it will give updates on its progress. afl-fuzz -i in1 -o out1 -x dictionary ./wrapper --cc @@ verilator-5.020/nodist/fuzzer/all0000755000175000017500000000122414544475344016747 0ustar carstencarsten#!/bin/bash ###################################################################### # DESCRIPTION: Fuzzer one-line setup & run # # Copyright 2019-2019 by Eric Rippey. This program is free software; you # can redistribute it and/or modify it under the terms of either the GNU # Lesser General Public License Version 3 or the Perl Artistic License # Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 ###################################################################### # Run all steps needed to configure and start fuzzer # Note that this assumes the system is a Debian-like Linux distribution set -e sudo ./setup_root ./setup_user ./run verilator-5.020/nodist/fuzzer/generate_dictionary0000755000175000017500000000427514544475344022227 0ustar carstencarsten#!/usr/bin/env python3 # pylint: disable=C0103,C0114,C0115,C0116,C0321 ###################################################################### # DESCRIPTION: Fuzzer dictionary generator # # Copyright 2019-2019 by Eric Rippey. This program is free software; you # can redistribute it and/or modify it under the terms of either the GNU Lesser # General Public License Version 3 or the Perl Artistic License Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 ###################################################################### # Attempts to pull a list of keywords out of the Flex input # These are then put in a dictionary of "interesting" sequences # This will be used to help the fuzzer pick interesting inputs more quickly. from subprocess import getstatusoutput from os import system def take_while(f, a): # any(a) => (a->bool)->[a]->[a] # Does the same think as Haskell's takewhile. out = [] for elem in a: if f(elem): out.append(elem) else: return out return out def skip_while(f, a): # any(a) => (a->bool)->[a]->[a] # Basically, the opposite thing from skipwhile while len(a) and f(a[0]): a = a[1:] return a def print_lines(a): # printable(a) => [a]->void for elem in a: print(elem) def write_file(filename, contents): # str->str->void with open(filename, "w", encoding="utf8") as fh: fh.write(contents) def parse_line(s): # str->maybe str if len(s) == 0: return None part = skip_while(lambda x: x != '"', s) if len(part) == 0 or part[0] != '"': return None literal_part = take_while(lambda x: x != '"', part[1:]) return ''.join(filter(lambda x: x != '\\', literal_part)) def main(): status, output = getstatusoutput('flex -T ../../src/verilog.l') assert status == 0 lines = output.splitlines() lines = take_while(lambda x: 'beginning dump of nfa' not in x, lines) tokens = set(filter(lambda x: x, map(parse_line, lines))) dirname = 'dictionary' r = system('mkdir -p ' + dirname) assert r == 0 for i, token in enumerate(tokens): write_file(dirname + '/' + str(i), token) if __name__ == '__main__': main() verilator-5.020/nodist/fuzzer/actual_fail0000755000175000017500000000317214544475344020447 0ustar carstencarsten#!/usr/bin/env python3 # pylint: disable=C0103,C0114,C0115,C0116,C0321,R0911 ###################################################################### # DESCRIPTION: Fuzzer result checker # # Copyright 2019-2019 by Eric Rippey. This program is free software; you # can redistribute it and/or modify it under the terms of either the GNU Lesser # General Public License Version 3 or the Perl Artistic License Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 ###################################################################### # This script is designed to rerun examples to see whether they have # unexpected types of output besides the ones that afl-fuzz detects as # such. from glob import glob from subprocess import getstatusoutput from argparse import ArgumentParser def interesting(s): if 'assert' in s: return 1 if 'Assert' in s: return 1 if 'Aborted' in s: return 1 if 'terminate' in s: if 'unterminated' in s: return 0 return 1 if 'Segmentation' in s: return 1 if 'internal error' in s: return 1 return 0 def main(): p = ArgumentParser() p.add_argument('--dir', default='out1/queue') args = p.parse_args() for infile in glob(args.dir + '/*'): # Input filenames are known not to contain spaces or other unusual # characters, therefore this works. status, output = getstatusoutput('../../bin/verilator_bin --cc ' + infile) if interesting(output): print(infile) print(status) print(output) if __name__ == '__main__': main() verilator-5.020/nodist/fuzzer/wrapper.cpp0000644000175000017500000000201114544475344020430 0ustar carstencarsten// -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // DESCRIPTION: Verilator fuzzing wrapper for verilator_bin // // Copyright 2019 by Eric Rippey. This program is free software; you // can redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License // Version 2.0. // SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 //************************************************************************* #include #include #include // The purpose of this script is to make sure that the results folder that // is generated by running verilator does not change the results of // subsequent runs. // This does slow down the execution to some degree but makes the results // more reliable. int main(int argc, char** argv, char** envp) { auto r = system("rm -rf obj_dir"); assert(r == 0); return execve("../../bin/verilator_bin", argv, envp); } verilator-5.020/nodist/fuzzer/.gitignore0000644000175000017500000000004214544475344020236 0ustar carstencarstenwrapper dictionary/ in* lex.yy.cc verilator-5.020/nodist/fuzzer/setup_user0000755000175000017500000000206014544475344020374 0ustar carstencarsten#!/bin/bash ###################################################################### # DESCRIPTION: Fuzzer setup to be run as a normal user # # Copyright 2019-2019 by Eric Rippey. This program is free software; you # can redistribute it and/or modify it under the terms of either the GNU # Lesser General Public License Version 3 or the Perl Artistic License # Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 ###################################################################### # This is the portion of the setup for fuzzing that does not require root access. set -e # Build instrumented version of verilator pushd ../.. autoconf AFL_HARDEN=1 CC=afl-gcc CXX=afl-g++ ./configure $(cd ..; pwd) make clean make -j $(ncpus) popd # Create a listing of likely snippets for the fuzzer to use. # Not essential, but makes things likely to be found faster. ./generate_dictionary # Set up input directory mkdir in1 echo "module m; initial \$display(\"Hello world!\n\"); endmodule" > in1/1.v # Compile wrapper program AFL_HARDEN=1 CXX=afl-g++ make wrapper verilator-5.020/nodist/fuzzer/setup_root0000755000175000017500000000156014544475344020405 0ustar carstencarsten#!/bin/bash ###################################################################### # DESCRIPTION: Fuzzer setup to be run as root # # Copyright 2019-2019 by Eric Rippey. This program is free software; you # can redistribute it and/or modify it under the terms of either the GNU # Lesser General Public License Version 3 or the Perl Artistic License # Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 ###################################################################### # This is the portion of the fuzzer setup that must be run as root. # Note that this assumes a Debian-like distribution. set -e # Get dependencies apt-get install afl mdm apt-get build-dep verilator # Run a couple pieces of setup which should speed up the fuzzer echo core >/proc/sys/kernel/core_pattern cd /sys/devices/system/cpu echo performance | tee cpu*/cpufreq/scaling_governor verilator-5.020/nodist/install_test0000755000175000017500000001150514544475344017362 0ustar carstencarsten#!/usr/bin/env python3 # pylint: disable=C0103,C0114,C0115,C0116,C0209,R0801,R0915 ###################################################################### import argparse import multiprocessing import os import shutil import subprocess import sys ###################################################################### def test(): if not os.path.exists("nodist/install_test"): sys.exit("%Error: Run from the top of the verilator kit") cleanenv() if os.path.exists("Makefile"): run("make distclean") # Try building from a scratch area srcdir = os.getcwd() blddir = srcdir + "/test_regress/obj_dir/install_test_bld" prefix = srcdir + "/test_regress/obj_dir/install_test_prefix" testdirp = srcdir + "/test_regress/obj_dir/install_test_testp" testdirn = srcdir + "/test_regress/obj_dir/install_test_testn" if Args.stage <= 0: print("== stage 0") run("/bin/rm -rf " + blddir) run("/bin/mkdir -p " + blddir) run("cd " + blddir + " && " + srcdir + "/configure --prefix " + prefix) run("cd " + blddir + " && make -j " + str(calc_jobs())) # Install it under the prefix if Args.stage <= 1: print("== stage 1") run("/bin/rm -rf " + prefix) run("/bin/mkdir -p " + prefix) run("cd " + blddir + " && make install") run("test -e " + prefix + "/share/man/man1/verilator.1") run("test -e " + prefix + "/share/verilator/examples/make_tracing_c/Makefile") run("test -e " + prefix + "/share/verilator/include/verilated.h") run("test -e " + prefix + "/bin/verilator") run("test -e " + prefix + "/bin/verilator_bin") run("test -e " + prefix + "/bin/verilator_bin_dbg") run("test -e " + prefix + "/bin/verilator_gantt") run("test -e " + prefix + "/bin/verilator_profcfunc") # run a test using just the path if Args.stage <= 2: print("== stage 2") odir = testdirp run("/bin/rm -rf " + odir) run("/bin/mkdir -p " + odir) path = prefix + "/bin" + ":" + prefix + "/share/bin" write_verilog(odir) run("cd " + odir + " && PATH=" + path + ":$PATH verilator --cc top.v --exe sim_main.cpp") run("cd " + odir + "/obj_dir && PATH=" + path + ":$PATH make -f Vtop.mk") run("cd " + odir + " && PATH=" + path + ":$PATH obj_dir/Vtop") # run a test using exact path to binary if Args.stage <= 3: print("== stage 3") odir = testdirn run("/bin/rm -rf " + odir) run("/bin/mkdir -p " + odir) write_verilog(odir) bin1 = prefix + "/bin" run("cd " + odir + " && " + bin1 + "/verilator --cc top.v --exe sim_main.cpp") run("cd " + odir + "/obj_dir && make -f Vtop.mk") run("cd " + odir + "/obj_dir && ./Vtop") if Args.stage <= 9: print("*-* All Finished *-*") def write_verilog(odir): shutil.copy2("examples/make_hello_c/top.v", odir + "/top.v") shutil.copy2("examples/make_hello_c/sim_main.cpp", odir + "/sim_main.cpp") def cleanenv(): for var in os.environ: if var in ('VERILATOR_ROOT', 'VERILATOR_INCLUDE', 'VERILATOR_NO_OPT_BUILD'): print("unset %s # Was '%s'" % (var, os.environ[var])) del os.environ[var] def calc_jobs(): return multiprocessing.cpu_count() + 1 def run(command): # run a system command, check errors print("\t%s" % command) os.system(command) status = subprocess.call(command, shell=True) if status < 0: raise RuntimeError("%Error: Command failed " + command + ", stopped") ####################################################################### ####################################################################### parser = argparse.ArgumentParser( allow_abbrev=False, formatter_class=argparse.RawDescriptionHelpFormatter, description= """install_test performs several make-and-install iterations to verify the Verilator kit. It isn't part of the normal "make test" due to the number of builds required.""", epilog= """Copyright 2009-2024 by Wilson Snyder. This program is free software; you can redistribute it and/or modify it under the terms of either the GNU Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0""") parser.add_argument('--debug', action='store_const', const=9, help='enable debug') parser.add_argument('--stage', type=int, default=0, help='run a specific test stage (see the script)') Args = parser.parse_args() test() ###################################################################### # Local Variables: # compile-command: "cd .. ; nodist/install_test" # End: verilator-5.020/Artistic0000644000175000017500000002156114544475344015137 0ustar carstencarstenArtistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble ******** This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions *********** "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution ******************************************************** (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version ****************************************************** (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source ********************************************************** (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified ****************************************************************** Versions without the Source *************************** (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package ********************************** (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version ******************************************************** (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions ****************** (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. verilator-5.020/.codacy.yml0000644000175000017500000000016014544475344015465 0ustar carstencarsten--- exclude_paths: - '.github/**' - 'ci/build_verilator.sh' - 'include/vltstd/**' - 'nodist/fastcov.py' verilator-5.020/install-sh0000644000175000017500000001271114544475344015430 0ustar carstencarsten#! /bin/sh # # install - install a program, script, or datafile # This comes from X11R5 (mit/util/scripts/install.sh). # # Copyright 1991 by the Massachusetts Institute of Technology # # Permission to use, copy, modify, distribute, and sell this software and its # documentation for any purpose is hereby granted without fee, provided that # the above copyright notice appear in all copies and that both that # copyright notice and this permission notice appear in supporting # documentation, and that the name of M.I.T. not be used in advertising or # publicity pertaining to distribution of the software without specific, # written prior permission. M.I.T. makes no representations about the # suitability of this software for any purpose. It is provided "as is" # without express or implied warranty. # # Calling this script install-sh is preferred over install.sh, to prevent # `make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. It can only install one file at a time, a restriction # shared with many OS's install programs. # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit="${DOITPROG-}" # put in absolute paths if you don't have them in your path; or use env. vars. mvprog="${MVPROG-mv}" cpprog="${CPPROG-cp}" chmodprog="${CHMODPROG-chmod}" chownprog="${CHOWNPROG-chown}" chgrpprog="${CHGRPPROG-chgrp}" stripprog="${STRIPPROG-strip}" rmprog="${RMPROG-rm}" mkdirprog="${MKDIRPROG-mkdir}" transformbasename="" transform_arg="" instcmd="$mvprog" chmodcmd="$chmodprog 0755" chowncmd="" chgrpcmd="" stripcmd="" rmcmd="$rmprog -f" mvcmd="$mvprog" src="" dst="" dir_arg="" while [ x"$1" != x ]; do case $1 in -c) instcmd="$cpprog" shift continue;; -d) dir_arg=true shift continue;; -m) chmodcmd="$chmodprog $2" shift shift continue;; -o) chowncmd="$chownprog $2" shift shift continue;; -g) chgrpcmd="$chgrpprog $2" shift shift continue;; -s) stripcmd="$stripprog" shift continue;; -t=*) transformarg=`echo $1 | sed 's/-t=//'` shift continue;; -b=*) transformbasename=`echo $1 | sed 's/-b=//'` shift continue;; *) if [ x"$src" = x ] then src=$1 else # this colon is to work around a 386BSD /bin/sh bug : dst=$1 fi shift continue;; esac done if [ x"$src" = x ] then echo "install: no input file specified" exit 1 else true fi if [ x"$dir_arg" != x ]; then dst=$src src="" if [ -d $dst ]; then instcmd=: else instcmd=mkdir fi else # Waiting for this to be detected by the "$instcmd $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if [ -f $src -o -d $src ] then true else echo "install: $src does not exist" exit 1 fi if [ x"$dst" = x ] then echo "install: no destination specified" exit 1 else true fi # If destination is a directory, append the input filename; if your system # does not like double slashes in filenames, you may need to add some logic if [ -d $dst ] then dst="$dst"/`basename $src` else true fi fi ## this sed command emulates the dirname command dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` # Make sure that the destination directory exists. # this part is taken from Noah Friedman's mkinstalldirs script # Skip lots of stat calls in the usual case. if [ ! -d "$dstdir" ]; then defaultIFS=' ' IFS="${IFS-${defaultIFS}}" oIFS="${IFS}" # Some sh's can't handle IFS=/ for some reason. IFS='%' set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'` IFS="${oIFS}" pathcomp='' while [ $# -ne 0 ] ; do pathcomp="${pathcomp}${1}" shift if [ ! -d "${pathcomp}" ] ; then $mkdirprog "${pathcomp}" else true fi pathcomp="${pathcomp}/" done fi if [ x"$dir_arg" != x ] then $doit $instcmd $dst && if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi && if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi && if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi && if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi else # If we're going to rename the final executable, determine the name now. if [ x"$transformarg" = x ] then dstfile=`basename $dst` else dstfile=`basename $dst $transformbasename | sed $transformarg`$transformbasename fi # don't allow the sed command to completely eliminate the filename if [ x"$dstfile" = x ] then dstfile=`basename $dst` else true fi # Make a temp file name in the proper directory. dsttmp=$dstdir/#inst.$$# # Move or copy the file name to the temp name $doit $instcmd $src $dsttmp && trap "rm -f ${dsttmp}" 0 && # and set any options; do chmod last to preserve setuid bits # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $instcmd $src $dsttmp" command. if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi && if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi && if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi && if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi && # Now rename the file to the real destination. $doit $rmcmd -f $dstdir/$dstfile && $doit $mvcmd $dsttmp $dstdir/$dstfile fi && exit 0 verilator-5.020/verilator.pc.in0000644000175000017500000000045214544475344016366 0ustar carstencarstenprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ datarootdir=@datarootdir@ includedir=@pkgdatadir@/include Name: verilator Description: fast free Verilog simulator URL: https://verilator.org Version: @PACKAGE_VERSION_NUMBER@ Requires: Libs: Cflags: -I${includedir} -I${includedir}/vltstd verilator-5.020/.gitattributes0000644000175000017500000000027214544475344016321 0ustar carstencarsten*.v linguist-language=SystemVerilog *.vh linguist-language=SystemVerilog *.sv linguist-language=SystemVerilog Changes linguist-language=reStructuredText nodist linguist-detectable=false verilator-5.020/CPPLINT.cfg0000644000175000017500000000066314544475344015224 0ustar carstencarstenset noparent linelength=100 filter=-build/c++11 filter=-build/header_guard filter=-build/include_order filter=-build/include_subdir filter=-readability/inheritance filter=-readability/nolint filter=-readability/todo filter=-runtime/references filter=-whitespace/blank_line filter=-whitespace/empty_if_body filter=-whitespace/indent filter=-whitespace/newline filter=-whitespace/braces filter=-whitespace/parens filter=-whitespace/todo verilator-5.020/.devcontainer/0000755000175000017500000000000014544475344016164 5ustar carstencarstenverilator-5.020/.devcontainer/devcontainer.json0000644000175000017500000000017114544475344021537 0ustar carstencarsten{ "name": "Verilator Build Environment", "build": { "dockerfile": "../ci/docker/buildenv/Dockerfile" } } verilator-5.020/.clang-tidy0000644000175000017500000000301314544475344015456 0ustar carstencarstenChecks: '*,-hicpp*,-android-cloexec-fopen,-cert-dcl50-cpp,-cert-env33-c,-cert-err34-c,-cert-err58-cpp,-clang-analyzer-core.UndefinedBinaryOperatorResult,-clang-analyzer-security*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-no-malloc,-cppcoreguidelines-owning-memory,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-cppcoreguidelines-pro-bounds-constant-array-index,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-cppcoreguidelines-pro-type-const-cast,-cppcoreguidelines-pro-type-reinterpret-cast,-cppcoreguidelines-pro-type-static-cast-downcast,-cppcoreguidelines-pro-type-union-access,-cppcoreguidelines-pro-type-vararg,-cppcoreguidelines-special-member-functions,-fuchsia-*,-google-default-arguments,-google-readability-todo,-google-runtime-references,-llvm-header-guard,-llvm-include-order,-misc-string-integer-assignment,-misc-string-literal-with-embedded-nul,-modernize-use-auto,-modernize-use-trailing-return-type,-readability-braces-around-statements,-readability-container-size-empty,-readability-delete-null-pointer,-readability-else-after-return,-readability-implicit-bool-conversion,-readability-named-parameter,-readability-static-accessed-through-instance' WarningsAsErrors: '' HeaderFilterRegex: '' FormatStyle: none CheckOptions: - key: google-readability-braces-around-statements.ShortStatementLines value: '2' - key: google-readability-namespace-comments.SpacesBeforeComments value: '2' verilator-5.020/LICENSE0000644000175000017500000001674414544475344014446 0ustar carstencarsten GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. verilator-5.020/codecov.yml0000644000175000017500000000150314544475344015571 0ustar carstencarsten# DESCRIPTION: codecov.io config # # Copyright 2020-2024 by Wilson Snyder. This program is free software; you # can redistribute it and/or modify it under the terms of either the GNU # Lesser General Public License Version 3 or the Perl Artistic License # Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 #################### # Validate: # curl --data-binary @codecov.yml https://codecov.io/validate codecov: require_ci_to_pass: no coverage: precision: 2 round: down range: "50...100" ignore: - "ci" - "docs" - "examples" - "include/gtkwave" - "include/vltstd" - "test_regress" parsers: gcov: branch_detection: conditional: yes loop: yes method: no macro: no comment: layout: "reach,diff,flags,tree" behavior: default require_changes: yes verilator-5.020/examples/0000755000175000017500000000000014544475344015243 5ustar carstencarstenverilator-5.020/examples/cmake_tracing_sc/0000755000175000017500000000000014544475344020517 5ustar carstencarstenverilator-5.020/examples/cmake_tracing_sc/CMakeLists.txt0000644000175000017500000000320314544475344023255 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake Example: Small CMakeLists.txt with SystemC tracing # # This is an example cmake script to build a verilog to SystemC project # using CMake and Verilator. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # This example builds the tracing_sc example using CMake # To use it, run the following: # cd /path/to/verilator/examples/cmake_tracing_sc # rm -rf build && mkdir build && cd build # cmake .. # cmake --build . cmake_minimum_required(VERSION 3.12) cmake_policy(SET CMP0074 NEW) project(cmake_tracing_sc_example CXX) find_package(verilator HINTS $ENV{VERILATOR_ROOT} ${VERILATOR_ROOT}) if (NOT verilator_FOUND) message(FATAL_ERROR "Verilator was not found. Either install it, or set the VERILATOR_ROOT environment variable") endif() # SystemC dependencies set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) # Find SystemC using SystemC's CMake integration find_package(SystemCLanguage QUIET) # Create a new executable target that will contain all your sources add_executable(example ../make_tracing_sc/sc_main.cpp) set_property( TARGET example PROPERTY CXX_STANDARD ${SystemC_CXX_STANDARD} ) # Add the Verilated circuit to the target verilate(example SYSTEMC COVERAGE TRACE INCLUDE_DIRS "../make_tracing_sc" VERILATOR_ARGS -f ../make_tracing_sc/input.vc -x-assign fast SOURCES ../make_tracing_sc/top.v) verilator_link_systemc(example) verilator-5.020/examples/cmake_tracing_sc/.gitignore0000644000175000017500000000005314544475344022505 0ustar carstencarsten*.dmp *.log *.csrc *.vcd obj_* logs build* verilator-5.020/examples/cmake_tracing_sc/Makefile0000644000175000017500000000676614544475344022176 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake example usage # # This file shows usage of the CMake script. # This makefile is here for testing the examples and should # generally not be added to a CMake project. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### ###################################################################### # Set up variables # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR_COVERAGE = verilator_coverage else export VERILATOR_ROOT VERILATOR_COVERAGE = $(VERILATOR_ROOT)/bin/verilator_coverage endif ###################################################################### # Check if CMake is installed and of correct version ifeq ($(shell which cmake),) TARGET := nocmake else CMAKE_VERSION := $(shell cmake --version | grep -Po '(\d[\.\d]+)') CMAKE_MAJOR := $(shell echo $(CMAKE_VERSION) | cut -f1 -d.) CMAKE_MINOR := $(shell echo $(CMAKE_VERSION) | cut -f2 -d.) CMAKE_GT_3_8 := $(shell [ $(CMAKE_MAJOR) -gt 3 -o \( $(CMAKE_MAJOR) -eq 3 -a $(CMAKE_MINOR) -ge 8 \) ] && echo true) ifneq ($(CMAKE_GT_3_8),true) TARGET := oldcmake else # Check if SC exists via a verilator call (empty if not) SYSTEMC_EXISTS := $(shell $(VERILATOR) --get-supported SYSTEMC) # Test whether SystemC is installed with CMake support # This will print a CMake error about processing arguments that can (currently) be ignored. ifneq (,$(SYSTEMC_EXISTS)) FINDSC := $(shell mkdir -p build && cd build && cmake --find-package -DNAME=SystemCLanguage -DCMAKE_USE_PTHREADS_INIT=ON -DCOMPILER_ID=GNU -DLANGUAGE=CXX -DMODE=EXIST -DThreads_FOUND=ON) ifneq (,$(findstring SystemCLanguage found,$(FINDSC))) SYSTEMC_SET := true endif endif ifeq ($(SYSTEMC_SET), true) TARGET := run else TARGET := nosc endif endif endif default: $(TARGET) run: @echo @echo "-- Verilator CMake SystemC tracing example" @echo @echo "-- VERILATE ----------------" mkdir -p build && cd build && cmake .. @echo @echo "-- BUILD -------------------" cmake --build build -j @echo @echo "-- RUN ---------------------" @mkdir -p logs build/example +trace @echo @echo "-- COVERAGE ----------------" $(VERILATOR_COVERAGE) --annotate logs/annotated logs/coverage.dat @echo @echo "-- DONE --------------------" @echo "To see waveforms, open vlt_dump.vcd in a waveform viewer" @echo clean mostlyclean distclean maintainer-clean: @rm -rf build logs nocmake: @echo @echo "%Skip: CMake has not been found" @echo oldcmake: @echo @echo "%Skip: CMake version is too old (need at least 3.8)" @echo nosc: @echo @echo "%Skip: CMake could not find SystemC." @echo "% Make sure that either:" @echo "% - The environment variables SYSTEMC_INCLUDE and SYSTEMC_LIBDIR are exported." @echo "% - Or, the environment variable SYSTEMC_ROOT is exported." @echo "% - Or, The environment variable SYSTEMC is exported." @echo "% - Or, if the SystemC installation provides CMake support," @echo "% that its installation prefix is in CMAKE_PREFIX_PATH." @echo "% Also that the C++ standard of the SystemC library is the same as this example." @echo "% Please see the Verilator documentation's CMake section for more information." @echo verilator-5.020/examples/cmake_hello_c/0000755000175000017500000000000014544475344020010 5ustar carstencarstenverilator-5.020/examples/cmake_hello_c/CMakeLists.txt0000644000175000017500000000232014544475344022545 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake Example: Small CMakeLists.txt # # This is an example cmake script to build a verilog to systemc project # using cmake and verilator. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # This example builds the tracing_c example using CMake # To use it, run the following: # cd /path/to/verilator/examples/cmake_c # rm -rf build && mkdir build && cd build # cmake .. # cmake --build . cmake_minimum_required(VERSION 3.12) cmake_policy(SET CMP0074 NEW) project(cmake_hello_c) find_package(verilator HINTS $ENV{VERILATOR_ROOT} ${VERILATOR_ROOT}) if (NOT verilator_FOUND) message(FATAL_ERROR "Verilator was not found. Either install it, or set the VERILATOR_ROOT environment variable") endif() # Create a new executable target that will contain all your sources add_executable(example ../make_hello_c/sim_main.cpp) # Add the Verilated circuit to the target verilate(example INCLUDE_DIRS "../make_hello_c" SOURCES ../make_hello_c/top.v) verilator-5.020/examples/cmake_hello_c/.gitignore0000644000175000017500000000000714544475344021775 0ustar carstencarstenbuild* verilator-5.020/examples/cmake_hello_c/Makefile0000644000175000017500000000407114544475344021452 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake example usage # # This file shows usage of the CMake script. # This makefile is here for testing the examples and should # generally not be added to a CMake project. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### ###################################################################### # Set up variables # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR_COVERAGE = verilator_coverage else export VERILATOR_ROOT VERILATOR_COVERAGE = $(VERILATOR_ROOT)/bin/verilator_coverage endif ###################################################################### # Check if CMake is installed and of correct version ifeq ($(shell which cmake),) TARGET := nocmake else CMAKE_VERSION := $(shell cmake --version | grep -Po '(\d[\.\d]+)') CMAKE_MAJOR := $(shell echo $(CMAKE_VERSION) | cut -f1 -d.) CMAKE_MINOR := $(shell echo $(CMAKE_VERSION) | cut -f2 -d.) CMAKE_GT_3_8 := $(shell [ $(CMAKE_MAJOR) -gt 3 -o \( $(CMAKE_MAJOR) -eq 3 -a $(CMAKE_MINOR) -ge 8 \) ] && echo true) ifeq ($(CMAKE_GT_3_8),true) TARGET := run else TARGET := oldcmake endif endif default: $(TARGET) run: @echo @echo "-- Verilator CMake hello world example" @echo @echo "-- VERILATE ----------------" mkdir -p build && cd build && cmake .. @echo @echo "-- BUILD -------------------" cmake --build build -j @echo @echo "-- RUN ---------------------" build/example @echo @echo "-- DONE --------------------" @echo clean mostlyclean distclean maintainer-clean: @rm -rf build logs nocmake: @echo @echo "%Skip: CMake has not been found" @echo oldcmake: @echo @echo "%Skip: CMake version is too old (need at least 3.8)" @echo verilator-5.020/examples/cmake_protect_lib/0000755000175000017500000000000014544475344020711 5ustar carstencarstenverilator-5.020/examples/cmake_protect_lib/CMakeLists.txt0000644000175000017500000000455214544475344023457 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake Example: Small CMakeLists.txt # # This is an example cmake script to build a verilog to systemc project # using cmake and verilator. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # This example builds the tracing_c example using CMake # To use it, run the following: # cd /path/to/verilator/examples/cmake_c # rm -rf build && mkdir build && cd build # cmake .. # cmake --build . cmake_minimum_required(VERSION 3.12) cmake_policy(SET CMP0074 NEW) project(cmake_protect_lib) find_package(verilator HINTS $ENV{VERILATOR_ROOT} ${VERILATOR_ROOT}) if (NOT verilator_FOUND) message(FATAL_ERROR "Verilator was not found. Either install it, or set the VERILATOR_ROOT environment variable") endif() # Create the main executable target add_executable(example ../make_protect_lib/sim_main.cpp) # Create a secret library add_library(verilated_secret STATIC) # or SHARED for a shared library target_link_libraries(example PRIVATE verilated_secret) # To create both libraries on CMake >= 3.12 replace the above 2 lines with the following: # add_library(verilated_secret OBJECT) # set_property(TARGET verilated_secret PROPERTY POSITION_INDEPENDENT_CODE 1) # add_library(verilated_secret_static STATIC $) # set_target_properties(verilated_secret_static PROPERTIES OUTPUT_NAME verilated_secret) # add_library(verilated_secret_shared SHARED $) # set_target_properties(verilated_secret_shared PROPERTIES OUTPUT_NAME verilated_secret) # target_link_libraries(example PRIVATE verilated_secret_static) # Setup random seed verilator_generate_key(KEY_INIT) set(PROTECT_KEY ${KEY_INIT} CACHE STRING "Random seed for protection") # Add the Verilated modules to the targets verilate(verilated_secret VERILATOR_ARGS --protect-lib verilated_secret --protect-key ${PROTECT_KEY} DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/verilated_secret SOURCES ../make_protect_lib/secret_impl.v) # Include location of verilated_secret.sv wrapper verilate(example VERILATOR_ARGS "-I${CMAKE_CURRENT_BINARY_DIR}/verilated_secret" SOURCES ../make_protect_lib/top.v) verilator-5.020/examples/cmake_protect_lib/.gitignore0000644000175000017500000000000714544475344022676 0ustar carstencarstenbuild* verilator-5.020/examples/cmake_protect_lib/Makefile0000644000175000017500000000407114544475344022353 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake example usage # # This file shows usage of the CMake script. # This makefile is here for testing the examples and should # generally not be added to a CMake project. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### ###################################################################### # Set up variables # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR_COVERAGE = verilator_coverage else export VERILATOR_ROOT VERILATOR_COVERAGE = $(VERILATOR_ROOT)/bin/verilator_coverage endif ###################################################################### # Check if CMake is installed and of correct version ifeq ($(shell which cmake),) TARGET := nocmake else CMAKE_VERSION := $(shell cmake --version | grep -Po '(\d[\.\d]+)') CMAKE_MAJOR := $(shell echo $(CMAKE_VERSION) | cut -f1 -d.) CMAKE_MINOR := $(shell echo $(CMAKE_VERSION) | cut -f2 -d.) CMAKE_GT_3_8 := $(shell [ $(CMAKE_MAJOR) -gt 3 -o \( $(CMAKE_MAJOR) -eq 3 -a $(CMAKE_MINOR) -ge 8 \) ] && echo true) ifeq ($(CMAKE_GT_3_8),true) TARGET := run else TARGET := oldcmake endif endif default: $(TARGET) run: @echo @echo "-- Verilator CMake protect_lib example" @echo @echo "-- VERILATE ----------------" mkdir -p build && cd build && cmake .. @echo @echo "-- BUILD -------------------" cmake --build build -j @echo @echo "-- RUN ---------------------" build/example @echo @echo "-- DONE --------------------" @echo clean mostlyclean distclean maintainer-clean: @rm -rf build logs nocmake: @echo @echo "%Skip: CMake has not been found" @echo oldcmake: @echo @echo "%Skip: CMake version is too old (need at least 3.8)" @echo verilator-5.020/examples/xml_py/0000755000175000017500000000000014544475344016553 5ustar carstencarstenverilator-5.020/examples/xml_py/sub.v0000644000175000017500000000070514544475344017535 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2019 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 // ====================================================================== module sub #(parameter type TYPE_t = logic) ( input TYPE_t in, output TYPE_t out ); // Some simple logic always_comb out = ~ in; endmodule verilator-5.020/examples/xml_py/vl_hier_graph0000755000175000017500000001275114544475344021320 0ustar carstencarsten#!/usr/bin/env python3 # -*- Python -*- See copyright, etc below # pylint: disable=C0103,C0114,C0115,C0115,C0116,C0209,R0914 ###################################################################### import argparse import os import subprocess import tempfile import xml.etree.ElementTree as ET # from pprint import pprint, pformat ####################################################################### class VlHierGraph: def __init__( self, verilator_args, # presently all verilator options are passed-thru debug=0, output_filename='graph.dot'): # output filename self.debug = debug self.next_vertex_number = 0 self.name_to_number = {} with tempfile.NamedTemporaryFile() as xml_temp: vargs = [ '--xml-output', xml_temp.name, '--bbox-sys', # Parse some stuff can't translate '--bbox-unsup', '--prefix vlxml' ] # So we know name of .xml output vargs += verilator_args self.run_verilator(vargs) self.tree = ET.parse(xml_temp.name) with open(output_filename, "w", encoding="utf8") as fh: # For more serious purposes, use the python graphviz package instead fh.write("digraph {\n") fh.write(" dpi=300;\n") fh.write(" order=LR;\n") fh.write( " node [fontsize=8 shape=\"box\" margin=0.01 width=0 height=0]" ) fh.write(" edge [fontsize=6]") # Find cells root = self.tree.getroot() netlist = root.find('netlist') for module in netlist.findall('module'): # origNames are before parameterization, name if after mod_name = module.get('name') mod_number = self.name_to_vertex_number(mod_name) fh.write(" n%d [label=\"%s\"" % (mod_number, mod_name)) if module.get('topModule'): fh.write(" color=\"red\" rank=1") fh.write("];\n") for instance in module.findall('instance'): inst_name = instance.get('name') def_name = instance.get('defName') def_number = self.name_to_vertex_number(def_name) fh.write(" n%d->n%d [label=\"%s\"];\n" % (mod_number, def_number, inst_name)) fh.write("}\n") def name_to_vertex_number(self, name): if name not in self.name_to_number: self.next_vertex_number += 1 self.name_to_number[name] = self.next_vertex_number return self.name_to_number[name] def run_verilator(self, vargs): """Run Verilator command, check errors""" if os.getenv("VERILATOR_ROOT"): command = os.getenv("VERILATOR_ROOT") + "/bin/verilator" else: command = "verilator" command += ' ' + ' '.join(vargs) if self.debug: print("\t%s " % command) status = subprocess.call(command, shell=True) if status != 0: raise RuntimeError("Command failed running Verilator with '" + command + "', stopped") ####################################################################### if __name__ == '__main__': parser = argparse.ArgumentParser( allow_abbrev=False, formatter_class=argparse.RawTextHelpFormatter, description= """Example of using Verilator XML output to create a .dot file showing the design module hierarchy. Example usage: vl_hier_graph -f input.vc top.v -o graph.dot dot -Tpdf -o graph.pdf graph.dot """, epilog="""All other arguments are pass-thru to Verilator: e.g.: +define+= Set preprocessor define -F Parse options from a file, relatively -f Parse options from a file -G= Overwrite toplevel parameter +incdir+ Directory to search for includes +libext++[ext]... Extensions for finding modules -v Verilog library -y Directory to search for modules This file ONLY is placed under the Creative Commons Public Domain, for any use, without warranty, 2019 by Wilson Snyder. SPDX-License-Identifier: CC0-1.0 """) parser.add_argument('-debug', '--debug', action='store_const', const=9, help='enable debug') parser.add_argument('-o', '--o', action='store', metavar='filename', required=True, help='output filename') (args, rem) = parser.parse_known_args() print( "NOTE: vl_hier_graph is only an example starting point for writing your own tool." ) # That is: # 1. We will accept basic patches # 2. We are not expecting to make this globally useful. (e.g. we don't cleanup obj_dir) # 3. "make install" will not install this. # 4. This has not had production-worthy validation. fc = VlHierGraph(output_filename=args.o, debug=args.debug, verilator_args=rem) ###################################################################### # Local Variables: # compile-command: "./vl_hier_graph -h ; VERILATOR_ROOT=$V4 ./vl_hier_graph +define+thru top.v" # End: verilator-5.020/examples/xml_py/vl_file_copy0000755000175000017500000001057314544475344021161 0ustar carstencarsten#!/usr/bin/env python3 # -*- Python -*- See copyright, etc below # pylint: disable=C0114,C0115,C0209,R0903 ###################################################################### import argparse import os import re import subprocess import tempfile import xml.etree.ElementTree as ET from shutil import copy2 # from pprint import pprint, pformat ####################################################################### class VlFileCopy: def __init__( self, verilator_args, # presently all verilator options are passed-thru debug=0, output_dir='copied'): # directory name we output file uses self.debug = debug with tempfile.NamedTemporaryFile() as xml_temp: vargs = [ '--xml-output', xml_temp.name, '--bbox-sys', # Parse some stuff can't translate '--bbox-unsup', '--prefix vlxml' ] # So we know name of .xml output vargs += verilator_args self.run_verilator(vargs) self.tree = ET.parse(xml_temp.name) os.makedirs(output_dir, 0o777, True) # Find and copy the files root = self.tree.getroot() xfiles = root.find('files') for xfile in xfiles.findall('file'): filename = xfile.get('filename') if not re.match('^<', filename): # e.g. if self.debug: print("\tcp %s %s" % (filename, output_dir)) copy2(filename, output_dir) def run_verilator(self, vargs): """Run Verilator command, check errors""" if os.getenv("VERILATOR_ROOT"): command = os.getenv("VERILATOR_ROOT") + "/bin/verilator" else: command = "verilator" command += ' ' + ' '.join(vargs) if self.debug: print("\t%s " % command) status = subprocess.call(command, shell=True) if status != 0: raise RuntimeError("Command failed running Verilator with '" + command + "', stopped") ####################################################################### if __name__ == '__main__': parser = argparse.ArgumentParser( allow_abbrev=False, formatter_class=argparse.RawTextHelpFormatter, description= """Example of using Verilator XML output to copy a list of files to an output directory (-odir, defaults to 'copied'), e.g. to easily create a tarball of the design to pass to others. Example usage: vl_file_copy -f input.vc top.v -odir mycopy # This will make at least mycopy/top.v """, epilog="""All other arguments are pass-thru to Verilator: e.g.: +define+= Set preprocessor define -F Parse options from a file, relatively -f Parse options from a file -G= Overwrite toplevel parameter +incdir+ Directory to search for includes +libext++[ext]... Extensions for finding modules -v Verilog library -y Directory to search for modules This file ONLY is placed under the Creative Commons Public Domain, for any use, without warranty, 2019 by Wilson Snyder. SPDX-License-Identifier: CC0-1.0 """) parser.add_argument('-debug', '--debug', action='store_const', const=9, help='enable debug') parser.add_argument('-odir', '--odir', action='store', metavar='directory', required=True, help='target output directory') (args, rem) = parser.parse_known_args() print( "NOTE: vl_file_copy is only an example starting point for writing your own tool." ) # That is: # 1. We will accept basic patches # 2. We are not expecting to make this globally useful. (e.g. we don't cleanup obj_dir) # 3. "make install" will not install this. # 4. This has not had production-worthy validation. fc = VlFileCopy(output_dir=args.odir, debug=args.debug, verilator_args=rem) ###################################################################### # Local Variables: # compile-command: "./vl_file_copy -h ; VERILATOR_ROOT=$V4 ./vl_file_copy +define+thru top.v" # End: verilator-5.020/examples/xml_py/.gitignore0000644000175000017500000000004514544475344020542 0ustar carstencarstenobj_* copied *.csv *.dot *.dmp *.pdf verilator-5.020/examples/xml_py/top.v0000644000175000017500000000153314544475344017546 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2019 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 // ====================================================================== module top ( input clk, input fastclk, input reset_l, output wire [1:0] out_small, output wire [39:0] out_quad, output wire [69:0] out_wide, input [1:0] in_small, input [39:0] in_quad, input [69:0] in_wide ); sub #(.TYPE_t(logic [1:0])) sub_small (.in(in_small), .out(out_small)); sub #(.TYPE_t(logic [39:0])) sub_quad (.in(in_quad), .out(out_quad)); sub #(.TYPE_t(logic [69:0])) sub_wide (.in(in_wide), .out(out_wide)); endmodule verilator-5.020/examples/xml_py/Makefile0000644000175000017500000000361014544475344020213 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator Example: XML tests # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # This makefile is not intended to be useful as an example itself, # it is just to run the small example scripts in this directory. # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR = verilator else export VERILATOR_ROOT VERILATOR = $(VERILATOR_ROOT)/bin/verilator endif DOT = dot PYTHON3 = python3 PYTHON_VERSION := $(shell ${PYTHON3} --version 2>&1) PYTHON_VERSION_FULL := $(wordlist 2,4,$(subst ., ,${PYTHON_VERSION})) PYTHON_VERSION_MAJOR := $(word 1,${PYTHON_VERSION_FULL}) PYTHON_VERSION_MINOR := $(word 2,${PYTHON_VERSION_FULL}) PYTHON_GE_3_5 := $(shell [ ${PYTHON_VERSION_MAJOR} -eq 3 -a ${PYTHON_VERSION_MINOR} -ge 5 ] && echo true) ifeq (${PYTHON_GE_3_5},true) default: test else default: python_message endif python_message: @echo "Found Python version ${PYTHON_VERSION}, but require >= 3.5" test: \ test-vl_file_copy \ test-vl_hier_graph \ test-vl_file_copy: @echo "-- vl_file_copy example" $(PYTHON3) vl_file_copy -odir copied top.v @cmp copied/top.v top.v @cmp copied/sub.v sub.v test-vl_hier_graph: @echo "-- vl_hier_graph example" $(PYTHON3) vl_hier_graph -o graph.dot top.v @echo "Manually run: " $(DOT) -Tpdf -o graph.pdf graph.dot ###################################################################### maintainer-copy:: clean mostlyclean distclean maintainer-clean:: -rm -rf obj_dir *.log *.csv *.dmp *.dot *.vpd *.pdf core copied verilator-5.020/examples/make_tracing_sc/0000755000175000017500000000000014544475344020354 5ustar carstencarstenverilator-5.020/examples/make_tracing_sc/sub.v0000644000175000017500000000306614544475344021341 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2003 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 // ====================================================================== module sub ( input clk, input fastclk, input reset_l ); // Example counter/flop reg [31:0] count_f; always_ff @ (posedge fastclk) begin if (!reset_l) begin /*AUTORESET*/ // Beginning of autoreset for uninitialized flops count_f <= 32'h0; // End of automatics end else begin count_f <= count_f + 1; end end // Another example flop reg [31:0] count_c; always_ff @ (posedge clk) begin if (!reset_l) begin /*AUTORESET*/ // Beginning of autoreset for uninitialized flops count_c <= 32'h0; // End of automatics end else begin count_c <= count_c + 1; if (count_c >= 3) begin $display("[%0t] fastclk is %0d times faster than clk\n", $time, count_f/count_c); // This write is a magic value the Makefile uses to make sure the // test completes successfully. $write("*-* All Finished *-*\n"); $finish; end end end // An example assertion always_ff @ (posedge clk) begin AssertionExample: assert(!reset_l || count_c<100); end // And example coverage analysis cover property (@(posedge clk) count_c==3); endmodule verilator-5.020/examples/make_tracing_sc/Makefile_obj0000644000175000017500000000433214544475344022650 0ustar carstencarsten# -*- Makefile -*- ####################################################################### # # DESCRIPTION: Verilator Example: Makefile for inside object directory # # This is executed in the object directory, and called by ../Makefile # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ####################################################################### default: Vtop # Include the rules made by Verilator include Vtop.mk # Use OBJCACHE (ccache) if using gmake and its installed COMPILE.cc = $(OBJCACHE) $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c ####################################################################### # Compile flags # Override some default compile flags CPPFLAGS += -MMD -MP CPPFLAGS += -DVL_DEBUG=1 # SystemC isn't too clean CPPFLAGS += -Wno-deprecated # Turn on some more flags (when configured appropriately) # For testing inside Verilator, "configure --enable-ccwarn" will do this # automatically; otherwise you may want this unconditionally enabled ifeq ($(CFG_WITH_CCWARN),yes) # Local... Else don't burden users USER_CPPFLAGS_WALL += -W -Werror -Wall endif # If you build your own rules from scratch, note you need to include # SystemC as follows (Vtop.mk file includes verilated.mk with these # already). # CPPFLAGS += $(SYSTEMC_CXX_FLAGS) $(addprefix -I, $(SYSTEMC_INCLUDE)) # LDFLAGS += $(SYSTEMC_CXX_FLAGS) $(addprefix -L, $(SYSTEMC_LIBDIR)) # See the benchmarking section of bin/verilator. # Support class optimizations. This includes the tracing and symbol table. # SystemC takes minutes to optimize, thus it is off by default. OPT_SLOW = # Fast path optimizations. Most time is spent in these classes. OPT_FAST = -Os -fstrict-aliasing #OPT_FAST = -O #OPT_FAST = ####################################################################### # Linking final exe -- presumes have a sim_main.cpp # Special compile rule sim_main.o: sim_main.cpp $(VM_PREFIX).h ###################################################################### ###################################################################### # Automatically understand dependencies DEPS := $(wildcard *.d) ifneq ($(DEPS),) include $(DEPS) endif verilator-5.020/examples/make_tracing_sc/input.vc0000644000175000017500000000020114544475344022036 0ustar carstencarsten// This file typically lists flags required by a large project, e.g. include directories +librescan +libext+.v+.sv+.vh+.svh -y . verilator-5.020/examples/make_tracing_sc/sc_main.cpp0000644000175000017500000001014314544475344022470 0ustar carstencarsten// -*- SystemC -*- // DESCRIPTION: Verilator Example: Top level main for invoking SystemC model // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2017 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 //====================================================================== // For std::unique_ptr #include // SystemC global header #include // Include common routines #include #if VM_TRACE #include #endif #include // mkdir // Include model header, generated from Verilating "top.v" #include "Vtop.h" using namespace sc_core; using namespace sc_dt; int sc_main(int argc, char* argv[]) { // This is a more complicated example, please also see the simpler examples/make_hello_c. // Prevent unused variable warnings if (false && argc && argv) {} // Create logs/ directory in case we have traces to put under it Verilated::mkdir("logs"); // Set debug level, 0 is off, 9 is highest presently used // May be overridden by commandArgs argument parsing Verilated::debug(0); // Randomization reset policy // May be overridden by commandArgs argument parsing Verilated::randReset(2); #if VM_TRACE // Before any evaluation, need to know to calculate those signals only used for tracing Verilated::traceEverOn(true); #endif // Pass arguments so Verilated code can see them, e.g. $value$plusargs // This needs to be called before you create any model Verilated::commandArgs(argc, argv); // General logfile std::ios::sync_with_stdio(); // Define clocks sc_clock clk{"clk", 10, SC_NS, 0.5, 3, SC_NS, true}; sc_clock fastclk{"fastclk", 2, SC_NS, 0.5, 2, SC_NS, true}; // Define interconnect sc_signal reset_l; sc_signal in_small; sc_signal in_quad; sc_signal> in_wide; sc_signal out_small; sc_signal out_quad; sc_signal> out_wide; // Construct the Verilated model, from inside Vtop.h // Using unique_ptr is similar to "Vtop* top = new Vtop" then deleting at end const std::unique_ptr top{new Vtop{"top"}}; // Attach Vtop's signals to this upper model top->clk(clk); top->fastclk(fastclk); top->reset_l(reset_l); top->in_small(in_small); top->in_quad(in_quad); top->in_wide(in_wide); top->out_small(out_small); top->out_quad(out_quad); top->out_wide(out_wide); // You must do one evaluation before enabling waves, in order to allow // SystemC to interconnect everything for testing. sc_start(SC_ZERO_TIME); #if VM_TRACE // If verilator was invoked with --trace argument, // and if at run time passed the +trace argument, turn on tracing VerilatedVcdSc* tfp = nullptr; const char* flag = Verilated::commandArgsPlusMatch("trace"); if (flag && 0 == std::strcmp(flag, "+trace")) { std::cout << "Enabling waves into logs/vlt_dump.vcd...\n"; tfp = new VerilatedVcdSc; top->trace(tfp, 99); // Trace 99 levels of hierarchy Verilated::mkdir("logs"); tfp->open("logs/vlt_dump.vcd"); } #endif // Simulate until $finish while (!Verilated::gotFinish()) { #if VM_TRACE // Flush the wave files each cycle so we can immediately see the output // Don't do this in "real" programs, do it in an abort() handler instead if (tfp) tfp->flush(); #endif // Apply inputs if (sc_time_stamp() > sc_time(1, SC_NS) && sc_time_stamp() < sc_time(10, SC_NS)) { reset_l = !1; // Assert reset } else { reset_l = !0; // Deassert reset } // Simulate 1ns sc_start(1, SC_NS); } // Final model cleanup top->final(); // Close trace if opened #if VM_TRACE if (tfp) { tfp->close(); tfp = nullptr; } #endif // Coverage analysis (calling write only after the test is known to pass) #if VM_COVERAGE Verilated::mkdir("logs"); VerilatedCov::write("logs/coverage.dat"); #endif // Return good completion status return 0; } verilator-5.020/examples/make_tracing_sc/.gitignore0000644000175000017500000000004414544475344022342 0ustar carstencarsten*.dmp *.log *.csrc *.vcd obj_* logs verilator-5.020/examples/make_tracing_sc/top.v0000644000175000017500000000254514544475344021353 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2003 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 // ====================================================================== // This is intended to be a complex example of several features, please also // see the simpler examples/make_hello_c. module top ( // Declare some signals so we can see how I/O works input clk, input fastclk, input reset_l, output wire [1:0] out_small, output wire [39:0] out_quad, output wire [69:0] out_wide, input [1:0] in_small, input [39:0] in_quad, input [69:0] in_wide ); // Connect up the outputs, using some trivial logic assign out_small = ~reset_l ? '0 : (in_small + 2'b1); assign out_quad = ~reset_l ? '0 : (in_quad + 40'b1); assign out_wide = ~reset_l ? '0 : (in_wide + 70'b1); // And an example sub module. The submodule will print stuff. sub sub (/*AUTOINST*/ // Inputs .clk (clk), .fastclk (fastclk), .reset_l (reset_l)); // Print some stuff as an example initial begin $display("[%0t] Model running...\n", $time); end endmodule verilator-5.020/examples/make_tracing_sc/Makefile0000644000175000017500000000650314544475344022020 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator Example: Small Makefile # # This calls the object directory makefile. That allows the objects to # be placed in the "current directory" which simplifies the Makefile. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # Check for sanity to avoid later confusion ifneq ($(words $(CURDIR)),1) $(error Unsupported: GNU Make cannot build in directories containing spaces, build elsewhere: '$(CURDIR)') endif ###################################################################### # Set up variables # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR = verilator VERILATOR_COVERAGE = verilator_coverage else export VERILATOR_ROOT VERILATOR = $(VERILATOR_ROOT)/bin/verilator VERILATOR_COVERAGE = $(VERILATOR_ROOT)/bin/verilator_coverage endif VERILATOR_FLAGS = # Generate SystemC in executable form VERILATOR_FLAGS += -sc --exe # Generate makefile dependencies (not shown as complicates the Makefile) #VERILATOR_FLAGS += -MMD # Optimize VERILATOR_FLAGS += -x-assign fast # Warn abount lint issues; may not want this on less solid designs VERILATOR_FLAGS += -Wall # Make waveforms VERILATOR_FLAGS += --trace # Check SystemVerilog assertions VERILATOR_FLAGS += --assert # Generate coverage analysis VERILATOR_FLAGS += --coverage # Run Verilator in debug mode #VERILATOR_FLAGS += --debug # Add this trace to get a backtrace in gdb #VERILATOR_FLAGS += --gdbbt # Input files for Verilator VERILATOR_INPUT = -f input.vc top.v sc_main.cpp # Check if SC exists via a verilator call (empty if not) SYSTEMC_EXISTS := $(shell $(VERILATOR) --get-supported SYSTEMC) ###################################################################### ifneq ($(SYSTEMC_EXISTS),) default: run else default: nosc endif run: @echo @echo "-- Verilator tracing example" @echo @echo "-- VERILATE ----------------" $(VERILATOR) $(VERILATOR_FLAGS) $(VERILATOR_INPUT) @echo @echo "-- COMPILE -----------------" # To compile, we can either # 1. Pass --build to Verilator by editing VERILATOR_FLAGS above. # 2. Or, run the make rules Verilator does: # $(MAKE) -j -C obj_dir -f Vtop.mk # 3. Or, call a submakefile where we can override the rules ourselves: $(MAKE) -j -C obj_dir -f ../Makefile_obj @echo @echo "-- RUN ---------------------" @rm -rf logs @mkdir -p logs obj_dir/Vtop +trace @echo @echo "-- COVERAGE ----------------" @rm -rf logs/annotated $(VERILATOR_COVERAGE) --annotate logs/annotated logs/coverage.dat @echo @echo "-- DONE --------------------" @echo "To see waveforms, open vlt_dump.vcd in a waveform viewer" @echo ###################################################################### # Other targets nosc: @echo @echo "%Skip: SYSTEMC_INCLUDE not in environment" @echo "(If you have SystemC see the README, and rebuild Verilator)" @echo show-config: $(VERILATOR) -V maintainer-copy:: clean mostlyclean distclean maintainer-clean:: -rm -rf obj_dir logs *.log *.dmp *.vpd coverage.dat core verilator-5.020/examples/cmake_tracing_c/0000755000175000017500000000000014544475344020334 5ustar carstencarstenverilator-5.020/examples/cmake_tracing_c/CMakeLists.txt0000644000175000017500000000247714544475344023106 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake Example: Small CMakeLists.txt with tracing # # This is an example cmake script to build a verilog to systemc project # using cmake and verilator. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # This example builds the make_tracing_c example using CMake # To use it, run the following: # cd /path/to/verilator/examples/cmake_tracing_c # rm -rf build && mkdir build && cd build # cmake .. # cmake --build . cmake_minimum_required(VERSION 3.12) cmake_policy(SET CMP0074 NEW) project(cmake_tracing_c) find_package(verilator HINTS $ENV{VERILATOR_ROOT} ${VERILATOR_ROOT}) if (NOT verilator_FOUND) message(FATAL_ERROR "Verilator was not found. Either install it, or set the VERILATOR_ROOT environment variable") endif() # Create a new executable target that will contain all your sources add_executable(example ../make_tracing_c/sim_main.cpp) # Add the Verilated circuit to the target verilate(example COVERAGE TRACE INCLUDE_DIRS "../make_tracing_c" VERILATOR_ARGS -f ../make_tracing_c/input.vc -x-assign fast SOURCES ../make_tracing_c/top.v) verilator-5.020/examples/cmake_tracing_c/.gitignore0000644000175000017500000000001414544475344022317 0ustar carstencarstenbuild* logs verilator-5.020/examples/cmake_tracing_c/Makefile0000644000175000017500000000437714544475344022007 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake example usage # # This file shows usage of the CMake script. # This makefile is here for testing the examples and should # generally not be added to a CMake project. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### ###################################################################### # Set up variables # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR_COVERAGE = verilator_coverage else export VERILATOR_ROOT VERILATOR_COVERAGE = $(VERILATOR_ROOT)/bin/verilator_coverage endif ###################################################################### # Check if CMake is installed and of correct version ifeq ($(shell which cmake),) TARGET := nocmake else CMAKE_VERSION := $(shell cmake --version | grep -Po '(\d[\.\d]+)') CMAKE_MAJOR := $(shell echo $(CMAKE_VERSION) | cut -f1 -d.) CMAKE_MINOR := $(shell echo $(CMAKE_VERSION) | cut -f2 -d.) CMAKE_GT_3_8 := $(shell [ $(CMAKE_MAJOR) -gt 3 -o \( $(CMAKE_MAJOR) -eq 3 -a $(CMAKE_MINOR) -ge 8 \) ] && echo true) ifeq ($(CMAKE_GT_3_8),true) TARGET := run else TARGET := oldcmake endif endif default: $(TARGET) run: @echo @echo "-- Verilator CMake tracing example" @echo @echo "-- VERILATE ----------------" mkdir -p build && cd build && cmake .. @echo @echo "-- BUILD -------------------" cmake --build build -j @echo @echo "-- RUN ---------------------" @mkdir -p logs build/example +trace @echo @echo "-- COVERAGE ----------------" $(VERILATOR_COVERAGE) --annotate logs/annotated logs/coverage.dat @echo @echo "-- DONE --------------------" @echo "To see waveforms, open vlt_dump.vcd in a waveform viewer" @echo clean mostlyclean distclean maintainer-clean: @rm -rf build logs nocmake: @echo @echo "%Skip: CMake has not been found" @echo oldcmake: @echo @echo "%Skip: CMake version is too old (need at least 3.8)" @echo verilator-5.020/examples/make_protect_lib/0000755000175000017500000000000014544475344020546 5ustar carstencarstenverilator-5.020/examples/make_protect_lib/secret_impl.v0000644000175000017500000000135514544475344023247 0ustar carstencarsten// DESCRIPTION: Verilator: --protect-lib example secret module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2019 by Todd Strader. // SPDX-License-Identifier: CC0-1.0 // This module will be used as libsecret.a or libsecret.so without // exposing the source. module secret_impl ( input [31:0] a, input [31:0] b, output logic [31:0] x, input clk); logic [31:0] accum_q = 0; logic [31:0] secret_value = 9; initial $display("[%0t] %m: initialized", $time); always @(posedge clk) begin accum_q <= accum_q + a; if (accum_q > 10) x <= b; else x <= a + b + secret_value; end endmodule verilator-5.020/examples/make_protect_lib/.gitignore0000644000175000017500000000001314544475344022530 0ustar carstencarstenobj_* logs verilator-5.020/examples/make_protect_lib/top.v0000644000175000017500000000155214544475344021542 0ustar carstencarsten// DESCRIPTION: Verilator: --protect-lib example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2019 by Todd Strader. // SPDX-License-Identifier: CC0-1.0 // See also https://verilator.org/guide/latest/examples.html" module top (input clk); integer cyc = 0; logic [31:0] a = 0; logic [31:0] b = 0; logic [31:0] x; verilated_secret secret (.a, .b, .x, .clk); always @(posedge clk) begin $display("[%0t] cyc=%0d a=%0d b=%0d x=%0d", $time, cyc, a, b, x); cyc <= cyc + 1; if (cyc == 0) begin a <= 5; b <= 7; end else if (cyc == 1) begin a <= 6; b <= 2; end else if (cyc == 2) begin a <= 1; b <= 9; end else if (cyc > 3) begin $display("Done"); $finish; end end endmodule verilator-5.020/examples/make_protect_lib/Makefile0000644000175000017500000000723214544475344022212 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator Example: --protect-lib Makefile # # This calls the object directory makefiles. That allows the objects to # be placed in the "current directory" which simplifies the Makefile. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # Check for sanity to avoid later confusion ifneq ($(words $(CURDIR)),1) $(error Unsupported: GNU Make cannot build in directories containing spaces, build elsewhere: '$(CURDIR)') endif ###################################################################### # Set up variables # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR = verilator else export VERILATOR_ROOT VERILATOR = $(VERILATOR_ROOT)/bin/verilator endif VERILATOR_FLAGS = # Generate C++ VERILATOR_FLAGS += -cc # Optimize VERILATOR_FLAGS += -x-assign fast # Warn abount lint issues; may not want this on less solid designs VERILATOR_FLAGS += -Wall # This example does not use vl_time_stamp but rather # VerilatedContext::timeInc(), so to avoid a linker error on cygwin which # does not support weak symbols, we need to define VL_TIME_CONTEXT *in CPP* # to not compile in the vl_time_stamp using code. VERILATOR_FLAGS += -CFLAGS -DVL_TIME_CONTEXT # Make waveforms TOP_VERILATOR_FLAGS = $(VERILATOR_FLAGS) --trace ###################################################################### default: run run: @echo @echo "-- Verilator --protect-lib example -_--------------------------" @echo @echo "-- VERILATE secret module -------------------------------------" @echo " --protect-lib will produce both a static and shared library" @echo " In this example the static library is used, but some" @echo " simulators may require the shared library." @echo "---------------------------------------------------------------" $(VERILATOR) $(VERILATOR_FLAGS) --protect-lib verilated_secret -Mdir obj_dir_secret/ secret_impl.v @echo @echo "-- COMPILE protected library ----------------------------------" @echo " This builds verilated_secret.sv, libverilated_secret.a and" @echo " libverilated_secret.so which can be distributed apart from" @echo " the source" @echo "---------------------------------------------------------------" $(MAKE) -j 4 -C obj_dir_secret -f Vsecret_impl.mk @echo @echo "-- VERILATE top module ----------------------------------------" @echo " Use the SystemVerilog wrapper (verilated_secret.sv) and the" @echo " library (libverilated_secret.a) generated from the previous" @echo " step" @echo "---------------------------------------------------------------" $(VERILATOR) $(TOP_VERILATOR_FLAGS) --exe -LDFLAGS '../obj_dir_secret/libverilated_secret.a' top.v obj_dir_secret/verilated_secret.sv sim_main.cpp @echo @echo "-- COMPILE entire design --------------------------------------" $(MAKE) -j 4 -C obj_dir -f Vtop.mk @echo @echo "-- RUN --------------------------------------------------------" @mkdir -p logs obj_dir/Vtop +trace @echo @echo "-- DONE -------------------------------------------------------" @echo "To see waveforms, open logs/vlt_dump.vcd in a waveform viewer" @echo ###################################################################### # Other targets show-config: $(VERILATOR) -V maintainer-copy:: clean mostlyclean distclean maintainer-clean:: -rm -rf obj_dir* logs *.log core verilator-5.020/examples/make_protect_lib/sim_main.cpp0000644000175000017500000000362514544475344023054 0ustar carstencarsten// DESCRIPTION: Verilator: --protect-lib example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2019 by Todd Strader. // SPDX-License-Identifier: CC0-1.0 //====================================================================== // See examples/tracing_c for notes on tracing // Include common routines #include #include "Vtop.h" #if VM_TRACE #include #endif int main(int argc, char** argv) { if (false && argc && argv) {} // Construct context to hold simulation time, etc VerilatedContext* contextp = new VerilatedContext; contextp->debug(0); contextp->randReset(2); contextp->commandArgs(argc, argv); // Construct the Verilated model, including the secret module Vtop* top = new Vtop{contextp}; #if VM_TRACE // When tracing, the contents of the secret module will not be seen VerilatedVcdC* tfp = nullptr; const char* flag = contextp->commandArgsPlusMatch("trace"); if (flag && 0 == std::strcmp(flag, "+trace")) { contextp->traceEverOn(true); VL_PRINTF("Enabling waves into logs/vlt_dump.vcd...\n"); tfp = new VerilatedVcdC; top->trace(tfp, 99); Verilated::mkdir("logs"); tfp->open("logs/vlt_dump.vcd"); } #endif top->clk = 0; // Simulate until $finish while (!contextp->gotFinish()) { contextp->timeInc(1); top->clk = ~top->clk & 0x1; top->eval(); #if VM_TRACE if (tfp) tfp->dump(contextp->time()); #endif } // Final model cleanup top->final(); // Close trace if opened #if VM_TRACE if (tfp) { tfp->close(); tfp = nullptr; } #endif // Destroy model delete top; top = nullptr; delete contextp; contextp = nullptr; // Return good completion status // Don't use exit() or destructor won't get called return 0; } verilator-5.020/examples/cmake_hello_sc/0000755000175000017500000000000014544475344020173 5ustar carstencarstenverilator-5.020/examples/cmake_hello_sc/CMakeLists.txt0000644000175000017500000000302414544475344022732 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake Example: Small CMakeLists.txt with SystemC # # This is an example cmake script to build a verilog to SystemC project # using CMake and Verilator. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # This example builds the tracing_sc example using CMake # To use it, run the following: # cd /path/to/verilator/examples/cmake_sc # rm -rf build && mkdir build && cd build # cmake .. # cmake --build . cmake_minimum_required(VERSION 3.12) cmake_policy(SET CMP0074 NEW) project(cmake_hello_sc CXX) find_package(verilator HINTS $ENV{VERILATOR_ROOT} ${VERILATOR_ROOT}) if (NOT verilator_FOUND) message(FATAL_ERROR "Verilator was not found. Either install it, or set the VERILATOR_ROOT environment variable") endif() # SystemC dependencies set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) # Find SystemC using SystemC's CMake integration find_package(SystemCLanguage QUIET) # Create a new executable target that will contain all your sources add_executable(example ../make_hello_sc/sc_main.cpp) set_property( TARGET example PROPERTY CXX_STANDARD ${SystemC_CXX_STANDARD} ) # Add the Verilated circuit to the target verilate(example SYSTEMC INCLUDE_DIRS "../make_hello_sc" SOURCES ../make_hello_sc/top.v) verilator_link_systemc(example) verilator-5.020/examples/cmake_hello_sc/.gitignore0000644000175000017500000000000714544475344022160 0ustar carstencarstenbuild* verilator-5.020/examples/cmake_hello_sc/Makefile0000644000175000017500000000672114544475344021641 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator CMake example usage # # This file shows usage of the CMake script. # This makefile is here for testing the examples and should # generally not be added to a CMake project. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### ###################################################################### # Set up variables # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR_COVERAGE = verilator_coverage else export VERILATOR_ROOT VERILATOR_COVERAGE = $(VERILATOR_ROOT)/bin/verilator_coverage endif ###################################################################### # Check if CMake is installed and of correct version ifeq ($(shell which cmake),) TARGET := nocmake else CMAKE_VERSION := $(shell cmake --version | grep -Po '(\d[\.\d]+)') CMAKE_MAJOR := $(shell echo $(CMAKE_VERSION) | cut -f1 -d.) CMAKE_MINOR := $(shell echo $(CMAKE_VERSION) | cut -f2 -d.) CMAKE_GT_3_8 := $(shell [ $(CMAKE_MAJOR) -gt 3 -o \( $(CMAKE_MAJOR) -eq 3 -a $(CMAKE_MINOR) -ge 8 \) ] && echo true) ifneq ($(CMAKE_GT_3_8),true) TARGET := oldcmake else # Check if SC exists via a verilator call (empty if not) SYSTEMC_EXISTS := $(shell $(VERILATOR) --get-supported SYSTEMC) # Test whether SystemC is installed with CMake support # This will print a CMake error about processing arguments that can (currently) be ignored. ifneq (,$(SYSTEMC_EXISTS)) FINDSC := $(shell mkdir -p build && cd build && cmake --find-package -DNAME=SystemCLanguage -DCMAKE_USE_PTHREADS_INIT=ON -DCOMPILER_ID=GNU -DLANGUAGE=CXX -DMODE=EXIST -DThreads_FOUND=ON) ifneq (,$(findstring SystemCLanguage found,$(FINDSC))) SYSTEMC_SET := true endif endif ifeq ($(SYSTEMC_SET), true) TARGET := run else TARGET := nosc endif endif endif default: $(TARGET) run: @echo @echo "-- Verilator CMake SystemC hello-world simple example" @echo @echo "-- VERILATE ----------------" mkdir -p build && cd build && cmake .. @echo @echo "-- BUILD -------------------" cmake --build build -j @echo @echo "-- RUN ---------------------" @mkdir -p logs build/example @echo "-- DONE --------------------" @echo "Note: Once this example is understood, see examples/cmake_tracing_sc." @echo "Note: See also https://verilator.org/guide/latest/examples.html" clean mostlyclean distclean maintainer-clean: @rm -rf build logs nocmake: @echo @echo "%Skip: CMake has not been found" @echo oldcmake: @echo @echo "%Skip: CMake version is too old (need at least 3.8)" @echo nosc: @echo @echo "%Skip: CMake could not find SystemC." @echo "% Make sure that either:" @echo "% - The environment variables SYSTEMC_INCLUDE and SYSTEMC_LIBDIR are exported." @echo "% - Or, the environment variable SYSTEMC_ROOT is exported." @echo "% - Or, The environment variable SYSTEMC is exported." @echo "% - Or, if the SystemC installation provides CMake support," @echo "% that its installation prefix is in CMAKE_PREFIX_PATH." @echo "% Also that the C++ standard of the SystemC library is the same as this example." @echo "% Please see the Verilator documentation's CMake section for more information." @echo verilator-5.020/examples/make_hello_c/0000755000175000017500000000000014544475344017645 5ustar carstencarstenverilator-5.020/examples/make_hello_c/.gitignore0000644000175000017500000000004414544475344021633 0ustar carstencarsten*.dmp *.log *.csrc *.vcd obj_* logs verilator-5.020/examples/make_hello_c/top.v0000644000175000017500000000056514544475344020644 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2017 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 // See also https://verilator.org/guide/latest/examples.html" module top; initial begin $display("Hello World!"); $finish; end endmodule verilator-5.020/examples/make_hello_c/Makefile0000644000175000017500000000347314544475344021314 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator Example: Small Makefile # # This calls the object directory makefile. That allows the objects to # be placed in the "current directory" which simplifies the Makefile. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # Check for sanity to avoid later confusion ifneq ($(words $(CURDIR)),1) $(error Unsupported: GNU Make cannot build in directories containing spaces, build elsewhere: '$(CURDIR)') endif ###################################################################### # This is intended to be a minimal example. Before copying this to start a # real project, it is better to start with a more complete example, # e.g. examples/make_tracing_c. # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR = verilator else export VERILATOR_ROOT VERILATOR = $(VERILATOR_ROOT)/bin/verilator endif default: @echo "-- Verilator hello-world simple example" @echo "-- VERILATE & BUILD --------" $(VERILATOR) -cc --exe --build -j top.v sim_main.cpp @echo "-- RUN ---------------------" obj_dir/Vtop @echo "-- DONE --------------------" @echo "Note: Once this example is understood, see examples/make_tracing_c." @echo "Note: See also https://verilator.org/guide/latest/examples.html" ###################################################################### maintainer-copy:: clean mostlyclean distclean maintainer-clean:: -rm -rf obj_dir *.log *.dmp *.vpd core verilator-5.020/examples/make_hello_c/sim_main.cpp0000644000175000017500000000255014544475344022147 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2017 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 //====================================================================== // Include common routines #include // Include model header, generated from Verilating "top.v" #include "Vtop.h" int main(int argc, char** argv) { // See a similar example walkthrough in the verilator manpage. // This is intended to be a minimal example. Before copying this to start a // real project, it is better to start with a more complete example, // e.g. examples/c_tracing. // Construct a VerilatedContext to hold simulation time, etc. VerilatedContext* contextp = new VerilatedContext; // Pass arguments so Verilated code can see them, e.g. $value$plusargs // This needs to be called before you create any model contextp->commandArgs(argc, argv); // Construct the Verilated model, from Vtop.h generated from Verilating "top.v" Vtop* top = new Vtop{contextp}; // Simulate until $finish while (!contextp->gotFinish()) { // Evaluate model top->eval(); } // Final model cleanup top->final(); // Destroy model delete top; // Return good completion status return 0; } verilator-5.020/examples/make_tracing_c/0000755000175000017500000000000014544475344020171 5ustar carstencarstenverilator-5.020/examples/make_tracing_c/sub.v0000644000175000017500000000214614544475344021154 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog Test module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2003 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 // ====================================================================== module sub ( input clk, input reset_l ); // Example counter/flop reg [31:0] count_c; always_ff @ (posedge clk) begin if (!reset_l) begin /*AUTORESET*/ // Beginning of autoreset for uninitialized flops count_c <= 32'h0; // End of automatics end else begin count_c <= count_c + 1; if (count_c >= 3) begin // This write is a magic value the Makefile uses to make sure the // test completes successfully. $write("*-* All Finished *-*\n"); $finish; end end end // An example assertion always_ff @ (posedge clk) begin AssertionExample: assert (!reset_l || count_c<100); end // And example coverage analysis cover property (@(posedge clk) count_c==3); endmodule verilator-5.020/examples/make_tracing_c/Makefile_obj0000644000175000017500000000343714544475344022472 0ustar carstencarsten# -*- Makefile -*- ####################################################################### # # DESCRIPTION: Verilator Example: Makefile for inside object directory # # This is executed in the object directory, and called by ../Makefile # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ####################################################################### default: Vtop # Include the rules made by Verilator include Vtop.mk # Use OBJCACHE (ccache) if using gmake and its installed COMPILE.cc = $(OBJCACHE) $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c ####################################################################### # Compile flags # Turn on creating .d make dependency files CPPFLAGS += -MMD -MP # Compile in Verilator runtime debugging, so +verilator+debug works CPPFLAGS += -DVL_DEBUG=1 # Turn on some more compiler lint flags (when configured appropriately) # For testing inside Verilator, "configure --enable-ccwarn" will do this # automatically; otherwise you may want this unconditionally enabled ifeq ($(CFG_WITH_CCWARN),yes) # Local... Else don't burden users USER_CPPFLAGS_WALL += -W -Werror -Wall endif # See the benchmarking section of bin/verilator. # Support class optimizations. This includes the tracing and symbol table. # SystemC takes minutes to optimize, thus it is off by default. OPT_SLOW = # Fast path optimizations. Most time is spent in these classes. OPT_FAST = -Os -fstrict-aliasing #OPT_FAST = -O #OPT_FAST = ###################################################################### ###################################################################### # Automatically understand dependencies DEPS := $(wildcard *.d) ifneq ($(DEPS),) include $(DEPS) endif verilator-5.020/examples/make_tracing_c/input.vc0000644000175000017500000000020114544475344021653 0ustar carstencarsten// This file typically lists flags required by a large project, e.g. include directories +librescan +libext+.v+.sv+.vh+.svh -y . verilator-5.020/examples/make_tracing_c/.gitignore0000644000175000017500000000004414544475344022157 0ustar carstencarsten*.dmp *.log *.csrc *.vcd obj_* logs verilator-5.020/examples/make_tracing_c/top.v0000644000175000017500000000271714544475344021171 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2003 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 // ====================================================================== // This is intended to be a complex example of several features, please also // see the simpler examples/make_hello_c. module top ( // Declare some signals so we can see how I/O works input clk, input reset_l, output wire [1:0] out_small, output wire [39:0] out_quad, output wire [69:0] out_wide, input [1:0] in_small, input [39:0] in_quad, input [69:0] in_wide ); // Connect up the outputs, using some trivial logic assign out_small = ~reset_l ? '0 : (in_small + 2'b1); assign out_quad = ~reset_l ? '0 : (in_quad + 40'b1); assign out_wide = ~reset_l ? '0 : (in_wide + 70'b1); // And an example sub module. The submodule will print stuff. sub sub (/*AUTOINST*/ // Inputs .clk (clk), .reset_l (reset_l)); // Print some stuff as an example initial begin if ($test$plusargs("trace") != 0) begin $display("[%0t] Tracing to logs/vlt_dump.vcd...\n", $time); $dumpfile("logs/vlt_dump.vcd"); $dumpvars(); end $display("[%0t] Model running...\n", $time); end endmodule verilator-5.020/examples/make_tracing_c/Makefile0000644000175000017500000000576214544475344021643 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator Example: Small Makefile # # This calls the object directory makefile. That allows the objects to # be placed in the "current directory" which simplifies the Makefile. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # Check for sanity to avoid later confusion ifneq ($(words $(CURDIR)),1) $(error Unsupported: GNU Make cannot build in directories containing spaces, build elsewhere: '$(CURDIR)') endif ###################################################################### # Set up variables # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR = verilator VERILATOR_COVERAGE = verilator_coverage else export VERILATOR_ROOT VERILATOR = $(VERILATOR_ROOT)/bin/verilator VERILATOR_COVERAGE = $(VERILATOR_ROOT)/bin/verilator_coverage endif # Generate C++ in executable form VERILATOR_FLAGS += -cc --exe # Generate makefile dependencies (not shown as complicates the Makefile) #VERILATOR_FLAGS += -MMD # Optimize VERILATOR_FLAGS += -x-assign fast # Warn abount lint issues; may not want this on less solid designs VERILATOR_FLAGS += -Wall # Make waveforms VERILATOR_FLAGS += --trace # Check SystemVerilog assertions VERILATOR_FLAGS += --assert # Generate coverage analysis VERILATOR_FLAGS += --coverage # Run Verilator in debug mode #VERILATOR_FLAGS += --debug # Add this trace to get a backtrace in gdb #VERILATOR_FLAGS += --gdbbt # Input files for Verilator VERILATOR_INPUT = -f input.vc top.v sim_main.cpp ###################################################################### default: run run: @echo @echo "-- Verilator tracing example" @echo @echo "-- VERILATE ----------------" $(VERILATOR) $(VERILATOR_FLAGS) $(VERILATOR_INPUT) @echo @echo "-- BUILD -------------------" # To compile, we can either # 1. Pass --build to Verilator by editing VERILATOR_FLAGS above. # 2. Or, run the make rules Verilator does: # $(MAKE) -j -C obj_dir -f Vtop.mk # 3. Or, call a submakefile where we can override the rules ourselves: $(MAKE) -j -C obj_dir -f ../Makefile_obj @echo @echo "-- RUN ---------------------" @rm -rf logs @mkdir -p logs obj_dir/Vtop +trace @echo @echo "-- COVERAGE ----------------" @rm -rf logs/annotated $(VERILATOR_COVERAGE) --annotate logs/annotated logs/coverage.dat @echo @echo "-- DONE --------------------" @echo "To see waveforms, open vlt_dump.vcd in a waveform viewer" @echo ###################################################################### # Other targets show-config: $(VERILATOR) -V maintainer-copy:: clean mostlyclean distclean maintainer-clean:: -rm -rf obj_dir logs *.log *.dmp *.vpd coverage.dat core verilator-5.020/examples/make_tracing_c/sim_main.cpp0000644000175000017500000001135414544475344022475 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2017 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 //====================================================================== // For std::unique_ptr #include // Include common routines #include // Include model header, generated from Verilating "top.v" #include "Vtop.h" // Legacy function required only so linking works on Cygwin and MSVC++ double sc_time_stamp() { return 0; } int main(int argc, char** argv) { // This is a more complicated example, please also see the simpler examples/make_hello_c. // Prevent unused variable warnings if (false && argc && argv) {} // Create logs/ directory in case we have traces to put under it Verilated::mkdir("logs"); // Construct a VerilatedContext to hold simulation time, etc. // Multiple modules (made later below with Vtop) may share the same // context to share time, or modules may have different contexts if // they should be independent from each other. // Using unique_ptr is similar to // "VerilatedContext* contextp = new VerilatedContext" then deleting at end. const std::unique_ptr contextp{new VerilatedContext}; // Do not instead make Vtop as a file-scope static variable, as the // "C++ static initialization order fiasco" may cause a crash // Set debug level, 0 is off, 9 is highest presently used // May be overridden by commandArgs argument parsing contextp->debug(0); // Randomization reset policy // May be overridden by commandArgs argument parsing contextp->randReset(2); // Verilator must compute traced signals contextp->traceEverOn(true); // Pass arguments so Verilated code can see them, e.g. $value$plusargs // This needs to be called before you create any model contextp->commandArgs(argc, argv); // Construct the Verilated model, from Vtop.h generated from Verilating "top.v". // Using unique_ptr is similar to "Vtop* top = new Vtop" then deleting at end. // "TOP" will be the hierarchical name of the module. const std::unique_ptr top{new Vtop{contextp.get(), "TOP"}}; // Set Vtop's input signals top->reset_l = !0; top->clk = 0; top->in_small = 1; top->in_quad = 0x1234; top->in_wide[0] = 0x11111111; top->in_wide[1] = 0x22222222; top->in_wide[2] = 0x3; // Simulate until $finish while (!contextp->gotFinish()) { // Historical note, before Verilator 4.200 Verilated::gotFinish() // was used above in place of contextp->gotFinish(). // Most of the contextp-> calls can use Verilated:: calls instead; // the Verilated:: versions just assume there's a single context // being used (per thread). It's faster and clearer to use the // newer contextp-> versions. contextp->timeInc(1); // 1 timeprecision period passes... // Historical note, before Verilator 4.200 a sc_time_stamp() // function was required instead of using timeInc. Once timeInc() // is called (with non-zero), the Verilated libraries assume the // new API, and sc_time_stamp() will no longer work. // Toggle a fast (time/2 period) clock top->clk = !top->clk; // Toggle control signals on an edge that doesn't correspond // to where the controls are sampled; in this example we do // this only on a negedge of clk, because we know // reset is not sampled there. if (!top->clk) { if (contextp->time() > 1 && contextp->time() < 10) { top->reset_l = !1; // Assert reset } else { top->reset_l = !0; // Deassert reset } // Assign some other inputs top->in_quad += 0x12; } // Evaluate model // (If you have multiple models being simulated in the same // timestep then instead of eval(), call eval_step() on each, then // eval_end_step() on each. See the manual.) top->eval(); // Read outputs VL_PRINTF("[%" PRId64 "] clk=%x rstl=%x iquad=%" PRIx64 " -> oquad=%" PRIx64 " owide=%x_%08x_%08x\n", contextp->time(), top->clk, top->reset_l, top->in_quad, top->out_quad, top->out_wide[2], top->out_wide[1], top->out_wide[0]); } // Final model cleanup top->final(); // Coverage analysis (calling write only after the test is known to pass) #if VM_COVERAGE Verilated::mkdir("logs"); contextp->coveragep()->write("logs/coverage.dat"); #endif // Return good completion status // Don't use exit() or destructor won't get called return 0; } verilator-5.020/examples/make_hello_binary/0000755000175000017500000000000014544475344020707 5ustar carstencarstenverilator-5.020/examples/make_hello_binary/.gitignore0000644000175000017500000000004414544475344022675 0ustar carstencarsten*.dmp *.log *.csrc *.vcd obj_* logs verilator-5.020/examples/make_hello_binary/top.v0000644000175000017500000000056514544475344021706 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2017 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 // See also https://verilator.org/guide/latest/examples.html" module top; initial begin $display("Hello World!"); $finish; end endmodule verilator-5.020/examples/make_hello_binary/Makefile0000644000175000017500000000345414544475344022355 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator Example: Small Makefile # # This calls the object directory makefile. That allows the objects to # be placed in the "current directory" which simplifies the Makefile. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # Check for sanity to avoid later confusion ifneq ($(words $(CURDIR)),1) $(error Unsupported: GNU Make cannot build in directories containing spaces, build elsewhere: '$(CURDIR)') endif ###################################################################### # This is intended to be a minimal example. Before copying this to start a # real project, it is better to start with a more complete example, # e.g. examples/make_tracing_c. # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR = verilator else export VERILATOR_ROOT VERILATOR = $(VERILATOR_ROOT)/bin/verilator endif default: @echo "-- Verilator hello-world simple binary example" @echo "-- VERILATE & BUILD --------" $(VERILATOR) --binary -j 0 top.v @echo "-- RUN ---------------------" obj_dir/Vtop @echo "-- DONE --------------------" @echo "Note: Once this example is understood, see examples/make_hello_c." @echo "Note: See also https://verilator.org/guide/latest/examples.html" ###################################################################### maintainer-copy:: clean mostlyclean distclean maintainer-clean:: -rm -rf obj_dir *.log *.dmp *.vpd core verilator-5.020/examples/make_hello_sc/0000755000175000017500000000000014544475344020030 5ustar carstencarstenverilator-5.020/examples/make_hello_sc/sc_main.cpp0000644000175000017500000000257014544475344022151 0ustar carstencarsten// -*- SystemC -*- // DESCRIPTION: Verilator Example: Top level main for invoking SystemC model // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2017 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 //====================================================================== // SystemC global header #include // Include common routines #include // Include model header, generated from Verilating "top.v" #include "Vtop.h" using namespace sc_core; int sc_main(int argc, char* argv[]) { // See a similar example walkthrough in the verilator manpage. // This is intended to be a minimal example. Before copying this to start a // real project, it is better to start with a more complete example, // e.g. examples/c_tracing. // Construct the Verilated model, from Vtop.h generated from Verilating "top.v" Vtop* top = new Vtop{"top"}; // Pass arguments so Verilated code can see them, e.g. $value$plusargs // This needs to be called before you create any model Verilated::commandArgs(argc, argv); // Initialize SC model sc_start(1, SC_NS); // Simulate until $finish while (!Verilated::gotFinish()) { // Simulate 1ns sc_start(1, SC_NS); } // Final model cleanup top->final(); // Return good completion status return 0; } verilator-5.020/examples/make_hello_sc/.gitignore0000644000175000017500000000004414544475344022016 0ustar carstencarsten*.dmp *.log *.csrc *.vcd obj_* logs verilator-5.020/examples/make_hello_sc/top.v0000644000175000017500000000056514544475344021027 0ustar carstencarsten// DESCRIPTION: Verilator: Verilog example module // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2017 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 // See also https://verilator.org/guide/latest/examples.html" module top; initial begin $display("Hello World!"); $finish; end endmodule verilator-5.020/examples/make_hello_sc/Makefile0000644000175000017500000000420114544475344021465 0ustar carstencarsten###################################################################### # # DESCRIPTION: Verilator Example: Small Makefile # # This calls the object directory makefile. That allows the objects to # be placed in the "current directory" which simplifies the Makefile. # # This file ONLY is placed under the Creative Commons Public Domain, for # any use, without warranty, 2020 by Wilson Snyder. # SPDX-License-Identifier: CC0-1.0 # ###################################################################### # Check for sanity to avoid later confusion ifneq ($(words $(CURDIR)),1) $(error Unsupported: GNU Make cannot build in directories containing spaces, build elsewhere: '$(CURDIR)') endif ###################################################################### # This is intended to be a minimal example. Before copying this to start a # real project, it is better to start with a more complete example, # e.g. examples/make_tracing_sc. # If $VERILATOR_ROOT isn't in the environment, we assume it is part of a # package install, and verilator is in your path. Otherwise find the # binary relative to $VERILATOR_ROOT (such as when inside the git sources). ifeq ($(VERILATOR_ROOT),) VERILATOR = verilator else export VERILATOR_ROOT VERILATOR = $(VERILATOR_ROOT)/bin/verilator endif # Check if SC exists via a verilator call (empty if not) SYSTEMC_EXISTS := $(shell $(VERILATOR) --get-supported SYSTEMC) ifneq ($(SYSTEMC_EXISTS),) default: run else default: nosc endif run: @echo "-- Verilator hello-world simple example" @echo "-- VERILATE & COMPILE ------" $(VERILATOR) -sc --exe --build -j top.v sc_main.cpp @echo "-- RUN ---------------------" obj_dir/Vtop @echo "-- DONE --------------------" @echo "Note: Once this example is understood, see examples/make_tracing_sc." @echo "Note: See also https://verilator.org/guide/latest/examples.html" ###################################################################### nosc: @echo @echo "%Skip: SYSTEMC_INCLUDE not in environment" @echo "(If you have SystemC see the README, and rebuild Verilator)" @echo maintainer-copy:: clean mostlyclean distclean maintainer-clean:: -rm -rf obj_dir *.log *.dmp *.vpd core verilator-5.020/Makefile.in0000644000175000017500000004414614544475344015503 0ustar carstencarsten#***************************************************************************** # DESCRIPTION: Verilator top level: Makefile pre-configure version # # This file is part of Verilator. # # Code available from: https://verilator.org # #***************************************************************************** # # Copyright 2003-2024 by Wilson Snyder. This program is free software; you # can redistribute it and/or modify it under the terms of either the GNU # Lesser General Public License Version 3 or the Perl Artistic License # Version 2.0. # SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 # #****************************************************************************/ # # make all to compile and build Verilator. # make install to install it. # make TAGS to update tags tables. # # make clean or make mostlyclean # Delete all files from the current directory that are normally # created by building the program. Don't delete the files that # record the configuration. Also preserve files that could be made # by building, but normally aren't because the distribution comes # with them. # # make distclean # Delete all files from the current directory that are created by # configuring or building the program. If you have unpacked the # source and built the program without creating any other files, # `make distclean' should leave only the files that were in the # distribution. # # make maintainer-clean # Delete everything from the current directory that can be # reconstructed with this Makefile. This typically includes # everything deleted by distclean, plus more: C source files # produced by Bison, tags tables, info files, and so on. #### Start of system configuration section. #### srcdir = @srcdir@ VPATH = @srcdir@ HOST = @HOST@ EXEEXT = @EXEEXT@ DOXYGEN = doxygen INSTALL = @INSTALL@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_DATA = @INSTALL_DATA@ MAKEINFO = makeinfo POD2TEXT = pod2text MKINSTALLDIRS = $(SHELL) $(srcdir)/src/mkinstalldirs # Version (for docs/guide/conf.py) PACKAGE_VERSION_NUMBER = @PACKAGE_VERSION_NUMBER@ # Destination prefix for RPMs DESTDIR = #### Don't edit: You're much better using configure switches to set these prefix = @prefix@ exec_prefix = @exec_prefix@ # Directory in which to install scripts. bindir = @bindir@ # Directory in which to install manpages. mandir = @mandir@ # Directory in which to install library files. datadir = @datadir@ # Directory in which to install documentation info files. infodir = @infodir@ # Directory in which to install package specific files # Generally ${prefix}/share/verilator pkgdatadir = @pkgdatadir@ # Directory in which to install pkgconfig file # Generally ${prefix}/share/pkgconfig pkgconfigdir = @pkgconfigdir@ # Directory in which to install data across multiple architectures datarootdir = @datarootdir@ # Compile options CFG_WITH_CCWARN = @CFG_WITH_CCWARN@ CFG_WITH_DEFENV = @CFG_WITH_DEFENV@ CFG_WITH_LONGTESTS = @CFG_WITH_LONGTESTS@ PACKAGE_VERSION = @PACKAGE_VERSION@ #### End of system configuration section. #### ###################################################################### .SUFFIXES: SHELL = /bin/sh SUBDIRS = docs src test_regress \ examples/cmake_hello_c \ examples/cmake_hello_sc \ examples/cmake_tracing_c \ examples/cmake_tracing_sc \ examples/cmake_protect_lib \ examples/make_hello_binary \ examples/make_hello_c \ examples/make_hello_sc \ examples/make_tracing_c \ examples/make_tracing_sc \ examples/make_protect_lib \ examples/xml_py \ INFOS = verilator.html verilator.pdf INFOS_OLD = README README.html README.pdf EXAMPLES_FIRST = \ examples/make_hello_c \ examples/make_hello_sc \ EXAMPLES = $(EXAMPLES_FIRST) $(filter-out $(EXAMPLES_FIRST), $(sort $(wildcard examples/*))) # See uninstall also - don't put wildcards in this variable, it might uninstall other stuff # No verilator_ccache_report.1, verilator_difftree.1 as those are not bin/ installed VL_INST_MAN_FILES = \ verilator.1 \ verilator_coverage.1 \ verilator_gantt.1 \ verilator_profcfunc.1 \ default: all all: all_nomsg msg_test all_nomsg: verilator_exe $(VL_INST_MAN_FILES) .PHONY:verilator_exe .PHONY:verilator_bin$(EXEEXT) .PHONY:verilator_bin_dbg$(EXEEXT) .PHONY:verilator_coverage_bin_dbg$(EXEEXT) verilator_exe verilator_bin$(EXEEXT) verilator_bin_dbg$(EXEEXT) verilator_coverage_bin_dbg$(EXEEXT): @echo ------------------------------------------------------------ @echo "making verilator in src" $(MAKE) -C src $(OBJCACHE_JOBS) .PHONY:msg_test msg_test: all_nomsg @echo "Build complete!" @echo @echo "Now type 'make test' to test." @echo .PHONY: test ifeq ($(CFG_WITH_LONGTESTS),yes) # Local... Else don't burden users test: smoke-test test_regress # examples is part of test_regress's test_regress/t/t_a2_examples.pl # (because that allows it to run in parallel with other test_regress's) else test: smoke-test examples endif @echo "Tests passed!" @echo @echo "Now type 'make install' to install." @echo "Or type 'make' inside an examples subdirectory." @echo smoke-test: all_nomsg test_regress/t/t_a1_first_cc.pl test_regress/t/t_a2_first_sc.pl test_regress: all_nomsg $(MAKE) -C test_regress .PHONY: test-snap test-diff test-snap test-diff: $(MAKE) -C test_regress $@ examples: all_nomsg for p in $(EXAMPLES) ; do \ $(MAKE) -C $$p VERILATOR_ROOT=`pwd` || exit 10; \ done .PHONY: docs docs: info info: $(INFOS) verilator.1: ${srcdir}/bin/verilator pod2man $< $@ verilator_coverage.1: ${srcdir}/bin/verilator_coverage pod2man $< $@ %.1: ${srcdir}/bin/% help2man --no-info --no-discard-stderr --version-string=- $< -o $@ .PHONY: verilator.html verilator.html: $(MAKE) -C docs html # PDF needs DIST variables; but having configure.ac as dependency isn't detected .PHONY: verilator.pdf verilator.pdf: Makefile $(MAKE) -C docs verilator.pdf # See uninstall also - don't put wildcards in this variable, it might uninstall other stuff VL_INST_BIN_FILES = verilator verilator_bin$(EXEEXT) verilator_bin_dbg$(EXEEXT) verilator_coverage_bin_dbg$(EXEEXT) \ verilator_ccache_report verilator_coverage verilator_difftree verilator_gantt verilator_includer verilator_profcfunc # Some scripts go into both the search path and pkgdatadir, # so they can be found by the user, and under $VERILATOR_ROOT. VL_INST_INC_BLDDIR_FILES = \ include/verilated_config.h \ include/verilated.mk \ # Files under srcdir, instead of build time VL_INST_INC_SRCDIR_FILES = \ include/*.[chv]* \ include/*.sv \ include/gtkwave/*.[chv]* \ include/vltstd/*.[chv]* \ VL_INST_DATA_SRCDIR_FILES = \ examples/*/*.[chv]* \ examples/*/CMakeLists.txt \ examples/*/Makefile* \ examples/*/vl_* \ installbin: $(MKINSTALLDIRS) $(DESTDIR)$(bindir) ( cd ${srcdir}/bin ; $(INSTALL_PROGRAM) verilator $(DESTDIR)$(bindir)/verilator ) ( cd ${srcdir}/bin ; $(INSTALL_PROGRAM) verilator_coverage $(DESTDIR)$(bindir)/verilator_coverage ) ( cd ${srcdir}/bin ; $(INSTALL_PROGRAM) verilator_gantt $(DESTDIR)$(bindir)/verilator_gantt ) ( cd ${srcdir}/bin ; $(INSTALL_PROGRAM) verilator_profcfunc $(DESTDIR)$(bindir)/verilator_profcfunc ) ( cd bin ; $(INSTALL_PROGRAM) verilator_bin$(EXEEXT) $(DESTDIR)$(bindir)/verilator_bin$(EXEEXT) ) ( cd bin ; $(INSTALL_PROGRAM) verilator_bin_dbg$(EXEEXT) $(DESTDIR)$(bindir)/verilator_bin_dbg$(EXEEXT) ) ( cd bin ; $(INSTALL_PROGRAM) verilator_coverage_bin_dbg$(EXEEXT) $(DESTDIR)$(bindir)/verilator_coverage_bin_dbg$(EXEEXT) ) $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/bin ( cd ${srcdir}/bin ; $(INSTALL_PROGRAM) verilator_includer $(DESTDIR)$(pkgdatadir)/bin/verilator_includer ) ( cd ${srcdir}/bin ; $(INSTALL_PROGRAM) verilator_ccache_report $(DESTDIR)$(pkgdatadir)/bin/verilator_ccache_report ) ( cd ${srcdir}/bin ; $(INSTALL_PROGRAM) verilator_difftree $(DESTDIR)$(pkgdatadir)/bin/verilator_difftree ) # Man files can either be part of the original kit, or built in current directory # So important we use $^ so VPATH is searched installman: $(VL_INST_MAN_FILES) $(MKINSTALLDIRS) $(DESTDIR)$(mandir)/man1 for p in $^ ; do \ $(INSTALL_DATA) $$p $(DESTDIR)$(mandir)/man1/$$p; \ done installdata: $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/include/gtkwave $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/include/vltstd for p in $(VL_INST_INC_BLDDIR_FILES) ; do \ $(INSTALL_DATA) $$p $(DESTDIR)$(pkgdatadir)/$$p; \ done cd $(srcdir) \ ; for p in $(VL_INST_INC_SRCDIR_FILES) ; do \ $(INSTALL_DATA) $$p $(DESTDIR)$(pkgdatadir)/$$p; \ done $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/make_hello_binary $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/make_hello_c $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/make_hello_sc $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/make_tracing_c $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/make_tracing_sc $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/make_protect_lib $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/cmake_hello_c $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/cmake_hello_sc $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/cmake_tracing_c $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/cmake_tracing_sc $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/cmake_protect_lib $(MKINSTALLDIRS) $(DESTDIR)$(pkgdatadir)/examples/xml_py cd $(srcdir) \ ; for p in $(VL_INST_DATA_SRCDIR_FILES) ; do \ $(INSTALL_DATA) $$p $(DESTDIR)$(pkgdatadir)/$$p; \ done $(MKINSTALLDIRS) $(DESTDIR)$(pkgconfigdir) $(INSTALL_DATA) verilator.pc $(DESTDIR)$(pkgconfigdir) $(INSTALL_DATA) verilator-config.cmake $(DESTDIR)$(pkgdatadir) $(INSTALL_DATA) verilator-config-version.cmake $(DESTDIR)$(pkgdatadir) # We don't trust rm -rf, so rmdir instead as it will fail if user put in other files uninstall: -cd $(DESTDIR)$(bindir) && rm -f $(VL_INST_BIN_FILES) -cd $(DESTDIR)$(pkgdatadir)/bin && rm -f $(VL_INST_BIN_FILES) -cd $(DESTDIR)$(mandir)/man1 && rm -f $(VL_INST_MAN_FILES) -cd $(DESTDIR)$(pkgdatadir) && rm -f $(VL_INST_INC_BLDDIR_FILES) -cd $(DESTDIR)$(pkgdatadir) && rm -f $(VL_INST_INC_SRCDIR_FILES) -cd $(DESTDIR)$(pkgdatadir) && rm -f $(VL_INST_DATA_SRCDIR_FILES) -rm $(DESTDIR)$(pkgconfigdir)/verilator.pc -rm $(DESTDIR)$(pkgdatadir)/verilator-config.cmake -rm $(DESTDIR)$(pkgdatadir)/verilator-config-version.cmake -rmdir $(DESTDIR)$(pkgdatadir)/bin -rmdir $(DESTDIR)$(pkgdatadir)/include/gtkwave -rmdir $(DESTDIR)$(pkgdatadir)/include/vltstd -rmdir $(DESTDIR)$(pkgdatadir)/include -rmdir $(DESTDIR)$(pkgdatadir)/examples/make_hello_binary -rmdir $(DESTDIR)$(pkgdatadir)/examples/make_hello_c -rmdir $(DESTDIR)$(pkgdatadir)/examples/make_hello_sc -rmdir $(DESTDIR)$(pkgdatadir)/examples/make_tracing_c -rmdir $(DESTDIR)$(pkgdatadir)/examples/make_tracing_sc -rmdir $(DESTDIR)$(pkgdatadir)/examples/make_protect_lib -rmdir $(DESTDIR)$(pkgdatadir)/examples/cmake_hello_c -rmdir $(DESTDIR)$(pkgdatadir)/examples/cmake_hello_sc -rmdir $(DESTDIR)$(pkgdatadir)/examples/cmake_tracing_c -rmdir $(DESTDIR)$(pkgdatadir)/examples/cmake_tracing_sc -rmdir $(DESTDIR)$(pkgdatadir)/examples/cmake_protect_lib -rmdir $(DESTDIR)$(pkgdatadir)/examples/xml_py -rmdir $(DESTDIR)$(pkgdatadir)/examples -rmdir $(DESTDIR)$(pkgdatadir) -rmdir $(DESTDIR)$(pkgconfigdir) install: all_nomsg install-all install-all: installbin installman installdata install-msg install-here: installman info # Use --xml flag to see the cppcheck code to use for suppression CPPCHECK1_CPP = $(wildcard $(srcdir)/include/*.cpp) CPPCHECK2_CPP = $(wildcard $(srcdir)/examples/*/*.cpp) CPPCHECK3_CPP = $(wildcard $(srcdir)/src/Vlc*.cpp) CPPCHECK4_CPP = $(wildcard $(srcdir)/src/V3[A-D]*.cpp $(srcdir)/src/Verilator*.cpp) CPPCHECK5_CPP = $(wildcard $(srcdir)/src/V3[E-I]*.cpp) CPPCHECK6_CPP = $(wildcard $(srcdir)/src/V3[P-Z]*.cpp) CPPCHECK7_CPP = $(wildcard $(srcdir)/src/V3[L-R]*.cpp) CPPCHECK8_CPP = $(wildcard $(srcdir)/src/V3[S-Z]*.cpp) CHECK_CPP = $(CPPCHECK1_CPP) $(CPPCHECK2_CPP) $(CPPCHECK3_CPP) $(CPPCHECK4_CPP) \ $(CPPCHECK5_CPP) $(CPPCHECK6_CPP) $(CPPCHECK7_CPP) $(CPPCHECK8_CPP) CHECK_H = $(wildcard \ $(srcdir)/include/*.h \ $(srcdir)/src/*.h ) CHECK_YL = $(wildcard \ $(srcdir)/src/*.y \ $(srcdir)/src/*.l ) CPPCHECK = src/cppcheck_filtered cppcheck CPPCHECK_FLAGS = --enable=all --inline-suppr \ --suppress=cstyleCast --suppress=useInitializationList \ --suppress=nullPointer --suppress=nullPointerRedundantCheck --suppress=ctunullpointer \ --suppress=unusedFunction --suppress=unusedScopedObject \ --suppress=useStlAlgorithm CPPCHECK_FLAGS += --xml CPPCHECK_DEP = $(subst .cpp,.cppcheck,$(CHECK_CPP)) CPPCHECK_INC = -I$(srcdir)/include -I$(srcdir)/src/obj_dbg -I$(srcdir)/src cppcheck: cppcheck-1 cppcheck-2 cppcheck-3 cppcheck-4 cppcheck-5 cppcheck-6 cppcheck-7 cppcheck-8 cppcheck-1: $(CPPCHECK) $(CPPCHECK_FLAGS) -DVL_DEBUG=1 -DVL_CPPCHECK=1 $(CPPCHECK_INC) $(CPPCHECK1_CPP) cppcheck-2: $(CPPCHECK) $(CPPCHECK_FLAGS) -DVL_DEBUG=1 -DVL_CPPCHECK=1 $(CPPCHECK_INC) $(CPPCHECK2_CPP) cppcheck-3: $(CPPCHECK) $(CPPCHECK_FLAGS) -DVL_DEBUG=1 -DVL_CPPCHECK=1 $(CPPCHECK_INC) $(CPPCHECK3_CPP) cppcheck-4: $(CPPCHECK) $(CPPCHECK_FLAGS) -DVL_DEBUG=1 -DVL_CPPCHECK=1 $(CPPCHECK_INC) $(CPPCHECK4_CPP) cppcheck-5: $(CPPCHECK) $(CPPCHECK_FLAGS) -DVL_DEBUG=1 -DVL_CPPCHECK=1 $(CPPCHECK_INC) $(CPPCHECK5_CPP) cppcheck-6: $(CPPCHECK) $(CPPCHECK_FLAGS) -DVL_DEBUG=1 -DVL_CPPCHECK=1 $(CPPCHECK_INC) $(CPPCHECK6_CPP) cppcheck-7: $(CPPCHECK) $(CPPCHECK_FLAGS) -DVL_DEBUG=1 -DVL_CPPCHECK=1 $(CPPCHECK_INC) $(CPPCHECK7_CPP) cppcheck-8: $(CPPCHECK) $(CPPCHECK_FLAGS) -DVL_DEBUG=1 -DVL_CPPCHECK=1 $(CPPCHECK_INC) $(CPPCHECK8_CPP) CLANGTIDY = clang-tidy CLANGTIDY_FLAGS = -config='' \ -header-filter='.*' \ -checks='-fuchsia-*,-cppcoreguidelines-avoid-c-arrays,-cppcoreguidelines-init-variables,-cppcoreguidelines-avoid-goto,-modernize-avoid-c-arrays,-readability-magic-numbers,-readability-simplify-boolean-expr,-cppcoreguidelines-macro-usage' \ CLANGTIDY_DEP = $(subst .cpp,.cpp.tidy,$(CHECK_CPP)) CLANGTIDY_DEFS = -DVL_DEBUG=1 -DVL_CPPCHECK=1 clang-tidy: $(CLANGTIDY_DEP) %.cpp.tidy: %.cpp $(CLANGTIDY) $(CLANGTIDY_FLAGS) $< -- $(CLANGTIDY_DEFS) $(CPPCHECK_INC) | 2>&1 tee $@ %.h.tidy: %.h $(CLANGTIDY) $(CLANGTIDY_FLAGS) $< -- $(CLANGTIDY_DEFS) $(CPPCHECK_INC) -x c++-header | 2>&1 tee $@ analyzer-src: -rm -rf src/obj_dbg scan-build $(MAKE) -k verilator_coverage_bin_dbg$(EXEEXT) verilator_bin_dbg$(EXEEXT) analyzer-include: -rm -rf examples/*/obj* scan-build $(MAKE) -k examples format: clang-format yapf format-pl-exec CLANGFORMAT = clang-format-14 CLANGFORMAT_FLAGS = -i CLANGFORMAT_FILES = $(CHECK_CPP) $(CHECK_H) $(CHECK_YL) test_regress/t/*.c* test_regress/t/*.h clang-format: @$(CLANGFORMAT) --version | egrep 14.0 > /dev/null \ || echo "*** You are not using clang-format-14, indents may differ from master's ***" $(CLANGFORMAT) $(CLANGFORMAT_FLAGS) $(CLANGFORMAT_FILES) PY_PROGRAMS = \ bin/verilator_ccache_report \ bin/verilator_difftree \ bin/verilator_gantt \ bin/verilator_includer \ bin/verilator_profcfunc \ examples/xml_py/vl_file_copy \ examples/xml_py/vl_hier_graph \ docs/guide/conf.py \ docs/bin/vl_sphinx_extract \ docs/bin/vl_sphinx_fix \ src/astgen \ src/bisonpre \ src/config_rev \ src/cppcheck_filtered \ src/flexfix \ src/vlcovgen \ test_regress/t/*.pf \ nodist/clang_check_attributes \ nodist/code_coverage \ nodist/dot_importer \ nodist/fuzzer/actual_fail \ nodist/fuzzer/generate_dictionary \ nodist/install_test \ PY_FILES = \ $(PY_PROGRAMS) \ nodist/code_coverage.dat \ YAPF = yapf3 YAPF_FLAGS = -i yapf: $(YAPF) $(YAPF_FLAGS) $(PY_FILES) PYLINT = pylint PYLINT_FLAGS = --score=n --disable=R0801 RUFF = ruff RUFF_FLAGS = check --ignore=E402,E501,E701 # "make -k" so can see all tool result errors lint-py: $(MAKE) -k lint-py-pylint lint-py-ruff lint-py-pylint: $(PYLINT) $(PYLINT_FLAGS) $(PY_PROGRAMS) lint-py-ruff: $(RUFF) $(RUFF_FLAGS) $(PY_PROGRAMS) format-pl-exec: -chmod a+x test_regress/t/*.pl install-msg: @echo @echo "Installed binaries to $(DESTDIR)$(bindir)/verilator" @echo "Installed man to $(DESTDIR)$(mandir)/man1" @echo "Installed examples to $(DESTDIR)$(pkgdatadir)/examples" @echo @echo "For documentation see 'man verilator' or 'verilator --help'" @echo "For forums and to report bugs see https://verilator.org" @echo IN_WILD := ${srcdir}/*.in ${srcdir}/*/*.in # autoheader might not change config_package.h.in, so touch it ${srcdir}/config_package.h: ${srcdir}/config_package.h.in configure cd ${srcdir} && autoheader touch $@ Makefile: Makefile.in config.status $(IN_WILD) ./config.status src/Makefile: src/Makefile.in Makefile config.status: configure ./config.status --recheck configure: configure.ac ifeq ($(CFG_WITH_CCWARN),yes) # Local... Else don't burden users autoconf --warnings=all else autoconf endif maintainer-clean:: @echo "This command is intended for maintainers to use;" @echo "rebuilding the deleted files requires autoconf." rm -f configure clean mostlyclean distclean maintainer-clean maintainer-copy:: for dir in $(SUBDIRS); do \ echo making $@ in $$dir ; \ $(MAKE) -C $$dir $@ ; \ done clean mostlyclean distclean maintainer-clean:: rm -f $(SCRIPTS) *.tmp rm -f *.aux *.cp *.cps *.dvi *.fn *.fns *.ky *.kys *.log rm -f *.pg *.pgs *.toc *.tp *.tps *.vr *.vrs *.idx rm -f *.ev *.evs *.ov *.ovs *.cv *.cvs *.ma *.mas rm -f *.tex rm -rf examples/*/obj_dir* examples/*/logs rm -rf test_*/obj_dir rm -rf nodist/fuzzer/dictionary rm -rf nodist/obj_dir rm -rf verilator.txt distclean maintainer-clean:: rm -f *.info* *.1 $(INFOS) $(INFOS_OLD) $(VL_INST_MAN_FILES) rm -f Makefile config.status config.cache config.log TAGS rm -f verilator_bin* verilator_coverage_bin* rm -f bin/verilator_bin* bin/verilator_coverage_bin* rm -f include/verilated.mk include/verilated_config.h TAGFILES=${srcdir}/*/*.cpp ${srcdir}/*/*.h ${srcdir}/*/*.in \ ${srcdir}/*.in ${srcdir}/*.pod TAGS: $(TAGFILES) etags $(TAGFILES) .PHONY: doxygen doxygen: $(MAKE) -C docs doxygen ###################################################################### # Distributions DISTTITLE := Verilator $(word 1,$(PACKAGE_VERSION)) DISTNAME := verilator-$(word 1,$(PACKAGE_VERSION)) DISTDATEPRE := $(word 2,$(PACKAGE_VERSION)) DISTDATE := $(subst /,-,$(DISTDATEPRE)) DISTTAGNAME := $(subst .,_,$(subst -,_,$(DISTNAME))) tag: svnorcvs tag $(DISTTAGNAME) maintainer-diff: svnorcvs diff $(DISTTAGNAME) preexist: svnorcvs nexists $(DISTTAGNAME) maintainer-dist: preexist tag svnorcvs release $(DISTTAGNAME) verilator-5.020/docs/0000755000175000017500000000000014544475344014355 5ustar carstencarstenverilator-5.020/docs/_static/0000755000175000017500000000000014544475344016003 5ustar carstencarstenverilator-5.020/docs/_static/verilator_logo.png0000644000175000017500000002366014544475344021547 0ustar carstencarstenPNG  IHDRH^|oPLTE׮ $6Lsvͪ8Tc ,;<~]~WAbD]^/F(xdk!,-8LMjOkmRoppstRNS@f&IDATxҹ-pԝ%7L>2*ה9dx[{+0cxdxe=fw?J@ǻ?:(8xyހ\ s&6+Nf7p8!^)*.x9\BN൘o9Wb dtd8(D^*pSԉ V`/y 71fpê&z5r1ëEoIT-k";\ KgڠN]*5y\Bh !=b1%T61X4LXj]:=y:ІAV.Fk/m]B r#hۆK .UEnDdB T)oH&;|KezM)D*1vsS5:VdvU k]B ) A r1&uIJtJv2&V\4Π 2fM$fKZk(`N碩t)nzzSʑ; _0f.BL mX0nk*V۹/a%<3/DD'PhQ+`52yF@&2eϫU(`\"l\MŃv\' q1KQ0ЩyWTR\c}leRw)|^G3{)*W43fe.YtiDhOu+졶n7_ZYp W!Y}nMe Hb-\[WwD_\Yp`+1Uex}diB3W-e^y-\Tbz$折s9KM*uKU1 .+(-N[um p5m@ e:i;be%Ϗ^@%}9)"}}<ƥ 50ɂlqvJǬCX 4.%n2e9OԲ8f?8i,Ҫv.h\CsD[! ΂%KRk`wl4G@9R8'<ֈƹ*C8f.5vYqBj L>~+C窬ᘕc8fYp~/C^#4)ˆ¹*R;fJiH;RKtJDZGXp%U Y%T8ѸtGCL.kGua! <qby£V)ȂKqpĉƥg40m>xF7d9##Nr3_q950ɂEY'U91+ODwĉ7ȂsG7E/ӑZ,/p15Ĺ*8fh#N,\иN7C^7H8fhFl#ue#5T2ւ >Yy C'*R8 fLJETP|iܲ_}O]vN]wԍ[pˬgy'[- >2+Z) uX]TT`L}6:8NI"lOX433d=U:T3R4&Z)BgŷYNZ)ˣ\X˚][4N fTtJu3s.}a\&}1O)bUdl}1_.q3PNuK%N9eibUd-gE[Ifdeϵ*q.î率)cUxCĉjU`(k2ߺ`‡A}Q{!20TOڪ1@`Ud윯ɦDGw\񹌙V,fd߳M,5;`0Xf4S LFƧ J oˬ" G)1S,єT`BVGC%@+E< 9iu .S,PhyInP4"+BsBJTౖY%UԥfhXc0b^f&tOP q*q:39΂㩡Y.ka 09~!%b 0Bo7CuUaE }-u썍 5ǂȕ!Yp\'ٰб>HgVƄcȢ1y΂#Y62F5>Qzy΂/ۧ-zRJGuaRUzZVNpX\5U.*YSm+E.k㒳^:nĺ*D*e>2K; .t< Fˬ tz) .,!rYˆ9rYMR׍"eV$kUn]BiDpR@rHF r`3hEcKPdz{/̭(,{R.R0<-˖ dt٥?7.nV}. !uUp|BL( o1h`xRbZG(e'%0S1Q0fo`\݆J`F]<0S1U\<דJ8%bL-`x^H^4H7녺*Xl;y ]/$,ba>\╒`ן%ruUQLM4u#%h 0g`Yu]AMcp0NTYbʵ_{07x .KZwl_zr?KQ`.B 0w}-'K8d" kg4<Mp0TZ4d72J *Rko\innWQWʬfRdո| .N.$2[`R n."r%(-FNpN^YOQW:ʬ1ҧc}(0}l .b.`7f?oрA:٧2C%B9b O'F)d\!_( .9.8w5j O)2%( ܐSW`r pU!oʬܬRPW`r 0J̊*0eiuU33uU2+K~i܁*-$%%Α-8eV-4UYq ܰXkʬRl . &WnQW80[/eVU! Lʬ|\}r79*4-J< }B&**w~%š$l*5-|JA];|\Hom[pwWmi{b"qk[_E-ms>n[S\}Cl#R.[co*7FU VRWeɽ*2Vz>\ ^sU Έӓ/@eV'ꪀSkiimKȖq2QW7X3-GӽUZeVۈuU@*ƈsauUNyo+W[p{˯U!krj%uUB4ⴲ;d X[p鈓*2غc :;D]Uf?*`ӑ&񋊫o2+꽮o0NN-X֍sp ')F.~E]JzPqZ/CS* ~Ynȿۦ8uU@UVii QH1|(5c{"sr#d Ixq|yGb*g檀cV*NVn窸Dt߂yݐ?X"&%nM-݋vUm9II0 Ƭ>NmPũU)5UoNS-+&sUDYN7J¶eTW. 8i*`jbpRqS 檀ɉ򺕗 *`VԿ,KO A\qW2SsUtTt\xmڏէ(eO%sUHmNiR|\0Yڽ`L檀HˀE-#} o\n|*?|a ӴJ̓(UD;oܐoƬKңб@k\0;*ooO3WOUG4sUDݐ?@u%'cVB>` ge8is*\r FH=;\(8ًA sU@DW~}+?r [c8Y!\gQ<~} 8Uq0*N=d PRnm7Kd`6d.USqy\Wߐ~?3WDBhS%'WN+NUq 0*|C^`2WDBpC~įL0d Ybɡ'T=`^frsU\}CD+NkU7檐-ѮPq Y1WA&sU@c Q 7G0 \}CDd\jdMPsU@$ Pq#d p#O)Fp8%sU@Dl7}c%'?p>f\s)*k~ .oػ&  F۲;$?;~pՖ=;瘫b# Ǭ~цR*#1ZؐD/{%#_9w"6,ǬUA=o` .O1zC .ٜ'{UA18?fU2t<EyJa (*xWFvk}3WFEKb)ŝ*xg!Z`e.bK+%PC\"V(\̌Y}\R̫2 6v7Hwl\P8Y80WI07g t90W5 0Af:vR;sUf-Ǭ\j`}Ƭg_Kxң .1WUƬĄ*(b3HP6&VKAs/J7xKŧҎ'.-Pmjِ{g[L{ K8ŘթWfZep\y{\a^.Ƭ`cVKX 0=O1+o d_)A4<_)UAg옕cാAglz3Ǭ`+#Ǭݱq1Tb LaO \j܂/<`~.a.`Z}%Lo0U\L5m 0U0}-8`☕p 5ӹ*X+8fe ାVCt 8p {L'RX}V|y_)KH0A-82d.!DTt b$mY}AS 9ӹ*HrJ()dJ!\B-8 NByl  Htw ι*8ڽcVVti J\.6`:WvǬKh >O@7(C%L'+p Ufm fB:i Ͷ2SJ\:fe *]o9W^0 I.ػ 4HMgW~ĥ!~) !t<{u .a]p'`S sUYZ`:0WԘ\PcVK` .a 0U5f%*t<).8sU^Yi}Bp U .8sU^KL@ujJp Ti ֫1+%P XƬ'*t<)*Lo^RBp D .8%PcVKXLsU@Y .a 0 0jJp U S %W7Oz$*u< C)E:KL 71^4Xc<^dYv;x`9t43^Xg~i @2N0 nP @1P3 @1I @м yCChXd}&uַ4h lV!J04BC"+^,? ІӠ#6 04 h8~Ȋа] HNN8SA"P{+:РMC,tUp-HJ4PE.im9&i@@AbFiPei|U܆zӀ( ?hmG'(KFԎ հmj4H6 4@f.?I\i@1 K`hCg UAႥ7^-"4@ ]w:4< - $^D)0 vh{3 ̤_/4']v,hf4+4\6l U\gHBÑ3הNYI|^ ii` KwdƱNrm WzE gPL4Lȸd=M6$iOi4lqAF! MaS@4VARF! O@wi`Ѐ40ӰӐOOO!"pJ|2J86ii4zU(*c()4$vMWe%qLä%I3 _в i`}4p5o( 0 4 ңAhg4@ӐDKPI<0oIӀ-=(>434OC$47^5YehHX&Ad!F(ӠLm(hΧsdB4ՇFe},ӀuQ!vS !v#3 "k|Yܛ,4$D D `da S{ʙ4 #E²1dFNaNHKLC3 #MMCZH V5>4 HKiQA%i`:2SY6AEP Ґw*/B;յZ&KFÔ ftlJKCx)4*Y4Լɛ}}fp>4D HaA:4{U&+leȨ|4Ki3ӯLV'iСa rc(cW @/UA.U؜6Y7V4(ľ6tmp^*B)}b)m4Lwh%B/{ e/a$1ʃ*C.K4;o႞f7h9 6]ړF{Lh@; 2ù4Q9hj }}mUshС!I68Hmlm84|Ũ 4KhP!4k' dpѠ1{iYA ΋z& <~fN4QIA>{w0DQp֖ %3z*ip)Qi?woV!c4v4[0J{oIi(iKC g0 ]7R))u|n^e(77GabuJf ]db j&Vqv$ꍿl}3Rf}XyZ4vxZ46`؄٥o/S~=^܅j<*«ZYK=OW.yD#ޱ 4L˃$n@=1q k祷x]r}5r@:!waoO l]c@DqwEn$*'yD%!Y$yu-;0b3IJ<:W#0w-h?A۸jRPׁ;/%WmD;l!es n_V@]VARh"fσ}|ΩPN,Qz @,B4}&*'&r͎sNP<{=M/'CϋJ ~/+ aPP7^GeV*Vu6iUn^TV$9x !ԝT~QjFTRD0rv"Dޅ 곦}m< SUG @,텦iYAYOFk:*펴@xk0٥k/ҝ즘It51@JʓoC"N!FŋJer B=YT=;% bRhvE4ʏ u{H٥]\m u?țsZ<(oj<6K1SEQ j,. (r BTWa0,6\_]㿘w=R)xJV"gHG!ҐMN_?7g`Q'9"DnB]f;DR\z1?w!.Jʡ|?7&֌u%#e-M6*E3<҂V.}7Z^vY geh٥p , :j). /܄J8 ,Tz u2X_}Iz5Uԥ_ԏJ R\wiHq֕Z4Y=Blz-z.!bpDb;$Xt75me{z,ޭ_, [U.WXmkTD85&OKaËt3V#)DЙ~U^ kr23+>!DEKs&C\:{4(hivW+6*Mñ`a љ2V4MEl*MVhC|lG5uB8ukͱ.>Y}(Ob 1J`I۔ BleCX!B.਒5?% o8^X1k? l6+*ԞfuT ->W+99t4͕=4W?1rX0UV(-t:,Vjʄ&d2@ybQ'MB p:Ng[A?["]|TNbJNZ`x(]Gc~m&Zd:;?]'ldPLDߣ ]M`A`cj) TJʓk$ 'e6z@_Y 0ey˳m!b .4 q*=v3(rI!jB&7 Vӿ &PەPdƀ!5rZ2y6r$g-#@'+uXY1[xк2Wyy LY-0)L!zaol7CVAF|, T1 a=kc+I$'ɠd^`HMnW3H`DWp3&zy<#[:4<~p!5f;:QsӦ~t2hr_ZpUQUUUfD^c#EC-p^xͰշ!!/`)w$bB [Zt ZC1L#l16ybw$y ZWdW b6}GBui#u1>sO>ߔ@)9!蘲%;f,gRi*5N?PY @{b{e V30UP_`)#.MdPk %]+DU}x,?nm]m KAi_Y @\)j6|>X-:9n]ҫnSGңǫ@D&rUqwFr5:-Lgu[1['z\.8-ծ!;PN4hw7]_Scg,z;]M\ڞٲT,,~glm.%pIENDB`verilator-5.020/docs/_static/verilator_32x32_min.png0000644000175000017500000000312314544475344022223 0ustar carstencarstenPNG  IHDR DgAMA asRGB pHYs.#.#x?vPLTEGpL  Njk}xwsp8TR|$5Bcv<[*7T+*mXLsc[';tW3Zem,8d%8(,B$+Egf!5P\n/FAbKqIn o 0~)?S}KqIl=]e';&:%~CiqT~f':!6Q1I()>)>+Cd4FG 0T Qmoc{!\tWvwzks3M#Ow-D=RS 7ILfL(,/@A6Qj"./0AB^Gk @Xd"3Fpz1J=YFwgL8FrVuvbf,C3eo4EN~HZq$׮խ¢ސ-tRNS[T (y!m|:#u ,cO>,r0ȕ%k>7ygǀrѲ-[/EaabD[HFю,0aX{.3VWN[?Xаւ97T/|s}a`jD/?\f'CF_w^-S Jg1" ;iX6iR ֝%6ftA#& bjuٴ[i;LoB mmkkUdGS2Qtlnw yz6fXuPw)۶ttIwZJ=z[GӺ^5 s# Nj>4 V[!]!V<ߧC'}B߾t>V(>4}7 t zv;] div.version { color: #111; } .fa-github::before, .icon-github::before { content: ""; } .fa-home::before, .icon-home::before { content: ""; } .fa-arrow-circle-right::before, .icon-circle-arrow-right::before { content: ""; } .fa-arrow-circle-left::before, .icon-circle-arrow-left::before { content: ""; } verilator-5.020/docs/internals.rst0000644000175000017500000025222114544475344017112 0ustar carstencarsten|Logo| ===================== Verilator Internals ===================== .. contents:: :depth: 3 Introduction ============ This file discusses internal and programming details for Verilator. It's a reference for developers and debugging problems. See also the Verilator internals presentation at https://www.veripool.org. Code Flows ========== Verilator Flow -------------- The main flow of Verilator can be followed by reading the Verilator.cpp ``process()`` function: 1. First, the files specified on the command line are read. Reading involves preprocessing, then lexical analysis with Flex and parsing with Bison. This produces an abstract syntax tree (AST) representation of the design, which is what is visible in the .tree files described below. 2. Verilator then makes a series of passes over the AST, progressively refining and optimizing it. 3. Cells in the AST first linked, which will read and parse additional files as above. 4. Functions, variable, and other references are linked to their definitions. 5. Parameters are resolved, and the design is elaborated. 6. Verilator then performs additional edits and optimizations on the hierarchical design. This includes coverage, assertions, X elimination, inlining, constant propagation, and dead code elimination. 7. References in the design are then pseudo-flattened. Each module's variables and functions get "Scope" references. A scope reference is an occurrence of that un-flattened variable in the flattened hierarchy. A module that occurs only once in the hierarchy will have a single scope and single VarScope for each variable. A module that occurs twice will have a scope for each occurrence, and two VarScopes for each variable. This allows optimizations to proceed across the flattened design while still preserving the hierarchy. 8. Additional edits and optimizations proceed on the pseudo-flat design. These include module references, function inlining, loop unrolling, variable lifetime analysis, lookup table creation, always splitting, and logic gate simplifications (pushing inverters, etc.). 9. Verilator orders the code. Best case, this results in a single "eval" function, which has all always statements flowing from top to bottom with no loops. 10. Verilator mostly removes the flattening, so that code may be shared between multiple invocations of the same module. It localizes variables, combines identical functions, expands macros to C primitives, adds branch prediction hints, and performs additional constant propagation. 11. Verilator finally writes the C++ modules. Key Classes Used in the Verilator Flow -------------------------------------- ``AstNode`` ~~~~~~~~~~~ The AST is represented at the top level by the class ``AstNode``. This abstract class has derived classes for the individual components (e.g. ``AstGenerate`` for a generate block) or groups of components (e.g. ``AstNodeFTask`` for functions and tasks, which in turn has ``AstFunc`` and ``AstTask`` as derived classes). An important property of the ``AstNode`` type hierarchy is that all non-final subclasses of ``AstNode`` (i.e.: those which themselves have subclasses) must be abstract as well, and be named with the prefix ``AstNode*``. The ``astgen`` (see below) script relies on this. Each ``AstNode`` has pointers to up to four children, accessed by the ``op1p`` through ``op4p`` methods. These methods are then abstracted in a specific Ast\* node class to a more specific name. For example, with the ``AstIf`` node (for ``if`` statements), ``thensp`` calls ``op2p`` to give the pointer to the AST for the "then" block, while ``elsesp`` calls ``op3p`` to give the pointer to the AST for the "else" block, or NULL if there is not one. These accessors are automatically generated by ``astgen`` after parsing the ``@astgen`` directives in the specific ``AstNode`` subclasses. ``AstNode`` has the concept of a next and previous AST - for example, the next and previous statements in a block. Pointers to the AST for these statements (if they exist) can be obtained using the ``back`` and ``next`` methods. It is useful to remember that the derived class ``AstNetlist`` is at the top of the tree, so checking for this class is the standard way to see if you are at the top of the tree. By convention, each function/method uses the variable ``nodep`` as a pointer to the ``AstNode`` currently being processed. There are notable sub-hierarchies of the ``AstNode`` sub-types, namely: 1. All AST nodes representing data types derive from ``AstNodeDType``. 2. All AST nodes representing expressions (i.e.: anything that stands for, or evaluates to a value) derive from ``AstNodeExpr``. ``VNVisitor`` ~~~~~~~~~~~~~ The passes are implemented by AST visitor classes. These are implemented by subclasses of the abstract class, ``VNVisitor``. Each pass creates an instance of the visitor class, which in turn implements a method to perform the pass. ``V3Graph`` ~~~~~~~~~~~ A number of passes use graph algorithms, and the class ``V3Graph`` is provided to represent those graphs. Graphs are directed, and algorithms are provided to manipulate the graphs and output them in `GraphViz `__ dot format. ``V3Graph.h`` provides documentation of this class. ``V3GraphVertex`` ~~~~~~~~~~~~~~~~~ ``V3GraphVertex`` is the base class for vertices in a graph. Vertices have an associated ``fanout``, ``color`` and ``rank``, which may be used in algorithms for ordering the graph. A generic ``user``/``userp`` member variable is also provided. Virtual methods are provided to specify the name, color, shape, and style to be used in dot output. Typically users provide derived classes from ``V3GraphVertex`` which will reimplement these methods. Iterators are provided to access in and out edges. Typically these are used in the form: :: for (V3GraphEdge *edgep = vertexp->inBeginp(); edgep; edgep = edgep->inNextp()) { ``V3GraphEdge`` ~~~~~~~~~~~~~~~ ``V3GraphEdge`` is the base class for directed edges between pairs of vertices. Edges have an associated ``weight`` and may also be made ``cutable``. A generic ``user``/``userp`` member variable is also provided. Accessors, ``fromp`` and ``top`` return the "from" and "to" vertices respectively. Virtual methods are provided to specify the label, color, and style to be used in dot output. Typically users provided derived classes from ``V3GraphEdge``, which will reimplement these methods. ``V3GraphAlg`` ~~~~~~~~~~~~~~ This is the base class for graph algorithms. It implements a ``bool`` method, ``followEdge`` which algorithms can use to decide whether an edge is followed. This method returns true if the graph edge has a weight greater than one and a user function, ``edgeFuncp`` (supplied in the constructor) returns ``true``. A number of predefined derived algorithm classes and access methods are provided and documented in ``V3GraphAlg.cpp``. ``DfgGraph`` ~~~~~~~~~~~~ The data-flow graph-based combinational logic optimizer (DFG optimizer) converts an ``AstModule`` into a ``DfgGraph``. The graph represents the combinational equations (~continuous assignments) in the module, and for the duration of the DFG passes, it takes over the role of the represented ``AstModule``. The ``DfgGraph`` keeps hold of the represented ``AstModule``, and the ``AstModule`` retains all other logic that is not representable as a data-flow graph. At the end of optimization, the combinational logic represented by the ``DfgGraph`` is converted back into AST form and is re-inserted into the corresponding ``AstModule``. The ``DfgGraph`` is distinct from ``V3Graph`` for efficiency and other desirable properties which make writing DFG passes easier. ``DfgVertex`` ~~~~~~~~~~~~~ The ``DfgGraph`` represents combinational logic equations as a graph of ``DfgVertex`` vertices. Each sub-class of ``DfgVertex`` corresponds to an expression (a sub-class of ``AstNodeExpr``), a constant, or a variable reference. LValues and RValues referencing the same storage location are represented by the same ``DfgVertex``. Consumers of such vertices read as the LValue, writers of such vertices write the RValue. The bulk of the final ``DfgVertex`` sub-classes are generated by ``astgen`` from the corresponding ``AstNode`` definitions. Scheduling ---------- Verilator implements the Active and NBA regions of the SystemVerilog scheduling model as described in IEEE 1800-2017 chapter 4, and in particular sections 4.5 and Figure 4.1. The static (Verilation time) scheduling of SystemVerilog processes is performed by code in the ``V3Sched`` namespace. The single entry point to the scheduling algorithm is ``V3Sched::schedule``. Some preparatory transformations important for scheduling are also performed in ``V3Active`` and ``V3ActiveTop``. High-level evaluation functions are constructed by ``V3Order``, which ``V3Sched`` invokes on subsets of the logic in the design. Scheduling deals with the problem of evaluating 'logic' in the correct order and the correct number of times in order to compute the correct state of the SystemVerilog program. Throughout this section, we use the term 'logic' to refer to all SystemVerilog constructs that describe the evolution of the state of the program. In particular, all SystemVerilog processes and continuous assignments are considered 'logic', but not for example variable definitions without initialization or other miscellaneous constructs. Classes of logic ~~~~~~~~~~~~~~~~ The first step in the scheduling algorithm is to gather all the logic present in the design, and classify it based on the conditions under which the logic needs to be evaluated. The classes of logic we distinguish between are: - SystemVerilog ``initial`` processes, that need to be executed once at startup. - Static variable initializers. These are a separate class as they need to be executed before ``initial`` processes. - SystemVerilog ``final`` processes. - Combinational logic. Any process or construct that has an implicit sensitivity list with no explicit sensitivities is considered 'combinational' logic. This includes among other things, ``always @*`` and ``always_comb`` processes, and continuous assignments. Verilator also converts some other ``always`` processes to combinational logic in ``V3Active`` as described below. - Clocked logic. Any process or construct that has an explicit sensitivity list, with no implicit sensitivities, is considered 'clocked' (or 'sequential') logic. This includes, among other things ``always`` and ``always_ff`` processes with an explicit sensitivity list. Note that the distinction between clocked logic and combinational logic is only important for the scheduling algorithm within Verilator as we handle the two classes differently. It is possible to convert clocked logic into combinational logic if the explicit sensitivity list of the clocked logic is the same as the implicit sensitivity list of the equivalent combinational logic would be. The canonical examples are: ``always @(a) x = a;``, which is considered to be clocked logic by Verilator, and the equivalent ``assign x = a;``, which is considered to be combinational logic. ``V3Active`` in fact converts all clocked logic to combinational logic whenever possible, as this provides advantages for scheduling as described below. There is also a 'hybrid' logic class, which has both explicit and implicit sensitivities. This kind of logic does not arise from a SystemVerilog construct, but is created during scheduling to break combinational cycles. Details of this process and the hybrid logic class are described below. Scheduling of simple classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SystemVerilog ``initial`` and ``final`` blocks can be scheduled (executed) in an arbitrary order. Static variable initializers need to be executed in source code order in case there is a dependency between initializers, but the ordering of static variable initialization is otherwise not defined by the SystemVerilog standard (particularly, in the presence of hierarchical references in static variable initializers). The scheduling algorithm handles all three of these classes the same way and schedules the logic in these classes in source code order. This step yields the ``_eval_static``, ``_eval_initial`` and ``_eval_final`` functions which execute the corresponding logic constructs. Scheduling of clocked and combinational logic ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For performance, clocked and combinational logic needs to be ordered. Conceptually this minimizes the iterations through the evaluation loop presented in the reference algorithm in the SystemVerilog standard (IEEE 1800-2017 section 4.5), by evaluating logic constructs in data-flow order. Without going into a lot of detail here, accept that well thought out ordering is crucial to good simulation performance, and also enables further optimizations later on. At the highest level, ordering is performed by ``V3Order::order``, which is invoked by ``V3Sched::schedule`` on various subsets of the combinational and clocked logic as described below. The important thing to highlight now is that ``V3Order::order`` operates by assuming that the state of all variables driven by combinational logic is consistent with that combinational logic. While this might seem subtle, it is very important, so here is an example: :: always_comb d = q + 2; always @(posedge clock) q <= d; During ordering, ``V3Order`` will assume that ``d`` equals ``q + 2`` at the beginning of an evaluation step. As a result it will order the clocked logic first, and all downstream combinational logic (like the assignment to ``d``) will execute after the clocked logic that drives inputs to the combinational logic, in data-flow (or dependency) order. At the end of the evaluation step, this ordering restores the invariant that variables driven by combinational logic are consistent with that combinational logic (i.e., the circuit is in a settled/steady state). One of the most important optimizations for performance is to only evaluate combinational logic, if its inputs might have changed. For example, there is no point in evaluating the above assignment to ``d`` on a negative edge of the clock signal. Verilator does this by pushing the combinational logic into the same (possibly multiple) event domains as the logic driving the inputs to that combinational logic, and only evaluating the combinational logic if at least one driving domain has been triggered. The impact of this activity gating is very high (observed 100x slowdown on large designs when turning it off), it is the reason we prefer to convert clocked logic to combinational logic in ``V3Active`` whenever possible. The ordering procedure described above works straightforward unless there are combinational logic constructs that are circularly dependent (a.k.a.: the UNOPTFLAT warning). Combinational scheduling loops can arise in sound (realizable) circuits as Verilator considers each SystemVerilog process as a unit of scheduling (albeit we do try to split processes into smaller ones to avoid this circularity problem whenever possible, this is not always possible). Breaking combinational loops ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Combinational loops are broken by the introduction of instances of the 'hybrid' logic class. As described in the previous section, combinational loops require iteration until the logic is settled, in order to restore the invariant that combinationally driven signals are consistent with the combinational logic. To achieve this, ``V3Sched::schedule`` calls ``V3Sched::breakCycles``, which builds a dependency graph of all combinational logic in the design, and then breaks all combinational cycles by converting all combinational logic that consumes a variable driven via a 'back-edge' into hybrid logic. Here 'back-edge' just means a graph edge that points from a higher-rank vertex to a lower rank vertex in some consistent ranking of the directed graph. Variables driven via a back-edge in the dependency graph are marked, and all combinational logic that depends on such variables is converted into hybrid logic, with the back-edge driven variables listed as explicit 'changed' sensitivities. Hybrid logic is handled by ``V3Order`` mostly in the same way as combinational logic, with two exceptions: - Explicit sensitivities of hybrid logic are ignored for the purposes of data-flow ordering with respect to other combinational or hybrid logic. I.e.: an explicit sensitivity suppresses the implicit sensitivity on the same variable. This could also be interpreted as ordering the hybrid logic as if all variables listed as explicit sensitivities were substituted as constants with their current values. - The explicit sensitivities are included as an additional driving domain of the logic, and also cause evaluation when triggered. This means that hybrid logic is evaluated when either any of its implicit sensitivities might have been updated (the same way as combinational logic, by pushing it into the domains that write those variables), or if any of its explicit sensitivities are triggered. The effect of this transformation is that ``V3Order`` can proceed as if there are no combinational cycles (or alternatively, under the assumption that the back-edge-driven variables don't change during one evaluation pass). The evaluation loop invoking the ordered code, will then re-invoke it on a follow on iteration, if any of the explicit sensitivities of hybrid logic have actually changed due to the previous invocation, iterating until all the combinational (including hybrid) logic have settled. One might wonder if there can be a race condition between clocked logic triggered due to a combinational signal change from the previous evaluation pass, and a combinational loop settling due to hybrid logic, if the clocked logic reads the not yet settled combinationally driven signal. Such a race is indeed possible, but our evaluation is consistent with the SystemVerilog scheduling semantics (IEEE 1800-2017 chapter 4), and therefore any program that exhibits such a race has non-deterministic behavior according to the SystemVerilog semantics, so we accept this. Settling combinational logic after initialization ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ At the beginning of simulation, once static initializer and ``initial`` blocks have been executed, we need to evaluate all combinational logic, in order to restore the invariant utilized by ``V3Order`` that the state of all combinationally driven variables are consistent with the combinational logic. To achieve this, we invoke ``V3Order::order`` on all of the combinational and hybrid logic, and iterate the resulting evaluation function until no more hybrid logic is triggered. This yields the `_eval_settle` function, which is invoked at the beginning of simulation after the `_eval_initial`. Partitioning logic for correct NBA updates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``V3Order`` can order logic corresponding to non-blocking assignments (NBAs) to yield correct simulation results, as long as all the sensitivity expressions of clocked logic triggered in the Active scheduling region of the current time step are known up front. I.e., the ordering of NBA updates is only correct if derived clocks that are computed in an Active region update (that is, via a blocking or continuous assignment) are known up front. We can ensure this by partitioning the logic into two regions. Note these regions are a concept of the Verilator scheduling algorithm, and they do not directly correspond to the similarly named SystemVerilog scheduling regions as defined in the standard: - All logic (clocked, combinational and hybrid) that transitively feeds into, or drives via a non-blocking or continuous assignments (or via any update that SystemVerilog executes in the Active scheduling region), a variable that is used in the explicit sensitivity list of some clocked or hybrid logic, is assigned to the 'act' region. - All other logic is assigned to the 'nba' region. For completeness, note that a subset of the 'act' region logic, specifically, the logic related to the pre-assignments of NBA updates (i.e., AstAssignPre nodes), is handled separately, but is executed as part of the 'act' region. Also note that all logic representing the committing of an NBA (i.e., Ast*Post) nodes) will be in the 'nba' region. This means that the evaluation of the 'act' region logic will not commit any NBA updates. As a result, the 'act' region logic can be iterated to compute all derived clock signals up front. The correspondence between the SystemVerilog Active and NBA scheduling regions, and the internal 'act' and 'nba' regions, is that 'act' contains all Active region logic that can compute a clock signal, while 'nba' contains all other Active and NBA region logic. For example, if the only clocks in the design are top-level inputs, then 'act' will be empty, and 'nba' will contain the whole of the design. The partitioning described above is performed by ``V3Sched::partition``. Replication of combinational logic ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We will separately invoke ``V3Order::order`` on the 'act' and 'nba' region logic. Combinational logic that reads variables driven from both 'act' and 'nba' region logic has the problem of needing to be reevaluated even if only one of the regions updates an input variable. We could pass additional trigger expressions between the regions to make sure combinational logic is always reevaluated, or we can replicate combinational logic that is driven from multiple regions, by copying it into each region that drives it. Experiments show this simple replication works well performance-wise (and notably ``V3Combine`` is good at combining the replicated code), so this is what we do in ``V3Sched::replicateLogic``. In ``V3Sched::replicateLogic``, in addition to replicating logic into the 'act' and 'nba' regions, we also replicate combinational (and hybrid) logic that depends on top level inputs. These become a separate 'ico' region (Input Combinational logic), which we will always evaluate at the beginning of a time-step to ensure the combinational invariant holds even if input signals have changed. Note that this eliminates the need of changing data and clock signals on separate evaluations, as was necessary with earlier versions of Verilator). Constructing the top level `_eval` function ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To construct the top level `_eval` function, which updates the state of the circuit to the end of the current time step, we invoke ``V3Order::order`` separately on the 'ico', 'act' and 'nba' logic, which yields the `_eval_ico`, `_eval_act`, and `_eval_nba` functions. We then put these all together with the corresponding functions that compute the respective trigger expressions into the top level `_eval` function, which on the high level has the form: :: void _eval() { // Update combinational logic dependent on top level inputs ('ico' region) while (true) { _eval__triggers__ico(); // If no 'ico' region trigger is active if (!ico_triggers.any()) break; _eval_ico(); } // Iterate 'act' and 'nba' regions together while (true) { // Iterate 'act' region, this computes all derived clocks updaed in the // Active scheduling region, but does not commit any NBAs that executed // in 'act' region logic. while (true) { _eval__triggers__act(); // If no 'act' region trigger is active if (!act_triggers.any()) break; // Remember what 'act' triggers were active, 'nba' uses the same latch_act_triggers_for_nba(); _eval_act(); } // If no 'nba' region trigger is active if (!nba_triggers.any()) break; // Evaluate all other Active region logic, and commit NBAs _eval_nba(); } } Timing ------ Timing support in Verilator utilizes C++ coroutines, which is a new feature in C++20. The basic idea is to represent processes and tasks that await a certain event or simulation time as coroutines. These coroutines get suspended at the await, and resumed whenever the triggering event occurs, or at the expected simulation time. There are several runtime classes used for managing such coroutines defined in ``verilated_timing.h`` and ``verilated_timing.cpp``. ``VlCoroutineHandle`` ~~~~~~~~~~~~~~~~~~~~~ A thin wrapper around an ``std::coroutine_handle<>``. It forces move semantics, destroys the coroutine if it remains suspended at the end of the design's lifetime, and prevents multiple ``resume`` calls in the case of ``fork..join_any``. ``VlCoroutine`` ~~~~~~~~~~~~~~~ Return value of all coroutines. Together with the promise type contained within, it allows for chaining coroutines - resuming coroutines from up the call stack. The calling coroutine's handle is saved in the promise object as a continuation, that is, the coroutine that must be resumed after the promise's coroutine finishes. This is necessary as C++ coroutines are stackless, meaning each one is suspended independently of others in the call graph. ``VlDelayScheduler`` ~~~~~~~~~~~~~~~~~~~~ This class manages processes suspended by delays. There is one instance of this class per design. Coroutines ``co_await`` this object's ``delay`` function. Internally, they are stored in a heap structure sorted by simulation time in ascending order. When ``resume`` is called on the delay scheduler, all coroutines awaiting the current simulation time are resumed. The current simulation time is retrieved from a ``VerilatedContext`` object. ``VlTriggerScheduler`` ~~~~~~~~~~~~~~~~~~~~~~ This class manages processes that await events (triggers). There is one such object per each trigger awaited by coroutines. Coroutines ``co_await`` this object's ``trigger`` function. They are stored in two stages - `uncommitted` and `ready`. First, they land in the `uncommitted` stage, and cannot be resumed. The ``resume`` function resumes all coroutines from the `ready` stage and moves `uncommitted` coroutines into `ready`. The ``commit`` function only moves `uncommitted` coroutines into `ready`. This split is done to avoid self-triggering and triggering coroutines multiple times. See the `Scheduling with timing` section for details on how this is used. ``VlDynamicTriggerScheduler`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Like ``VlTriggerScheduler``, ``VlDynamicTriggerScheduler`` manages processes that await triggers. However, it does not rely on triggers evaluated externally by the 'act' trigger eval function. Instead, it is also responsible for trigger evaluation. Coroutines that make use of this scheduler must adhere to a certain procedure: :: __Vtrigger = 0; while (!__Vtrigger) { co_await __VdynSched.evaluation();
;
       __Vtrigger = ;
       [optionally] co_await __VdynSched.postUpdate();
       ;
   }
   co_await __VdynSched.resumption();

The coroutines get resumed at trigger evaluation time, evaluate their local
triggers, optionally await the post update step, and if the trigger is set,
await proper resumption in the 'act' eval step.

``VlForkSync``
~~~~~~~~~~~~~~

Used for synchronizing ``fork..join`` and ``fork..join_any``. Forking
coroutines ``co_await`` its ``join`` function, and forked ones call ``done``
when they're finished. Once the required number of coroutines (set using
``setCounter``) finish execution, the forking coroutine is resumed.

``VlForever``
~~~~~~~~~~~~~

A small utility awaitable type. It allows for blocking a coroutine forever. It
is currently only used for ``wait`` statements that await a constant false
condition. See the `Timing Pass` section for more details.

Timing Pass
~~~~~~~~~~~

There are two visitors in ``V3Timing.cpp``.

The first one, ``TimingSuspendableVisitor``, does not perform any AST
transformations. It is responsible for marking processes and C++ functions that
contain timing controls as suspendable. Processes that call suspendable
functions are also marked as suspendable. Functions that call, are overridden
by, or override suspendable functions are marked as suspendable as well.

The visitor keeps a dependency graph of functions and processes to handle such
cases. A function or process is dependent on a function if it calls it. A
virtual class method is dependent on another class method if it calls it,
overrides it, or is overriden by it.

The second visitor in ``V3Timing.cpp``, ``TimingControlVisitor``, uses the
information provided by ``TimingSuspendableVisitor`` and transforms each timing
control into a ``co_await``.

* event controls are turned into ``co_await`` on a trigger scheduler's
  ``trigger`` method. The awaited trigger scheduler is the one corresponding to
  the sentree referenced by the event control. This sentree is also referenced
  by the ``AstCAwait`` node, to be used later by the static scheduling code.
* if an event control waits on a local variable or class member, it uses a
  local trigger which it evaluates inline. It awaits a dynamic trigger
  scheduler multiple times: for trigger evaluation, updates, and resumption.
  The dynamic trigger scheduler is responsible for resuming the coroutine at
  the correct point of evaluation.
* delays are turned into ``co_await`` on a delay scheduler's ``delay`` method.
  The created ``AstCAwait`` nodes also reference a special sentree related to
  delays, to be used later by the static scheduling code.
* ``join`` and ``join_any`` are turned into ``co_await`` on a ``VlForkSync``'s
  ``join`` method. Each forked process gets a ``VlForkSync::done`` call at the
  end.

Assignments with intra-assignment timing controls are simplified into
assignments after those timing controls, with the LHS and RHS values evaluated
before them and stored in temporary variables.

``wait`` statements are transformed into while loops that check the condition
and then await changes in variables used in the condition. If the condition is
always false, the ``wait`` statement is replaced by a ``co_await`` on a
``VlForever``. This is done instead of a return in case the ``wait`` is deep in
a call stack (otherwise, the coroutine's caller would continue execution).

Each sub-statement of a ``fork`` is put in an ``AstBegin`` node for easier
grouping. In a later step, each of these gets transformed into a new, separate
function. See the `Forks` section for more detail.

Suspendable functions get the return type of ``VlCoroutine``, which makes them
coroutines. Later, during ``V3Sched``, suspendable processes are also
transformed into coroutines.

Scheduling with timing
~~~~~~~~~~~~~~~~~~~~~~

Timing features in Verilator are built on top of the static scheduler. Triggers
are used for determining which delay or trigger schedulers should resume. A
special trigger is used for the delay scheduler. This trigger is set if there
are any coroutines awaiting the current simulation time
(``VlDelayScheduler::awaitingCurrentTime()``).

All triggers used by a suspendable process are mapped to variables written in
that process. When ordering code using ``V3Order``, these triggers are provided
as external domains of these variables. This ensures that the necessary
combinational logic is triggered after a coroutine resumption.

There are two functions for managing timing logic called by ``_eval()``:

* ``_timing_commit()``, which commits all coroutines whose triggers were not set
  in the current iteration,
* ``_timing_resume()``, which calls `resume()` on all trigger and delay
  schedulers whose triggers were set in the current iteration.

Thanks to this separation, a coroutine awaiting a trigger cannot be suspended
and resumed in the same iteration, and it cannot be resumed before it suspends.

All coroutines are committed and resumed in the 'act' eval loop. With timing
features enabled, the ``_eval()`` function takes this form:

::

   void _eval() {
     while (true) {
       _eval__triggers__ico();
       if (!ico_triggers.any()) break;
       _eval_ico();
     }

     while (true) {
       while (true) {
         _eval__triggers__act();

         // Commit all non-triggered coroutines
         _timing_commit();

         if (!act_triggers.any()) break;
         latch_act_triggers_for_nba();

         // Resume all triggered coroutines
         _timing_resume();

         _eval_act();
       }
       if (!nba_triggers.any()) break;
       _eval_nba();
     }
   }

Forks
~~~~~

After the scheduling step, forks sub-statements are transformed into separate
functions, and these functions are called in place of the sub-statements. These
calls must be without ``co_await``, so that suspension of a forked process
doesn't suspend the forking process.

In forked processes, references to local variables are only allowed in
``fork..join``, as this is the only case that ensures the lifetime of these
locals are at least as long as the execution of the forked processes.


Multithreaded Mode
------------------

In ``--threads`` mode, the frontend of the Verilator pipeline is the same
as serial mode, up until V3Order.

``V3Order`` builds a fine-grained, statement-level dependency graph that
governs the ordering of code within a single ``eval()`` call. In serial
mode, that dependency graph is used to order all statements into a total
serial order. In parallel mode, the same dependency graph is the starting
point for a partitioner (``V3Partition``).

The partitioner's goal is to coarsen the fine-grained graph into a coarser
graph, while maintaining as much available parallelism as possible. Often
the partitioner can transform an input graph with millions of nodes into a
coarsened execution graph with a few dozen nodes, while maintaining enough
parallelism to take advantage of a modern multicore CPU. Runtime
synchronization cost is reasonable with so few nodes.


Partitioning
~~~~~~~~~~~~

Our partitioner is similar to the one Vivek Sarkar described in his 1989
paper *Partitioning and Scheduling Parallel Programs for Multiprocessors*.

Let's define some terms:


Par Factor
~~~~~~~~~~

The available parallelism or "par-factor" of a DAG is the total cost to
execute all nodes, divided by the cost to execute the longest critical path
through the graph. This is the speedup you would get from running the graph
in parallel, if given infinite CPU cores available and communication and
synchronization is zero.


Macro Task
~~~~~~~~~~

When the partitioner coarsens the graph, it combines nodes together.  Each
fine-grained node represents an atomic "task"; combined nodes in the
coarsened graph are "macro-tasks". This term comes from Sarkar. Each
macro-task executes from start to end on one processor, without any
synchronization to any other macro-task during its execution.
(Synchronization only happens before the macro-task begins or after it
ends.)


Edge Contraction
~~~~~~~~~~~~~~~~

Verilator's partitioner, like Sarkar's, primarily relies on "edge
contraction" to coarsen the graph. It starts with one macro-task per atomic
task and iteratively combines pairs of edge-connected macro-tasks.


Local Critical Path
~~~~~~~~~~~~~~~~~~~

Each node in the graph has a "local" critical path. That's the critical
path from the start of the graph to the start of the node, plus the node's
cost, plus the critical path from the end of the node to the end of the
graph.

Sarkar calls out an important trade-off: coarsening the graph reduces
runtime synchronization overhead among the macro-tasks, but it tends to
increase the critical path through the graph and thus reduces par-factor.

Sarkar's partitioner, and ours, chooses pairs of macro-tasks to merge such
that the growth in critical path is minimized. Each candidate merge would
result in a new node, which would have some local critical path.  We choose
the candidate that would produce the shortest local critical path. Repeat
until par-factor falls to a target threshold. It's a greedy algorithm, and
it's not guaranteed to produce the best partition (which Sarkar proves is
NP-hard).


Estimating Logic Costs
~~~~~~~~~~~~~~~~~~~~~~

To compute the cost of any given path through the graph, Verilator
estimates an execution cost for each task. Each macro-task has an execution
cost which is the sum of its tasks' costs. We assume that communication
overhead and synchronization overhead are zero, so the cost of any given
path through the graph is the sum of macro-task execution costs. Sarkar
does almost the same thing, except that he has nonzero estimates for
synchronization costs.

Verilator's cost estimates are assigned by ``InstrCountVisitor``.  This
class is perhaps the most fragile piece of the multithread
implementation. It's easy to have a bug where you count something cheap
(e.g. accessing one element of a huge array) as if it were expensive (eg.
by counting it as if it were an access to the entire array.) Even without
such gross bugs, the estimates this produce are only loosely predictive of
actual runtime cost. Multithread performance would be better with better
runtime costs estimates. This is an area to improve.


Scheduling Macro-Tasks at Runtime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

After coarsening the graph, we must schedule the macro-tasks for
runtime. Sarkar describes two options: you can dynamically schedule tasks
at runtime, with a runtime graph follower. Sarkar calls this the
"macro-dataflow model." Verilator does not support this; early experiments
with this approach had poor performance.

The other option is to statically assign macro-tasks to threads, with each
thread running its macro-tasks in a static order. Sarkar describes this in
Chapter 5. Verilator takes this static approach. The only dynamic aspect is
that each macro task may block before starting, to wait until its
prerequisites on other threads have finished.

The synchronization cost is cheap if the prereqs are done. If they're not,
fragmentation (idle CPU cores waiting) is possible. This is the major
source of overhead in this approach. The ``--prof-exec`` switch and the
``verilator_gantt`` script can visualize the time lost to such
fragmentation.


Locating Variables for Best Spatial Locality
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

After scheduling all code, we attempt to locate variables in memory, such
that variables accessed by a single macro-task are close together in
memory. This provides "spatial locality" - when we pull in a 64-byte cache
line to access a 2-byte variable, we want the other 62 bytes to be ones
we'll also likely access soon, for best cache performance.

This is critical for performance. It should allow Verilator
to scale to very large models. We don't rely on our working set fitting
in any CPU cache; instead we essentially "stream" data into caches from
memory. It's not literally streaming, where the address increases
monotonically, but it should have similar performance characteristics,
so long as each macro-task's dataset fits in one core's local caches.

To achieve spatial locality, we tag each variable with the set of
macro-tasks that access it. Let's call this set the "footprint" of that
variable. The variables in a given module have a set of footprints. We
can order those footprints to minimize the distance between them
(distance is the number of macro-tasks that are different across any two
footprints) and then emit all variables into the struct in
ordered-footprint order.

The footprint ordering is literally the traveling salesman problem, and
we use a TSP-approximation algorithm to get close to an optimal sort.

This is an old idea. Simulators designed at DEC in the early 1990s used
similar techniques to optimize both single-thread and multithread
modes. (Verilator does not optimize variable placement for spatial
locality in serial mode; that is a possible area for improvement.)


Improving Multithreaded Performance Further (a TODO list)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Wave Scheduling
+++++++++++++++

To allow the Verilated model to run in parallel with the testbench, it
might be nice to support "wave" scheduling, in which work on a cycle begins
before ``eval()`` is called or continues after ``eval()`` returns. For now,
all work on a cycle happens during the ``eval()`` call, leaving Verilator's
threads idle while the testbench (everything outside ``eval()``) is
working. This would involve fundamental changes within the partitioner,
however, it's probably the best bet for hiding testbench latency.


Efficient Dynamic Scheduling
++++++++++++++++++++++++++++

To scale to more than a few threads, we may revisit a fully dynamic
scheduler. For large (>16 core) systems, it might make sense to dedicate an
entire core to scheduling, so that scheduler data structures would fit in
its L1 cache and thus the cost of traversing priority-ordered ready lists
would not be prohibitive.


Static Scheduling with Runtime Repack
+++++++++++++++++++++++++++++++++++++

We could modify the static scheduling approach by gathering actual
macro-task execution times at run time, and dynamically re-packing the
macro-tasks into the threads also at run time. Say, re-pack once every
10,000 cycles or something. This has the potential to do better than our
static estimates about macro-task run times. It could potentially react to
CPU cores that aren't performing equally, due to NUMA or thermal throttling
or nonuniform competing memory traffic or whatever.


Clock Domain Balancing
++++++++++++++++++++++

Right now Verilator makes no attempt to balance clock domains across
macro-tasks. For a multi-domain model, that could lead to bad gantt chart
fragmentation. This could be improved if it's a real problem in practice.


Other Forms of MTask Balancing
++++++++++++++++++++++++++++++

The largest source of runtime overhead is idle CPUs, which happens due to
variance between our predicted runtime for each MTask and its actual
runtime. That variance is magnified if MTasks are homogeneous, containing
similar repeating logic which was generally close together in source code
and which is still packed together even after going through Verilator's
digestive tract.

If Verilator could avoid doing that, and instead would take source logic
that was close together and distribute it across MTasks, that would
increase the diversity of any given MTask, and this should reduce variance
in the cost estimates.

One way to do that might be to make various "tie breaker" comparison
routines in the sources to rely more heavily on randomness, and
generally try harder not to keep input nodes together when we have the
option to scramble things.

Profile-guided optimization make this a bit better, by adjusting mtask
scheduling, but this does not yet guide the packing into mtasks.


Performance Regression
++++++++++++++++++++++

It would be nice if we had a regression of large designs, with some
diversity of design styles, to test on both single- and multithreaded
modes. This would help to avoid performance regressions, and also to
evaluate the optimizations while minimizing the impact of parasitic noise.


Per-Instance Classes
++++++++++++++++++++

If we have multiple instances of the same module, and they partition
differently (likely; we make no attempt to partition them the same), then
the variable sort will be suboptimal for either instance. A possible
improvement would be to emit an unique class for each instance of a module,
and sort its variables optimally for that instance's code stream.


Verilated Flow
--------------

The evaluation loop outputted by Verilator is designed to allow a single
function to perform evaluation under most situations.

On the first evaluation, the Verilated code calls initial blocks, and then
"settles" the modules, by evaluating functions (from always statements)
until all signals are stable.

On other evaluations, the Verilated code detects what input signals have
changes. If any are clocks, it calls the appropriate sequential functions
(from ``always @ posedge`` statements). Interspersed with sequential
functions, it calls combo functions (from ``always @*``).  After this is
complete, it detects any changes due to combo loops or internally generated
clocks, and if one is found must reevaluate the model again.

For SystemC code, the ``eval()`` function is wrapped in a SystemC
``SC_METHOD``, sensitive to all inputs. (Ideally, it would only be sensitive
to clocks and combo inputs, but tracing requires all signals to cause
evaluation, and the performance difference is small.)

If tracing is enabled, a callback examines all variables in the design for
changes, and writes the trace for each change. To accelerate this process,
the evaluation process records a bitmask of variables that might have
changed; if clear, checking those signals for changes may be skipped.


Coding Conventions
==================


Compiler Version and C++14
--------------------------

Verilator requires C14. Verilator does not require any newer versions, but
is maintained to build successfully with C17/C20.


Indentation and Naming Style
----------------------------

We will work with contributors to fix up indentation style issues, but it
is appreciated if you could match our style:

- Use "mixedCapsSymbols" instead of "underlined_symbols".

- Use a "p" suffix on variables that are pointers, e.g., "nodep".

- Comment every member variable.

- In the include directory, use /// to document functions the user
  calls. (This convention has not been applied retroactively.)

C and Python indentation is automatically maintained with "make format"
using clang-format version 10.0.0, and yapf for python, and is
automatically corrected in the CI actions. For those manually formatting C
code:

- Use four spaces per level, and no tabs.

- Use two spaces between the end of source and the beginning of a
  comment.

- Use one space after if/for/switch/while and similar keywords.

- No spaces before semicolons, nor between a function's name and open
  parenthesis (only applies to functions; if/else has a following space).


The ``astgen`` Script
---------------------

The ``astgen`` script is used to generate some of the repetitive C++ code
related to the ``AstNode`` type hierarchy. An example is the abstract ``visit``
methods in ``VNVisitor``. There are other uses; please see the ``*__gen*``
files in the bulid directories and the ``astgen`` script for details.  A
description of the more advanced features of ``astgen`` are provided here.


Generating ``AstNode`` members
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Some of the member s of ``AstNode`` sub-classes are generated by ``astgen``.
These are emitted as pre-processor macro definitions, which then need to be
added to the ``AstNode`` sub-classes they correspond to. Specifically ``class
AstFoo`` should contain an instance of ``ASTGEN_MEMBERS_AstFoo;`` at class
scope.  The ``astgen`` script checks and errors if this is not present. The
method generated depends on whether the class is a concrete final class, or an
abstract ``AstNode*`` base-class, and on ``@astgen`` directives present in
comment sections in the body of the ``AstNode`` sub-class definitions.


List of ``@astgen`` directives
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``@astgen`` directives in comments contained in the body of ``AstNode``
sub-class definitions are parsed and contribute to the code generated by
``astgen``. The general syntax is ``@astgen  := ``,
where ```` determines what is being defined, and ```` is
a ```` dependent description of the definition. The list of
``@astgen`` directives are as follows:


``op`` operand  directives
+++++++++++++++++++++++++++++

The ``op1``, ``op2``, ``op3`` and ``op4`` directives are used to describe the
name and type of the up to 4 child operands of a node. The syntax of the
```` field is `` : ``, where ````
will be used as the base name of the generated operand accessors, and
```` is one of:

1. An ``AstNode`` sub-class, defining the operand to be of that type, always
   no-null, and with an always null ``nextp()``. That is, the child node is
   always present, and is a single ``AstNode`` (as opposed to a list).

2. ``Optional[]``. This is just like in point 1 above, but
   defines the child node to be optional, meaning it may be null.

3. ``List[AstNode sub-class]`` describes a list operand, which means the child
   node may have a non-null ``nextp()`` and in addition the child itself may be
   null, representing an empty list.


An example of the full syntax of the directive is
``@astgen op1 := lhsp : AstNodeExpr``.

``astnode`` generates accessors for the child nodes based on these directives.
For non-list children, the names of the getter and setter both are that of the
given ````. For list-type children, the getter is ````,
and instead of the setter, there an ``add`` method is generated
that appends new nodes (or lists of nodes) to the child list.


``alias op`` operand alias directives
++++++++++++++++++++++++++++++++++++++++

If a super-class already defined a name and type for a child node using the
``op`` directive, but a more appropriate name exists in the context of a
sub-class, then the alias directive can be used to introduce an additional name
for the child node. The is ``alias op := `` where
```` is the new name. ``op`` must have been defined in some
super-class of the current node.

Example: ``@astgen alias op1 := condp``


Generating ``DfgVertex`` sub-classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Most of the ``DfgVertex`` sub-classes are generated by ``astgen``, from the
definitions of the corresponding ``AstNode`` vertices.


Additional features of ``astgen``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In addition to generating ``AstNode`` members as described above,
``astgen`` is also use to handle some of the repetitive implementation code
that is still variable enough not to be handled in C++ macros.

In particular, ``astgen`` is used to pre-process some of the C++ source
files. For example in ``V3Const.cpp``, it is used to implement the
``visit()`` functions for each binary operation using the ``TREEOP`` macro.

The original C++ source code is transformed into C++ code in the ``obj_opt``
and ``obj_dbg`` sub-directories (the former for the optimized version of
Verilator, the latter for the debug version). So for example
``V3Const.cpp`` into ``V3Const__gen.cpp``.


Visitor Functions
-----------------

Verilator uses the "Visitor" design pattern to implement its refinement and
optimization passes. This allows separation of the pass algorithm from the
AST on which it operates. Wikipedia provides an introduction to the concept
at https://en.wikipedia.org/wiki/Visitor_pattern.

As noted above, all visitors are derived classes of ``VNVisitor``. All
derived classes of ``AstNode`` implement the ``accept`` method, which takes
as argument a reference to an instance or a ``VNVisitor`` derived class
and applies the visit method of the ``VNVisitor`` to the invoking AstNode
instance (i.e. ``this``).

One possible difficulty is that a call to ``accept`` may perform an edit
which destroys the node it receives as an argument. The
``acceptSubtreeReturnEdits`` method of ``AstNode`` is provided to apply
``accept`` and return the resulting node, even if the original node is
destroyed (if it is not destroyed, it will just return the original node).

The behavior of the visitor classes is achieved by overloading the
``visit`` function for the different ``AstNode`` derived classes. If a
specific implementation is not found, the system will look in turn for
overloaded implementations up the inheritance hierarchy. For example
calling ``accept`` on ``AstIf`` will look in turn for:

::

   void visit(AstIf* nodep)
   void visit(AstNodeIf* nodep)
   void visit(AstNodeStmt* nodep)
   void visit(AstNode* nodep)

There are three ways data is passed between visitor functions.

1. A visitor-class member variable. This is generally for passing
   "parent" information down to children. ``m_modp`` is a common
   example. It's set to NULL in the constructor, where that node
   (``AstModule`` visitor) sets it, then the children are iterated, then
   it's cleared. Children under an ``AstModule`` will see it set, while
   nodes elsewhere will see it clear. If there can be nested items (for
   example an ``AstFor`` under an ``AstFor``) the variable needs to be
   save-set-restored in the ``AstFor`` visitor; otherwise exiting the
   lower for will lose the upper for's setting.

2. User attributes. Each ``AstNode`` (**Note.** The AST node, not the
   visitor) has five user attributes, which may be accessed as an
   integer using the ``user1()`` through ``user4()`` methods, or as a
   pointer (of type ``AstNUser``) using the ``user1p()`` through
   ``user4p()`` methods (a common technique lifted from graph traversal
   packages).

   A visitor first clears the one it wants to use by calling
   ``AstNode::user#ClearTree()``, then it can mark any node's
   ``user#()`` with whatever data it wants. Readers just call
   ``nodep->user()``, but may need to cast appropriately, so you'll often
   see ``VN_CAST(nodep->userp(), SOMETYPE)``. At the top of each visitor
   are comments describing how the ``user()`` stuff applies to that
   visitor class. For example:

   ::

      // NODE STATE
      // Cleared entire netlist
      //   AstModule::user1p()     // bool. True to inline this module

   This says that at the ``AstNetlist`` ``user1ClearTree()`` is called.
   Each :literal:`AstModule's `user1()` is used to indicate if we're
   going to inline it.

   These comments are important to make sure a ``user#()`` on a given
   ``AstNode`` type is never being used for two different purposes.

   Note that calling ``user#ClearTree`` is fast; it doesn't walk the
   tree, so it's ok to call fairly often. For example, it's commonly
   called on every module.

3. Parameters can be passed between the visitors in close to the
   "normal" function caller to callee way. This is the second ``vup``
   parameter of type ``AstNUser`` that is ignored on most of the visitor
   functions. V3Width does this, but it proved messier than the above
   and is deprecated. (V3Width was nearly the first module written.
   Someday this scheme may be removed, as it slows the program down to
   have to pass vup everywhere.)


Iterators
---------

``VNVisitor`` provides a set of iterators to facilitate walking over
the tree. Each operates on the current ``VNVisitor`` class (as this)
and takes an argument type ``AstNode*``.

``iterate``
   Applies the ``accept`` method of the ``AstNode`` to the visitor
   function.

``iterateAndNextIgnoreEdit``
   Applies the ``accept`` method of each ``AstNode`` in a list (i.e.
   connected by ``nextp`` and ``backp`` pointers).

``iterateAndNextNull``
   Applies the ``accept`` method of each ``AstNode`` in a list, only if
   the provided node is non-NULL. If a node is edited by the call to
   ``accept``, apply ``accept`` again, until the node does not change.

``iterateListBackwards``
   Applies the ``accept`` method of each ``AstNode`` in a list, starting
   with the last one.

``iterateChildren``
   Applies the ``iterateAndNextNull`` method on each child ``op1p``
   through ``op4p`` in turn.

``iterateChildrenBackwards``
   Applies the ``iterateListBackwards`` method on each child ``op1p``
   through ``op4p`` in turn.


Caution on Using Iterators When Child Changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Visitors often replace one node with another node; V3Width and V3Const
are major examples. A visitor which is the parent of such a replacement
needs to be aware that calling iteration may cause the children to
change. For example:

::

   // nodep->lhsp() is 0x1234000
   iterateAndNextNull(nodep->lhsp());  // and under covers nodep->lhsp() changes
   // nodep->lhsp() is 0x5678400
   iterateAndNextNull(nodep->lhsp());

Will work fine, as even if the first iterate causes a new node to take
the place of the ``lhsp()``, that edit will update ``nodep->lhsp()``, and
the second call will correctly see the change. Alternatively:

::

   lp = nodep->lhsp();
   // nodep->lhsp() is 0x1234000, lp is 0x1234000
   iterateAndNextNull(lp); **lhsp=NULL;**  // and under covers nodep->lhsp() changes
   // nodep->lhsp() is 0x5678400, lp is 0x1234000
   iterateAndNextNull(lp);

This will cause bugs or a core dump, as lp is a dangling pointer. Thus
it is advisable to set lhsp=NULL shown in the \*'s above to make sure
these dangles are avoided. Another alternative used in special cases,
mostly in V3Width, is to use acceptSubtreeReturnEdits, which operates on
a single node and returns the new pointer if any. Note
acceptSubtreeReturnEdits does not follow ``nextp()`` links.

::

   lp = acceptSubtreeReturnEdits(lp)


Identifying Derived Classes
---------------------------

A common requirement is to identify the specific ``AstNode`` class we
are dealing with. For example, a visitor might not implement separate
``visit`` methods for ``AstIf`` and ``AstGenIf``, but just a single
method for the base class:

::

   void visit(AstNodeIf* nodep)

However that method might want to specify additional code if it is
called for ``AstGenIf``. Verilator does this by providing a ``VN_IS``
method for each possible node type, which returns true if the node is of
that type (or derived from that type). So our ``visit`` method could
use:

::

   if (VN_IS(nodep, AstGenIf) {
     
   }

Additionally the ``VN_CAST`` method converts pointers similar to C++
``dynamic_cast``. This either returns a pointer to the object cast to
that type (if it is of class ``SOMETYPE``, or a derived class of
``SOMETYPE``) or else NULL. (However, for true/false tests, use ``VN_IS``
as that is faster.)


.. _Testing:

Testing
=======

For an overview of how to write a test, see the BUGS section of the
`Verilator Manual `_.

It is important to add tests for failures as well as success (for
example to check that an error message is correctly triggered).

Tests that fail should, by convention have the suffix ``_bad`` in their
name, and include ``fails = 1`` in either their ``compile`` or
``execute`` step as appropriate.


Preparing to Run Tests
----------------------

For all tests to pass, you must install the following packages:

-  SystemC to compile the SystemC outputs, see http://systemc.org

-  Parallel::Forker from CPAN to run tests in parallel; you can install
   this with e.g. "sudo cpan install Parallel::Forker".

-  vcddiff to find differences in VCD outputs. See the readme at
   https://github.com/veripool/vcddiff

-  Cmake for build paths that use it.


Controlling the Test Driver
---------------------------

The test driver script `driver.pl` runs tests; see the `Test Driver`
section.  The individual test drivers are written in Perl; see `Test
Language`.


Manual Test Execution
---------------------

A specific regression test can be executed manually. To start the
"EXAMPLE" test, run the following command.

::

   test_regress/t/t_EXAMPLE.pl


Regression Testing for Developers
---------------------------------

Developers will also want to call ./configure with two extra flags:

``--enable-ccwarn``
   This causes the build to stop on warnings as well as errors. A good way
   to ensure no sloppy code gets added; however it can be painful when it
   comes to testing, since third party code used in the tests (e.g.
   SystemC) may not be warning free.

``--enable-longtests``
   In addition to the standard C, SystemC examples, also run the tests
   in the ``test_regress`` directory when using *make test*'. This is
   disabled by default, as SystemC installation problems would otherwise
   falsely indicate a Verilator problem.

When enabling the long tests, some additional Perl modules are needed,
which you can install using cpan.

::

   cpan install Parallel::Forker

There are some traps to avoid when running regression tests

- When checking the MANIFEST, the test will fail on unexpected code in the
  Verilator tree. So make sure to keep any such code outside the tree.

- Not all Linux systems install Perldoc by default. This is needed for the
  ``--help`` option to Verilator, and also for regression testing.  This
  can be installed using CPAN:

  ::

    cpan install Pod::Perldoc

  Many Linux systems also offer a standard package for this. Red
  Hat/Fedora/Centos offer *perl-Pod-Perldoc*', while
  Debian/Ubuntu/Linux Mint offer \`perl-doc'.

- Running regression may exhaust resources on some Linux systems,
  particularly file handles and user processes. Increase these to
  respectively 16,384 and 4,096. The method of doing this is
  system-dependent, but on Fedora Linux it would require editing the
  ``/etc/security/limits.conf`` file as root.

Diffing generated code after changes
------------------------------------

When making a change in the code generation area that should not change the
actual emitted code, it is useful to perform a diff to make sure the emitted
code really did not change. To do this, the top level Makefile provides the
*test-snap* and *test-diff* targets:

- Run the test suite with ``make test``
- Take a snapshot with ``make test-snap``
- Apply your changes
- Run the test suite again with ``make test``
- See the changes in the output with ``make test-diff``

Continuous Integration
----------------------

Verilator uses GitHub Actions which automatically tests the master branch
for test failures on new commits. It also runs a daily cron job to validate
all tests against different OS and compiler versions.

Developers can enable Actions on their GitHub repository so that the CI
environment can check their branches too by enabling the build workflow:

-  On GitHub, navigate to the main page of the repository.

-  Under your repository name, click Actions.

-  In the left sidebar, click the workflow you want to enable ("build").

-  Click Enable workflow.


Fuzzing
-------

There are scripts included to facilitate fuzzing of Verilator. These
have been successfully used to find a number of bugs in the frontend.

The scripts are based on using `American fuzzy
lop `__ on a Debian-like system.

To get started, cd to "nodist/fuzzer/" and run "./all". A sudo password may
be required to setup the system for fuzzing.


Debugging
=========


Debug Levels
------------

The "UINFO" calls in the source indicate a debug level. Messages level 3
and below are globally enabled with ``--debug``. Higher levels may be
controlled with ``--debugi ``. An individual source file levels may
be controlled with ``-debugi- ``. For example ``--debug
--debugi 5 --debugi-V3Width 9`` will use the debug binary at default
debug level 5, with the V3Width.cpp file at level 9.


--debug
-------

When you run with ``--debug``, there are three primary output file types
placed into the obj_dir, .vpp, .tree and .dot files.

.vpp Output
-----------

Verilator creates a *{mod_prefix}*\ __inputs\ .vpp file containing all the
files that were read, filtered by preprocessing. This file can be fed back
into Verilator, replacing on the command line all of the previous input
files, to enable simplification of test cases.

Verilator also creates .vpp files for each individual file passed on the
command line.


.dot Output
-----------

Dot files are dumps of internal graphs in `GraphViz
`__ dot format. When a dot file is dumped,
Verilator will also print a line on stdout that can be used to format the
output, for example:

::

   dot -Tps -o ~/a.ps obj_dir/Vtop_foo.dot

You can then print a.ps. You may prefer gif format, which doesn't get
scaled so it can be more useful with large graphs.

For interactive graph viewing consider `xdot
`__ or `ZGRViewer
`__. If you know of better
viewers (especially for large graphs) please let us know.


.tree Output
------------

Tree files are dumps of the AST Tree and are produced between every major
algorithmic stage. An example:

::

     NETLIST 0x90fb00  {a0ah}
    1: MODULE 0x912b20  {a8ah}  top  L2 [P]
   *1:2: VAR 0x91a780  {a22ah} @dt=0xa2e640(w32)  out_wide [O] WIRE
    1:2:1: BASICDTYPE 0xa2e640  {e24ah} @dt=this(sw32)  integer kwd=integer range=[31:0]

The following summarizes the above example dump, with more detail on each
field in the section below.

+---------------+--------------------------------------------------------+
| ``1:2:``      | The hierarchy of the ``VAR`` is the ``op2p``           |
|               | pointer under the ``MODULE``, which in turn is the     |
|               | ``op1p`` pointer under the ``NETLIST``                 |
+---------------+--------------------------------------------------------+
| ``VAR``       | The AstNodeType (e.g. ``AstVar``).                     |
+---------------+--------------------------------------------------------+
| ``0x91a780``  | Address of this node.                                  |
+---------------+--------------------------------------------------------+
| ````     | The 74th edit to the netlist was the last              |
|               | modification to this node.                             |
+---------------+--------------------------------------------------------+
| ``{a22ah}``   | This node is related to the source filename            |
|               | "a", where "a" is the first file read, "z" the 26th,   |
|               | and "aa" the 27th. Then line 22 in that file, then     |
|               | column 8 (aa=0, az=25, ba=26, ...).                    |
+---------------+--------------------------------------------------------+
| ``@dt=0x...`` | The address of the data type this node contains.       |
+---------------+--------------------------------------------------------+
| ``w32``       | The data-type width() is 32 bits.                      |
+---------------+--------------------------------------------------------+
| ``out_wide``  | The name() of the node, in this case, the name of the  |
|               | variable.                                              |
+---------------+--------------------------------------------------------+
| ``[O]``       | Flags which vary with the type of node, in this        |
|               | case, it means the variable is an output.              |
+---------------+--------------------------------------------------------+

In more detail, the following fields are dumped common to all nodes. They
are produced by the ``AstNode::dump()`` method:

Tree Hierarchy
   The dump lines begin with numbers and colons to indicate the child
   node hierarchy. As noted above, ``AstNode`` has lists of items at the
   same level in the AST, connected by the ``nextp()`` and ``prevp()``
   pointers. These appear as nodes at the same level. For example, after
   inlining:

   ::

       NETLIST 0x929c1c8  {a0} w0
      1: MODULE 0x92bac80  {e14} w0  TOP_t  L1 [P]
      1:1: CELLINLINE 0x92bab18  {e14} w0  v -> t
      1:1: CELLINLINE 0x92bc1d8  {e24} w0  v__DOT__i_test_gen -> test_gen
      ...
      1: MODULE 0x92b9bb0  {e47} w0  test_gen  L3
      ...

AstNode type
   The textual name of this node AST type (always in capitals). Many of
   these correspond directly to Verilog entities (for example ``MODULE``
   and ``TASK``), but others are internal to Verilator (for example
   ``NETLIST`` and ``BASICDTYPE``).

Address of the node
   A hexadecimal address of the node in memory. Useful for examining
   with the debugger. If the actual address values are not important,
   then using the ``--dump-tree-addrids`` option will convert address
   values to short identifiers of the form ``([A-Z]*)``, which is
   hopefully easier for the reader to cross-reference throughout the
   dump.

Last edit number
   Of the form ```` or ```` , where ``nnnn`` is the
   number of the last edit to modify this node. The trailing ``#``
   indicates the node has been edited since the last tree dump
   (typically in the last refinement or optimization pass). GDB can
   watch for this; see << /Debugging >>.

Source file and line
   Of the form ``{xxnnnn}``, where C{xx} is the filename letter (or
   letters) and ``nnnn`` is the line number within that file. The first
   file is ``a``, the 26th is ``z``, the 27th is ``aa``, and so on.

User pointers
   Shows the value of the node's user1p...user4p, if non-NULL.

Data type
   Many nodes have an explicit data type. "@dt=0x..." indicates the
   address of the data type (AstNodeDType) this node uses.

   If a data type is present and is numeric, it then prints the width of
   the item. This field is a sequence of flag characters and width data
   as follows:

   -  ``s`` if the node is signed.

   -  ``d`` if the node is a double (i.e. a floating point entity).

   -  ``w`` always present, indicating this is the width field.

   -  ``u`` if the node is unsized.

   -  ``/nnnn`` if the node is unsized, where ``nnnn`` is the minimum
      width.

Name of the entity represented by the node if it exists
   For example, for a ``VAR`` is the name of the variable.

Many nodes follow these fields with additional node-specific
information. Thus the ``VARREF`` node will print either ``[LV]`` or
``[RV]`` to indicate a left value or right value, followed by the node
of the variable being referred to. For example:

::

   1:2:1:1: VARREF 0x92c2598  {e24} w0  clk [RV] <- VAR 0x92a2e90  {e18} w0  clk [I] INPUT

In general, examine the ``dump()`` method in ``V3AstNodes.cpp`` of the node
type in question to determine additional fields that may be printed.

The ``MODULE`` has a list of ``CELLINLINE`` nodes referred to by its
``op1p()`` pointer, connected by ``nextp()`` and ``prevp()`` pointers.

Similarly, the ``NETLIST`` has a list of modules referred to by its
``op1p()`` pointer.


.tree.dot Output
----------------

``*.tree.dot`` files are dumps of the AST Tree in `GraphViz
`__ dot format. This can be used to visualize the
AST Tree. The vertices correspond to ``AstNode`` instances, and the edges
represent the pointers (``op1p``, ``op2p``, etc) between the nodes.


Debugging with GDB
------------------

The `driver.pl` script accepts ``--debug --gdb`` to start
Verilator under gdb and break when an error is hit, or the program is about
to exit. You can also use ``--debug --gdbbt`` to just backtrace and then
exit gdb. To debug the Verilated executable, use ``--gdbsim``.

If you wish to start Verilator under GDB (or another debugger), then you
can use ``--debug`` and look at the underlying invocation of
``verilator_dbg``. For example

::

   t/t_alw_dly.pl --debug

shows it invokes the command:

::

   ../verilator_bin_dbg --prefix Vt_alw_dly --x-assign unique --debug
     -cc -Mdir obj_dir/t_alw_dly --debug-check -f input.vc t/t_alw_dly.v

Start GDB, then ``start`` with the remaining arguments.

::

   gdb ../verilator_bin_dbg
   ...
   (gdb) start --prefix Vt_alw_dly --x-assign unique --debug -cc -Mdir
             obj_dir/t_alw_dly --debug-check  -f input.vc t/t_alw_dly.v
             > obj_dir/t_alw_dly/vlt_compile.log
   ...
   Temporary breakpoint 1, main (argc=13, argv=0xbfffefa4, env=0xbfffefdc)
       at ../Verilator.cpp:615
   615         ios::sync_with_stdio();
   (gdb)

You can then continue execution with breakpoints as required.

To break at a specific edit number which changed a node (presumably to
find what made a  line in the tree dumps):

::

   watch AstNode::s_editCntGbl==####

Then, when the watch fires, to break at every following change to that
node:

::

   watch m_editCount

To print a node:

::

   pn nodep
   # or: call dumpGdb(nodep)  # aliased to "pn" in src/.gdbinit
   pnt nodep
   # or: call dumpTreeGdb(nodep)  # aliased to "pnt" in src/.gdbinit

When GDB halts, it is useful to understand that the backtrace will commonly
show the iterator functions between each invocation of ``visit`` in the
backtrace. You will typically see a frame sequence something like:

::

   ...
   visit()
   iterateChildren()
   iterateAndNext()
   accept()
   visit()
   ...


Adding a New Feature
====================

Generally, what would you do to add a new feature?

1. File an issue (if there isn't already) so others know what you're
   working on.

2. Make a testcase in the test_regress/t/t_EXAMPLE format, see `Testing`.

3. If grammar changes are needed, look at the git version of VerilogPerl's
   src/VParseGrammar.y, as this grammar supports the full SystemVerilog
   language and has a lot of back-and-forth with Verilator's grammar. Copy
   the appropriate rules to src/verilog.y and modify the productions.

4. If a new Ast type is needed, add it to the appropriate V3AstNode*.h.
   Follow the convention described above about the AstNode type hierarchy.
   Ordering of definitions is enforced by ``astgen``.

5. Now you can run ``test_regress/t/t_.pl --debug`` and it'll
   probably fail, but you'll see a
   ``test_regress/obj_dir/t_/*.tree`` file which you can examine
   to see if the parsing worked. See also the sections above on debugging.

6. Modify the later visitor functions to process the new feature as needed.


Adding a New Pass
-----------------

For more substantial changes, you may need to add a new pass. The simplest
way to do this is to copy the ``.cpp`` and ``.h`` files from an existing
pass. You'll need to add a call into your pass from the ``process()``
function in ``src/verilator.cpp``.

To get your pass to build, you'll need to add its binary filename to the
list in ``src/Makefile_obj.in`` and reconfigure.


"Never" features
----------------

Verilator ideally would support all of IEEE, and has the goal to get close
to full support. However the following IEEE sections and features are not
anticipated to be ever implemented for the reasons indicated.

IEEE 1800-2017 3.3 modules within modules
    Little/no tool support, and arguably not a good practice.
IEEE 1800-2017 6.12 "shortreal"
    Little/no tool support, and easily promoted to real.
IEEE 1800-2017 11.11 Min, typ, max
    No SDF support, so will always use typical.
IEEE 1800-2017 20.16 Stochastic analysis
    Little industry use.
IEEE 1800-2017 20.17 PLA modeling
    Little industry use and outdated technology.
IEEE 1800-2017 31 Timing checks
    No longer relevant with static timing analysis tools.
IEEE 1800-2017 32 SDF annotation
    No longer relevant with static timing analysis tools.
IEEE 1800-2017 33 Config
    Little industry use.



Test Driver
===========

This section documents the test driver script, `driver.pl`.  driver.pl
invokes Verilator or another simulator on each test file.  For test file
contents description see `Test Language`.

The driver reports the number of tests which pass, fail, or skipped (some
resource required by the test is not available, such as SystemC).

There are thousands of tests, and for faster completion you may want to run
the regression tests with OBJCACHE enabled and in parallel on a machine
with many cores.  See the -j option and OBJCACHE environment variable.


driver.pl Non-Scenario Arguments
--------------------------------

--benchmark []
  Show execution times of each step.  If an optional number is given,
  specifies the number of simulation cycles (for tests that support it).

--debug
  Same as ``verilator --debug``: Use the debug version of Verilator which
  enables additional assertions, debugging messages, and structure dump
  files.

--debugi(-) 
  Same as ``verilator --debugi level``: Set Verilator internal debugging
  level globally to the specified debug level (1-10).

--dump-tree
  Same as ``verilator --dump-tree``: Enable Verilator writing .tree debug
  files with dumping level 3, which dumps the standard critical stages.
  For details on the format see `.tree Output`.

--gdb
  Same as ``verilator --gdb``: Run Verilator under the debugger.

--gdbbt
  Same as ``verilator --gdbbt``: Run Verilator under the debugger, only to
  print backtrace information.  Requires ``--debug``.

--gdbsim
  Run Verilator generated executable under the debugger.

--golden
  Update golden files, equivalent to ``export HARNESS_UPDATE_GOLDEN=1``.

--hashset /
  Split tests based on a hash of the test names into  and run only
  tests in set number  (0..-1).

--help
  Displays help message and exits.

--j #
  Run number of parallel tests, or 0 to determine the count based on the
  number of cores installed.  Requires Perl's Parallel::Forker package.

--quiet
  Suppress all output except for failures and progress messages every 15
  seconds.  Intended for use only in automated regressions.  See also
  ``--rerun``, and ``--verbose`` which is not the opposite of ``--quiet``.

--rerun
  Rerun all tests that failed in this run. Reruns force the flags
  ``--no-quiet --j 1``.

--rr
  Same as ``verilator --rr``: Run Verilator and record with ``rr``.

--rrsim
  Run Verilator generated executable and record with ``rr``.

--sanitize
  Enable address sanitizer to compile Verilated C++ code.  This may detect
  misuses of memory, such as out-of-bound accesses, use-after-free, and
  memory leaks.

--site
  Run site specific tests also.

--stop
  Stop on the first error.

--trace
  Set the simulator specific flags to request waveform tracing.

--verbose
  Compile and run the test in verbose mode. This means ``TEST_VERBOSE``
  will be defined for the test (Verilog and any C++/SystemC wrapper).

--verilated-debug
  For tests using the standard C++ wrapper, enable runtime debug mode.


driver.pl Scenario Arguments
----------------------------

The following options control which simulator is used, and which tests are
run.  Multiple flags may be used to run multiple simulators/scenarios
simultaneously.

--atsim
  Run ATSIM simulator tests.

--dist
  Run simulator-agnostic distribution tests.

--ghdl
  Run GHDL simulator tests.

--iv
  Run Icarus Verilog simulator tests.

--ms
  Run ModelSim simulator tests.

--nc
  Run Cadence NC-Verilog simulator tests.

--vcs
  Run Synopsys VCS simulator tests.

--vlt
  Run Verilator tests in single-threaded mode.  Default unless another
  scenario flag is provided.

--vltmt
  Run Verilator tests in multithreaded mode.

--xsim
  Run Xilinx XSim simulator tests.


driver.pl Environment
---------------------

HARNESS_UPDATE_GOLDEN
  If true, update all .out golden reference files.  Typically, instead the
  ``--golden`` option is used to update only a single test's reference.

SYSTEMC
  Root directory name of SystemC kit.  Only used if ``SYSTEMC_INCLUDE`` not
  set.

SYSTEMC_INCLUDE
  Directory name with systemc.h in it.

VERILATOR_ATSIM
  Command to use to invoke Atsim.

VERILATOR_GHDL
  Command to use to invoke GHDL.

VERILATOR_GDB
  Command to use to invoke GDB debugger.

VERILATOR_IVERILOG
  Command to use to invoke Icarus Verilog.

VERILATOR_MAKE
  Command to use to rebuild Verilator and run single test.

VERILATOR_MODELSIM
  Command to use to invoke ModelSim.

VERILATOR_NCVERILOG
  Command to use to invoke ncverilog.

VERILATOR_ROOT
  Standard path to Verilator distribution root; see primary Verilator
  documentation.

VERILATOR_TESTS_SITE
  Used with ``--site``, a colon-separated list of directories with tests to
  be added to testlist.

VERILATOR_VCS
  Command to use to invoke VCS.

VERILATOR_XELAB
  Command to use to invoke XSim xelab

VERILATOR_XVLOG
  Command to use to invoke XSim xvlog


Test Language
=============

This section describes the format of the ``test_regress/t/*.pl`` test
language files, executed by `driver.pl`.

Test Language Summary
---------------------

For convenience, a summary of the most commonly used features is provided
here, with a reference in a later section. All test files typically have a
call to the ``lint`` or ``compile`` subroutine to compile the test. For
run-time tests, this is followed by a call to the ``execute``
subroutine. Both of these functions can optionally be provided with
arguments specifying additional options.

If those complete, the script calls ``ok`` to increment the count of
successful tests and then returns 1 as its result.

The driver.pl script assumes by default that the source Verilog file name
matches the test script name. So a test whose driver is
``t/t_mytest.pl`` will expect a Verilog source file ``t/t_mytest.v``.
This can be changed using the ``top_filename`` subroutine, for example

::

   top_filename("t/t_myothertest.v");

By default, all tests will run with major simulators (Icarus Verilog, NC,
VCS, ModelSim, etc.) as well as Verilator, to allow results to be
compared. However, if you wish a test only to be used with Verilator, you
can use the following:

::

   scenarios(vlt => 1);

Of the many options that can be set through arguments to ``compiler`` and
``execute``, the following are particularly useful:

``verilator_flags2``
  A list of flags to be passed to verilator when compiling.

``fails``
  Set to 1 to indicate that the compilation or execution is intended to fail.

For example, the following would specify that compilation requires two
defines and is expected to fail.

::

   compile(
      verilator_flags2 => ["-DSMALL_CLOCK -DGATED_COMMENT"],
      fails => 1,
      );

Hints On Writing Tests
----------------------

There is generally no need for the test to create its own main program or
top level shell as the driver creates one automatically, however some tests
require their own C++ or SystemC test harness. This is commonly given the
same name as the test, but with .cpp as suffix
(``test_regress/t/t_EXAMPLE.cpp``). This can be specified as follows:

::

   compile(
      make_top_shell   => 0,
      make_main        => 0,
      verilator_flags2 => ["--exe $Self->{t_dir}/$Self->{name}.cpp"], );

Tests should be self-checking, rather than producing lots of output. If a
test succeeds it should print ``*-* All Finished *-*`` to standard output
and terminate (in Verilog ``$finish``), if not it should just stop (in
Verilog ``$stop``) as that signals an error.

If termination should be triggered from the C++ wrapper, the following code
can be used:

::

   vl_fatal(__FILE__, __LINE__, "dut", "");
   exit(1);

Where it might be useful for a test to produce output, it should qualify
this with ``TEST_VERBOSE``. For example in Verilog:

::

   `ifdef TEST_VERBOSE
       $write("Conditional generate if MASK [%1d] = %d\n", g, MASK[g]);
   `endif

Or in a hand-written C++ wrapper:

::

   #ifdef TEST_VERBOSE
      std::cout << "Read a=" << a << std::endl;
   #endif

A filename that should be used to check the output results is given with
``expect_filename``. This should not generally be used to decide if a test
has succeeded. However, in the case of tests that are designed to fail at
compile time, it is the only option. For example:

::

   compile(
      fails => 1,
      expect_filename => $Self->{golden_filename},
      );

Note ``expect_filename`` strips some debugging information from the logfile
when comparing.


Test Language Compile/Lint/Run Arguments
----------------------------------------

This section describes common arguments to ``compile()``, ``lint()``, and
``run()``.  The full list of arguments can be found by looking at the
``driver.pl`` source code.

all_run_flags
  A list of flags to be passed when running the simulator (Verilated model
  or one of the other simulators).

check_finished
  True to indicate successful completion of the test is indicated by the
  string ``*-* All Finished *-*`` being printed on standard output. This is
  the normal way for successful tests to finish.

expect
  A quoted list of strings or regular expression to be matched in the
  output. See `Hints On Writing Tests` for more detail on how this argument
  should be used.

fails
  True to indicate this step is expected to fail.  Tests that are expected
  to fail generally have _bad in their filename.

make_main
  False to disable the automatic creation of a C++ test wrapper (for
  example when a hand-written test wrapper is provided using ``verilator
  --exe``).

make_top_shell
  False to disable the automatic creation of a top level shell to run the
  executable (for example when a hand-written test wrapper is provided
  using ``verilator --exe``).

ms_flags / ms_flags2 / ms_run_flags
  The equivalent of ``v_flags``, ``v_flags2`` and ``all_run_flags``, but
  only for use with the ModelSim simulator.

nc_flags / nc_flags2 / nc_run_flags
  The equivalent of ``v_flags``, ``v_flags2`` and ``all_run_flags``, but
  only for use with the Cadence NC simulator.

iv_flags / iv_flags2 / iv_run_flags
  The equivalent of ``v_flags``, ``v_flags2`` and ``all_run_flags``, but
  only for use with the Icarus Verilog simulator.

v_flags
  A list of standard Verilog simulator flags to be passed to the simulator
  compiler (Verilator or one of the other simulators).  This list is create
  by the driver and rarely changed, use ``v_flags2`` instead.

v_flags2
  A list of standard Verilog simulator flags to be passed to the simulator
  compiler (Verilator or one of the other simulators). Unlike ``v_flags``,
  these options may be overridden in some simulation files.

  Similar sets of flags exist for atsim, GHDL, Cadence NC, ModelSim and
  Synopsys VCS.

vcs_flags / vcs_flags2 / vcs_run_flags
  The equivalent of ``v_flags``, ``v_flags2`` and ``all_run_flags``, but
  only for use with the Synopsys VCS simulator.

verilator_flags / verilator_flags2
  The equivalent of ``v_flags`` and ``v_flags2``, but only for use with
  Verilator.  If a flag is a standard flag, ``+incdir`` for example, pass
  it with ``v_flags2`` instead.

benchmarksim
  Output the number of model evaluations and execution time of a test to
  ``test_output_dir>/_benchmarksim.csv``. Multiple invocations
  of the same test file will append to to the same .csv file.

xsim_flags / xsim_flags2 / xsim_run_flags
  The equivalent of ``v_flags``, ``v_flags2`` and ``all_run_flags``, but
  only for use with the Xilinx XSim simulator.


Distribution
============

Copyright 2008-2024 by Wilson Snyder. Verilator is free software; you can
redistribute it and/or modify it under the terms of either the GNU Lesser
General Public License Version 3 or the Perl Artistic License Version 2.0.

SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

.. |Logo| image:: https://www.veripool.org/img/verilator_256_200_min.png
verilator-5.020/docs/verilated.dox0000644000175000017500000000250114544475344017046 0ustar  carstencarstenPROJECT_NAME           = "Verilator"
INPUT                  = ../../include
OUTPUT_DIRECTORY       = _build/doxygen/verilated

EXTRACT_ALL            = NO
EXTRACT_LOCAL_CLASSES  = NO
EXTRACT_PRIVATE        = NO
EXTRACT_STATIC         = YES
FULL_PATH_NAMES        = NO
GENERATE_HTML          = NO
GENERATE_LATEX         = NO
GENERATE_XML           = YES
HIDE_FRIEND_COMPOUNDS  = YES
HIDE_IN_BODY_DOCS      = YES
HIDE_UNDOC_CLASSES     = YES
HIDE_UNDOC_MEMBERS     = YES
INTERNAL_DOCS          = NO
OPTIMIZE_OUTPUT_FOR_C  = NO
RECURSIVE              = NO
SHOW_INCLUDE_FILES     = NO
WARN_IF_UNDOCUMENTED   = NO

ENABLE_PREPROCESSING   = YES
MACRO_EXPANSION        = YES
EXPAND_ONLY_PREDEF     = YES
PREDEFINED             = \
                         "DOXYGEN=1" \
                         "VL_ATTR_NORETURN=" \
                         "VL_ATTR_PRINTF()=" \
                         "VL_ATTR_WEAK=" \
                         "VL_GUARDED_BY()=" \
                         "VL_MT_SAFE=" \
                         "VL_MT_SAFE_EXCLUDES()=" \
                         "VL_MT_SAFE_POSTINIT=" \
                         "VL_MT_UNSAFE=" \
                         "VL_MT_UNSAFE_ONE=" \
                         "VL_NOT_FINAL=" \
                         "VL_PURE=" \
                         "VL_REQUIRES()=" \
                         "__restrict=" \
verilator-5.020/docs/guide/0000755000175000017500000000000014544475344015452 5ustar  carstencarstenverilator-5.020/docs/guide/index.rst0000644000175000017500000000124314544475344017313 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

######################
Verilator User's Guide
######################

.. toctree::
   :maxdepth: 2
   :caption: Getting Started

   overview.rst
   examples.rst
   install.rst
   install-cmake.rst


.. toctree::
   :maxdepth: 2
   :caption: User's Guide

   verilating.rst
   connecting.rst
   simulating.rst
   contributing.rst
   faq.rst


.. toctree::
   :maxdepth: 1
   :caption: Reference Guide

   languages.rst
   extensions.rst
   executables.rst
   warnings.rst
   files.rst
   environment.rst
   deprecations.rst
   contributors.rst
   changes.rst
   copyright.rst
verilator-5.020/docs/guide/examples.rst0000644000175000017500000000063514544475344020026 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

.. _Examples:

========
Examples
========

This section covers the following examples:

* :ref:`Example C++ Execution`
* :ref:`Example SystemC Execution`
* :ref:`Examples in the Distribution`

.. toctree::
   :maxdepth: 1
   :hidden:

   example_binary.rst
   example_cc.rst
   example_sc.rst
   example_dist.rst
verilator-5.020/docs/guide/example_binary.rst0000644000175000017500000000303714544475344021206 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

.. _Example Create-Binary Execution:

Example Create-Binary Execution
===============================

We'll compile this SystemVerilog example into a Verilated simulation binary.  For
an example that discusses the next level of detail see :ref:`Example C++
Execution`.

.. include:: example_common_install.rst

Now, let's create an example Verilog file:

.. code-block:: bash

     mkdir test_our
     cd test_our

     cat >our.v <<'EOF'
       module our;
          initial begin $display("Hello World"); $finish; end
       endmodule
     EOF

Now we run Verilator on our little example.

.. code-block:: bash

     verilator --binary -j 0 -Wall our.v

Breaking this command down:

#. :vlopt:`--binary` telling Verilator to do everything needed to create a
   simulation executable.

#. :vlopt:`-j` `0` to Verilate using use as many CPU threads as the machine
   has.

#. :vlopt:`-Wall` so Verilator has stronger lint warnings
   enabled.

#. An finally, :command:`our.v`, which is our SystemVerilog design file.

And now we run it:

.. code-block:: bash

     obj_dir/Vour

And we get as output:

.. code-block:: bash

     Hello World
     - our.v:2: Verilog $finish

You're better off using a Makefile to run the steps for you, so when your
source changes, it will automatically run all of the appropriate steps.  To
aid this, Verilator can create a makefile dependency file.  For examples
that do this, see the :file:`examples` directory in the distribution.
verilator-5.020/docs/guide/example_cc.rst0000644000175000017500000000506014544475344020305 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

.. _Example C++ Execution:

Example C++ Execution
=====================

We'll compile this example into C++.  For an extended and commented version
of what this C++ code is doing, see
:file:`examples/make_tracing_c/sim_main.cpp` in the distribution.

.. include:: example_common_install.rst

Now, let's create an example Verilog and C++ wrapper file:

.. code-block:: bash

     mkdir test_our
     cd test_our

     cat >our.v <<'EOF'
       module our;
          initial begin $display("Hello World"); $finish; end
       endmodule
     EOF

     cat >sim_main.cpp <<'EOF'
       #include "Vour.h"
       #include "verilated.h"
       int main(int argc, char** argv) {
           VerilatedContext* contextp = new VerilatedContext;
           contextp->commandArgs(argc, argv);
           Vour* top = new Vour{contextp};
           while (!contextp->gotFinish()) { top->eval(); }
           delete top;
           delete contextp;
           return 0;
       }
     EOF

Now we run Verilator on our little example;

.. code-block:: bash

     verilator --cc --exe --build -j 0 -Wall sim_main.cpp our.v

Breaking this command down:

#. :vlopt:`--cc` to get C++ output (versus e.g., SystemC, or only linting).

#. :vlopt:`--exe`, along with our :command:`sim_main.cpp` wrapper file, so
   the build will create an executable instead of only a library.

#. :vlopt:`--build` so Verilator will call make itself. This is we don't
   need to manually call make as a separate step. You can also write your
   own compile rules, and run make yourself as we show in :ref:`Example
   SystemC Execution`.)

#. :vlopt:`-j 0 <-j>` to Verilate using use as many CPU threads as the
   machine has.

#. :vlopt:`-Wall` so Verilator has stronger lint warnings
   enabled.

#. And finally, :command:`our.v` which is our SystemVerilog design file.

Once Verilator completes we can see the generated C++ code under the
:file:`obj_dir` directory.

.. code-block:: bash

     ls -l obj_dir

(See :ref:`Files Read/Written` for descriptions of some of the files that
were created.)

And now we run it:

.. code-block:: bash

     obj_dir/Vour

And we get as output:

.. code-block:: bash

     Hello World
     - our.v:2: Verilog $finish

You're better off using a Makefile to run the steps for you, so when your
source changes, it will automatically run all of the appropriate steps.  To
aid this, Verilator can create a makefile dependency file.  For examples
that do this, see the :file:`examples` directory in the distribution.
verilator-5.020/docs/guide/faq.rst0000644000175000017500000004777714544475344017001 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

******************************
FAQ/Frequently Asked Questions
******************************

.. Extra heading level here so sidebar index looks nice

Questions
=========

Can I contribute?
"""""""""""""""""

Please contribute!  Just submit a pull request, or raise an issue to
discuss if you are looking for something to help on.  For more information
see our contributor agreement.


How widely is Verilator used?
"""""""""""""""""""""""""""""

Verilator is used by many of the largest silicon design companies, large
organizations such as CERN, and even by college student projects.

Verilator is one of the "big 4" simulators, meaning one of the four leading
SystemVerilog simulators available, namely the closed-source products Synopsys
VCS (tm), Mentor Questa/ModelSim (tm), Cadence
Xcelium/Incisive/NC-Verilog/NC-Sim (tm), and the open-source Verilator.
The three closed-source offerings are often collectively called the "big 3"
simulators.


Does Verilator run under Windows?
"""""""""""""""""""""""""""""""""

Yes, ideally, run Ubuntu under Windows Subsystem for Linux (WSL2).
Alternatively, use Cygwin, though this tends to be slower and is not
regularly tested.  Verilated output also compiles under Microsoft Visual
C++, but this is also not regularly tested.


Can you provide binaries?
"""""""""""""""""""""""""

You can install Verilator via the system package manager (apt, yum, etc.)
on many Linux distributions, including Debian, Ubuntu, SuSE, Red Hat, and
others.  These packages are provided by the Linux distributions and
generally will lag the version of the mainline Verilator repository.  If no
binary package is available for your distribution, how about you set one
up?


How can it be faster than (name-a-big-3-closed-source-simulator)?
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Generally, the implied part of the question is "... with all of the
manpower they can put into developing it."

Most simulators must comply with the complete IEEE 1364 (Verilog) and IEEE
1800 (SystemVerilog) standards, meaning they have to be event-driven.  This
prevents them from being able to reorder blocks and make netlist-style
optimizations, which are where most of the gains come from.

You should not be scared by non-compliance.  Your synthesis tool isn't
compliant with the whole standard to start with, so your simulator need not
be either.  Verilator is closer to the synthesis interpretation, which is
a good thing for getting working silicon.


Will Verilator output remain under my own license/copyright?
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Your SystemVerilog, VPI/DPI, or main() C++ code remains under your own license.

It's just like how using GCC on your programs does not change the copyright
of your program; this is why Verilator uses the "GNU **Lesser** Public
License Version 3" instead of the more typical "GNU Public License".  See
the licenses for details.

Some examples:

* Any SystemVerilog or other input fed into Verilator remains your own.

* Any of your VPI/DPI C++ routines that Verilator calls remain your own.

* Any of your main() C++ code that calls into Verilator remains your own.

* If you change Verilator itself, for example, changing or adding a file
  under the src/ directory in the repository, you must make the source code
  available under the GNU Lesser Public License.

* If you change a header Verilator provides, for example, under include/ in
  the repository, you must make the source code available under the GNU
  Lesser Public License.

You also have the option of using the Perl Artistic License, which again
does not require you to release your Verilog, C++, or generated code. This
license also allows you to modify Verilator for internal use without
distributing the modified version.  But please contribute back to the
community!

Under both licenses, you can offer a commercial product based on
Verilator directly or embedded within.  However, under both licenses,
any changes you make to Verilator for such a product must be open-sourced.

As is standard with Open Source, contributions back to Verilator will be
placed under the Verilator copyright and LGPL/Artistic license.  Small test
cases will be released into the public domain so they can be used anywhere,
and large tests under the LGPL/Artistic, unless requested otherwise.


Why is running Verilator (to create a model) so slow?
"""""""""""""""""""""""""""""""""""""""""""""""""""""

Verilator may require more memory than the resulting simulation,
as Verilator internally creates all of the state of the resulting
generated simulator to optimize it.  If it takes more than a few
minutes or so (and you're not using :vlopt:`--debug` since debug mode is
disk bound), see if your machine is paging; most likely, you need to run it
on a machine with more memory. Very large designs are known to have topped
64 GB resident set size.  Alternatively, see :ref:`Hierarchical Verilation`.


How do I generate waveforms (traces) in C++?
""""""""""""""""""""""""""""""""""""""""""""

See also the next question for tracing in SystemC mode.

A. Pass the :vlopt:`--trace` option to Verilator, and in your top-level C
   code, call ``Verilated::traceEverOn(true)``.  Then you may use
   ``$dumpfile`` and ``$dumpvars`` to enable traces, the same as with any
   Verilog simulator. See ``examples/make_tracing_c`` in the distribution.

B. Or, for finer-grained control, or C++ files with multiple Verilated
   modules, you may also create the trace purely from C++.  Create a
   VerilatedVcdC object, and in your main loop, right after ``eval()`` call
   ``trace_object->dump(contextp->time())`` every time step, and finally
   call ``trace_object->close()``.

   .. code-block:: C++
      :emphasize-lines: 1,5-8,12

      #include "verilated_vcd_c.h"
      ...
      int main(int argc, char** argv) {
          const std::unique_ptr contextp{new VerilatedContext};
          ...
          Verilated::traceEverOn(true);
          VerilatedVcdC* tfp = new VerilatedVcdC;
          topp->trace(tfp, 99);  // Trace 99 levels of hierarchy (or see below)
          // tfp->dumpvars(1, "t");  // trace 1 level under "t"
          tfp->open("obj_dir/t_trace_ena_cc/simx.vcd");
          ...
          while (contextp->time() < sim_time && !contextp->gotFinish()) {
              contextp->timeInc(1);
              topp->eval();
              tfp->dump(contextp->time());
          }
          tfp->close();
      }

You also need to compile :file:`verilated_vcd_c.cpp` and add it to your
link, preferably by adding the dependencies in your Makefile's
:code:`$(VK_GLOBAL_OBJS)` link rule.  This is done for you if you are using
the Verilator :vlopt:`--binary` or :vlopt:`--exe` option.

you can call :code:`trace_object->trace()` on multiple Verilated objects
with the same trace file if you want all data to land in the same output
file.


How do I generate waveforms (traces) in SystemC?
""""""""""""""""""""""""""""""""""""""""""""""""

A. Pass the :vlopt:`--trace` option to Verilator, and in your top-level
   :code:`sc_main()`, call :code:`Verilated::traceEverOn(true)`.  Then you
   may use :code:`$dumpfile` and code:`$dumpvars` to enable traces, as
   with any Verilog simulator; see the non-SystemC example in
   :file:`examples/make_tracing_c`. This will trace only the module
   containing the :code:`$dumpvar`.

B. Or, you may create a trace purely from SystemC, which may trace all
   Verilated designs in the SystemC model. Create a VerilatedVcdSc object
   as you would create a standard SystemC trace file.  For an example, see
   the call to ``VerilatedVcdSc`` in the
   :file:`examples/make_tracing_sc/sc_main.cpp` file of the distribution,
   and below.

C. Alternatively, you may use the C++ trace mechanism described in the
   previous question; note that the timescale and timeprecision will be
   inherited from your SystemC settings.

   .. code-block:: C++
      :emphasize-lines: 1,5-8

      #include "verilated_vcd_sc.h"
      ...
      int main(int argc, char** argv) {
          ...
          Verilated::traceEverOn(true);
          VerilatedVcdSc* tfp = new VerilatedVcdSc;
          topp->trace(tfp, 99);  // Trace 99 levels of hierarchy
          tfp->open("obj_dir/t_trace_ena_cc/simx.vcd");
          ...
          sc_start(1);
          ...
          tfp->close();
      }



You also need to compile :file:`verilated_vcd_sc.cpp` and
:file:`verilated_vcd_c.cpp` and add them to your link, preferably by adding
the dependencies in your Makefile's :code:`$(VK_GLOBAL_OBJS)` link rule.
This is done for you if you are using the Verilator :vlopt:`--binary` or
:vlopt:`--exe` option.

You can call :code:`->trace()` on multiple Verilated objects with the same
trace file if you want all data to land in the same output file.


How do I generate FST waveforms (traces) in C++ or SystemC?
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

FST is a trace file format developed by GTKWave.  Verilator provides basic
FST support.  To dump traces in FST format, add the :vlopt:`--trace-fst`
option to Verilator and either A. use :code:`$dumpfile & $dumpvars` in
Verilog as described in the VCD example above,

Or, in C++ change the include described in the VCD example above:

.. code-block:: C++

      #include "verilated_fst_c.h"
      VerilatedFstC* tfp = new VerilatedFstC;


Or, in SystemC, change the include described in the VCD example above:

.. code-block:: C++

      #include "verilated_fst_sc.h"
      VerilatedFstC* tfp = new VerilatedFstSc;


Currently, supporting FST and VCD in a single simulation is impossible, but
such requirement should be rare.  You can however ifdef around the trace
format in your C++ main loop, and select VCD or FST at compile time.


How do I view waveforms (aka dumps or traces)?
""""""""""""""""""""""""""""""""""""""""""""""

Verilator creates standard VCD (Value Change Dump) and FST files.  VCD
files are viewable with the open-source GTKWave (recommended), or Dinotrace
(legacy) programs, or any of the many closed-source offerings; FST is
supported only by GTKWave.


How do I speed up writing large waveform (trace) files?
"""""""""""""""""""""""""""""""""""""""""""""""""""""""

A. Instead of calling ``VerilatedVcdC->open`` or ``$dumpvars`` at the
   beginning of time, delay calling it until the time stamp where you want
   tracing to begin.

B. Add the :option:`/*verilator&32;tracing_off*/` metacomment to any very
   low-level modules you never want to trace (such as perhaps library
   cells).

C. Use the :vlopt:`--trace-depth` option to limit the tracing depth, for
   example :vlopt:`--trace-depth 1 <--trace-depth>` to see only the
   top-level signals.

D. You can also consider using FST tracing instead of VCD. FST dumps are a
   fraction of the size of the equivalent VCD. FST tracing can be slower
   than VCD tracing, but it might be the only option if the VCD file size
   is prohibitively large.

E. Write your trace files to a machine-local solid-state drive instead of a
   network drive.  Network drives are generally far slower.


Where is the translate_off command?  (How do I ignore a construct?)
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Translate on/off pragmas are generally a bad idea, as it's easy to have
mismatched pairs, and you can't see what another tool sees by just
preprocessing the code.  Instead, use the preprocessor; Verilator defines
the ``\`VERILATOR`` define for you, so just wrap the code in an ifndef
region:

 .. code-block:: sv
    :emphasize-lines: 1

    `ifndef VERILATOR
       Something_Verilator_Dislikes;
    `endif

Most synthesis tools similarly define SYNTHESIS for you.


Why do I get "unexpected 'do'" or "unexpected 'bit'" errors?
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

The words \ ``do``\ , \ ``bit``\ , \ ``ref``\ , \ ``return``\ , and others
are reserved keywords in SystemVerilog.  Older Verilog code might use these
as identifiers, and you should change your code to not use them to ensure it
works with newer tools.  Alternatively, surround them by the Verilog
2005/SystemVerilog begin_keywords pragma to indicate Verilog 2001 code.

.. code-block:: sv
   :emphasize-lines: 1

   `begin_keywords "1364-2001"
      integer bit; initial bit = 1;
   `end_keywords


If you want the whole design parsed as Verilog 2001, see the
:vlopt:`--default-language` option.


How do I prevent my assertions from firing during reset?
""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Call :code:`Verilated::assertOn(false)` before you first call the model,
then turn it back on after reset.  It defaults to true.  When false, all
assertions controlled by :vlopt:`--assert` are disabled.


Why do I get "undefined reference to sc_time_stamp()?
"""""""""""""""""""""""""""""""""""""""""""""""""""""

In Verilator 4.200 and later, using the timeInc function is recommended
instead.  See the :ref:`Connecting to C++` examples.  Some linkers (MSVC++)
still require :code:`sc_time_stamp()` to be defined; either define this
with :code:`double sc_time_stamp() { return 0; }` or compile the Verilated
code with :code:`-CFLAGS -DVL_TIME_CONTEXT`.

Before Verilator 4.200, the :code:`sc_time_stamp()` function needs to be
defined in C++ (non SystemC) to return the current simulation time.


Why do I get "undefined reference to \`VL_RAND_RESET_I' or \`Verilated::...'"?
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

You need to link your compiled Verilated code against the
:code:`verilated.cpp` file found in the include directory of the Verilator
kit.  This is one target in the ``$(VK_GLOBAL_OBJS)`` make variable, which
should be part of your Makefile's link rule.  If you use :vlopt:`--exe` or
:vlopt:`--binary`, this is done for you.


Is the PLI supported?
"""""""""""""""""""""

Only somewhat.  More specifically, the common PLI-ish calls $display,
$finish, $stop, $time, $write are converted to C++ equivalents.  You can
also use the "import DPI" SystemVerilog feature to call C code (see the
chapter above).  There is also limited VPI access to public signals.

If you want something more complex, since Verilator emits standard C++
code, you can write C++ routines that can access and modify signal
values without needing any PLI interface code, and call it with
$c("{any_c++_statement}").

See the :ref:`Connecting` section.


How do I make a Verilog module that contains a C++ object?
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

You need to add the object to the structure Verilator creates, then
use $c to call a method inside your object.  The
:file:`test_regress/t/t_extend_class` files in the distribution show an
example of how to do this.


How do I get faster build times?
""""""""""""""""""""""""""""""""

* When running make, pass the make variable VM_PARALLEL_BUILDS=1, so that
  builds occur in parallel. Note this is now set by default if an output
  file is large enough to be split due to the :vlopt:`--output-split`
  option.

* Verilator emits any infrequently executed "cold" routines into separate
  __Slow.cpp files. This can accelerate compilation as optimization can be
  disabled on these routines. See the OPT_FAST and OPT_SLOW make variables
  and :ref:`Benchmarking & Optimization`.

* Use a recent compiler.  Newer compilers tend to be faster.

* Compile in parallel on many machines and use caching; see the web for the
  ccache, sccache, distcc, or icecream packages. ccache will skip GCC runs between
  identical source builds, even across different users.  If ccache was
  installed when Verilator was built, it is used, or see OBJCACHE
  environment variable to override this. Also see the
  :vlopt:`--output-split` option and :ref: `Profiling ccache efficiency`.

* To reduce the compile time of classes that use a Verilated module (e.g., a
  top CPP file) you may wish to add a
  :option:`/*verilator&32;no_inline_module*/` metacomment to your top-level
  module. This will decrease the amount of code in the model's Verilated
  class, improving compile times of any instantiating top-level C++ code,
  at a relatively small cost of execution performance.

* Use :ref:`hierarchical verilation`.


Why do so many files need to recompile when I add a signal?
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Adding a new signal requires the symbol table to be recompiled.  Verilator
uses one large symbol table, resulting in 2-3 fewer assembly
instructions for each signal access.  This makes the execution time 10-15%
faster, but can result in more compilations when something changes.


How do I access Verilog functions/tasks in C?
"""""""""""""""""""""""""""""""""""""""""""""

Use the SystemVerilog Direct Programming Interface.  You write a Verilog
function or task with input/outputs that match what you want to call in
with C.  Then mark that function as a DPI export function.  See the DPI
chapter in the IEEE Standard.


How do I access C++ functions/tasks in Verilog?
"""""""""""""""""""""""""""""""""""""""""""""""

Use the SystemVerilog Direct Programming Interface.  You write a Verilog
function or task with input/outputs that match what you want to call in
with C.  Then mark that function as a DPI import function.  See the DPI
chapter in the IEEE Standard.


How do I access signals in C?
"""""""""""""""""""""""""""""

The best thing to do is to make a SystemVerilog "export DPI" task or
function that accesses that signal, as described in the DPI chapter in the
manual and DPI tutorials on the web.  This will allow Verilator to
optimize the model better and should be portable across simulators.

If you really want raw access to the signals, declare the signals you will
be accessing with a :option:`/*verilator&32;public*/` metacomment before
the closing semicolon.  Then scope into the C++ class to read the value of
the signal, as you would any other member variable.

Signals are the smallest of 8-bit unsigned chars (equivalent to uint8_t),
16-bit unsigned shorts (uint16_t), 32-bit unsigned longs (uint32_t), or
64-bit unsigned long longs (uint64_t) that fit the width of the signal.
Generally, you can use just uint32_t's for 1 to 32 bits, or uint64_t for
1 to 64 bits, and the compiler will properly up-convert smaller entities.
Note that even signed ports are declared as unsigned; you must sign extend
yourself to the appropriate signal width.

Signals wider than 64 bits are stored as an array of 32-bit uint32_t's.
Thus, to read bits 31:0, access signal[0], and for bits 63:32, access
signal[1].  Unused bits (for example, bit numbers 65-96 of a 65-bit vector)
will always be zero.  If you change the value, you must pack
zeros in the unused bits, or core-dumps may result because Verilator strips
array bound checks where it believes them to be unnecessary to improve
performance.

In the SYSTEMC example above, if you had in our.v:

 .. code-block:: sv

      input clk /*verilator public*/;
      // Note the placement of the semicolon above

From the sc_main.cpp file, you'd then:

 .. code-block:: C++

      #include "Vour.h"
      #include "Vour_our.h"
      std::cout << "clock is " << top->our->clk << std::endl;


In this example, clk is a bool you can read or set as any other variable.
The value of normal signals may be set, though your code shouldn't change
clocks, or you'll get strange results.


Should a module be in Verilog or SystemC?
"""""""""""""""""""""""""""""""""""""""""

Sometimes there is a block that only interconnects instances, and you have a
choice if you write it in Verilog or SystemC.  Everything else being
equal, the best performance is when Verilator sees all of the design.  So, look
at the hierarchy of your design, labeling instances as to if they are
SystemC or Verilog.  Then:

* A module with only SystemC instances below must be SystemC.

* A module with a mix of Verilog and SystemC instances below must be
  SystemC. (As Verilator cannot connect to lower-level SystemC instances.)

* A module with only Verilog instances below can be either, but for best
  performance should be Verilog.  (The exception is if you have a design
  that is instantiated many times; in this case, Verilating one of the lower
  modules and instantiating that Verilated instances multiple times into a
  SystemC module *may* be faster.)
verilator-5.020/docs/guide/simulating.rst0000644000175000017500000004753414544475344020375 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

.. _Simulating:

************************************
Simulating (Verilated-Model Runtime)
************************************

This section describes items related to simulating, that is, using a
Verilated model's executable.  For the runtime arguments to a simulated
model, see :ref:`Simulation Runtime Arguments`.


.. _Benchmarking & Optimization:

Benchmarking & Optimization
===========================

For best performance, run Verilator with the :vlopt:`-O3`
:vlopt:`--x-assign fast <--x-assign>`
:vlopt:`--x-initial fast <--x-initial>`
:vlopt:`--noassert <--assert>` options.  The :vlopt:`-O3`
option will require a longer time to run Verilator, and
:vlopt:`--x-assign fast <--x-assign>`
:vlopt:`--x-initial fast <--x-assign>`
may increase the risk of reset bugs in trade for performance; see the above
documentation for these options.

If using Verilated multithreaded, use ``numactl`` to ensure you use
non-conflicting hardware resources. See :ref:`Multithreading`. Also,
consider using profile-guided optimization; see :ref:`Thread PGO`.

Minor Verilog code changes can also give big wins.  You should not have any
:option:`UNOPTFLAT` warnings from Verilator.  Fixing these warnings can
result in huge improvements; one user fixed their one UNOPTFLAT warning by
making a simple change to a clocked latch used to gate clocks and gained a
60% performance improvement.

Beyond that, the performance of a Verilated model depends primarily on your
C++ compiler and the size of your CPU's caches. Experience shows that the
instruction cache size often limits large models, and reducing code size,
if possible, can be beneficial.

The supplied $VERILATOR_ROOT/include/verilated.mk file uses the OPT,
OPT_FAST, OPT_SLOW, and OPT_GLOBAL variables to control optimization. You
can set these when compiling the output of Verilator with Make, for
example:

.. code-block:: bash

     make OPT_FAST="-Os -march=native" -f Vour.mk Vour__ALL.a

OPT_FAST specifies optimization options for those parts of the model
on the fast path. This is mostly code that is executed every
cycle. OPT_SLOW applies to slow-path code, which rarely executes, often
only once at the beginning or end of the simulation. OPT_SLOW is
ignored if VM_PARALLEL_BUILDS is not 1, in which case all generated code
will be compiled in a single compilation unit using OPT_FAST. See also the
Verilator :vlopt:`--output-split` option. The OPT_GLOBAL variable applies
to common code in the runtime library used by Verilated models (shipped in
$VERILATOR_ROOT/include). Additional C++ files passed on the verilator
command line use OPT_FAST. The OPT variable applies to all compilation
units and the specific "OPT" variables described above.

You can also use the :vlopt:`-CFLAGS` and/or :vlopt:`-LDFLAGS` options on
the verilator command line to pass arguments directly to the compiler or
linker.

The default values of the "OPT" variables are chosen to yield good
simulation speed with reasonable C++ compilation times. To this end,
OPT_FAST is set to "-Os" by default. Higher optimization such as "-O2" or
"-O3" may help (though often they provide only a minimal performance
benefit), but compile times may be excessively large even with medium-sized
designs. Compilation times can be improved at the expense of simulation
speed by reducing optimization, for example, with OPT_FAST="-O0". Often
good simulation speed can be achieved with OPT_FAST="-O1 -fstrict-aliasing"
but with improved compilation times.  Files controlled by OPT_SLOW have
little effect on performance, and therefore OPT_SLOW is empty by default
(equivalent to "-O0") for improved compilation speed. In common use cases,
there should be little benefit in changing OPT_SLOW.  OPT_GLOBAL is set to
"-Os" by default, and there should rarely be a need to change it. As the
runtime library is small compared to many Verilated models, disabling
optimization on the runtime library should not seriously affect overall
compilation time but may have a detrimental effect on simulation speed,
especially with tracing. In addition to the above, for best results, use
OPT="-march=native", the latest Clang compiler (about 10% faster than GCC),
and link statically.

Generally, the answer to which optimization level gives the best user
experience depends on the use case, and some experimentation can pay
dividends. For a speedy debug cycle during development, especially on large
designs where C++ compilation speed can dominate, consider using lower
optimization to get to an executable faster. For throughput-oriented use
cases, for example, regressions, it is usually worth spending extra
compilation time to reduce total CPU time.

If you will be running many simulations on a single model, you can
investigate profile-guided optimization. See :ref:`Compiler PGO`.

Modern compilers also support link-time optimization (LTO), which can help,
especially if you link in DPI code. To enable LTO on GCC, pass "-flto" in
both compilation and link. Note that LTO may cause excessive compile times
on large designs.

Unfortunately, using the optimizer with SystemC files can result in
compilation taking several minutes. (The SystemC libraries have many little
inlined functions that drive the compiler nuts.)

If using your own makefiles, you may want to compile the Verilated
code with ``--MAKEFLAGS -DVL_INLINE_OPT=inline``. This will inline
functions; however, this requires that all cpp files be compiled in a single
compiler run.

You may uncover further tuning possibilities by profiling the Verilog code.
See :ref:`profiling`.

When done optimizing, please let the author know the results.  We like to
keep tabs on how Verilator compares and may be able to suggest additional
improvements.


.. _Coverage Analysis:

Coverage Analysis
=================

Verilator supports adding code to the Verilated model to support
SystemVerilog code coverage.  With :vlopt:`--coverage`, Verilator enables
all forms of coverage:

* :ref:`User Coverage`
* :ref:`Line Coverage`
* :ref:`Toggle Coverage`

When a model with coverage is executed, it will create a coverage file for
collection and later analysis, see :ref:`Coverage Collection`.


.. _User Coverage:

Functional Coverage
-------------------

With :vlopt:`--coverage` or :vlopt:`--coverage-user`, Verilator will
translate functional coverage points the user has inserted manually in
SystemVerilog code through into the Verilated model.

Currently, all functional coverage points are specified using SystemVerilog
assertion syntax, which must be separately enabled with :vlopt:`--assert`.

For example, the following SystemVerilog statement will add a coverage
point under the coverage name "DefaultClock":

.. code-block:: sv

    DefaultClock: cover property (@(posedge clk) cyc==3);


.. _Line Coverage:

Line Coverage
-------------

With :vlopt:`--coverage` or :vlopt:`--coverage-line`, Verilator will
automatically add coverage analysis at each code flow change point (e.g.,
at branches).  At each such branch, a counter is incremented.  At the end
of a test, the counters, filename, and line number corresponding to each
counter are written into the coverage file.

Verilator automatically disables coverage of branches with a $stop in
them, as it is assumed that $stop branches contain an error check that should
not occur.  A :option:`/*verilator&32;coverage_block_off*/` metacomment
will perform a similar function on any code in that block or below, or
:option:`/*verilator&32;coverage_off*/` and
:option:`/*verilator&32;coverage_on*/` will disable and enable coverage
respectively around a block of code.

Verilator may over-count combinatorial (non-clocked) blocks when those
blocks receive signals which have had the :option:`UNOPTFLAT` warning
disabled; for the most accurate results, do not disable this warning when
using coverage.


.. _Toggle Coverage:

Toggle Coverage
---------------

With :vlopt:`--coverage` or :vlopt:`--coverage-toggle`, Verilator will
automatically add toggle coverage analysis  into the Verilated model.

Every bit of every signal in a module has a counter inserted, and the
counter will increment on every edge change of the corresponding bit.

Signals that are part of tasks or begin/end blocks are considered local
variables and are not covered.  Signals that begin with underscores (see
:vlopt:`--coverage-underscore`), are integers, or are very wide (>256 bits
total storage across all dimensions, see :vlopt:`--coverage-max-width`) are
also not covered.

Hierarchy is compressed, so if a module is instantiated multiple times,
coverage will be summed for that bit across **all** instantiations of that
module with the same parameter set.  A module instantiated with different
parameter values is considered a different module and will get counted
separately.

Verilator makes a minimally-intelligent decision about what clock domain
the signal goes to, and only looks for edges in that clock domain.  This
means that edges may be ignored if it is known that the receiving logic
could never see the edge.  This algorithm may improve in the future. The
net result is that coverage may be lower than what would be seen by looking
at traces, but the coverage is a more accurate representation of the
quality of stimulus into the design.

There may be edges counted near time zero while the model stabilizes.  It's
a good practice to zero all coverage just before releasing reset to prevent
counting such behavior.

A :option:`/*verilator&32;coverage_off*/`
:option:`/*verilator&32;coverage_on*/` metacomment pair can be used around
signals that do not need toggle analysis, such as RAMs and register files.


.. _Coverage Collection:

Coverage Collection
-------------------

When any coverage flag is used to Verilate, Verilator will add appropriate
coverage point insertions into the model and collect the coverage data.

To get the coverage data from the model, in the user wrapper code,
typically at the end once a test passes, call
:code:`Verilated::threadContextp()->coveragep()->write` with an argument of the filename for
the coverage data file to write coverage data to (typically
"logs/coverage.dat").

Run each of your tests in different directories, potentially in parallel.
Each test will create a :file:`logs/coverage.dat` file.

After running all of the tests, execute the :command:`verilator_coverage`
command, passing arguments pointing to the filenames of all the
individual coverage files.  :command:`verilator_coverage` will read the
:file:`logs/coverage.dat` file(s), and create an annotated source code
listing showing code coverage details.

:command:`verilator_coverage` may also be used for test grading, computing
which tests are important to give full verification coverage on the design.

For an example, see the :file:`examples/make_tracing_c/logs` directory.
Grep for lines starting with '%' to see what lines Verilator believes need
more coverage.

Additional options of :command:`verilator_coverage` allow for the merging
of coverage data files or other transformations.

Info files can be written by verilator_coverage for import to
:command:`lcov`.  This enables using :command:`genhtml` for HTML reports
and importing reports to sites such as `https://codecov.io
`_.


.. _Profiling:

Code Profiling
==============

The Verilated model may be code-profiled using GCC or Clang's C++ profiling
mechanism.  Verilator provides additional flags to help map the resulting
C++ profiling results back to the original Verilog code responsible for the
profiled C++ code functions.

To use profiling:

#. Use Verilator's :vlopt:`--prof-cfuncs`.
#. Build and run the simulation model.
#. The model will create gmon.out.
#. Run :command:`gprof` to see where in the C++ code the time is spent.
#. Run the gprof output through the :command:`verilator_profcfunc` program,
   and it will tell you what Verilog line numbers on which most of the time
   is being spent.


.. _Execution Profiling:

Execution Profiling
===================

For performance optimization, it is helpful to see statistics and visualize how
execution time is distributed in a verilated model.

With the :vlopt:`--prof-exec` option, Verilator will:

* Add code to the Verilated model to record execution flow.

* Add code to save profiling data in non-human-friendly form to the file
  specified with :vlopt:`+verilator+prof+exec+file+\`.

* In multithreaded models, add code to record each macro-task's start and
  end time across several calls to eval. (What is a macro-task?  See the
  Verilator internals document (:file:`docs/internals.rst` in the
  distribution.)

The :command:`verilator_gantt` program may then be run to transform the
saved profiling file into a visual format and produce related statistics.

.. figure:: figures/fig_gantt_min.png

   Example verilator_gantt output, as viewed with GTKWave.

   The measured_parallelism shows the number of CPUs being used at a given moment.

   The cpu_thread section shows which thread is executing on each physical CPU.

   The thread_mtask section shows which macro-task is running on a given thread.

For more information, see :command:`verilator_gantt`.


.. _Profiling ccache efficiency:

Profiling ccache efficiency
===========================

The Verilator-generated Makefile supports basic profiling of ccache
behavior during the build. This can be used to track down files that might
be unnecessarily rebuilt, though as of today, even minor code changes will
usually require rebuilding a large number of files. Improving ccache
efficiency during the edit/compile/test loop is an active development area.

To get a basic report of how well ccache is doing, add the `ccache-report`
target when invoking the generated Makefile:

.. code-block:: bash

     make -C obj_dir -f Vout.mk Vout ccache-report

This will print a report based on all executions of ccache during this
invocation of Make. The report is also written to a file, in this example
`obj_dir/Vout__cache_report.txt`.

To use the `ccache-report` target, at least one other explicit build target
must be specified, and OBJCACHE must be set to 'ccache'.

This feature is currently experimental and might change in subsequent
releases.

.. _Save/Restore:

Save/Restore
============

The intermediate state of a Verilated model may be saved so that it may
later be restored.

To enable this feature, use :vlopt:`--savable`.  There are limitations in
what language features are supported along with :vlopt:`--savable`; if you
attempt to use an unsupported feature, Verilator will throw an error.

To use save/restore, the user wrapper code must create a VerilatedSerialize
or VerilatedDeserialze object and then call the :code:`<<` or :code:`>>`
operators on the generated model and any other data the process needs to be
saved/restored.  These functions are not thread-safe and are typically
called only by a main thread.

For example:

.. code-block:: C++

     void save_model(const char* filenamep) {
         VerilatedSave os;
         os.open(filenamep);
         os << main_time;  // user code must save the timestamp
         os << *topp;
     }
     void restore_model(const char* filenamep) {
         VerilatedRestore os;
         os.open(filenamep);
         os >> main_time;
         os >> *topp;
     }


Profile-Guided Optimization
===========================

Profile-guided optimization is the technique where profiling data is
collected by running your simulation executable; then this information is
used to guide the next Verilation or compilation.

There are two forms of profile-guided optimizations.  Unfortunately, for
best results, they must each be performed from the highest level code to the
lowest, which means performing them separately and in this order:

* :ref:`Thread PGO`
* :ref:`Compiler PGO`

Other forms of PGO may be supported in the future, such as clock and reset
toggle rate PGO, branch prediction PGO, statement execution time PGO, or
others, as they prove beneficial.


.. _Thread PGO:

Thread Profile-Guided Optimization
----------------------------------

Verilator supports profile-guided optimization (Verilation) of multithreaded
models (Thread PGO) to improve performance.

When using multithreading, Verilator computes how long macro tasks take and
tries to balance those across threads.  (What is a macro-task?  See the
Verilator internals document (:file:`docs/internals.rst` in the
distribution.)  If the estimations are incorrect, the threads will not be
balanced, leading to decreased performance.  Thread PGO allows collecting
profiling data to replace the estimates and better optimize these
decisions.

To use Thread PGO, Verilate the model with the :vlopt:`--prof-pgo` option. This
will code to the verilated model to save profiling data for profile-guided
optimization.

Run the model executable. When the executable exits, it will create a
profile.vlt file.

Rerun Verilator, optionally omitting the :vlopt:`--prof-pgo` option and
adding the :file:`profile.vlt` generated earlier to the command line.

Note there is no Verilator equivalent to GCC's --fprofile-use.  Verilator's
profile data file (:file:`profile.vlt`) can be placed directly on the
verilator command line without any option prefix.

If results from multiple simulations are to be used in generating the
optimization, multiple simulation's profile.vlt may be concatenated
externally, or each file may be fed as separate command line options into
Verilator.  Verilator will sum the profile results, so a long-running test
will have more weight for optimization proportionally than a
shorter-running test.

If you provide any profile feedback data to Verilator and it cannot use
it, it will issue the :option:`PROFOUTOFDATE` warning that threads were
scheduled using estimated costs.  This usually indicates that the profile
data was generated from a different Verilog source code than Verilator is
currently running against. Therefore, repeat the data collection phase to
create new profiling data, then rerun Verilator with the same input source
files and that new profiling data.


.. _Compiler PGO:

Compiler Profile-Guided Optimization
------------------------------------

GCC and Clang support compiler profile-guided optimization (PGO). This
optimizes any C/C++ program, including Verilated code.  Using compiler PGO
typically yields improvements of 5-15% on both single-threaded and
multithreaded models.

Please see the appropriate compiler documentation to use PGO with GCC or
Clang.  The process in GCC 10 was as follows:

1. Compile the Verilated model with the compiler's "-fprofile-generate"
   flag:

   .. code-block:: bash

      verilator [whatever_flags] --make \
          -CFLAGS -fprofile-generate -LDFLAGS -fprofile-generate

   Or, if calling make yourself, add -fprofile-generate appropriately to your
   Makefile.

2. Run your simulation. This will create \*.gcda file(s) in the same
   directory as the source files.

3. Recompile the model with -fprofile-use. The compiler will read the
   \*.gcda file(s).

   For GCC:

   .. code-block:: bash

      verilator [whatever_flags] --build \
          -CFLAGS "-fprofile-use -fprofile-correction"

   For Clang:

   .. code-block:: bash

      llvm-profdata merge -output default.profdata *.profraw
      verilator [whatever_flags] --build \
          -CFLAGS "-fprofile-use -fprofile-correction"

   or, if calling make yourself, add these CFLAGS switches appropriately to
   your Makefile.

Clang and GCC also support -fauto-profile, which uses sample-based
feedback-directed optimization.  See the appropriate compiler
documentation.


.. _Runtime Debugging:

Runtime Debugging
=================

To debug a Verilated executable, use the standard GNU debugger ``gdb`` or a
similar tool. Typically you will want to have debugger symbols inserted by
the compiler, assertions enabled in the C library, and assertions enabled
in the Verilated library. (These options slow down the executable, so do
this only when debugging.) To enable this, Verilate with:

    -CFLAGS -ggdb  -LDFLAGS -ggdb  -CFLAGS -DVL_DEBUG=1  -CFLAGS -D_GLIBCXX_DEBUG

The :vlopt:`-CFLAGS` and/or :vlopt:`-LDFLAGS` options pass arguments
directly to the compiler or linker.
verilator-5.020/docs/guide/exe_sim.rst0000644000175000017500000000717114544475344017643 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

.. _Simulation Runtime Arguments:

Simulation Runtime Arguments
============================

The following are the arguments that may be passed to a Verilated
executable, provided that executable calls
:code:`VerilatedContext*->commandArgs(argc, argv)`.

All simulation runtime arguments begin with "+verilator", so that the
user's executable may skip over all "+verilator" arguments when parsing its
command line.

Summary:

   .. include:: ../_build/gen/args_verilated.rst


.. option:: +verilator+debug

   Enable simulation runtime debugging.  Equivalent to
   :vlopt:`+verilator+debugi+4 <+verilator+debugi+\>`.

.. option:: +verilator+debugi+

   Enable simulation runtime debugging at the provided level.

.. option:: +verilator+error+limit+

   Set number of non-fatal errors (e.g. assertion failures) before exiting
   simulation runtime. Also affects number of $stop calls needed before
   exit. Defaults to 1.

.. option:: +verilator+help

   Display help and exit.

.. option:: +verilator+prof+exec+file+

   When a model was Verilated using :vlopt:`--prof-exec`, sets the
   simulation runtime filename to dump to.  Defaults to
   :file:`profile_exec.dat`.

.. option:: +verilator+prof+exec+start+

   When a model was Verilated using :vlopt:`--prof-exec`, the simulation
   runtime will wait until $time is at this value (expressed in units of
   the time precision), then start the profiling warmup, then
   capturing. Generally this should be set to some time that is well within
   the normal operation of the simulation, i.e. outside of reset. If 0, the
   dump is disabled. Defaults to 1.

.. option:: +verilator+prof+exec+window+

   When a model was Verilated using :vlopt:`--prof-exec`, after $time
   reaches :vlopt:`+verilator+prof+exec+start+\`, Verilator will
   warm up the profiling for this number of eval() calls, then will capture
   the profiling of this number of eval() calls.  Defaults to 2, which
   makes sense for a single-clock-domain module where it's typical to want
   to capture one posedge eval() and one negedge eval().

.. option:: +verilator+prof+threads+file+

   Removed in 5.020. Was an alias for
   :vlopt:`+verilator+prof+exec+file+\`

.. option:: +verilator+prof+threads+start+

   Removed in 5.020. Was an alias for
   :vlopt:`+verilator+prof+exec+start+\`

.. option:: +verilator+prof+threads+window+

   Removed in 5.020. Was an alias for
   :vlopt:`+verilator+prof+exec+window+\`

.. option:: +verilator+prof+vlt+file+

   When a model was Verilated using :vlopt:`--prof-pgo`, sets the
   profile-guided optimization data runtime filename to dump to.  Defaults
   to :file:`profile.vlt`.

.. option:: +verilator+rand+reset+

   When a model was Verilated using
   :vlopt:`--x-initial unique <--x-initial>`, sets the simulation runtime
   initialization technique.  0 = Reset to zeros. 1 = Reset to all-ones.  2
   = Randomize.  See :ref:`Unknown States`.

.. option:: +verilator+seed+

   For $random and :vlopt:`--x-initial unique <--x-initial>`, set the
   simulation runtime random seed value.  If zero or not specified picks a
   value from the system random number generator.

.. option:: +verilator+noassert

   Disable assert checking per runtime argument. This is the same as
   calling :code:`VerilatedContext*->assertOn(false)` in the model.

.. option:: +verilator+V

   Shows the verbose version, including configuration information.

.. option:: +verilator+version

   Displays program version and exits.
verilator-5.020/docs/guide/verilating.rst0000644000175000017500000004313314544475344020354 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

**********
Verilating
**********

Verilator may be used in five major ways:

* With the :vlopt:`--binary` option, Verilator will translate the design
  into an executable, via generating C++ and compiling it.  See
  :ref:`Binary, C++ and SystemC Generation`.

* With the :vlopt:`--cc` or :vlopt:`--sc` options, Verilator will translate
  the design into C++ or SystemC code, respectively.  See :ref:`Binary, C++
  and SystemC Generation`.

* With the :vlopt:`--lint-only` option, Verilator will lint the design to
  check for warnings but will not typically create any output files.

* With the :vlopt:`--xml-only` option, Verilator will create XML output
  that may be used to feed into other user-designed tools.  See
  :file:`docs/xml.rst` in the distribution.

* With the :vlopt:`-E` option, Verilator will preprocess the code according
  to IEEE preprocessing rules and write the output to standard out. This
  is useful to feed other tools and to debug how "\`define" statements are
  expanded.


.. _Binary, C++ and SystemC Generation:

Binary, C++ and SystemC Generation
==================================

Verilator will translate a SystemVerilog design into C++ with the
:vlopt:`--cc` option, or into SystemC with the :vlopt:`--sc` option.  It
will translate into C++ and compile it into an executable binary with the
:vlopt:`--binary` option.

When using these options:

#. Verilator reads the input Verilog code and determines all "top modules", that
   is, modules or programs that are not used as instances under other cells.
   If :vlopt:`--top-module` is used, then that determines the top module, and
   all other top modules are removed; otherwise a :vlopt:`MULTITOP` warning
   is given.

#. Verilator writes the C++/SystemC code to output files into the
   :vlopt:`--Mdir` option-specified directory, or defaults to "obj_dir".
   The prefix is set with :vlopt:`--prefix`, or defaults to the name of the
   top module.

#. If :vlopt:`--binary` or :vlopt:`--main` is used, Verilator creates a C++
   top wrapper to read command line arguments, create the model, and
   execute the model.

#. If :vlopt:`--binary` or :vlopt:`--exe` is used, Verilator creates
   makefiles to generate a simulation executable, otherwise, it creates
   makefiles to generate an archive (.a) containing the objects.

#. If :vlopt:`--binary` or :vlopt:`--build` is used, it calls :ref:`GNU
   Make` or :ref:`CMake` to build the model.

Once a model is built, the next step is typically for the user to run it,
see :ref:`Simulating`.


.. _Hierarchical Verilation:

Hierarchical Verilation
=======================

Large designs may take long (e.g., 10+ minutes) and huge memory (e.g., 100+
GB) to Verilate.  In hierarchical mode, the user manually selects some
large lower-level hierarchy blocks to separate from the larger design. For
example, a core may be the hierarchy block separated out of a multi-core
SoC design.

Verilator is run in hierarchical mode on the whole SoC.  Verilator will
make two models, one for the CPU hierarchy block and one for the SoC.  The
Verilated code for the SoC will automatically call the CPU Verilated model.

The current hierarchical Verilation is based on :vlopt:`--lib-create`. Each
hierarchy block is Verilated into a library. User modules of the hierarchy
blocks will see a tiny wrapper generated by :vlopt:`--lib-create`.


Usage
-----

Users need to mark one or more moderate-size modules as hierarchy block(s).
There are two ways to mark a module:

* Write :option:`/*verilator&32;hier_block*/` metacomment in HDL code.

* Add a :option:`hier_block` line in the :ref:`Configuration Files`.

Then pass the :vlopt:`--hierarchical` option to Verilator.

The compilation is the same as when not using hierarchical mode.

.. code-block:: bash

    make -C obj_dir -f Vtop_module_name.mk


Limitations
-----------

Hierarchy blocks have some limitations, including:

* The hierarchy block cannot be accessed using dot (.) from the upper
  module(s) or other hierarchy blocks.

* Signals in the block cannot be traced.

* Modport cannot be used at the hierarchical block boundary.

* The simulation speed is likely not as fast as flat Verilation, in which
  all modules are globally scheduled.

* Generated clocks may not work correctly if generated in the hierarchical
  model and passed into another hierarchical model or the top module.

* Delays are not allowed in hierarchy blocks.

But, the following usage is supported:

* Nested hierarchy blocks. A hierarchy block may instantiate other
  hierarchy blocks.

* Parameterized hierarchy block. Parameters of a hierarchy block can be
  overridden using :code:`#(.param_name(value))` construct.


.. _Overlapping Verilation and Compilation:

Overlapping Verilation and Compilation
--------------------------------------

Verilator needs to run 2 + *N* times in hierarchical Verilation, where *N*
is the number of hierarchy blocks. One of the two is for the top module,
which refers to the wrappers of all other hierarchy blocks.  The second of the
two is the initial run that searches modules marked with
:option:`/*verilator&32;hier_block*/` metacomment and creates a plan and
write in :file:`{prefix}_hier.mk`.  This initial run internally invokes
other *N* + 1 runs, so you don't have to care about these *N* + 1 times of
run. The additional *N* is the Verilator run for each hierarchical block.

If ::vlopt:`-j {jobs} <-j>` option is specified, Verilation for hierarchy
blocks runs in parallel.

If :vlopt:`--build` option is specified, C++ compilation also runs as soon
as a hierarchy block is Verilated. C++ compilation and Verilation for other
hierarchy blocks run simultaneously.


Cross Compilation
=================

Verilator supports cross-compiling Verilated code.  This is generally used
to run Verilator on a Linux system and produce C++ code that is then compiled
on Windows.

Cross-compilation involves up to three different OSes.  The build system is
where you configure and compile Verilator, the host system is where you run
Verilator, and the target system is where you compile the Verilated code
and run the simulation.

Verilator requires the build and host system types to be the
same, though the target system type may be different.  To support this,
:command:`./configure` and make Verilator on the build system.  Then, run
Verilator on the host system.  Finally, the output of Verilator may be
compiled on the different target system.

To support this, none of the files that Verilator produces will reference
any configure-generated build-system-specific files, such as
:file:`config.h` (which is renamed in Verilator to :file:`config_package.h`
to reduce confusion.)  The disadvantage of this approach is that
:file:`include/verilatedos.h` must self-detect the requirements of the
target system, rather than using configure.

The target system may also require edits to the Makefiles, the simple
Makefiles produced by Verilator presume the target system is the same type
as the build system.


.. _Multithreading:

Multithreading
==============

Verilator supports multithreaded simulation models.

With :vlopt:`--threads 1 <--threads>`, the generated model is
single-threaded; however, the support libraries are multithread safe. This
allows different instantiations of the model(s) to potentially each be run
under a different thread. All threading is the responsibility of the user's
C++ testbench.

With :vlopt:`--threads {N} <--threads>`, where N is at least 2, the
generated model will be designed to run in parallel on N threads. The
thread calling eval() provides one of those threads, and the generated
model will create and manage the other N-1 threads. It's the client's
responsibility not to oversubscribe the available CPU cores. Under CPU
oversubscription, the Verilated model should not livelock nor deadlock;
however, you can expect performance to be far worse than it would be with
the proper ratio of threads and CPU cores.

The thread used for constructing a model must be the same thread that calls
:code:`eval()` into the model; this is called the "eval thread". The thread
used to perform certain global operations, such as saving and tracing, must
be done by a "main thread". In most cases, the eval thread and main thread
are the same thread (i.e. the user's top C++ testbench runs on a single
thread), but this is not required.

When making frequent use of DPI imported functions in a multithreaded
model, it may be beneficial to performance to adjust the
:vlopt:`--instr-count-dpi` option based on some experimentation. This
influences the partitioning of the model by adjusting the assumed execution
time of DPI imports.

When using :vlopt:`--trace` to perform VCD tracing, the VCD trace
construction is parallelized using the same number of threads as specified
with :vlopt:`--threads`, and is executed on the same thread pool as the model.

The :vlopt:`--trace-threads` options can be used with :vlopt:`--trace-fst`
to offload FST tracing using multiple threads. If :vlopt:`--trace-threads` is
given without :vlopt:`--threads`, then :vlopt:`--trace-threads` will imply
:vlopt:`--threads 1 <--threads>`, i.e., the support libraries will be
thread safe.

With :vlopt:`--trace-threads 0 <--trace-threads>`, trace dumps are produced
on the main thread. This again gives the highest single-thread performance.

With :vlopt:`--trace-threads {N} <--trace-threads>`, where N is at least 1,
up to N additional threads will be created and managed by the trace files
(e.g., VerilatedFstC), to offload construction of the trace dump. The main
thread will be released to proceed with execution as soon as possible, though
some main thread blocking is still necessary while capturing the
trace. FST tracing can utilize up to 2 offload threads, so there is no use
of setting :vlopt:`--trace-threads` higher than 2 at the moment.

When running a multithreaded model, the default Linux task scheduler often
works against the model by assuming short-lived threads and thus
it often schedules threads using multiple hyperthreads within the same
physical core. For best performance, use the :command:`numactl` program to
(when the threading count fits) select unique physical cores on the same
socket. The same applies for :vlopt:`--trace-threads` as well.

As an example, if a model was Verilated with
:vlopt:`--threads 4 <--threads>`, we consult:

.. code-block:: bash

    egrep 'processor|physical id|core id' /proc/cpuinfo

To select cores 0, 1, 2, and 3 that are all located on the same socket (0)
but have different physical cores.  (Also useful is
:command:`numactl --hardware`, or :command:`lscpu`, but those don't show
hyperthreading cores.)  Then we execute:

.. code-block:: bash

    numactl -m 0 -C 0,1,2,3 -- verilated_executable_name

This will limit memory to socket 0, and threads to cores 0, 1, 2, 3,
(presumably on socket 0), optimizing performance.  Of course, this must be
adjusted if you want another simulator to use, e.g., socket 1, or if you
Verilated with a different number of threads.  To see what CPUs are
actually used, use :vlopt:`--prof-exec`.


Multithreaded Verilog and Library Support
-----------------------------------------

$display/$stop/$finish are delayed until the end of an eval() call
to maintain ordering between threads. This may result in additional tasks
completing after the $stop or $finish.

If using :vlopt:`--coverage`, the coverage routines are fully thread-safe.

If using the DPI, Verilator assumes pure DPI imports are thread-safe,
balancing performance versus safety. See :vlopt:`--threads-dpi`.

If using :vlopt:`--savable`, the save/restore classes are not multithreaded
and must be called only by the eval thread.

If using :vlopt:`--sc`, the SystemC kernel is not thread-safe; therefore,
the eval thread and main thread must be the same.

If using :vlopt:`--trace`, the tracing classes must be constructed and
called from the main thread.

If using :vlopt:`--vpi`, since SystemVerilog VPI was not architected by
IEEE to be multithreaded, Verilator requires all VPI calls are only made
from the main thread.


.. _GNU Make:

GNU Make
========

Verilator defaults to creating GNU Make makefiles for the model.  Verilator
will call make automatically when the :vlopt:'--build' option is used.

If calling Verilator from a makefile, the :vlopt:'-MMD' option will create
a dependency file, allowing Make to only run Verilator if input Verilog
files change.

.. _CMake:

CMake
=====

Verilator can be run using CMake, which takes care of both running
Verilator and compiling the output. There is a CMake example in the
:file:`examples/` directory. The following is a minimal CMakeLists.txt that
would build the code listed in :ref:`Example C++ Execution`

.. code-block:: CMake

     project(cmake_example)
     find_package(verilator HINTS $ENV{VERILATOR_ROOT})
     add_executable(Vour sim_main.cpp)
     verilate(Vour SOURCES our.v)

:code:`find_package` will automatically find an installed copy of
Verilator, or use a local build if VERILATOR_ROOT is set.

Using CMake >= 3.12 and the Ninja generator is recommended, though other
combinations should work. To build with CMake, change to the folder
containing CMakeLists.txt and run:

.. code-block:: bash

     mkdir build
     cd build
     cmake -GNinja ..
     ninja

Or to build with your system default generator:

.. code-block:: bash

     mkdir build
     cd build
     cmake ..
     cmake --build .

If you're building the example, you should have an executable to run:

.. code-block:: bash

     ./Vour

The package sets the CMake variables verilator_FOUND, VERILATOR_ROOT,
and VERILATOR_BIN to the appropriate values and creates a verilate()
function. verilate() will automatically create custom commands to run
Verilator and add the generated C++ sources to the target specified.

Verilate in CMake
-----------------

.. code-block:: CMake

     verilate(target SOURCES source ... [TOP_MODULE top] [PREFIX name]
              [TRACE] [TRACE_FST] [SYSTEMC] [COVERAGE]
              [INCLUDE_DIRS dir ...] [OPT_SLOW ...] [OPT_FAST ...]
              [OPT_GLOBAL ..] [DIRECTORY dir] [THREADS num]
              [TRACE_THREADS num] [VERILATOR_ARGS ...])

Lowercase and ... should be replaced with arguments; the uppercase parts
delimit the arguments and can be passed in any order or left out entirely
if optional.

verilate(target ...) can be called multiple times to add other Verilog
modules to an executable or library target.

When generating Verilated SystemC sources, you should list the
SystemC include directories and link to the SystemC libraries.

.. describe:: target

   Name of a target created by add_executable or add_library.

.. describe:: COVERAGE

   Optional. Enables coverage if present, equivalent to "VERILATOR_ARGS
   --coverage".

.. describe:: DIRECTORY

   Optional. Set the verilator output directory. It is preferable to use
   the default, which will avoid collisions with other files.

.. describe:: INCLUDE_DIRS

   Optional. Sets directories that Verilator searches (same as -y).

.. describe:: OPT_SLOW

   Optional. Set compiler options for the slow path. You may want to reduce
   the optimization level to improve compile times with large designs.

.. describe:: OPT_FAST

   Optional. Set compiler options for the fast path.

.. describe:: OPT_GLOBAL

   Optional. Set compiler options for the common runtime library used by
   Verilated models.

.. describe:: PREFIX

   Optional. Sets the Verilator output prefix. Defaults to the name of the
   first source file with a "V" prepended. It must be unique in each call
   to verilate(), so this is necessary if you build a module multiple times
   with different parameters. It must be a valid C++ identifier, i.e., it
   contains no white space and only characters A-Z, a-z, 0-9 or _.

.. describe:: SOURCES

   List of Verilog files to Verilate. You must provide at least one file.

.. describe:: SYSTEMC

   Optional. Enables SystemC mode, defaults to C++ if not specified.

   When using Accellera's SystemC with CMake support, a CMake target is
   available that simplifies the SystemC steps. This will only work if
   CMake can find the SystemC installation, and this can be configured by
   setting the CMAKE_PREFIX_PATH variable during CMake configuration.

   Don't forget to set the same C++ standard for the Verilated sources as
   the SystemC library. This can be specified using the SYSTEMC_CXX_FLAGS
   environment variable.

.. describe:: THREADS

   Optional. Enable a multithreaded model; see :vlopt:`--threads`.

.. describe:: TRACE_THREADS

   Optional. Enable multithreaded FST trace; see :vlopt:`--trace-threads`.

.. describe:: TOP_MODULE

   Optional. Sets the name of the top module. Defaults to the name of the
   first file in the SOURCES array.

.. describe:: TRACE

   Optional. Enables VCD tracing if present, equivalent to "VERILATOR_ARGS
   --trace".

.. describe:: TRACE_FST

   Optional. Enables FST tracing if present, equivalent to "VERILATOR_ARGS
   --trace-fst".

.. describe:: VERILATOR_ARGS

   Optional. Extra arguments to Verilator. Do not specify :vlopt:`--Mdir`
   or :vlopt:`--prefix` here; use DIRECTORY or PREFIX.


SystemC Link in CMake
---------------------

Verilator's CMake support provides a convenience function to automatically
find and link to the SystemC library.  It can be used as:

.. code-block:: CMake

     verilator_link_systemc(target)

where target is the name of your target.

The search paths can be configured by setting some variables:

.. describe:: SYSTEMC_INCLUDE

   Sets the direct path to the SystemC includes.

.. describe:: SYSTEMC_LIBDIR

   Sets the direct path to the SystemC libraries.

.. describe:: SYSTEMC_ROOT

   Sets the installation prefix of an installed SystemC library.

.. describe:: SYSTEMC

   Sets the installation prefix of an installed SystemC library. (Same as
   SYSTEMC_ROOT).
verilator-5.020/docs/guide/executables.rst0000644000175000017500000000073114544475344020511 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

*********************************
Executable and Argument Reference
*********************************

This section describes the executables that are part of Verilator, and the
options to each executable.

.. toctree::
   :maxdepth: 1
   :hidden:

   exe_verilator.rst
   exe_verilator_coverage.rst
   exe_verilator_gantt.rst
   exe_verilator_profcfunc.rst
   exe_sim.rst
verilator-5.020/docs/guide/example_dist.rst0000644000175000017500000000247114544475344020666 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

.. _Examples in the Distribution:

Examples in the Distribution
============================

See the ``examples/`` directory that is part of the distribution, and
is installed (in an OS-specific place, often in e.g.
``/usr/local/share/verilator/examples``).  These examples include:

examples/make_hello_binary
   Example GNU-make simple Verilog->binary conversion
examples/make_hello_c
   Example GNU-make simple Verilog->C++ conversion
examples/make_hello_sc
   Example GNU-make simple Verilog->SystemC conversion
examples/make_tracing_c
   Example GNU-make Verilog->C++ with tracing
examples/make_tracing_sc
   Example GNU-make Verilog->SystemC with tracing
examples/make_protect_lib
   Example using --protect-lib
examples/cmake_hello_c
   Example building make_hello_c with CMake
examples/cmake_hello_sc
   Example building make_hello_sc with CMake
examples/cmake_tracing_c
   Example building make_tracing_c with CMake
examples/cmake_tracing_sc
   Example building make_tracing_sc with CMake
examples/cmake_protect_lib
   Example building make_protect_lib with CMake

To run an example copy the example to a new directory and run it.

::

      cp -rp {path_to}/examples/make_hello_c make_hello_c
      cd make_hello_c
      make
verilator-5.020/docs/guide/exe_verilator_gantt.rst0000644000175000017500000000452714544475344022261 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

verilator_gantt
===============

Verilator_gantt creates a visual representation to help analyze Verilator
multithreaded simulation performance by showing when each macro-task
starts, ends, and when each thread is busy or idle.

For an overview of the use of verilator_gantt, see :ref:`Profiling`.

Gantt Chart VCD
---------------

Verilated_gantt creates a value change dump (VCD) format dump file which
may be viewed in a waveform viewer (e.g., C):

.. figure:: figures/fig_gantt_min.png

   Example verilator_gantt output, as viewed with GTKWave.

The viewed waveform chart has time on the X-axis, with one unit for each
time tick of the system's high-performance counter.


Gantt Chart VCD Signals
-----------------------

In waveforms, there are the following signals. In GTKWave, use "decimal"
data format to remove the leading zeros and make the traces easier to read.

trace/section
  Shows the name of the current top of the execution section stack.
  Set GTKWave data format to "ASCII".

trace/depth
  Shows the depth of the execution section stack.
  Set GTKWave data format to "Analog".

measured_parallelism
  The number of mtasks active at this time, for best performance, this will
  match the thread count. In GTKWave, use a data format of "analog step" to
  view this signal.

predicted_parallelism
  The number of mtasks Verilator predicted would be active at this time,
  for best performance this will match the thread count. In GTKWave, use a
  data format of "analog step" to view this signal.

cpu#_thread
  For the given CPU number, the thread number measured to be executing.

mtask#_cpu
  For the given mtask id, the CPU it was measured to execute on.

thread#_mtask
  For the given thread number, the mtask id it was executing.

predicted_thread#_mtask
  For the given thread number, the mtask id Verilator predicted would be
  executing.


verilator_gantt Arguments
-------------------------

.. program:: verilator_gantt

.. option:: 

The filename to read data from; the default is "profile_exec.dat".

.. option:: --help

Displays a help summary, the program version, and exits.

.. option:: --no-vcd

Disables creating a .vcd file.

.. option:: --vcd 

Sets the output filename for vcd dump; the default is "verilator_gantt.vcd".
verilator-5.020/docs/guide/overview.rst0000644000175000017500000000465114544475344020060 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

********
Overview
********

Welcome to Verilator!

The Verilator package converts Verilog [#]_ and SystemVerilog [#]_ hardware
description language (HDL) designs into a C++ or SystemC model that, after
compiling, can be executed.  Verilator is not a traditional simulator but a
compiler.

Verilator is typically used as follows:

1. The :command:`verilator` executable is invoked with parameters similar
to GCC or other simulators such as Cadence Verilog-XL/NC-Verilog, or
Synopsys VCS.  Verilator reads the specified SystemVerilog code, lints it,
optionally adds coverage and waveform tracing support, and compiles the
design into a source-level multithreaded C++ or SystemC "model".  The
resulting model's C++ or SystemC code is output as .cpp and .h files. This
is referred to as "Verilating", and the process is "to Verilate"; the
output is a "Verilated" model.

2. For simulation, a small-user written C++ wrapper file is required, the
"wrapper".  This wrapper defines the C++ standard function "main()", which
instantiates the Verilated model as a C++/SystemC object.

3. The user C++ wrapper, the files created by Verilator, a "runtime
library" provided by Verilator, and, if applicable SystemC libraries are
then compiled using a C++ compiler to create a simulation executable.

4. The resulting executable will perform the actual simulation during
"simulation runtime".

5. If appropriately enabled, the executable may also generate waveform
traces of the design that may be viewed.  It may also create coverage
analysis data for post-analysis.

The best place to get started is to try the :ref:`Examples`.


.. [#] Verilog is defined by the `Institute of Electrical and Electronics
       Engineers (IEEE) Standard for Verilog Hardware Description
       Language`, Std. 1364, released in 1995, 2001, and 2005.  The
       Verilator documentation uses the shorthand, e.g., "IEEE 1364-2005",
       to refer to the, e.g., 2005 version of this standard.

.. [#] SystemVerilog is defined by the `Institute of Electrical and
       Electronics Engineers (IEEE) Standard for SystemVerilog - Unified
       Hardware Design, Specification, and Verification Language`, Standard
       1800, released in 2005, 2009, 2012, and 2017.  The Verilator
       documentation uses the shorthand e.g., "IEEE 1800-2017", to refer to
       the, e.g., 2017 version of this standard.
verilator-5.020/docs/guide/changes.rst0000644000175000017500000000111514544475344017612 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

****************
Revision History
****************

.. COMMENT above header must use ### so there is an extra level of headers
   here so the index won't show the huge list of revisions when clicking on
   "Revision History" in the sidebar.

Changes are contained in the :file:`Changes` file of the distribution, and
also summarized below.  To subscribe to new versions, see `Verilator
Announcements `_.

.. include:: ../_build/gen/Changes
verilator-5.020/docs/guide/environment.rst0000644000175000017500000001425514544475344020557 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

Environment
===========

This section describes the environment variables used by Verilator and
associated programs.

.. option:: LD_LIBRARY_PATH

   A generic Linux/OS variable specifying what directories have shared
   object (.so) files.  This path should include SystemC and other
   shared objects needed at simulation runtime.

.. option:: MAKE

   Names the executable of the make command invoked when using the
   :vlopt:`--build` option.  Some operating systems may require "gmake" to
   this variable to launch GNU make.  If this variable is not specified,
   "make" is used.

.. option:: MAKEFLAGS

   Flags created by :command:`make` to pass to submakes. Verilator searches
   this variable to determine if a jobserver is used; see
   :vlopt:`--build-jobs`.

.. option:: OBJCACHE

   Optionally specifies a caching or distribution program to place in front
   of all runs of the C++ compiler.  For example, "ccache" or "sccache".  If using
   :command:`distcc` or :command:`icecc`/:command:`icecream`, they would
   generally be run under :command:`ccache`; see the documentation for
   those programs.  If OBJCACHE is not set, and at configure time ccache
   was present, ccache will be used as a default.

.. option:: SYSTEMC

   Deprecated.  Used only if :option:`SYSTEMC_INCLUDE` or
   :option:`SYSTEMC_LIBDIR` is not set.  If set, specifies the directory
   containing the SystemC distribution.  If not specified, it will come
   from a default optionally specified at configure time (before Verilator
   was compiled).

.. option:: SYSTEMC_ARCH

   Deprecated.  Used only if :option:`SYSTEMC_LIBDIR` is not set.
   Specifies the architecture name used by the SystemC kit.  This is the
   part after the dash in the "lib-{...}" directory name created by a
   :command:`make` in the SystemC distribution.  If not set, Verilator will
   try to intuit the proper setting, or use the default optionally
   specified at configure time (before Verilator was compiled).

.. option:: SYSTEMC_CXX_FLAGS

   Specifies additional flags that are required to be passed to GCC when
   building the SystemC model.  System 2.3.0 may need this set to
   "-pthread".

.. option:: SYSTEMC_INCLUDE

   If set, specifies the directory containing the systemc.h header file.
   If not specified, it will come from a default optionally specified at
   configure time (before Verilator was compiled), or computed from
   SYSTEMC/include.

.. option:: SYSTEMC_LIBDIR

   If set, specifies the directory containing the libsystemc.a library.  If
   not specified, it will come from a default optionally specified at
   configure time (before Verilator was compiled), or computed from
   SYSTEMC/lib-SYSTEMC_ARCH.

.. option:: VERILATOR_BIN

   If set, specifies an alternative name of the ``verilator`` binary.  May
   be used for debugging and selecting between multiple operating system
   builds.

.. option:: VERILATOR_COVERAGE_BIN

   If set, specifies an alternative name of the ``verilator_coverage``
   binary.  May be used for debugging and selecting between multiple
   operating system builds.

.. option:: VERILATOR_GDB

   If set, the command to run when using the :vlopt:`--gdb` option, such as
   "ddd".  If not specified, it will use "gdb".

.. option:: VERILATOR_ROOT

   The ``VERILATOR_ROOT`` environment variable is used in several places:

   * At ``./configure`` time: If set, it is embedded into the binary, and
     at runtime if ``VERILATOR_ROOT`` is not set, the embedded value is
     used for the runtime default.

   * When ``verilator`` is run: If ``VERILATOR_ROOT`` is set it will be
     used to find the ``verilator_bin`` executable (this is the actual
     Verilator binary; ``verilator`` is a Perl wrapper). If not set, the
     ``verilator`` script uses other methods to find ``verilator_bin``
     (looking in the same directory and falling back to ``$PATH``).

   * When ``make`` is run on the Makefile generated by ``verilator``: The
     value of ``VERILATOR_ROOT`` (falling back to the value embedded in the
     binary if not set) is used to find the include files
     (``include/verilated.mk``).

   If you are using a pre-compiled Verilator package, you should not need
   to set ``VERILATOR_ROOT`` - the value embedded in the binary should be
   correct.  In fact this option *does not work* with Verilator packages
   that have been installed with ``make install``. If a Verilator package
   has been installed using ``./configure --prefix=/some/path && make
   install`` and then moved to another location, you cannot use
   ``VERILATOR_ROOT`` to point to the new version.

   See :ref:`Installation` for more details.


Make Variables
==============

This section describes the make variables used by Verilator. These may be
set by passing them to make e.g. ``make CXX=my-gcc ...``.

.. option:: AR

   Optionally overrides the default :command:`ar` (archive) binary used by
   the Verilated makefiles. If AR is not set, the version found at
   configure time is used.

.. option:: CXX

   Optionally overrides the default compiler binary used by the Verilated
   makefiles. If CXX is not set, the version found at configure time is
   used.  Note the default flags passed to the compiler are determined at
   configuration time, so changing the CXX compiler version using this
   variable, as opposed to passing it at configuration time, may not give
   desired results.

.. option:: LINK

   Optionally overrides the default linker binary used by the Verilated
   makefiles. If LINK is not set, the version found at configure time is
   used.  Note the default flags passed to the linker are determined at
   configuration time, so changing the LINK version using this variable, as
   opposed to passing it at configuration time, may not give desired
   results.

.. option:: PERL

   Optionally overrides the default :command:`perl` binary used by the
   Verilated makefiles. If PERL is not set, the version found at configure
   time, and compiled into the Verilator binary, is used.

.. option:: PYTHON3

   Optionally overrides the default :command:`python3` binary used by the
   Verilated makefiles. If PYTHON3 is not set, the version found at
   configure time is used.
verilator-5.020/docs/guide/example_sc.rst0000644000175000017500000000346614544475344020335 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

.. _Example SystemC Execution:

Example SystemC Execution
=========================

This is an example similar to the :ref:`Example C++ Execution`, but using
SystemC. We'll also explicitly run make.

.. include:: example_common_install.rst

Now, let's create an example Verilog, and SystemC wrapper file:

.. code-block:: bash

     mkdir test_our_sc
     cd test_our_sc

     cat >our.v <<'EOF'
       module our (clk);
          input clk;  // Clock is required to get initial activation
          always @(posedge clk)
             begin $display("Hello World"); $finish; end
       endmodule
     EOF

     cat >sc_main.cpp <<'EOF'
       #include "Vour.h"
       int sc_main(int argc, char** argv) {
           Verilated::commandArgs(argc, argv);
           sc_clock clk{"clk", 10, SC_NS, 0.5, 3, SC_NS, true};
           Vour* top = new Vour{"top"};
           top->clk(clk);
           while (!Verilated::gotFinish()) { sc_start(1, SC_NS); }
           delete top;
           return 0;
       }
     EOF

Now we run Verilator on our little example:

.. code-block:: bash

     verilator --sc --exe -Wall sc_main.cpp our.v

This example does not use --build, therefore we need to explicitly compile
it:

.. code-block:: bash

     make -j -C obj_dir -f Vour.mk Vour

And now we run it:

.. code-block:: bash

     obj_dir/Vour

And we get, after the SystemC banner, the same output as the C++ example:

.. code-block:: bash

     SystemC 2.3.3-Accellera

     Hello World
     - our.v:4: Verilog $finish

Really, you're better off using a Makefile to run the steps for you so when
your source changes it will automatically run all of the appropriate steps.
For examples that do this see the :file:`examples` directory in the
distribution.
verilator-5.020/docs/guide/conf.py0000644000175000017500000001614514544475344016760 0ustar  carstencarsten# pylint: disable=C0103,C0114,C0116,C0301,E0402,W0622
#
# Configuration file for Verilator's Sphinx documentation builder.
# Copyright 2003-2024 by Wilson Snyder.
# SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0
#
# This file only contains overridden options. For a full list:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
#
# ----------------------------------------------------------------------
# -- Path setup

import os
import re
import sys

sys.path.insert(0, os.path.abspath('./_ext'))

import sphinx_rtd_theme  # pylint: disable=wrong-import-position,


def get_vlt_version():
    filename = "../../Makefile"
    with open(filename, "r", encoding="utf8") as fh:
        for line in fh:
            match = re.search(r"PACKAGE_VERSION *= *([a-z0-9.]+) +([-0-9]+)",
                              line)
            if match:
                return match.group(1), match.group(2)
            match = re.search(r"PACKAGE_VERSION *= *([a-z0-9.]+) +devel", line)
            if match:
                try:
                    data = os.popen('git log -n 1 --pretty=%cs').read()
                except Exception:  # pylint: disable=broad-except
                    data = ""  # fallback, and Sphinx will fill in today's date
                return "Devel " + match.group(1), data
    return "unknown", "unknown"


def setup(app):
    app.add_css_file('css/vlt_sphinx.css')


# ----------------------------------------------------------------------
# -- Project information

project = 'Verilator'
copyright = '2022 by Wilson Snyder, under LGPL-3.0 or Artistic-2.0'
author = 'Wilson Snyder'

# The master toctree document.
master_doc = "index"

version, today_fmt = get_vlt_version()
release = version

rst_prolog = """
.. role:: vlopt(option)
"""

# ----------------------------------------------------------------------
# -- General configuration

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
# To install:
#   sudo install enchant
#   sudo pip3 install sphinx sphinx_rtd_theme breathe sphinxcontrib-spelling
# We keep this list empty for now to avoid needing dependencies
extensions = []
# extensions = ['breathe', 'sphinxcontrib.spelling']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = [
    '_build', 'Thumbs.db', '.DS_Store', 'internals.rst', 'xml.rst', 'gen/ex_*',
    'CONTRIBUTING.rst'
]

# Warn about refs
nitpicky = True
nitpicky_ignore = []

# Number figures for referencing
numfig = True

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = [".rst"]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

# Could use this for internals<->guide references
# intersphinx_mapping = { 'sphinx': ('https://sphinx-doc.org/', None), }

# ----------------------------------------------------------------------
# -- Options for HTML output

# html_baseurl =

html_domain_indices = False

html_logo = "../_static/verilator_192_150_min.png"

html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

html_theme_options = {
    'logo_only': True,
    'style_nav_header_background': "#45acf8",  # Default is #2980B9
    # 'canonical_url':
}

html_context = {
    'display_github': True,
    'github_user': 'verilator',
    'github_repo': 'verilator',
    'github_version': 'master/docs/guide/',
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['../_static']

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False

html_copy_source = False
html_show_sourcelink = False

html_use_index = False

html_favicon = "../_static/verilator_32x32_min.png"

# Custom sidebar templates, maps document names to template names.
# html_sidebars

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# ----------------------------------------------------------------------
# -- Options for Latex output

latex_logo = "../_static/verilator_logo.png"

latex_elements = {
    'extraclassoptions': 'openany,oneside',
    'papersize': 'letterpaper',
    'makeindex': '',
    'printindex': '',
    # 'pointsize': '10pt',
    # 'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
# latex_documents = [
#    (
#        master_doc,
#        "Verilog-to-Routing.tex",
#        "Verilog-to-Routing Documentation",
#        "VTR Developers",
#        "manual",
#    ),
# ]

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

latex_domain_indices = False

# ----------------------------------------------------------------------
# -- Options for manual page output

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
# man_pages = [(master_doc, "verilog-to-routing", "Verilog-to-Routing Documentation", [author], 1)]

# If true, show URL addresses after external links.
# man_show_urls = False

# ----------------------------------------------------------------------
# -- Options for spelling

spelling_word_list_filename = ['spelling.txt']
spelling_ignore_contributor_names = True

# ----------------------------------------------------------------------
# -- Options for doxygen

# if shutil.which("doxygen"):
#    breathe_projects = {
#        "verilated": "../_build/doxygen/verilated/xml",
#    }
#    breathe_default_project = "verilated"
#
#    if not os.environ.get("SKIP_DOXYGEN", None) == "True":
#        for prjname, prjdir in breathe_projects.items():
#            print("Generating doxygen files for {}...".format(prjname))
#            os.makedirs(prjdir, exist_ok=True)
#            cmd = "cd ../_doxygen && doxygen {}.dox".format(prjname)
#            subprocess.call(cmd, shell=True)
#    else:
#        for prjname, prjdir in breathe_projects.items():
#            assert os.path.exists(prjdir) == True, "Regenerate doxygen XML for {}".format(prjname)

breathe_projects = {"verilated": "_build/doxygen/verilated/xml/"}
breathe_default_project = "verilated"
breathe_default_members = 'members'
verilator-5.020/docs/guide/install-cmake.rst0000644000175000017500000000441014544475344020727 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

.. _CMakeInstallation:

******************
CMake Installation
******************

This section discusses how to build and install Verilator using cmake.
Currently cmake is only officially supported for Windows builds (not Linux).

.. _Tools Install:

Quick Install
=============

1. Install Python for your platform from https://www.python.org/downloads/.
2. Install CMake for your platform from https://cmake.org/download/ or build it from source.
3. If the compiler of your choice is MSVC, then install https://visualstudio.microsoft.com/downloads/.
   If the compiler of your choice is Clang, then install https://releases.llvm.org/download.html or build it from source.
4. For flex and bison use https://github.com/lexxmark/winflexbison to build and install.
5. For build on Windows using MSVC set environment variable WIN_FLEX_BISON to install directory.
   For build on Windows/Linux/OS-X using ninja set the environment variable
   FLEX_INCLUDE to the directory containing FlexLexer.h and ensure that flex/bison
   is available within the PATH.

To obtain verilator sources download https://github.com/verilator/verilator/archive/refs/heads/master.zip
or clone https://github.com/verilator/verilator using git :ref:`Obtain Sources`.

To build using MSVC:

::

   cd verilator  # directory containing source files of verilator
   mkdir build
   cmake .. -DCMAKE_BUILD_TYPE=Release --install-prefix $PWD/../install
   cmake --build . --config Release
   cmake --install . --prefix $PWD/../install


To build using ninja:

::

    cd verilator
    mkdir build
    cmake -G Ninja .. -DCMAKE_BUILD_TYPE=Release --install-prefix $PWD/../install -DCMAKE_MAKE_PROGRAM= -DBISON_EXECUTABLE= -DFLEX_EXECUTABLE=
     #execute ninja
    cmake --install . --prefix $PWD/../install


.. _CMake Usage:

Usage
=====

To use Verilator set the environment variable ``VERILATOR_ROOT`` to the
install directory specified in the above build.

Example
=======

::

    cd verilator/examples
    cd cmake_hello_c
    mkdir build
    cd build
    cmake ..  # cmake -G Ninja ..
    cmake --build . --config Release # ninja
    # execute the generated binary
verilator-5.020/docs/guide/figures/0000755000175000017500000000000014544475344017116 5ustar  carstencarstenverilator-5.020/docs/guide/figures/fig_gantt_min.png0000644000175000017500000011210714544475344022433 0ustar  carstencarstenPNG


IHDR  Ä>pi~}").ߟ
މݺt߭n7l<]>Ďg4=P@l93"Ҝ)qByw8R!V;hƯmc>eSc@ BBjmkm3s[c5j?Hd#Ho~	}z"uoN/)!?A[vVvV;3u\dà@
uOV;hƯm0 BBjmkm3s[E8:PmA[m`A[q)ԿE;8v"Bp&83D.(OHHHHHHc!)>6=>Yjk(8a P	
P\7XCy	/:>HpV#5NEpeS=^['mfwcyk-?kOmx3ρ|HCSp^ZySNl0rO	}|nWNv/UB\s7sM/:>Hp^ZySNl08^Ͽr7{M.I䊻n!BKjN迶?~Ax=|>p	y|nyxMb
;~7(	'K/'0rPsG<^{l_&,S7}q|?og*}lt.v"8f}
cp(莵ia u^CGOb
;=)j5Mq7P	eZmP!^/ot ;PILx#yo؉0莶cWu7Fw~OOm_$^0g5P.xğmz)!Gİ>o_'߰x%'۹޺$t-ouyYȤ;_/}
Ѡ:6qǟ0V\7$g2}V\7{\7*Q2~Bz$ Yӯϙ5A1N?ˀzX5u5Gj0\RHHHHHHc!)>6꽄>39NHHHHHHHs\R>Hpf0؉\}` 3`'pAF
}z3i,$?@
Bb%Xk(N` tH8k`
")!Gs`8Q<¢t{Zwmq0^1.gz_[}ji|ȇ꽄>@f~'$(rmJ5]9}a_s7=Ƈ6#YJk'qH^-#|c3zqBvˏ \?cmw*v~Ax=}}cϾ~yV\3\wMyx-rvx >! ixBA_Fqܴ/.tm8IO_
}NkuVC~}gH7BͿ?V6؉WD {"l0,!?Owoq*w|AmjYotڴ
0.	~@4Y@fBLerveXnxo>=_
*D	}" 녾SPI@"׌~>tg؉DcRu7Fw}GќTyۣ;Z?k*ݡ1z4_#Ɨ/:>HrfN~~}x)H	W	IK.[],OPͯrE^Nۮ˗/Ooƹ:oj4iV\7$g|O@4 ^<\F/W$wa'q?@!=oG{3zYig̚ W1Nw}_.7
	P^FB꽅>RϤl>hiOxhhܥP) ;2B#!!!!!!͙B@pAhK;#`'pA g39N@gs	;8v"Bp&83D.>Lpf0؉\}` 3`'pA g39N@gs	;8v"Bp&83D.>Lpf0؉\}` 3`'pA g39N@gs!L!  P}` 3`'pA g39N|Чvrp;ܔ[7Xk.'jbuuKboIyVA.ROqt,1IX\;&V@J٧֮׶'vֵ|AשBZkM<'vn5vOO )!vrcvvL1O]m5TOkS#ѵ.6Ty.O<`ck줟A.RC$busX=(]cdZ2_kDY5]GCk]m4\P۹yNJǷI?5>1xioxߋxmTy{L^o|nrv^Z~է?}lk&1>9)!vrcvvL1O]m5TOkS#ѵ.6Ty.O<`ck줟8MBpLhSo%ܮt_X}oM@
urܘ]n+kSkWk[z
Փh;Z!}ht˵&Uj;7X;A3wYf$zy0HQuKBw[K`ڄ6'caEw!dnI|^/KCQ=2f<5>;uR^j}m
:tz^ׇ9ȍ/p;1IX\;&V@J٧֮׶'vֵ|AשBZkM<'vn5vOfD
	Y_E$~XR/:~9NnL.V7׎Ѓ5F+-Iu-_suj|>?F*E	lxx|{S&H,oΞ`r6cb$eޢ-l!Ϫr!7%^;b"4#%4/DW7"q8<)خ5i,N)]n#mH(5#|
ՓhеK/OY6$VʓiVR1]CmrBȲ]$(vtV(wKĽqBm+|~[-(YB.D\g?Q~Lh۩[q_Pȿ1E@
oGaud#iU1bg^KVl%?g]_{qFrIyt_E	,fF-Bx?XߏͥN"|B0Aq+ANFBwf<>>;󛱾<4nZY#T/xhj?:P:*c13%+^3.կ8_<:vH"l	YQ^
vhN${3$j*x6q̶Nx-Ϛ/>Ve$%?`H߽Rx;q~ʖgYEX<>Ͽkc.O/w?e~㯩T9vuByv߂?sXVNs˱qY~`
 RCXmHZq1eג[x}^ѯ\R};mbuB,م(a=CHB6R:![BBLRCXmHZq1eג[x}^ѯ\R};mbuB,م(:PtZqq"؟1|>eChm++?v!lRLRCrt{e^j&Έ9:>4ǵ{}?c}ʆ6V^3V~:Cb٤(:P˼MNsut}hk`/(
mfuȇIJIQ^0=tH}y:#s_Q)Bh[yXe`z0BB0.R379uF99iS6Ѷc!&Ey
a :'G-`\fnrꌘsCs\;Ͻ~9Fߧlmm5cǮC>$M@
Bz#9oA	\ˇz3'S[YI3\&&7_PF[vVN}Cy
a h_mGF=kf:|-u}i.s}Hk)!NF{Y#_|>veG˾-\@
u}Q{dþ)jֈ2_]`6o>ׇ`z0BBdA5c9X~Mn۲!):P;GF=kf:|-u}i.s}Hk)!NF{Y#_|>veG˾-\@
u}Q{dþ)jֈ2_]`6o>ׇ`z0BBdA5c9X~Mn۲!):P!c\Q{dþ)x
&	_|iˉ9X~.מ2B
*hK>>hpf0؉\B						iBB^
u	;8v"Bp&83D.7	}Ċ				.+)p'`tH>O1no{Y\'T[nodBB!j	~:Po6g@uBuqGwww{l;]E8iyޗCTymqf^1.gz^[}jǶfBB!j	/':|G@B8&4S)Zjg}a_swc:Po6g@uBuq<qG;VJa"a%;uG/9tkws]ru-'Z㋐3~n|BMgRB3X`{e|]LzӽuBݕl֞W֜!?~g=BԬ
-]G"	3-1焌8l?B"nP"`OZd/Dz^ͪH	Py||vj?|M}]sI,B۽_|5aӘJ)o	m>Q6N/>whRH$UH(O_9sCDhN}GJhT_9}+9nmo#FDv1oS+_N=BԜl
}:2MB?%-V)/skͩo'69W8!ܹ6{}"41
7& ;tHB_#`4%kmu_^g}:BDCBRuCƄ	-O
!ZK_H?+[Dc۞ЉͭH	g?͍|yBO#*ÏPwQƫfs@
u}`4%kmu_^g}:BH^u).T&[5Jg?IE}>.["2~%4s(jBr|k*'b=<>.u{Ob[Ǿbncn99.;uCbB?NXF=Ҕu~yɻ1#Џ#`4%kmu_^g}6B/,q;˿1/az2?1d,;B\:PHSFVu#?uBb'ynju%:@5¶/ܾpaBBgdc Ma[]Ynw0tH~5#Ɓ=Rl#pUr/>`~A.Yb$kW/:>HA.Yb$kW/:>HA.Yb$kW/:>HA.Yb$kW/:>HA.Yb$kW/:>HA.Yb$kW/:>HA.Yb$kW/z/O#Z`_\Nθ` P) 
P\3X?yFB_
u}5G8a$ P	
P\3X?yFB_
u}5G8a$ P	
P\3X?yFB_
u}5G8a$ P	
P\3X?yFB_
u}5G8a$ P!9@
9Gxa$ PuGr`'pAF}$$$$$$9S}.mz)qGp$83D.>Lpf0؉\}` 3`'pA g39N@gs	;8v"Bp&83D.>Lpf0؉\}` 3`'pA g39N@gs	;8v"Bp&83D.>Lpf0؉\}` #>Ҝ)>6긣8v"Bp&83D.>Lpf0؉\o,Ibǒ*/IH5KXu{HP*/I\ӷ`k\{*礯9/|ɥ`j@B8Jje<<ך׽	O;IIL~[m4:ڱ(6T6,PW05t H_$YCZ{i|ݫ㐔4*F{izoAlcʲ]uSCe8Jje<<ך׽	O;IIL~[m4:ڱ(6T6,PW|%nnזۇ,s8ߝ6]pax㳔1?\N{mO[v)ԿAF	OM\-u58c|n_$QqĐbT	v,ro>CK]y:Y)$6$o;U箭
WRCT
u58c|n_$QqĐbT	v,ro>CK]` /nKNo]v!8s ߥf6݄뱷+;@s.m^$̷dJR*٫O_:ʄN迶_hnj4҇wcp<5qHiY1zSnv_eBÊN?f3Oc/}[!2_PηR !x
6]<^Bbow}riH_5؊t#qž}'Wm]4}usY"|o"B?"ibm4-qH_HHKֽgNmbҌ}tFMӉ\&UN)F}YKA'ƻ޿۳i~vB4V>|kxjj|ߤe-N5R#bҌ#C~@ϱc/}[!2_PηRX~L]Zo
מUH׎{+E@
ur8Zj,7iY1zSw;24P?3sl,bKߖ}ȇ̗>4-50HJGlւ9pӉH L$/˿ oܦMS8⶷hX]?C}nB<ztp(>=N8Zj,7iY1zSw;24P?3sl,bKߖ}ȇ̗>4-5@Exrw)
+]8g]O^$ruIE:;^ۧ;[=|	^g]mcǸA!=M>L
_nׇo):Zjt]ZbujuvBqHR1IFšugGǛ%&ނƲe1jS#Чn{j.A$T~Jk~mm0~.׾k	kqׯ5k^ڄ[P9X,fC]-p8&-|_f;(fвc^k_j'?E8$%1Cm;xkǢ^ڄ[P9X,fC]-Ё 7	Y*%U^Xk$rNۑXTj_$VL96goTI_s^m:fK]-p-]bSOhޤP83D.4g
M/:gs	;8v"䛅>uD:PX5MKGb$[*reXe4o]2eȼ-e+Ij)ԿM菆8_vXZuxs){mkm]K~/&'ZF΁K+[bln˴_32ާ	iG21ZA
u}n~it=biיΥdUu-k;n/ծ,oOK1oȷ.v|/lR![.lu	uSC>Ƒ{گ3Kk[nZ[}19q2w^]Ycvcߐo]:7_b٤C\fj)yvw{\V-hSq[}Ywq{l;+?u
u?\N387C
oGCVg,fp,5sZ=GsmzGOeSrN^Yu2ic٧(Ĥ%u.[%='p}k|π]p|Sd(0BB#
1fSk:"=HRq0w][h_"iߺ,v*?VIb<\&m,5@/nKNo]v!(s߅fa6%B_[2'[K$Y}aȘwΥ͋VuWIS[*v>}(:~!
e,i-<Ё#
1՗W5kRjGM}z%Fk7ŏWҟBmCUʣ!Y&m,5@5$OIGH/m/BZBTBܭ
j#
TƀǍK
_4Hm-zt'&/]AeBE$/zTZq(擾t#
1߭dLHVL.}>{%Fao7N[pݞ)HsPX6}H[mcQ/.K} bb	fgwY~[F񰾨>$vv>Vl+3V_Ԭڥ}D>jbeC]
OnHڷ.VY*އldSB?&}uÄ~+_?vk*};E@
4ޅ4#
1՗Y\5Z=-F*?wfd#?"iߺ,v*?VIb<\&m,5@5$ŅP~yt뿞N$	7!m2+	˻ȧ;̥22mڄcXEty=gCg+yt?ZEF(zt'w!wh1ɑmzKקfͤnuD>jbs 1ɍ5OeSrN^Yu2ic٧(XyO"fqzrǦT6gQSI	]ڄ\V#&_$r߾HE:;#ul30
.~ކD9eOm\NuL$ܟ#
ǴG,1ߡdubե}$(-FNܵ}F'c-7[i;͗X6)-Y6򺄺Z`֣;?=H ][vq9gܟ#
10=ba>=J֌^'%usm/}#}kYŏnBi;͗X6)-Y6򺄺Z;/,z.tce`/VC
ﻣ?n~it=biיΥdUu-k;n/ծ,oOK1oȷ.v||z'j)ԿMl+$VyMj~k-Ē*6I$Gv$1VY* [L|42/erYJҦZZ?~͛$;2B#!!!!!!͙B@pAhK;#`'pA g39N@gsVOHrc}Sz^5ˉB'43V2O%tjO{A
o1FQ_9jFͱvz?ӯcMMX˨鉎g1_V=ږJio0t HGYq7=O"돎75c-Ʀ':Fמ|Ymh[+utЁ :~5ei;h?Z?:>^{e٣m鯔4^Ͽw=^[~{/g[z~Ixݩvñw鵎{|oVLmWgȇ sK_{
}匘w鳗3j+c15!dLH5#tb.H
-䒀GN85>kށg.8)t=wmW(0BB?M_{
}匘w鳗3j+c15!dLH5#﨓ֻʏ.CQD5=y_mJ%;@s.m2*rj댪O}-:~!јJB?ΨX<*t,v
gF]鳗N'_Q~=J
+pl:ƥ[ABԊQ=
	U$L#$q6q6"_i>mRw[ߏ8(zludÍqžǍK
_4HCkRU,iiBH_
BUWb|[L/ZZX Vbz]鳗Q25s1b+kIUF)Ftľ,Y6Hq,_}XVCѣ;Vxxww{!Q].21]&Q҇aKm?͈+}O~FJ/Wz3MHלzje2"}kd
|;B|h	d,~D^{V!?>/ed)!|uLy˯`[VŮ,|#֮R/(LMW<#tK?ԃP;,_{ zRѿBwY<_O'݄mP;3e&/iTDn=Gchw>PУ;ԇGY!㌊%wk#dPݖ0jl܌Xg/gD(LM!RzW<#ttͩvY&S+G@`(gٹUR:RE!ХMh|g qm.ݑMsa6pZ`1?ȂBz{\goG4qݐUOYGbm/F@TSF-kד_ϡؿ5:=h[xFckz̗fR[ݰ!GftoRSMYGkw}G/
yu! v?jG_).$qЏپX=߿z@یƿs8c_kGڛGQc#_kc6{-:`:@B~*j/'1V7%XW埱Z(,zb/M3c)tY-1_LVZ=0t77B&}5`'pAF}$$$$$$9S}.mz)qGp$83D.>Lpf0؉\}` 9Byj>$*r궦Q~%1VY*XeG'U>*n>JR-/J%Xee,!uSC!O9ujRVߑߋ\'=L_OQp;wL)zZ{:,dmeFlRL
R[02Bw\Ek/ۧ[nx^;=cEud}FHdYӶ2O#C6)j)CBJ;bG|/r\3-~>U/TvotGj1k/#[5F"ȲyIQWL~t?^[>*-~ZcXi!x=v?\\*է?}l1SۍsC>P)ce)nKZr˨=7^̦pGӻat.%mL|OĮ!,;.kKQ^Lsv^KzO[[Bz;=X⺞+_	tHnwFQ_˨=7^̦pGӻat.%mL|OĮ!,;.kKQ^4rڎ&D݉mt.CQD5=y_mb0%SH!ԗιy_>層J	WV&5uBݕBDsU15& 74R>ؒM`fÌeiSϲaZ
qt-S7|AKnwJdcvA.VcɣS\k2j-ͩa#hi7n3Ơ&IZۤ/&e#,c,J1⥠#e	=JB	En#6|V|_<Ľѳ,-Bm>$Q[˽p)_K?̨/^F9|{qOz;wuė21=چ$\	+/Ey
P	mBcOgj'U"ᛄ6>a\9!~-@p@8ȿ_:P?J诿Zs>nKZbaFuF2jͩ'm4-m8:wu/iKeb{"vu
aItD_V^zRѿBw͔~t뿞N$	w忤Ty͇",a=⶷oxw?C}/RI(0ḄT/Ǟ)n~-{aF5/&6V9vOv}qOzᣄ|t.%mL|OĮ!,;.kKQ^46O7QK",P/"zR.!ؔʜЦ($!~EzTy&/\_GztG~'߾ce'xl.6~PHom|{ruCbHO9d*Oujגꋤw\Ek/ۧYDK۽ӫzǔj'k/#[5F"ȲyIQWztQB02]/u֣ONMZ\'=L_Owd~htGj>J)CZk铨oH#BvVid~&E]-g_ee`/VzзR;)d;.wd"I5SB-mFTHpf0؉\\O9d4g
M/%)!pG
;+hgs	;#G	B
;+5pf0؉\N `'pAr ` 3`'pAr>#(AZ`'pAr>CP;#)>783D.Hз>v"Bp&83D.Hgd%}@+83D.HЧ[|hJ`'pAr;%gsV39N@gs	;2B#!!!!!!͙B@pAhK;#`'pA g39N@gsVO̒$Vy,IZ#Uwݎ*R$eʱ9;}V^ȵrNBh[m1\j)ԿIπ$YCZ{i|ݫ㐔4*F{izoAlcʲ]uSCe8Jje<<ך׽	O;IIL~[m4:ڱ(6T6,PW05t H_$YCZ{i|ݫ㐔4*F{izoAlcʲ]u@1ms8ߝ]_Ͽw=^[ӆB}_.gmN'R?8Zjfp-k1ƈ5f+;LIL(!Ũ{sXKߖ}ȇ̗>4-5@
	y>ᄥoN6
'{tπ]zZJ@
ur8fqѲcXcR#˔4*R7>׎Emه||CCy:߲KQ^ؼ;2I!Sw#}Y6/[]Sw]%QNm)է/v'źw1-o"c|>|7>5ѯ7BN迶_h.^!/1״چ
{kK]&-k1_.׽+]/?#\s?цw#6.ڦ_'=bx6pgcyOϱc/}[!2_PηRQb}l߇seS;hW~7?	w'w^o[8:
y@/tyԇ-jCj!x* GldwB}m%S(Ǘ/zDby&o\ĊWu5d-ƒK#ތa9)g-_ʇ=P=IcG~JBp_!lS#tb.IbS/6e	Ɛ;޿۳f0җL9z_w5`dH/d	펲iW3>o	AB?k Wò&4.hY1r
pEmM0.Tdb҄lt=2'CI_~@ϱc/}[!2_PηRQbcPD6DWNwԅڳN%k_~9Pп]y_q_(F@_)i[jB~#r&o>`ۖO|q8B}d3;rɞe{aMx0JBcB}E{۲҇temr;9Bbx^E98r'LI  aDyȴǾIdnmn}9ķd}@No}~qL܏逺{/Z4λ["o|x,Ôr
 R'vm/0+%u5.-k1FE[QJg<XL??P=IrB躳ME{izoAlcʲ]ubz'Sӥc-u5.-k1~V7-_bײ9^^惓KԖ/Xuh\η7͛Xh|.[^rs0\~{izoAlcʲ]ubHHG1qRW3xyhY1z5폯{wFšhtcQb/mB-m,[Yˡ`j@B,Ibǒ*/IH5KXu{HP*/I\ӷ`k\{*礯9/|ɥ-S 8)ԿE;2B#!!!!!!͙B@pAhK;#`'pA g39N@gsfOml+$VyMj~k-Ē*6I$Gv$1VY* [L|42/erYJҦZA
o6F#~9\J^Zu[גɉsR[|2m׹̧){BL.`j@BB߇8_vXZuxs){mkm]K~/&'ZF΁K+[bln˴_K,}Ȗ,y]B]-Ё :qd4R2֪ۺdV_LNܵjW⧥7[i;͗X6)-Y6򺄺ZL}Yws{lׄ˻-;x׸Sa\|ھ?.gznncS۟>9Ǟ|H-Bv#
1fSk:"=HRq0w][h_"iߺ,v*?VIb<\&m,5@-ĒG$wQ||Ŝ#-!=vEܵ5J@
uOl+3V_389O|#IH9Kv=blӣ}}P۩X9'e/:sS6NLR-B!]HwswKq*;JEzIB_db]InyIzx*~;ѯrrtmw?<]^5c!%r_Jmѯ5k;67}>LlcK26^
֜npjK쇉Sv$v'Y8J}Ɯn=öF\Xso]j;*'T2ic٧(/ԶI}:'"0!· X^tH8za\eol}P%,BE6amڐ"~'4^n<* GldwBkBYQi֬3k;෵RA׊e
o}^ָX2fE'WFƄ;IV]yQ~z3VlJgtm)ǹ(s.:Fku{&&"uCIcPb5#mUF)F[ml-~е1ƗA?T9k>{?V<:[m[qK*9J}ƜK]
Y_Xso]j;*'T2ic٧(ǁa	F+oAݝu|,\XU*җk\'8!r'w%`Ӑ,!9X̎/Rпs(uL4VJ?Z>b=Dvױ2/73v}peskK%|4_7bJ5>mӹjی+:9pJ}ƜG־lsaۅB?TOeSrN^Yu2ic٧(#"|W1>ċAwz,ԵmoϻyGw;
m~O2ͷ*!!qQУ;G94P|%a 7
e郑*­>M#7hXL_5\`]Y{ܡ΍ˣϓ@Vܒ؞#bR;7\Bjβ͢OnHڷ.ʏsX2ϪCp>I>Ey
eD*~:<^0λ[B|%>_!!/}oFw8,o
ݯtGŹAe8Rcct=;蹏m(b"ȉ6bmWT^ؾ΋9n_ǡڶk񓊱˴_K,}Ȗ,y]B]-Bz${[>sθ
~?S^-6|}`zݎ9؇4zk*lRm>mbg?:w-7ȶ|Et̹p{:,׶&e2F^PW/f .qCc6F#~9\J^Zu[גɉsR[|2m׹̧){BL.`j@BۄȶBIbפV_7B,Ij*oI|tmJcbu_ʗI#R.u$mj~=W#͋$;2B#!!!!!!͙B@pAhK;#`'pA g39N@gsVOHrc}Sz^5ˉB'43V2O%tjO{A
o1FQ_9jFͱvz?ӯcMMX˨鉎g1_V=ږJio0t HGYq7=O"돎75c-Ʀ':Fמ|Ymh[+utЁ :~5ei;h?Z?:>^{e٣m鯔Am4NخqX|;}{$z7Wj$kOmڮϐ)ԿA1*T11g/g嗩WLǦckN=C2Z>jG<KsO8a)>w{>6O}&_ow]3-o"c|>|7SЧf;B"WH	vWU11>~QX~sR]>h\1̍wr=g]>ҧ3ZOW4
/Ɨ3nؙc`e[Ż_<#t{OԊQ=lmt[CA:pwb%î#I}CClۖ
yԇ-jCXk?_4V>b#1
2OFEBcSAKCrJ:րX{Q}zipr,~+i>~|]kt~inH9#ݿű;N[;ߙQ1ډ$*#^
mڏMd	F+,җ8un,"˝/xW19ŔW9JB4m#+hM	[075kL!}N]祃ǚc%H˛>,PL~R2SBLVئD`ԁ鎺P^{ߘ'Rf_ˁ,!p_(F@i~i:עm>*~ן0.52k]kO^l#ƚՎ/3@Ƶ׋=󌡼H?qϞ=g>z3MǸXZdLH5#AaU>+fZYyAz,Եmoϻ߮?ݡo*wTcMYD_C;cB1)[xF{BԊQ=ైO`$y%)/v:3߃8r'LI(۠qcvPm>)o/"?:w~Eo{VB:>y1
 R'R팎C}3}w!eW3=`nk?5OJ6et>r/soM/B߻aWkbvXs2@3/mKCHB?8@ d=}WzɟO'h8J\b?_i\>TnCMq>hǀ+)!~/7|GxFc?ѶWJ{|/׎)_}qu|s젝k-X{S>2jlzckz̗fR[LROX$*~k=J3VYkcRO,if8e.%KJ1~RSp,4/R\v"dGBBBBBB3ЦBwG39N@gs	;rЧXe#S.V4/5c$*Kz$GGIELV̳cQe6d`j@B_S{PVߑߋ\'=L_OQp;wL)zZ{:,dmeFlRL
RC;.wd"I5SB-mFT,=kV6OYRRPݖ9*3Q{oNMK۽8w{=}:|]K{]s]mCXv].ׄXsig',?		ƧK	L`	5s(ꄸ箭!WRC9*3Q{oNMK۽8w{=}:|]K{]s]mCXv].ׄy9a&&A&)vJw׻;E|Kvꎳ$ʩ-"S?ۗODXW.f[%c|ӗ׽7?}k_-8
:~7|¶oxݸDcU 7.g]sna[^}[z]%|ȹSϲa>NIsË%ڣ~yя|:X|g:>4g\{nYuė21=چ$\	+/Ey
%uG0&&!܁GrQ˫q 	w'w^o[887t}LE`r"X"Ǘ/zK^lnĜW{,䵝ݠ~(ߠf-Y9,o;'rg'tcj-3"3m^Sz|MtQCǠ&IZۤ/&e#,c,J1⥠A`qOP:8}B& S=xb/K#<*".4G	]臐ek<ϥEWi;XҸr?T}pC{$Eo:̩M>G0:E(_~%۷>KGls,Иuė21=چ$\	+/Ey
%>,K0Edj3r.מ7 4tm5N/Iﮯyҡ	Q`v|0BHOkr~@cXY&fҸr?T~}[U{$ϯ2SB`>9[ֳQq|}s~Y׆}Υ_gw%E_ҖDj²r&5@Ǡ˿6JVm<Ǣ(umq{{tv0dk]BS:MiAd^ |פ+@ce%bfJ"ʅ;Y46$=Y9,j;ԧ&Eg>˅KEp!r&6>5>-~vK"<>1S:|]K{]s]mCXv].ׄO74jeޮWQGߊz"8r'LI'۠upiI}TT>“'8E71q?BC߯ƽ:zbl	>83`|)G
}b-Z]@\}$N·*mP\'%k1ŧߝ:dT=]|v]Њ.k~tfkc↝d9,]>Q3LŤ{Jo
nXcEud}FHdYӶ2O#C6)j#^_-/kޞ++&GP|]_+k">+8\g%{}$M7(ߝop;Scڅ~lr_mCZoH#BvVid~&E]-vL~~):5k)iw\Ek/ۧ[nx^;=cEud}FHdYӶ2O#C6)j)ԏ5F\i_k&*kIUJ81VIbJᯇTR	V},rg%*$,m&E]-[?)Ap4/R `'pAF}$$$$$$9S}.mz)qGp$83D.>Lpf0؉\}` 3`'pA g39N@gs	;8v"Bp&83D.>Lpf0؉\}` 3`'pA g39N@gs	;8v"Bp&83D.>Lpf0؉\}` #>Ҝ)>6긣8v"Bp&83D.>Lpf0؉\o?7KiX#*I|$L4IoL$LX){]c]$	$))K_Rat1ZˈO-3;:bf͔m?|ZIt~.K]g*BBm313S1̾j>0s|Vlg[nʖC!;&V.bv]L&eog*BBm313S1̾j>0s|Vlg[nʖC!;&V.bv]L&eog5ߝ=ڮ"_
ms8^Ͽw0к
)scpS۟>9ǟ|H>/=2d?gggcۙ}}af7T\ۅʵ+e1;I.U&Ӥ-M'!?s6S3g6C9m.TX,Ibv24Vm2>Nd')ۋVQDNBǵ{绱.wvHj/FF;%zIԖ_u~XW.f-QO*~ۇ{SЧf;Z'7BN迶vj4&isLkd2u-dڶ&'#pK(dq8&ؘmXusWn/<߱=1~# >7^lV^l]<}
ۄle~
cb9iri,TӶgAb65-Z:Kvp`/b
-h7nMZD!	_;ƽ⋑l
%^bȕm,k[m6Xk?(_4V>b#Z_+C$:>B`@KCL2ۤ-ḱUW+211/rZsy~	m3$3ɛO}-dIz!}P
"wǭ|К5L"e{144T*1^)$AGlEm1X	\|[YcY;;޿+_(җχspſ@k@;_**ٸKq]"Ӯf|.GMږK`zOBe^V)߱>>S~$w>ψ9_ȵ֋ȹ̝COӍNcÊ-?6![cCXyN{\*Y4	eDDUH%/ş5KtG](_c }B?	?	şbot0;P*OZ02f<؏/_kXUmGܷ'eoR_]j]㵄b"٭KbY_NkC'1JŒ0cm}q?<+6[#$FŠ]˵]\1rYRe2iGBw읬R@vt\	1v|sr>7zև/N>r۽aȝ^Xͼ&1+ۄluk;&V.bv]L&,{m|'7	M$r6@-4_?﹈wh/P$޸e̜_vKWA=Hx/-[w껈F☸IO_}B%([᱐v|P
 R,?tu}_qXۦ5"Z\>/CxmbC`|n7M2964?-52|Bs	x}?1,?+3IʖC!;&V.bv]L&eoYɻ\Bz$?+	Ch0:K$V)6>*ϯ.bsk䆃nǗc;DO;գ;įYk->?uŮ^emPZ^17\^G$^	+/Infmu~Ȏ˲$f*Ib[MaZ~~ )ԿF'Gֶu#23S1쾎h>9>+-i3eO()CeR9Y
:PŠ4IIb$U>cXg&U^$V7&U~vXg&I,C.ձuBVRyV<6-/E
م>Z` #>Ҝ)>6긣8v"Bp&83D.>Lpf0؉\owX#*$VIb$U>[XG%Uޚ$V%U>CXIbצ]~Dq%.$u<+WA {_rdg+axGǑAG5لڷKl%ץ,buu<+WA&	9:v#>f_	;:4ǻb_]]ϵ
1P}m#VGi;"
U :dF0CJ%q==㈾:V~mȎ	k:LYyVCcy,zܖIO?KYsyu1w>eкSa\|ھ?.gznjkOmn{!Bo;2G}f?1пfwt)ghFwz81,ԾkcB.F,:PHXi-/>	y>q6zme/'sзGعouB\s+6rdg+axGǑvfxW'B[!;&Tb2Ϊy[<qGe.YI|Jw?$"v]:;ߍuս{=ETk|12_C)b#Z_+Ϥ/X%PR#S7NU^Im/rӲnڊ岷E'TrǺҷh/Կrbt_r 95MGٜ w t=JctU3nlSs&u^g,I5cچ?ϝX۲j+VJ	QF">'-xzEBG}fb&3k,kǗp6q'Tw{%[a"}x3>G{,ZR]Zh₽݅0Bsۅ(=҈wEh.$tbe1mu5c_y>irbt_r`:9A0FSj|?ټG5Pbb#tYϵ
1-~RgamYӖƳhDGDUHS'<]9cY;TNwԅǢA˵U.k_~9PпjieѿP,f6#h*FeK]߻\OėG}o2fΎc%+۠DQ?{8?[]Cة7~b󓊟6_9<7=+A!N]>cmXuC*
`|)g?C\
c1xm/Na)$O:+Q6>ƺڷJnȾxqDǝgf+@?峏xΕZyyK"؜~|u^-_ݮcچPy}LY
U!GB߱2׏Ngm/׭XYm-cua'a?jkb\_}~^M-?B;|z{s%x1=/Ȝ-늳x7ltkcBn
Fw)/}_=F/93Ɍa0KV`xWlB[%z:}:Fૠ@
o*$Vy$ʏH%Iْ*?*I$-I*M6BKm%Ҏ$/v$	cY:O\~Oo~_͋}`'pAF}$$$$$$9S}.mz)qGp$83D.>Lpf0؉\}` &,j$ʑ$gLWX応$V7$U>2I^XPO%InDچ*$Io	B~Qmnob9+ogᨶkp~mzuFc!-_RC2O!ݳ&qy93&3pD5Cud~mzVy&>dc>4)!?ݧY8VG<؜cÙ}8ߡ:26T=mk~}mNO>PYό[Ʊ:*̸fQm.MY:#ɳ64_Z㋵OsOn=r&85}-O[ӉqܵB@>#>3oꨘg3}lr8G]?S7ghrC6V~̏m2>Nd)ۋVaDNBǵ{绱.wvHj/FF;%zIԖ(_w~XW.f[Ew}7?}ku"{+k+-Ak׫Fcb(}Oz//5XY^xDuS91|scwc=T܍1g͆ 18$oc}qNYg5o]]emuˇs1ORm!H/=QnaDJd?wrewoD%|/!CwouVl{#{lm~V/sG"YdSֶ9lx/+?ߝZ?}8G	_/z?2&M숮rz딾\5/=*>G3. ?ֱ8؎D|.l|ny9ykx!6JRG[6ΧkN1R뱇IɶDH[X	O[Mp;#6YcY;JrÊBrm!lh
rK|Y%W1(Qݾ/6붂P%sE|L&ɋ'5~=FXns[Za[]aM*m B6:?Y5	e!D6UHS'<଱_*;BzֵU.k_~9Pп]_`"ѿP,f)!},++֕Z~G
*:8Y"撱Ɋ3:#1dž>5}fu=Vc>
>:&&txdm5ʗhEʏxVD-nj>$T/?	J2K;r 嗕_8qk/Fje.ԵmoϻGFQ[֎IƯ#W_Oe5##zt(A}(BBJp2.۱ƊGhďyԦogsl1@u$ܶ}afc%}`zS~e$n'uB:?Wc
KB6V~̏ijZDdRSJ|o˝?bo0_Il>e8Żl? .-jU/_'#F☸IO߯~}zJPH'/}౐v>ԹnH+K>'bG>J>Rp+9sO}c9qz12Z#cfo->[\GVl>$XCeW7O+[:PK1rd3Yc)3b8G{V{Q7BlrJ,q?BzXj})#cLqY?ݳؓu?:!P+?d+	ԕXyr&jNti-/>	̹տχ;?,'42̓%=g}⺞8_	tH32Z#cfo->S\gpVl>$'vON&TJB69u%}nEy[=qGe.6|J"%;uG/'ѫ>ﺦqnK	SRhaDo:q/DBFh|?Bb]InyIO_B>5:+k+-AcU}o|,/էq:9
X+#7b}Mn[n0Δ#==W\^ݏq;^{ܺ
Y)[/xmmM,oiVie|c3%b74soIY_{QEvTaFvpfp$,pro!POա^H_6g/1wJ
tq
EB߱u.:g#~G?lRB}Fw'Vhͯp_$	=>',Y"^ߍR#/@k9M(i;k_z{6p?JH/	Nb{.P+?);sύSz0EV"6Hw/FlƲv|	goB(gQɌBrmhd[^_
cbم(}_/i'XkWuMX1Xq)-O
E\9wD0.:D 4hdGqԮ
_]Eڐ61{]ס:V~?S/vƳjEd+:eIx#6YcY;TNwԅ+@җk\'8!r'&cEh|sGB7:_:P%zMn1[>hϷJ8kJY*ѝAEN1m8K&{-Ԉ!$Nr 嗕_8qk/F}`e.ԵmoϻoO2ֺSOe5#|4>nZc#zt(>_	tH>BklcXDPVJc!Rc|`dMï2r,sd[brsX1%LԊa4MոG?Gm(1FJB6:V~V	֙eg*gfm˝?bo0_Il>g8Żl({O]lzV>K2';D71q?b󓊟6_{!('\_pH6x,!1uCc/z/Oi-,}4i]/be}ȏe'W$}b>jbM(ϸ_ߖϲ?psy3`TzqmsOCxS=GϋuS3Y^b}{>om޼wW^+?d+	لCgeid>׺\_3<$9$)ͳR.Ӭ?=/E
BR` #>Ҝ)>6긣8v"Bp&83D.>Lpf0؉\}` 3`'pA g39N@gs	;8v"Bp&83D.>Lpf0؉\}` 3?7IENDB`verilator-5.020/docs/guide/exe_verilator.rst0000644000175000017500000022363414544475344021066 0ustar  carstencarsten.. Copyright 2003-2024 by Wilson Snyder.
.. SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

verilator Arguments
===================

The following arguments may be passed to the "verilator" executable.

Summary:

   .. include:: ../_build/gen/args_verilator.rst


.. option:: 

   Specifies the Verilog file containing the top module to be Verilated.

.. option:: 

   Used with :vlopt:`--exe` to specify optional C++ files to be linked in
   with the Verilog code.  The file path should either be absolute, or
   relative to where the make will be executed from, or add to your
   makefile's VPATH the appropriate directory to find the file.

   See also :vlopt:`-CFLAGS` and :vlopt:`-LDFLAGS` options, which are
   useful when the C++ files need special compiler flags.

.. option:: 

   Specifies optional object or library files to be linked with the
   Verilog code, as a shorthand for
   :vlopt:`-LDFLAGS \ <-LDFLAGS>`. The file path should either be
   absolute, or relative to where the make will be executed from, or add
   the appropriate directory to your makefile's VPATH to find the file.

   If any files are specified in this way, Verilator will include a make
   rule that uses these files when linking the module's executable.  This
   generally is only useful when used with the :vlopt:`--exe` option.

.. option:: +1364-1995ext+

.. option:: +1364-2001ext+

.. option:: +1364-2005ext+

.. option:: +1800-2005ext+

.. option:: +1800-2009ext+

.. option:: +1800-2012ext+

.. option:: +1800-2017ext+

   Specifies the language standard to be used with a specific filename
   extension, .

   For compatibility with other simulators, see also the synonyms
   :vlopt:`+verilog1995ext+\`, :vlopt:`+verilog2001ext+\`, and
   :vlopt:`+systemverilogext+\`.

   For any source file, the language specified by these options takes
   precedence over any language specified by the
   :vlopt:`--default-language` or :vlopt:`--language` options.

   These options take effect in the order they are encountered. Thus the
   following would use Verilog 1995 for ``a.v`` and Verilog 2001 for
   ``b.v``:

   .. code-block:: bash

        verilator ... +1364-1995ext+v a.v +1364-2001ext+v b.v

   These options are only recommended for legacy mixed language designs, as
   the preferable option is to edit the code to repair new keywords, or add
   appropriate ```begin_keywords``.

   .. note::

      ```begin_keywords`` is a SystemVerilog construct, which specifies
      *only* the set of keywords to be recognized. This also controls some
      error messages that vary between language standards.  At present,
      Verilator tends to be overly permissive, e.g., it will accept many
      grammar and other semantic extensions which might not be legal when
      set to an older standard.

.. option:: --assert

   Enable all assertions.

.. option:: --autoflush

   After every $display or $fdisplay, flush the output stream.  This
   ensures that messages will appear immediately but may reduce
   performance. For best performance, call :code:`fflush(stdout)`
   occasionally in the C++ main loop.  Defaults to off, which will buffer
   output as provided by the normal C/C++ standard library IO.

.. option:: --bbox-sys

   Black box any unknown $system task or function calls.  System tasks will
   become no-operations, and system functions will be replaced with unsized
   zero.  Arguments to such functions will be parsed, but not otherwise
   checked.  This prevents errors when linting in the presence of
   company-specific PLI calls.

   Using this argument will likely cause incorrect simulation.

.. option:: --bbox-unsup

   Black box some unsupported language features, currently UDP tables, the
   cmos and tran gate primitives, deassign statements, and mixed edge
   errors.  This may enable linting of the rest of the design even when
   unsupported constructs are present.

   Using this argument will likely cause incorrect simulation.

.. option:: --binary

   Create a Verilated simulator binary.  Alias for :vlopt:`--main`
   :vlopt:`--exe` :vlopt:`--build` :vlopt:`--timing`.

   See also :vlopt:`-j`.

.. option:: --build

   After generating the SystemC/C++ code, Verilator will invoke the
   toolchain to build the model library (and executable when :vlopt:`--exe`
   is also used).  Verilator manages the build itself, and for this --build
   requires GNU Make to be available on the platform.

   :vlopt:`--build` cannot be specified when using :vlopt:`-E`,
   :vlopt:`--dpi-hdr-only`, :vlopt:`--lint-only`, or :vlopt:`--xml-only`.

.. option:: --build-dep-bin 

   Rarely needed.  When a dependency (.d) file is created, this filename
   will become a source dependency, such that a change in this binary will
   have ``make`` rebuild the output files.  Defaults to the full path to
   the Verilator binary.

   This option was named `--bin` before version 4.228.

.. option:: --build-jobs []

   Specify the level of parallelism for :vlopt:`--build`. If zero, uses the
   number of threads in the current hardware. Otherwise, the  must
   be a positive integer specifying the maximum number of parallel build
   jobs.

   This forms the :command:`make` option ``-j`` value, unless the
   :option:`MAKEFLAGS` environment variable contains ``-jobserver-auth``,
   in which case Verilator assumes that make's jobserver is being used.

   See also :vlopt:`-j`.

.. option:: --cc

   Specify C++ without SystemC output mode; see also the :vlopt:`--sc`
   option.

.. option:: -CFLAGS 

   Add specified C compiler argument to the generated makefiles. For
   multiple flags, either pass them as a single argument with space
   separators quoted in the shell (:command:`-CFLAGS "-a -b"`), or use
   multiple -CFLAGS options (:command:`-CFLAGS -a -CFLAGS -b`).

   When make is run on the generated makefile, these will be passed to the
   C++ compiler (g++/clang++/msvc++).

.. option:: --clk 

   With :vlopt:`--clk`, the specified signal is marked as a clock signal.

   The provided signal name is specified using a RTL hierarchy path. For
   example, v.foo.bar.  If the signal is the input to top-module, then
   directly provide the signal name. Alternatively, use a
   :option:`/*verilator&32;clocker*/` metacomment in RTL file to mark the
   signal directly.

   If clock signals are assigned to vectors and later used as individual
   bits, Verilator will attempt to decompose the vector and connect the
   single-bit clock signals.

   In versions before 5.000, the clocker attribute is useful in cases where
   Verilator does not properly distinguish clock signals from other data
   signals. Using clocker will cause the signal indicated to be considered a
   clock, and remove it from the combinatorial logic reevaluation checking
   code. This may greatly improve performance.

.. option:: --no-clk 

   Prevent the specified signal from being marked as a clock. See
   :vlopt:`--clk`.

.. option:: --compiler 

   Enables workarounds for the specified C++ compiler (list below).
   This does not change any performance tuning options, but it may
   in the future.

   clang
     Tune for clang.  This may reduce execution speed as it enables several
     workarounds to avoid silly hard-coded limits in clang.  This includes
     breaking deep structures as for msvc, as described below.

   gcc
     Tune for GNU C++, although generated code should work on almost any
     compliant C++ compiler.  Currently, the default.

   msvc
     Tune for Microsoft Visual C++.  This may reduce execution speed as it
     enables several workarounds to avoid silly hard-coded limits in
     MSVC++.  This includes breaking deeply nested parenthesized
     expressions into sub-expressions to avoid error C1009, and breaking
     deep blocks into functions to avoid error C1061.

.. option:: --converge-limit 

   Rarely needed.  Specifies the maximum number of runtime iterations
   before creating a model failed to converge error.  Defaults to 100.

.. option:: --coverage

   Enables all forms of coverage, an alias for :vlopt:`--coverage-line`
   :vlopt:`--coverage-toggle` :vlopt:`--coverage-user`.

.. option:: --coverage-line

   Enables basic block line coverage analysis. See :ref:`Line Coverage`.

.. option:: --coverage-max-width 

   Rarely needed.  Specify the maximum bit width of a signal
   subject to toggle coverage.  Defaults to 256, as covering large vectors
   may greatly slow coverage simulations.

.. option:: --coverage-toggle

   Enables adding signal toggle coverage.  See :ref:`Toggle Coverage`.

.. option:: --coverage-underscore

   Enable coverage of signals that start with an underscore. Normally,
   these signals are not covered.  See also :vlopt:`--trace-underscore`
   option.

.. option:: --coverage-user

   Enables adding user-inserted functional coverage.  See :ref:`User Coverage`.

.. option:: -D=

   Defines the given preprocessor symbol.  Similar to
   :vlopt:`+define <+define+>`, but does not allow multiple
   definitions with a single option using plus signs. "+define" is relatively
   standard across Verilog tools, while "-D" is similar to
   :command:`gcc -D`.

.. option:: --debug

   Run under debug.

   * Select the debug executable of Verilator (if available).  This
     generally is a less-optimized binary with symbols present (so GDB can be used on it).
   * Enable debugging messages (equivalent to :vlopt:`--debugi 3 <--debugi>`).
   * Enable internal assertions (equivalent to :vlopt:`--debug-check`).
   * Enable intermediate form dump files (equivalent to
     :vlopt:`--dumpi-tree 3 <--dumpi-tree>`).
   * Leak to make node numbers unique (equivalent to
     :vlopt:`--debug-leak <--no-debug-leak>`.
   * Call abort() instead of exit() if there are any errors (so GDB can see
     the program state).

.. option:: --debug-check

   Rarely needed.  Enable internal debugging assertion checks, without
   changing debug verbosity.  Enabled automatically with :vlopt:`--debug`
   option.

.. option:: --no-debug-leak

   In :vlopt:`--debug` mode, by default, Verilator intentionally leaks
   AstNode instances instead of freeing them, so that each node pointer is
   unique in the resulting tree files and dot files.

   This option disables the leak. This may avoid out-of-memory errors when
   Verilating large models in :vlopt:`--debug` mode.

   Outside of :vlopt:`--debug` mode, AstNode instances should never be
   leaked, and this option has no effect.

.. option:: --debugi 

   Rarely needed - for developer use.  Set the internal debugging level
   globally to the specified debug level (1-10). Higher levels produce more
   detailed messages.

.. option:: --debugi- 

   Rarely needed - for developer use.  Set the specified Verilator source
   file to the specified level (e.g.,
   :vlopt:`--debugi-V3Width 9 <--debugi>`). Higher levels produce more
   detailed messages.  See :vlopt:`--debug` for other implications of
   enabling debug.

.. option:: --no-decoration

   When creating output Verilated code, minimize comments, white space,
   symbol names, and other decorative items, at the cost of reduced
   readability. This may assist C++ compile times. This will not typically
   change the ultimate model's performance, but may in some cases.

.. option:: --default-language 

   Select the language used by default when first processing each
   Verilog file.  The language value must be "VAMS", "1364-1995",
   "1364-2001", "1364-2001-noconfig", "1364-2005", "1800-2005",
   "1800-2009", "1800-2012", "1800-2017", or "1800+VAMS".

   Any language associated with a particular file extension (see the
   various +*\ ext+ options) will be used in preference to the
   language specified by :vlopt:`--default-language`.

   The :vlopt:`--default-language` is only recommended for legacy code
   using the same language in all source files, as the preferable option is
   to edit the code to repair new keywords, or add appropriate
   :code:`\`begin_keywords`. For legacy mixed-language designs, the various
   ``+ext+`` options should be used.

   If no language is specified, either by this option or ``+ext+``
   options, then the latest SystemVerilog language (IEEE 1800-2017) is
   used.

.. option:: +define+=

.. option:: +define+=[+=][...]

   Defines the given preprocessor symbol, or multiple symbols if separated
   by plus signs.  Similar to :vlopt:`-D <-D>`; +define is relatively
   standard across Verilog tools while :vlopt:`-D <-D>` is similar to
   :command:`gcc -D`.

.. option:: --dpi-hdr-only

   Only generate the DPI header file.  This option does not affect on the
   name or location of the emitted DPI header file, it is output in
   :vlopt:`--Mdir` as it would be without this option.

.. option:: --dump-defines

   With :vlopt:`-E`, suppress normal output, and instead print a list of
   all defines existing at the end of pre-processing the input
   files. Similar to GCC "-dM" option. This also gives you a way of finding
   out what is predefined in Verilator using the command:

   .. code-block:: bash

       touch foo.v ; verilator -E --dump-defines foo.v

.. option:: --dump-dfg

   Rarely needed.  Enable dumping DfgGraph .dot debug files with dumping
   level 3.

.. option:: --dump-graph

   Rarely needed.  Enable dumping V3Graph .dot debug files with dumping
   level 3. Before Verilator 4.228, :vlopt:`--dump-tree` used
   to include this option.

.. option:: --dump-tree

   Rarely needed.  Enable dumping Ast .tree debug files with dumping level 3,
   which dumps the standard critical stages.  For details on the format, see
   the Verilator Internals manual.  :vlopt:`--dump-tree` is enabled
   automatically with :vlopt:`--debug`, so
   :vlopt:`--debug --no-dump-tree <--dump-tree>` may be useful if the dump
   files are large and not desired.

.. option:: --dump-tree-dot

   Rarely needed.  Enable dumping Ast .tree.dot debug files in Graphviz
   Dot format. This option implies :vlopt:`--dump-tree`, unless
   :vlopt:`--dumpi-tree` was passed explicitly.

.. option:: --dump-tree-addrids

   Rarely needed - for developer use.  Replace AST node addresses with
   short identifiers in tree dumps to enhance readability.  Each unique
   pointer value is mapped to a unique identifier, but note that this is
   not necessarily unique per node instance as an address might get reused
   by a newly allocated node after a node with the same address has been
   dumped and then freed.

.. option:: --dump-

   Rarely needed - for developer use. Enable all dumping in the given
   source file at level 3.

.. option:: --dumpi-dfg 

   Rarely needed - for developer use.  Set the internal DfgGraph dumping level
   globally to the specified value.

.. option:: --dumpi-graph 

   Rarely needed - for developer use.  Set internal V3Graph dumping level
   globally to the specified value.

.. option:: --dumpi-tree 

   Rarely needed - for developer use.  Set internal Ast dumping level
   globally to the specified value.

.. option:: --dumpi- 

   Rarely needed - for developer use. Set the dumping level in the
   specified Verilator source file to the specified value (e.g.,
   `--dumpi-V3Order 9`).  Level 0 disables dumps and is equivalent to
   `--no-dump-`.  Level 9 enables the dumping of everything.

.. option:: -E

   Preprocess the source code, but do not compile, similar to C++
   preprocessing using :command:`gcc -E`.  Output is written to standard
   out.  Beware of enabling debugging messages, as they will also go to
   standard out. See :vlopt:`--no-std`, which is implied by this.

   See also :vlopt:`--dump-defines`, :vlopt:`-P`, and
   :vlopt:`--pp-comments` options.

.. option:: --error-limit 

   After this number of errors are encountered during Verilator run, exit.
   Warnings are not counted in this limit.  Defaults to 50.

   It does not affect simulation runtime errors, for those, see
   :vlopt:`+verilator+error+limit+\`.

.. option:: --exe

   Generate an executable.  You will also need to pass additional .cpp
   files on the command line that implement the main loop for your
   simulation.

.. option:: --expand-limit 

   Rarely needed.  Fine-tune optimizations to set the maximum size of an
   expression in 32-bit words to expand into separate word-based
   statements.

.. option:: -F 

   Read the specified file, and act as if all text inside it was specified
   as command line arguments.  Any relative paths are relative to the
   directory containing the specified file.  See also :vlopt:`-f`
   option. Note :option:`-F` is relatively standard across Verilog tools.

.. option:: -f 

   Read the specified file, and act as if all text inside it was specified
   as command line arguments.  Any relative paths are relative to the
   current directory.  See also :vlopt:`-F` option. Note :option:`-f` is
   relatively standard across Verilog tools.

   The file may contain :code:`//` comments which are ignored until the end of
   the line.  It may also contain :code:`/* .. */` comments which are
   ignored, be cautious that wildcards are not handled in -f files, and
   that :code:`directory/*` is the beginning of a comment, not a wildcard.
   Any :code:`$VAR`, :code:`$(VAR)`, or :code:`${VAR}` will be replaced
   with the specified environment variable.

.. option:: -FI 

   Force include of the specified C++ header file.  All generated C++ files
   will insert a #include of the specified file before any other
   includes. The specified file might be used to contain define prototypes
   of custom :code:`VL_VPRINTF` functions, and may need to include
   :file:`verilatedos.h` as this file is included before any other standard
   includes.

.. option:: --flatten

   Force flattening of the design's hierarchy, with all modules, tasks, and
   functions inlined. Typically used with :vlopt:`--xml-only`.
   Flattening large designs may require significant CPU time, memory and
   storage.

.. option:: -fno-acyc-simp

.. option:: -fno-assemble

.. option:: -fno-case

.. option:: -fno-combine

.. option:: -fno-const

.. options: -fno-const-before-dfg

   Do not apply any global expression folding prior to the DFG pass. This
   option is solely for the purpose of DFG testing and should not be used
   otherwise.

.. option:: -fno-const-bit-op-tree

.. option:: -fno-dedup

.. option:: -fno-dfg

   Disable all use of the DFG-based combinational logic optimizer.
   Alias for :vlopt:`-fno-dfg-pre-inline` and :vlopt:`-fno-dfg-post-inline`.

.. option:: -fno-dfg-peephole

   Disable the DFG peephole optimizer.

.. option:: -fno-dfg-peephole-

   Disable individual DFG peephole optimizer pattern.

.. option:: -fno-dfg-pre-inline

   Do not apply the DFG optimizer before inlining.

.. option:: -fno-dfg-post-inline

   Do not apply the DFG optimizer after inlining.

.. option:: -fno-expand

.. option:: -fno-gate

.. option:: -fno-inline

.. option:: -fno-life

.. option:: -fno-life-post

.. option:: -fno-localize

.. option:: -fno-merge-cond

.. option:: -fno-merge-cond-motion

.. option:: -fno-merge-const-pool

.. option:: -fno-reloop

.. option:: -fno-reorder

.. option:: -fno-split

.. option:: -fno-subst

.. option:: -fno-subst-const

.. option:: -fno-table

   Rarely needed. Disables one of the internal optimization steps. These
   are typically used only when recommended by a maintainer to help debug
   or work around an issue.

.. option:: -future0