Compare commits

..
163 Commits
Author SHA1 Message Date
Wilson Snyder dfcd412e5f Version bump 2019-10-06 09:40:36 -04:00
Wilson Snyder 307549e8a6 Internals: Fix some cppcheck warnings. 2019-10-06 08:20:02 -04:00
Wilson Snyder 09b79a731a Fix more output spacing issues. 2019-10-05 21:52:33 -04:00
Wilson Snyder 4544a2fd99 Fix extra declaration of trace() in submodules. 2019-10-05 20:16:33 -04:00
Wilson Snyder e09c918198 Fix indentation broke in 977a767477. 2019-10-05 18:00:45 -04:00
Wilson Snyder 9bf6135f6d Remove some output tabs. 2019-10-05 17:35:08 -04:00
Wilson Snyder d472ef63e9 Internals: Cleanup some misnamed classes. No functional change. 2019-10-05 08:17:21 -04:00
Wilson Snyder f1c04b5d25 Fix extra space in mtask comment. No functional change. 2019-10-04 22:54:57 -04:00
Wilson Snyder 1cf29c4d20 Fix truncation of comments, broke in f133c4d0b3. 2019-10-04 22:54:17 -04:00
Maarten De Braekeleer 977a767477 Avoid tabs in C output.
Signed-off-by: Wilson Snyder <[email protected]>
2019-10-04 21:10:53 -04:00
Wilson Snyder 771a301f66 Commentary: Remove newlines, upsets some patches. No functional change. 2019-10-04 20:17:11 -04:00
Wilson Snyder a9954a71c3 Fix case statements with strings, bug1536. 2019-10-04 19:13:39 -04:00
Wilson Snyder 967dc24fda Commentary 2019-10-04 17:42:34 -04:00
Wilson Snyder e1e45cf13c Internals: Move option checks to notify(). 2019-10-03 22:18:29 -04:00
Wilson Snyder bd89c71694 Internals: Refactor to avoid V3Global requirements in V3String. No functional change intended. 2019-10-02 21:38:16 -04:00
Stefan Wallentowitz 633131b984 Return vpiModule when it is the scope.
Return the vpiModule when it is searched for by name and not the vpiScope,
now that we actually have it (one step further to supporting vpiModule in
complete).

Signed-off-by: Stefan Wallentowitz <[email protected]>
Signed-off-by: Wilson Snyder <[email protected]>
2019-10-02 18:47:12 -04:00
Wilson Snyder 99db18b6c3 Commentary 2019-10-02 18:47:06 -04:00
Todd Strader 961a8e190f Internals: Remove rogue character. 2019-10-02 08:52:26 -04:00
Stefan Wallentowitz 045ff25f80 Support vpiModule, bug1469.
Add very basic support for vpiModule. Basically it allows to traverse
the module tree to find a variable etc. It does not support more than
vpi_iterate and vpi_scan for vpiModule along basic operations like
vpi_get_str on vpiModule.

The support is added non-intrusively to non-VPI verilator runs. It
essentially:

 - Tracks the creation of cell instances and keeps them alive until
   the emit phase. They are there converted to scopes if modules.

 - Emits empty (don't add anything during construction)
   VerilatedScopes for all inlined modules, only for those inlined
   modules that are on the hierarchical path to public variables.

 - Adds VerilatedHierarchy as abstraction to structure of the
   scopes. It is only created for VPI designs. It allows to traverse
   the hierarchy from the top (NULL).

Signed-off-by: Stefan Wallentowitz <[email protected]>
Signed-off-by: Wilson Snyder <[email protected]>
2019-10-01 21:57:45 -04:00
Wilson Snyder 66209d1114 Tests: Less verbose status. 2019-10-01 21:32:38 -04:00
Todd Strader 3f1fe2d18a Internals: Travis CI environment. 2019-10-01 06:05:11 -04:00
Wilson Snyder 8b6fb26272 Return good exit status on --help. 2019-09-30 23:15:10 -04:00
Wilson Snyder 881362bb04 Fix clang compile warnings. 2019-09-30 21:55:31 -04:00
Wilson Snyder 239ef1ae6d Fix misc bad-syntax crashes, bug1533. 2019-09-30 20:00:30 -04:00
Wilson Snyder 9eaec3b5c1 Fix misc bad-syntax crashes, bug1530. 2019-09-30 19:48:01 -04:00
Wilson Snyder dd4aa948ae Tests: Have driver report ETA. 2019-09-30 19:22:36 -04:00
Wilson Snyder 12fa085b26 Fix misc bad-syntax crashes, bug1529. 2019-09-30 19:22:14 -04:00
Wilson Snyder 9d6b0d7dd6 Tests: Fix broken contributors check. 2019-09-30 18:56:04 -04:00
Wilson Snyder a1405dac8e Fix misc bad-syntax crashes, bug1532. 2019-09-30 18:50:27 -04:00
Todd Strader cb115e1a15 Commentary 2019-09-30 09:33:17 -04:00
Wilson Snyder 1c7eb89df5 Commentary: Update contributing indentation. 2019-09-29 17:11:13 -04:00
Wilson Snyder 6e91f82a7d Commentary: Fix logo rendering 2019-09-29 17:09:03 -04:00
Wilson Snyder 17123cd0e0 Add contributing document. Convert internals to asciidoc format. Part of last commit. 2019-09-29 17:05:13 -04:00
Wilson Snyder 3f0c5b7550 WIP 2019-09-29 17:03:07 -04:00
Wilson Snyder f6e0e9adec Internals: Use SHA256 instead of insecure SHA1. 2019-09-28 13:32:28 -04:00
Wilson Snyder dea1531f40 Commentary 2019-09-28 11:38:23 -04:00
Wilson Snyder edcfaa888d Commentary 2019-09-28 11:13:30 -04:00
Todd Strader 28b9db1903 Add AstVFile and AstTextBlock, towards bug1490. 2019-09-27 04:24:38 -04:00
Todd Strader 9e64be71a7 Add XSim user run flags 2019-09-27 01:12:53 -04:00
Stefan Wallentowitz 99a8845a96 Fix VerilatedVpioVar vpiMemory/vpiReg accessor, bug1528.
Signed-off-by: Wilson Snyder <[email protected]>
2019-09-27 00:01:09 -04:00
Wilson Snyder be4692772c Ignore MCD fopenw with --bbox-unsup. 2019-09-26 23:37:22 -04:00
Wilson Snyder 4f315d9078 Fix ugly error on interface misuse, bug1525. 2019-09-25 21:53:01 -04:00
Wilson Snyder f133c4d0b3 Fix mis-indenting AstComments with C++ symbols. 2019-09-24 19:07:22 -04:00
Wilson Snyder 8490046028 Internals: AstComment optional suppression of at. No functional change intended. 2019-09-23 18:44:45 -04:00
Lukasz Dalek d6ac351dcb Add --public-flat-rw switch, bug1511.
This switch exposes VARs, PORTs and WIREs to C++ code. It must be use
with care as it has a significant performance impact and may result in
mis-simulation of generated clocks. Anyhow, it is prefered over
--public and useful for VPI.

Signed-off-by: Lukasz Dalek <[email protected]>
Signed-off-by: Stefan Wallentowitz <[email protected]>
Signed-off-by: Wilson Snyder <[email protected]>
2019-09-23 07:56:07 -04:00
Stefan Wallentowitz 502bd6cbd6 Tests: Set VM_PREFIX from test script.
Signed-off-by: Wilson Snyder <[email protected]>
2019-09-21 08:26:34 -04:00
Philipp Wagner d7b6b53c4d Make callCbs() public.
VerilatedVpi::callCbs() can be used by the user to signal
simulation-related callbacks, e.g.
VerilatedVpi::callCbs(cbStartOfSimulation).

The information if any callbacks have been called may be important to
drive an evaluation until no further changes are observed.

Signed-off-by: Lukasz Dalek <[email protected]>
Signed-off-by: Philipp Wagner <[email protected]>
Signed-off-by: Stefan Wallentowitz <[email protected]>
Signed-off-by: Wilson Snyder <[email protected]>
2019-09-21 07:43:20 -04:00
Stefan Wallentowitz 96725b3431 Tests: To allow reuse of cpp files, allow to set the PLI filename.
Signed-off-by: Wilson Snyder <[email protected]>
2019-09-19 18:46:45 -04:00
Stefan Wallentowitz 8686ed9b00 Fix vpiType accessor, bug1510.
Signed-off-by: Wilson Snyder <[email protected]>
2019-09-18 12:24:19 -04:00
Stefan Wallentowitz 32e1207782 Fix vpiType accessor, bug1509.
Signed-off-by: Wilson Snyder <[email protected]>
2019-09-18 07:22:59 -04:00
Wilson Snyder 900115bb2d Fix false warning on backward indexing, bug1507. 2019-09-17 15:17:23 -04:00
Wilson Snyder 3469c78153 Fix bad module name. 2019-09-16 21:09:18 -04:00
Wilson Snyder baa634343b Fix config_rev revision detection on old versions. 2019-09-13 07:20:26 -04:00
Wilson Snyder 1471f5691a Fix error on multidimensional cells, bug1505. 2019-09-12 19:06:26 -04:00
Wilson Snyder e556269692 Commentary - Spelling fixes 2019-09-12 07:22:22 -04:00
Todd Strader d1af69f91d Produce man files with 'make all' 2019-09-11 10:01:18 -04:00
Wilson Snyder fa904f386c Commentary - Spelling fixes 2019-09-09 07:50:21 -04:00
Todd Strader a4daae66de -LDLIBS isn't an option 2019-09-06 13:04:47 -04:00
Todd Strader c813026566 Make Syms file honor --output-split-cfuncs, bug1499. 2019-09-04 06:15:41 -04:00
Wilson Snyder 314cd92129 Support $fseek, $ftell, $frewind, bug1496. 2019-09-03 21:28:15 -04:00
Wilson Snyder 3bc260c55d Fix make test with no VERILATOR_ROOT, bug1494. 2019-09-01 11:15:42 -04:00
Wilson Snyder 4c0f95af10 devel release 2019-08-29 19:12:47 -04:00
Wilson Snyder 35fe205fd6 Version bump 2019-08-29 18:58:38 -04:00
Todd Strader 70cf2582d6 Add XSim support to driver.pl, bug1493. 2019-08-29 17:00:49 -04:00
Todd Strader ec620387af Add --dpi-hdr-only, bug1491. 2019-08-27 21:36:59 -04:00
Wilson Snyder e1e4bde125 Remove old V3ClkGater code 2019-08-27 17:51:06 -04:00
Todd Strader b947391662 Retain widthSized when simulating 2019-08-12 15:38:58 -04:00
Wilson Snyder edc0f442e4 Tests: Add tests for bug1487. 2019-08-09 05:45:44 -04:00
Wilson Snyder 562b9551bf Internals: Remove some unused arguments. No functional change intended. 2019-08-09 04:12:49 -04:00
Wilson Snyder f74af949da Remove trailing spaces. 2019-08-08 17:53:49 -04:00
Wilson Snyder 81e806e895 Fix elaboration time errors, bug1429. 2019-08-04 22:34:54 -04:00
Wilson Snyder 7d4958264a Support arbitrary-argument $warning/$info etc 2019-08-04 21:50:08 -04:00
Wilson Snyder 88b87429dc Tests: Add elaboration info test. 2019-08-04 21:31:06 -04:00
Wilson Snyder 429f463032 Don't check SYSTEMC environment, for part of CMake support, bug1363. 2019-08-04 20:21:58 -04:00
Wilson Snyder af4a39603c Makefile: Run hello world before other examples. 2019-08-04 20:20:29 -04:00
Wilson Snyder a13d230d8c Tests: Less verbosity 2019-08-04 15:04:34 -04:00
Wilson Snyder b7bd5956ea Concats should be unsigned 2019-08-04 14:48:17 -04:00
Wilson Snyder 1a36e05cc6 Fix core dump on v3Number replace'ed assertions. 2019-08-04 14:14:28 -04:00
Wilson Snyder 71265a8ec9 Internals: Rename unsized functions. No functional change. 2019-08-04 12:39:35 -04:00
Wilson Snyder 3a720204c2 Internals: Remove m_logicMap as m_detailedMap covers it. No functional change intended. 2019-08-04 08:16:24 -04:00
Wilson Snyder a95f58749f Fix internal error on gate optimization of assign, bug1475. 2019-08-03 21:49:39 -04:00
Wilson Snyder 9e58ede480 Internals: Rename V3Hashed functions for future commit. No functional change. 2019-08-03 19:05:59 -04:00
Wilson Snyder cf2ac30f66 Fix date. 2019-08-02 21:39:32 -04:00
Wilson Snyder 68b22a4a3d Tests: Summarize any skips. 2019-07-30 22:20:37 -04:00
Wilson Snyder 875dc9a27e --debug doesn't take an arg 2019-07-30 18:40:38 -04:00
Maarten De Braekeleer 1332446f2a Spelling fixes.
Signed-off-by: Wilson Snyder <[email protected]>
2019-07-30 18:27:36 -04:00
Wilson Snyder 6b798830c9 Fix spacing 2019-07-29 21:07:37 -04:00
Wilson Snyder ffa23b59b8 Tests: Add iff test, bug1482. 2019-07-26 19:31:02 -04:00
Maarten De Braekeleer 7d27461054 Spelling fixes.
Signed-off-by: Wilson Snyder <[email protected]>
2019-07-26 12:58:13 -04:00
Maarten De Braekeleer b3f318d8ab Add contributor certification. 2019-07-26 12:57:42 -04:00
Todd Strader 4a14788c9b When showing an error, show the instance location 2019-07-26 12:52:38 -04:00
Wilson Snyder 5560da2934 Commentary 2019-07-26 06:24:26 -04:00
Todd Strader 43ce048f9e Add rr support 2019-07-25 21:34:09 -04:00
Todd Strader b045111a67 Refactor SimulateVisitor to use AstConst 2019-07-23 13:58:17 -04:00
Todd Strader 654571bd1c V3Number cleanup 2019-07-22 15:07:08 -04:00
Todd Strader a3fd105acb Add more Travis coverage 2019-07-18 05:31:02 -04:00
Wilson Snyder 97561bf064 When showing an error, show source code. 2019-07-14 21:42:03 -04:00
Wilson Snyder a4820fc700 Misc minor error cleanups from show-source branch. 2019-07-14 20:59:56 -04:00
Wilson Snyder ee469eedaf Fix some errors reporting wrong objects. 2019-07-14 15:06:49 -04:00
Wilson Snyder a49d819437 Tests: Default test_regress to quiet 2019-07-14 15:04:19 -04:00
Wilson Snyder cbb9288cb1 Fix some errors reporting wrong objects. 2019-07-14 12:21:39 -04:00
Wilson Snyder 173efbc829 Offer suggestions on bad identifier errors. 2019-07-14 10:08:53 -04:00
Wilson Snyder 0fef3b02ec Fix some parse tokens having wrong fileline. 2019-07-13 12:01:26 -04:00
Wilson Snyder d1ee6689c4 Internals: Make V3LanguageWords a singleton. 2019-07-13 08:57:42 -04:00
Wilson Snyder b3eab9d78a Tests: Move t_math_synmul to extended tests. 2019-07-12 19:35:28 -04:00
Wilson Snyder defd05bdd7 Tests: Fix driver checking threads/gcc for extended tests. 2019-07-12 19:35:10 -04:00
Wilson Snyder a7e5cccf33 In errors, single quote signals and other from-user data. 2019-07-11 22:36:32 -04:00
Wilson Snyder 0f857ce423 In errors, single quote signals and other from-user data. 2019-07-11 22:09:30 -04:00
Wilson Snyder 83cf1882de Quote reserved word messages, and related internal cleanups. 2019-07-11 20:49:35 -04:00
Wilson Snyder e17543d6d8 Tests: Fill in some missing error coverage holes. 2019-07-11 20:18:36 -04:00
Wilson Snyder dacf45fea9 Fix error message continuations to avoid linenumber repetition 2019-07-11 19:15:40 -04:00
Wilson Snyder 13a20c5ee9 Internals: Fix inserted tabs. 2019-07-11 07:05:33 -04:00
Wilson Snyder 58dfe9d071 Internals: Detab and fix spacing style issues. No functional change.
When diff, recommend using "git diff --ignore-all-space"
When merging, recommend using "git merge -Xignore-all-space"
2019-07-11 06:57:49 -04:00
Wilson Snyder 6c5cc885a6 Internals: Cleanup FileLine constructors. No functional change intended. 2019-07-10 22:04:58 -04:00
Sebastien Van Cauwenberghe 2c44ab61ac Fix GDB returning wrong error code on Fedora 30
Signed-off-by: Wilson Snyder <[email protected]>
2019-07-10 06:47:20 -04:00
Sebastien Van Cauwenberghe 0847ea57ae Docs: Add name to contributors
Signed-off-by: Wilson Snyder <[email protected]>
2019-07-10 06:46:28 -04:00
Wilson Snyder 9af84c71f5 Internals: More UASSERT_OBJ conversions. No functional change intended. 2019-07-07 09:01:36 -04:00
Wilson Snyder 4ce77d3e68 Header mentions public use. 2019-07-07 09:00:57 -04:00
Philipp Wagner 3c67791624 docs: Document parse-order-dependency for config files, bug1474
Signed-off-by: Wilson Snyder <[email protected]>
2019-07-06 18:09:23 -04:00
Philipp Wagner a281c00752 docs: Contributor signoff
Signed-off-by: Wilson Snyder <[email protected]>
2019-07-06 18:08:22 -04:00
Wilson Snyder 2ca418288d Fix enum values not being sized based on parent, bug1442. 2019-07-06 16:26:44 -04:00
Wilson Snyder bea34d0ced Internals: Misc enum cleanups. No functional change. 2019-07-06 15:50:25 -04:00
Wilson Snyder a5f2ce0dad Tests: Disable t_leak on Travis-CI. 2019-07-06 13:47:17 -04:00
Gianfranco Costamagna 07ae7146e3 Honour system flags, this makes debug flags being injected correctly.
Signed-off-by: Wilson Snyder <[email protected]>
2019-07-06 13:02:36 -04:00
Wilson Snyder 8548ecfdac Internals: Add UASSERT_OBJ macro to replace hand-done ifs. No functional change intended.
This makes it easier to filter out correctly zero code-coverage lines.
2019-07-06 12:57:50 -04:00
Wilson Snyder 7e54ff1b37 Additional lcov code coverage. 2019-07-05 22:30:19 -04:00
Wilson Snyder a4b9745e6e Fix lifetime opt dropping 2019-07-05 22:30:19 -04:00
Wilson Snyder 8612ba2b8d Internals: Commentary and fix gate debug glibc warning 2019-07-05 22:30:19 -04:00
Todd Strader fea6e047e2 Add Travis badge 2019-07-05 05:26:08 -04:00
Wilson Snyder 01ef7122e9 Internals: Add lcov code coverage markers. 2019-06-30 22:37:03 -04:00
Wilson Snyder ac43e7322b Internals: Remove dead code. 2019-06-30 22:11:56 -04:00
Wilson Snyder 02a3f2089f Include filenames in savable error. 2019-06-30 22:01:53 -04:00
Wilson Snyder 33ad834106 Tests: Close some test coverage holes. 2019-06-30 22:00:18 -04:00
Wilson Snyder efe739c52f Tests: Cover --error-limit and update docs (found via coverage). 2019-06-30 21:36:57 -04:00
Wilson Snyder 5cd531a5e0 Tests: Fix glib warning 2019-06-30 21:35:55 -04:00
Wilson Snyder 0e8dfdbb71 Tests: Less verbosity. 2019-06-30 17:45:42 -04:00
Wilson Snyder ec32a9b976 Tests: Close some test coverage holes. 2019-06-30 17:38:41 -04:00
Wilson Snyder 1aae6df669 Internals: Run graph self tests on --debug-self-test 2019-06-30 17:36:58 -04:00
Wilson Snyder f7641d2ecc Change MULTITOP to warning to help linting, see manual. 2019-06-30 16:46:48 -04:00
Wilson Snyder 5f27c41ee3 Test driver: Cleanup rerun flags & status. 2019-06-29 21:36:33 -04:00
Wilson Snyder 51df77099a Test driver: With --quiet print summary every 15sec or Travis barfs. 2019-06-29 15:58:00 -04:00
Wilson Snyder b8b7e5c978 Test driver: Add --rerun and --quiet options 2019-06-29 15:24:56 -04:00
Wilson Snyder dddcfeb482 Test driver: Move one_test, no functional change. 2019-06-29 13:37:01 -04:00
Wilson Snyder 8d63f83177 Tests: Reduce verbosity unless use --verbose 2019-06-29 13:11:30 -04:00
Wilson Snyder d43e9aa2c5 Fix not in array context on non-power-of-two slices, msg2946. 2019-06-29 11:30:38 -04:00
Wilson Snyder a2c1b7f827 Tests: Fix t_flag_csplit skip on old make. 2019-06-29 08:25:50 -04:00
Wilson Snyder 2fff92fe78 Tests: Add array MDA test. 2019-06-29 08:12:00 -04:00
Wilson Snyder ba9af4aabf For internal messages, use <command-line> and <built-in> to match GCC. 2019-06-29 07:39:34 -04:00
Wilson Snyder ef02678305 tests: Fix default make test, broke earlier commit. 2019-06-29 07:22:19 -04:00
Wilson Snyder 6990db70fa Avoid unique internal fileline in selftest. 2019-06-28 22:34:01 -04:00
Wilson Snyder af5616c077 Fix line number in dup vars. 2019-06-28 22:34:01 -04:00
Todd Strader 009f053d6e Add initial Travis CI config 2019-06-27 11:26:25 -04:00
Wilson Snyder 6903c52ef7 Tests: Add coverage of missing include error. 2019-06-26 19:12:57 -04:00
Wilson Snyder aa65dfb1bc Tests: Use only 2 threads for t_gantt. 2019-06-26 19:06:52 -04:00
Wilson Snyder 84a2cd0ec7 Remove some old DIRPROJECT dead code. 2019-06-26 18:50:38 -04:00
Wilson Snyder 8e7559c6c9 Show included-from filenames in warnings, bug1439. 2019-06-22 17:01:39 -04:00
Wilson Snyder 951521320a Warnings: Suppress dup lines, and use lowercase note: to match gcc 2019-06-22 16:12:17 -04:00
Wilson Snyder abc0eb92a0 Debug: Show only first line of suppressed warnings 2019-06-22 14:25:31 -04:00
Wilson Snyder c514bb26e8 Always internal module wrapper TOP. 2019-06-22 13:43:49 -04:00
Wilson Snyder 5cb6474cc6 Fix not reporting some duplicate signals/ports, bug1462. 2019-06-22 12:43:48 -04:00
Wilson Snyder b8eb6368e9 Tests: Fix up duplicate var declarations. 2019-06-22 12:32:13 -04:00
Wilson Snyder 6239deb1df Tests: Disable t_flag_csplit with old make. 2019-06-19 08:44:40 -04:00
Wilson Snyder 89c2a6070a devel release 2019-06-16 10:01:09 -04:00
574 changed files with 11608 additions and 9656 deletions
+1 -1
View File
@@ -2,7 +2,7 @@ Checks: 'clang-diagnostic-*,clang-analyzer-*,*,-modernize*,-hicpp*,-and
WarningsAsErrors: ''
HeaderFilterRegex: ''
FormatStyle: none
CheckOptions:
CheckOptions:
- key: google-readability-braces-around-statements.ShortStatementLines
value: '2'
- key: google-readability-namespace-comments.SpacesBeforeComments
+111
View File
@@ -0,0 +1,111 @@
# DESCRIPTION: Travis-CI config
#
# Copyright 2003-2019 by Todd Strader. 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.
language: cpp
matrix:
include:
# Non-cron build will just run on whatever linux flavor we get
- if: type != cron
os: linux
compiler: gcc
env:
- SCENARIOS=--dist
- if: type != cron
os: linux
compiler: gcc
env:
- SCENARIOS=--vlt
- if: type != cron
os: linux
compiler: gcc
env:
- SCENARIOS=--vltmt
# Cron builds try different OS/compiler combinations
- if: type = cron
dist: xenial
compiler: gcc
env:
- SCENARIOS=--dist
- if: type = cron
dist: xenial
compiler: gcc
env:
- SCENARIOS=--vlt
- if: type = cron
dist: xenial
compiler: gcc
env:
- SCENARIOS=--vltmt
- if: type = cron
dist: xenial
compiler: clang
env:
- SCENARIOS=--dist
- if: type = cron
dist: xenial
compiler: clang
env:
- SCENARIOS=--vlt
- if: type = cron
dist: xenial
compiler: clang
env:
- SCENARIOS=--vltmt
# - if: type = cron
# os: osx
# compiler: gcc
# env:
# - SCENARIOS=--dist
# - if: type = cron
# os: osx
# compiler: gcc
# env:
# - SCENARIOS=--vlt
# - if: type = cron
# os: osx
# compiler: gcc
# env:
# - SCENARIOS=--vltmt
- if: type = cron
dist: trusty
compiler: gcc
env:
- SCENARIOS=--dist
- if: type = cron
dist: trusty
compiler: gcc
env:
- SCENARIOS=--vlt
- if: type = cron
dist: trusty
compiler: gcc
env:
- SCENARIOS=--vltmt
cache: ccache
# Some tests require gdb
addons:
apt:
packages:
- gdb
before_install:
# Perl modules needed for testing
- yes yes | sudo cpan -fi Unix::Processors Parallel::Forker Bit::Vector
before_script:
- export VLT_JOBS=$((`nproc` + 1))
- export OBJCACHE=ccache
- export VERILATOR_ROOT=`pwd`
- autoconf
script:
- >
./configure --enable-maintainer-mode --enable-longtests &&
make -j $VLT_JOBS &&
make test_regress DRIVER_FLAGS="-j 0 --quiet --rerun"
after_script:
- ccache -s
+58 -2
View File
@@ -2,7 +2,63 @@ Revision history for Verilator
The contributors that suggested a given feature are shown in []. Thanks!
* Verilator 4.016 2016-06-16
* Verilator 4.020 2019-10-06
*** Support $fseek, $ftell, $frewind, bug1496. [Howard Su]
*** Add --public-flat-rw, bug1511. [Stefan Wallentowitz]
*** Support vpiModule, bug1469. [Stefan Wallentowitz]
**** Make Syms file honor --output-split-cfuncs, bug1499. [Todd Strader]
**** Fix make test with no VERILATOR_ROOT, bug1494. [Ahmed El-Mahmoudy]
**** Fix error on multidimensional cells, bug1505. [Anderson Ignacio Da Silva]
**** Fix config_rev revision detection on old versions.
**** Fix false warning on backward indexing, bug1507. [Hao Shi]
**** Fix vpiType accessor, bug1509, bug1510. [Stefan Wallentowitz]
**** Fix ugly error on interface misuse, bug1525. [Bogdan Vukobratovic]
**** Fix misc bad-syntax crashes, bug1529-bug1533. [Eric Rippey]
**** Fix case statements with strings, bug1536. [Philipp Wagner]
* Verilator 4.018 2019-08-29
** When showing an error, show source code and offer suggestions of replacements.
** When showing an error, show the instance location, bug1305. [Todd Strader]
*** Add --rr, bug1481. [Todd Strader]
*** Change MULTITOP to warning to help linting, see manual.
*** Add XSim support to driver.pl, bug1493. [Todd Strader]
**** Show included-from filenames in warnings, bug1439. [Todd Strader]
**** Fix elaboration time errors, bug1429. [Udi Finkelstein]
**** Fix not reporting some duplicate signals/ports, bug1462. [Peter Gerst]
**** Fix not in array context on non-power-of-two slices, msg2946. [Yu Sheng Lin]
**** Fix system compile flags injection. [Gianfranco Costamagna]
**** Fix enum values not being sized based on parent, bug1442. [Dan Petrisko]
**** Fix internal error on gate optimization of assign, bug1475. [Oyvind Harboe]
**** Add --dpi-hdr-only, bug1491. [Todd Strader]
* Verilator 4.016 2019-06-16
*** Add --quiet-exit, bug1436. [Todd Strader]
@@ -3282,7 +3338,7 @@ of input ports exists for tracing.
* Verilator 0.0 1994/7/8
**** First code written.
----------------------------------------------------------------------
This uses outline mode in Emacs. See C-h m [M-x describe-mode].
+1
View File
@@ -14,6 +14,7 @@
.*\.key
.*\.vcd
.*\.1
\.travis\.yml
/obj_dir/
/obj_dbg/
/obj_nc/
+20 -52
View File
@@ -83,7 +83,7 @@ infodir = @infodir@
pkgdatadir = @pkgdatadir@
# Directory in which to install pkgconfig file
# Generall ${prefix}/share/pkgconfig
# Generally ${prefix}/share/pkgconfig
pkgconfigdir = @pkgconfigdir@
# Directory in which to install data across multiple architectures
@@ -107,9 +107,8 @@ SUBDIRS = src test_regress \
examples/hello_world_c examples/hello_world_sc \
examples/tracing_c examples/tracing_sc \
INFOS = README README.html README.pdf internals.txt internals.html \
internals.pdf verilator.txt verilator.html verilator.pdf \
$(VL_INST_MAN_FILES)
INFOS = README README.html README.pdf \
verilator.txt verilator.html verilator.pdf
# Files that can be generated, but should be up to date for a distribution.
DISTDEP = info Makefile
@@ -127,11 +126,13 @@ DISTFILES_INC = $(INFOS) .gitignore \
bin/verilator_includer \
bin/verilator_profcfunc \
docs/.gitignore \
docs/CONTRIBUTING.adoc \
docs/CONTRIBUTORS \
docs/Makefile.in \
docs/TODO \
docs/doxygen-mainpage \
docs/doxygen.config \
docs/internals.adoc \
docs/verilator_logo.png \
install-sh configure *.pod \
include/*.[chv]* \
@@ -180,12 +181,21 @@ INST_PROJ_BIN_FILES = \
DISTFILES := $(DISTFILES_INC)
EXAMPLES_FIRST = \
examples/hello_world_c \
examples/hello_world_sc \
EXAMPLES = $(EXAMPLES_FIRST) $(filter-out $(EXAMPLES_FIRST), $(sort $(wildcard examples/*)))
ifeq ($(OBJCACHE_JOBS),)
ifneq ($(OBJCACHE_HOSTS),)
export OBJCACHE_JOBS := -j $(shell objcache --jobs "$(OBJCACHE_HOSTS)")
endif
endif
# See uninstall also - don't put wildcards in this variable, it might uninstall other stuff
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)
@@ -226,7 +236,7 @@ test_regress: all_nomsg
$(MAKE) -C test_regress
examples: all_nomsg
for p in examples/* ; do \
for p in $(EXAMPLES) ; do \
$(MAKE) -C $$p VERILATOR_ROOT=`pwd` || exit 10; \
done
@@ -269,31 +279,12 @@ README.pdf: README.pod Makefile $(POD2LATEXFIX)
pdflatex README.tex
-rm -f README.toc README.aux README.idx README.out
internals.txt: internals.pod
-rm -f $@
$(POD2TEXT) --loose $< > $@
internals.html: internals.pod
pod2html $< >$@
# PDF needs DIST variables; but having configure.ac as dependency isn't detected
internals.pdf: internals.pod Makefile $(POD2LATEXFIX)
pod2latex --full --out internals.tex $<
$(PERL) $(POD2LATEXFIX) "$(DISTTITLE) Internals Manual" "${DISTDATE}" < internals.tex > internals2.tex
mv internals2.tex internals.tex
pdflatex internals.tex
pdflatex internals.tex
-rm -f internals.toc internals.aux internals.idx internals.out
# See uninstall also - don't put wildcards in this variable, it might uninstall other stuff
VL_INST_BIN_FILES = verilator verilator_bin verilator_bin_dbg verilator_coverage_bin_dbg \
verilator_coverage 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.
# See uninstall also - don't put wildcards in this variable, it might uninstall other stuff
VL_INST_MAN_FILES = verilator.1 verilator_coverage.1 verilator_gantt.1 verilator_profcfunc.1
VL_INST_INC_BLDDIR_FILES = \
include/verilated_config.h \
include/verilated.mk \
@@ -377,34 +368,9 @@ install-here: installman ftp
ifeq ($(VERILATOR_AUTHOR_SITE),1) # Local... Else don't burden users
DISTNAMEREV = $(shell sed -e '/DTVERSION/!d' -e 's/.*verilator_\([^"]*\).*/\1/' -e q ${srcdir}/src/config_rev.h)
DIRPROJECT := $(shell project_dir --project)
VERILATOR_CAD_DIR = $(CAD_DIR)/verilator/$(DISTNAMEREV)/$(DIRPROJECT_ARCH)
INST_PROJ_CVS = cp_if_cvs_diff
install-project: dist
@echo "Install-project to $(DIRPROJECT)"
strip bin/verilator_bin*
strip bin/verilator_coverage_bin*
$(MAKE) install-project-quick
for p in $(VL_INST_MAN_FILES) ; do \
$(INSTALL_DATA) $$p $(DIRPROJECT_PREFIX)/man/man1/$$p; \
done
$(INST_PROJ_CVS) $(DISTNAME).tgz $(DIRPROJECT)/hw/utils/verilator/verilator.tgz
rm $(DISTNAME).tgz
install-project-quick:
ifeq ($(CFG_WITH_DEFENV),yes)
@echo "%Error: Reconfigure with './configure --disable-defenv' to avoid hardcoded paths."
false
endif
@echo "Install-project-quick (no strip) to $(DIRPROJECT)"
for p in $(INST_PROJ_FILES) ; do \
$(INST_PROJ_CVS) $$p $(DIRPROJECT)/hw/utils/verilator/$$p; \
done
for p in $(INST_PROJ_BIN_FILES) ; do \
$(INST_PROJ_CVS) $$p $(DIRPROJECT)/hw/utils/verilator/$$p-$(DIRPROJECT_ARCH); \
done
install-cadtools: dist
@echo "Install-project to $(CAD_DIR)"
strip bin/verilator_bin*
@@ -445,7 +411,8 @@ CPPCHECK_H = $(wildcard \
$(srcdir)/src/*.h )
CPPCHECK = src/cppcheck_filtered
CPPCHECK_FLAGS = --enable=all --inline-suppr \
--suppress=unusedScopedObject --suppress=cstyleCast --suppress=useInitializationList
--suppress=unusedScopedObject --suppress=cstyleCast --suppress=useInitializationList \
--suppress=nullPointerRedundantCheck
CPPCHECK_FLAGS += --xml
CPPCHECK_DEP = $(subst .cpp,.cppcheck,$(CPPCHECK_CPP))
CPPCHECK_INC = -I$(srcdir)/include -I$(srcdir)/src/obj_dbg -I$(srcdir)/src
@@ -521,11 +488,12 @@ clean mostlyclean distclean maintainer-clean::
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 test_*/obj_dir
rm -rf examples/*/obj_dir examples/*/logs
rm -rf test_*/obj_dir
rm -rf nodist/obj_dir
distclean maintainer-clean::
rm -f *.info* *.1 $(INFOS)
rm -f *.info* *.1 $(INFOS) $(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*
+5 -3
View File
@@ -3,6 +3,8 @@
=pod
=for html <a href="https://travis-ci.com/verilator/verilator"><img src="https://travis-ci.com/verilator/verilator.svg?branch=master"></a>
=head1 NAME
Welcome to Verilator. This is the Verilator package's README file.
@@ -30,7 +32,7 @@ The resulting executable will perform the actual simulation.
Verilator is developed and has primary testing on Ubuntu. Versions have
also built on Redhat Linux, Macs OS-X, HPUX and Solaris. It should run
with minor porting on any Linix-ish platform. Verilator also works on
with minor porting on any Linux-ish platform. Verilator also works on
Windows under Cygwin, and Windows under MinGW (gcc -mno-cygwin). Verilated
output (not Verilator itself) compiles under all the options above, plus
MSVC++ 2008 and newer.
@@ -98,7 +100,7 @@ To use Verilator you will need the C<perl>, C<make> (or C<gmake>), and
C<g++> (or C<clang>) packages. To compile Verilator in addition to the above you need the C<flex>,
C<bison> and C<texi2html> packages installed.
sudo apt-get install git make autoconf g++ flex bisonz # First time prerequisites
sudo apt-get install git make autoconf g++ flex bison # First time prerequisites
sudo apt-get install libgz # Non-Ubuntu (ignore if gives error)
sudo apt-get install libfl2 libfl-dev zlibc zlib1g zlib1g-dev # Ubuntu only (ignore if gives error)
@@ -164,7 +166,7 @@ needed files.
=item 2.
You may eventually be instaling onto a project/company-wide "CAD" tools
You may eventually be installing onto a project/company-wide "CAD" tools
disk that may support multiple versions of every tool.
unset VERILATOR_ROOT # if your shell is bash
+88 -30
View File
@@ -17,13 +17,6 @@ eval 'exec perl -wS $0 ${1+"$@"}'
require 5.006_001;
use warnings;
BEGIN {
if ($ENV{DIRPROJECT} && $ENV{DIRPROJECT_PERL_BOOT}) {
# Magic to allow author testing of perl packages in local directory
require $ENV{DIRPROJECT}."/".$ENV{DIRPROJECT_PERL_BOOT};
}
}
use Getopt::Long;
use FindBin qw($RealBin $RealScript);
use IO::File;
@@ -41,6 +34,7 @@ autoflush STDERR 1;
$Debug = 0;
my $opt_gdb;
my $opt_rr;
my $opt_gdbbt;
my $opt_quiet_exit;
@@ -62,12 +56,13 @@ Getopt::Long::config("no_auto_abbrev","pass_through");
if (! GetOptions(
# Major operating modes
"help" => \&usage,
"debug:s" => \&debug,
"debug" => \&debug,
# "version!" => \&version, # Also passthru'ed
# Switches
"gdb!" => \$opt_gdb,
"gdbbt!" => \$opt_gdbbt,
"quiet-exit!" => \$opt_quiet_exit,
"rr!" => \$opt_rr,
# Additional parameters
"<>" => sub {}, # Ignored
)) {
@@ -100,6 +95,10 @@ if ($opt_gdb) {
." -ex \"run ".join(' ', @quoted_sw)."\""
." -ex 'set width 0'"
." -ex 'bt'");
} elsif ($opt_rr) {
# Record with rr
run ("rr record ".verilator_bin()
." ".join(' ', @quoted_sw));
} elsif ($opt_gdbbt && $Debug) {
# Run under GDB to get gdbbt
run ("gdb"
@@ -107,7 +106,7 @@ if ($opt_gdb) {
." --batch --quiet --return-child-result"
." -ex \"run ".join(' ', @quoted_sw)."\""
." -ex 'set width 0'"
." -ex 'bt'");
." -ex 'bt' -ex 'quit'");
} else {
# Normal, non gdb
run(verilator_bin()." ".join(' ',@quoted_sw));
@@ -116,7 +115,7 @@ if ($opt_gdb) {
#----------------------------------------------------------------------
sub usage {
pod2usage(-verbose=>2, -exitval=>2, -output=>\*STDOUT);
pod2usage(-verbose=>2, -exitval=>0, -output=>\*STDOUT);
}
sub debug {
@@ -166,7 +165,8 @@ sub gdb_works {
." --batch-silent --quiet --return-child-result"
." -ex 'run -n'" # `echo -n`
." -ex 'set width 0'"
." -ex 'bt'");
." -ex 'bt'"
." -ex 'quit'");
my $status = $?;
return $status==0;
}
@@ -298,6 +298,7 @@ detailed descriptions in L</"VERILATION ARGUMENTS"> for more information.
--debugi-<srcfile> <level> Enable debugging a source file at a level
--default-language <lang> Default language to parse
+define+<var>=<value> Set preprocessor define
--dpi-hdr-only Only produce the DPI header file
--dump-defines Show preprocessor defines with -E
--dump-tree Enable dumping .tree files
--dump-treei <level> Enable dumping .tree files at a level
@@ -320,7 +321,6 @@ detailed descriptions in L</"VERILATION ARGUMENTS"> for more information.
--inhibit-sim Create function to turn off sim
--inline-mult <value> Tune module inlining
-LDFLAGS <flags> Linker pre-object flags for makefile
-LDLIBS <flags> Linker library flags for makefile
--l2-name <value> Verilog scope name of the top module
--language <lang> Default language standard to parse
+libext+<ext>+[ext]... Extensions for finding modules
@@ -354,11 +354,13 @@ detailed descriptions in L</"VERILATION ARGUMENTS"> for more information.
--prof-threads Enable generating gantt chart data for threads
--private Debugging; see docs
--public Debugging; see docs
--public-flat-rw Mark all variables, etc as public_flat_rw
-pvalue+<name>=<value> Overwrite toplevel parameter
--quiet-exit Don't print the command on failure
--relative-includes Resolve includes relative to current file
--no-relative-cfuncs Disallow 'this->' in generated functions
--report-unoptflat Extra diagnostics for UNOPTFLAT
--rr Run Verilator and record with rr
--savable Enable model save-restore
--sc Create SystemC output
--stats Create statistics file
@@ -740,6 +742,11 @@ Defines the given preprocessor symbol, or multiple symbols if separated by
plusses. Similar to -D; +define is fairly standard across Verilog tools
while -D is an alias for GCC compatibility.
=item --dpi-hdr-only
Only generate the DPI header file. This option has no effect on the name
or location of the file.
=item --dump-defines
With -E, suppress normal output, and instead print a list of all defines
@@ -775,8 +782,8 @@ will also go to standard out.
=item --error-limit I<value>
After this number of errors or warnings are encountered, exit. Defaults to
50.
After this number of errors are encountered, exit. Warnings are not
counted in this limit. Defaults to 50.
=item --exe
@@ -1162,6 +1169,16 @@ inlining. This will also turn off inlining as if all modules had a
/*verilator public_module*/, unless the module specifically enabled it with
/*verilator inline_module*/.
=item --public-flat-rw
Declares all variables, ports and wires public as if they had /*verilator
public_flat_rw*/ comments. This will make them VPI accessible by their
flat name, but not turn off module inlining. This is particularly useful
in combination with --vpi. This may also in some rare cases result in
mis-simulation of generated clocks. Instead of this global switch, marking
only those signals that need public_flat_rw is typically significantly
better performing.
=item -pvalue+I<name>=I<value>
Overwrites the given parameter(s) of the toplevel module. See -G for a
@@ -1198,6 +1215,10 @@ printing. For example:
will generate a PDF Vt_unoptflat_simple_2_35_unoptflat.dot.pdf from the DOT
file.
=item --rr
Run Verilator and record with rr. See: rr-project.org.
=item --savable
Enable including save and restore functions in the generated model.
@@ -1287,7 +1308,7 @@ good value.
When the input Verilog contains more than one top level module, specifies
the name of the top level Verilog module to become the top, and sets the
default for if --prefix is not used. This is not needed with standard
designs with only one top.
designs with only one top. See also the MULTITOP warning section.
=item --trace
@@ -2451,6 +2472,10 @@ Configuration files are parsed after the normal Verilog preprocessing, so
`ifdefs, `defines, and comments may be used as if it were normal Verilog
code.
Note that file or line-specific configuration only applies to files read
after the configuration file. It is therefore recommended to pass the
configuration file to Verilator as first file.
The grammar of configuration commands is as follows:
=over 4
@@ -2902,7 +2927,8 @@ signal should be declared public_flat (see above), but read-only.
Used after an input, output, register, or wire declaration to indicate the
signal should be declared public_flat_rd (see above), and also writable,
where writes should be considered to have the timing specified by the given
sensitivity edge list.
sensitivity edge list. Set for all variables, ports and wires using the
--public-flat-rw switch.
=item /*verilator public_module*/
@@ -3725,14 +3751,31 @@ correctly.
=item MULTITOP
Error that there are multiple top level modules, that is modules not
instantiated by any other module. Verilator only supports a single top
level, if you need more, create a module that wraps all of the top modules.
Warns that there are multiple top level modules, that is modules not
instantiated by any other module, and both modules were put on the command
line (not in a library). Three likely cases:
Often this error is because some low level cell is being read in, but is
not really needed. The best solution is to insure that each module is in a
unique file by the same name. Otherwise, make sure all library files are
read in as libraries with -v, instead of automatically with -y.
1. A single module is intended to be the top. This warning then occurs
because some low level cell is being read in, but is not really needed as
part of the design. The best solution for this situation is to ensure that
only the top module is put on the command line without any flags, and all
remaining library files are read in as libraries with -v, or are
automatically resolved by having filenames that match the module names.
2. A single module is intended to be the top, the name of it is known, and
all other modules should be ignored if not part of the design. The best
solution is to use the --top-module option to specify the top module's
name. All other modules that are not part of the design will be for the
most part ignored (they must be clean in syntax and their contents will be
removed as part of the Verilog module elaboration process.)
3. Multiple modules are intended to be design tops, e.g. when linting a
library file. As multiple modules are desired, disable the MULTITOP
warning. All input/outputs will go uniquely to each module, with any
conflicting and identical signal names being uniquified by adding a prefix
based on the top module name followed by __02E (a Verilator-encoded ASCII
".'). This renaming is done even if the two modules' signals seem
identical, e.g. multiple modules with a "clk" input.
=item PINCONNECTEMPTY
@@ -4121,17 +4164,32 @@ code to add appropriate prints to see what is going on.
=over 4
=item Does it run under Windows?
=item Can I contribute?
Please contribute! Just file an issue asking for a merge, or ask on the
forums if looking for something to help on. For more information see our
contributor agreement.
=item How commonly is Verilator used?
Verilator is used by many of the largest silicon design companies, and all
the way down to college projects. Verilator is a "big 4" simulator,
meaning one of the 4 main SystemVerilog simulators available, namely the
commercial products Synopsys' VCS (tm), Mentor's ModelSim (tm), Cadence
Incisive/NC-Verilog/NC-Sim, and the open-source Verilator. The three
commercial choices are commonly collectively called the "big 3" simulators.
=item Does Verilator run under Windows?
Yes, using Cygwin. Verilated output also compiles under Microsoft Visual
C++ Version 7 or newer, but this is not tested every release.
C++, but this is not tested every release.
=item Can you provide binaries?
Verilator is available as a RPM for Debian/Ubuntu, SuSE, Fedora, and
perhaps other systems; this is done by porters and may slightly lag the
primary distribution. If there isn't a binary build for your distribution,
how about you set one up? Please contact the authors for assistance.
Verilator is available as a RPM for Debian/Ubuntu, SuSE, Fedora, and other
distributions; this is done by porters and may slightly lag the primary
distribution. If there isn't a binary build for your distribution, how
about you set one up? Please contact the authors for assistance.
Note people sometimes request binaries when they are having problems with
their C++ compiler. Alas, binaries won't help this, as in the end a fully
@@ -4175,7 +4233,7 @@ 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.
=item Why is Verilation so slow?
=item Why is running Verilator (to create a model) so slow?
Verilator needs more memory than the resulting simulator will require, as
Verilator creates internally all of the state of the resulting generated
+1 -8
View File
@@ -17,13 +17,6 @@ eval 'exec perl -wS $0 ${1+"$@"}'
require 5.006_001;
use warnings;
BEGIN {
if ($ENV{DIRPROJECT} && $ENV{DIRPROJECT_PERL_BOOT}) {
# Magic to allow author testing of perl packages in local directory
require $ENV{DIRPROJECT}."/".$ENV{DIRPROJECT_PERL_BOOT};
}
}
use Getopt::Long;
use FindBin qw($RealBin $RealScript);
use IO::File;
@@ -73,7 +66,7 @@ run(verilator_coverage_bin()
#----------------------------------------------------------------------
sub usage {
pod2usage(-verbose=>2, -exitval=>2, -output=>\*STDOUT);
pod2usage(-verbose=>2, -exitval=>0, -output=>\*STDOUT);
}
sub debug {
+2 -2
View File
@@ -168,8 +168,8 @@ sub filter {
#----------------------------------------------------------------------
sub usage {
pod2usage(-verbose=>2, -exitval=>2, -output=>\*STDOUT);
exit(1);
pod2usage(-verbose=>2, -exitval=>0, -output=>\*STDOUT);
exit(1); # Unreachable
}
sub debug {
+2 -2
View File
@@ -43,8 +43,8 @@ exit(0);
#######################################################################
sub usage {
pod2usage(-verbose=>2, -exitval=>2, -output=>\*STDOUT);
exit(1);
pod2usage(-verbose=>2, -exitval=>0, -output=>\*STDOUT);
exit(1); # Unreachable
}
sub parameter {
+2 -2
View File
@@ -39,8 +39,8 @@ profcfunc($Opt_File);
#----------------------------------------------------------------------
sub usage {
pod2usage(-verbose=>2, -exitval=>2, -output=>\*STDOUT);
exit(1);
pod2usage(-verbose=>2, -exitval=>0, -output=>\*STDOUT);
exit(1); # Unreachable
}
sub debug {
+8 -6
View File
@@ -6,7 +6,7 @@
#AC_INIT([Verilator],[#.### YYYY-MM-DD])
#AC_INIT([Verilator],[#.### devel])
AC_INIT([Verilator],[4.016 2019-06-16],
AC_INIT([Verilator],[4.020 2019-10-06],
[https://www.veripool.org/verilator],
[verilator],[https://www.veripool.org/verilator])
# When releasing, also update header of Changes file
@@ -91,10 +91,10 @@ AC_SUBST(CFG_WITH_PREC11)
AC_MSG_RESULT($CFG_WITH_PREC11)
# Compiler flags
CFLAGS=-I${includedir}
CPPFLAGS=-I${includedir}
CXXFLAGS=-I${includedir}
LDFLAGS=-L${libdir}
CFLAGS+=" -I${includedir}"
CPPFLAGS+=" -I${includedir}"
CXXFLAGS+=" -I${includedir}"
LDFLAGS+=" -L${libdir}"
# Checks for programs.
AC_PROG_CC
@@ -273,7 +273,9 @@ AC_SUBST(CFG_CXXFLAGS_PARSER)
# 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)
_MY_CXX_CHECK_OPT(CFG_CXXFLAGS_NO_UNUSED,-faligned-new)
# 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)])
_MY_CXX_CHECK_OPT(CFG_CXXFLAGS_NO_UNUSED,-fbracket-depth=4096)
_MY_CXX_CHECK_OPT(CFG_CXXFLAGS_NO_UNUSED,-Qunused-arguments)
_MY_CXX_CHECK_OPT(CFG_CXXFLAGS_NO_UNUSED,-Wno-bool-operation)
+82
View File
@@ -0,0 +1,82 @@
= How to contribute to Verilator
Thanks for using Verilator! We welcome your contributions in whatever form.
This contributing document contains some suggestions that may make
contributions flow more efficiently.
==== Did you find a bug?
* Please **Ensure the bug was not already reported** by searching
https://www.veripool.org/projects/verilator/issues[Verilator Issues].
* If you're unable to find an open issue addressing the problem,
https://www.veripool.org/projects/verilator/issues/new[open a new issue].
** Be sure to include a **code sample** or an **executable test case**
demonstrating the bug and expected behavior that is not occurring.
** The ideal example works against other simulators, and is in the
test_regress/t test format, as described in
link:internals.adoc[docs/internals].
==== Did you write a patch that fixes a bug?
* Please https://www.veripool.org/projects/verilator/issues/new[Open a new
issue].
* You may attach a patch to the issue, or (preferred) may point to a github
repository branch within your github account.
** Verilator uses Travis CI to provide continuous integration. You may
want to setup Travis CI on your github branch to ensure your changes
keep the tests passing. See link:internals.adoc[docs/internals].
* Your source-code contributions must be certified as open source, under
the https://developercertificate.org/[Developer Certificate of
Origin]. On your first contribution, you must either:
** Have your patch include the addition of your name to
link:CONTRIBUTORS[docs/CONTRIBUTORS] (preferred).
** Use "git -s" as part of your commit. This adds a "signed-of-by"
attribute which will certify your contribution as described in the
https://github.com/wking/signed-off-by/blob/master/Documentation/SubmittingPatches[Signed-of-By
convention].
** Email, or post in an issue a statement that you certify your
contributions.
** In any of these cases your name will be added to
link:CONTRIBUTORS[docs/CONTRIBUTRORS] and you are agreeing all future
contributions are also certified.
** We occasionally accept contributions where people do not want their
name published. Please email us; you must still certify your
contribution using email.
* Your test contributions are generally considered released into the public
domain, unless you request otherwise or put a GNU/Artistic license on
your test file.
* Most important is we get your patch. If you'd like to clean up
indentation and related issues ahead of our feedback, that is
appreciated; please see the coding conventions in
link:internals.adoc[docs/internals].
==== Do you have questions?
* Please see the
https://www.veripool.org/projects/verilator/wiki/Faq[Verilator FAQ].
* Ask any question in the
https://www.veripool.org/projects/verilator/boards[Verilator forums].
==== Code of Conduct
* Our contributors and participants pledge to make participation in our
project and our community a positive experience for everyone. We follow
the https://www.contributor-covenant.org/version/1/4/code-of-conduct.html[Contributor
Covenant version 1.4].
Thanks!
+9 -1
View File
@@ -4,10 +4,18 @@ under the Developer Certificate of Origin
Please see the Verilator manual for additional contributors.
Jeremy Bennett
Alex Chadwick
Gianfranco Costamagna
Howard Su
Jeremy Bennett
John Coiner
Kanad Kanhere
Lukasz Dalek
Maarten De Braekeleer
Philipp Wagner
Richard Myers
Sebastien Van Cauwenberghe
Stefan Wallentowitz
Todd Strader
Wilson Snyder
Yves Mathieu
+956
View File
@@ -0,0 +1,956 @@
= Verilator Internals Documentation
:toc: right
// Github doesn't render unless absolute URL
image::https://www.veripool.org/img/verilator_256_200_min.png[Logo,256,200,role="right"]
== 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 http://www.veripool.org.
== Code Flows
=== Verilator Flow
The main flow of Verilator can be followed by reading the Verilator.cpp
`process()` function:
. 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.
. Verilator then makes a series of passes over the AST, progressively
refining and optimizing it.
. Cells in the AST first linked, which will read and parse additional files
as above.
. Functions, variable and other references are linked to their definitions.
. Parameters are resolved and the design is elaborated.
. Verilator then performs many additional edits and optimizations on the
hierarchical design. This includes coverage, assertions, X elimination,
inlining, constant propagation, and dead code elimination.
. 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.
. 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).
. 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.
. 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.
. 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).
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), `ifsp` 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.
`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.
==== `AstNVisitor`
The passes are implemented by AST visitor classes. These are implemented
by subclasses of the abstract class, `AstNVisitor`. 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 to output them in
http://www.graphviz.org/[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 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`.
=== 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 not prohibitive 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 are 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 simply 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 simply 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 `InstrCountCostVisitor`. This
class is perhaps the most fragile piece of the multithread implementation.
It's easy to have a bug where you count something cheap (eg. 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-threads` 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 turns out to be 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 multi-thread 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.
===== 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 multi-threaded
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 a 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
=== Indentation style
We will work with contributors to fix up indentation style issues, but it
is appreciated if you could match our style:
* All files should contain the magic header to insure standard indentation:
+
// -*- mode: C++; c-file-style: "cc-mode" -*-
+
This sets indentation to the `cc-mode` defaults. (Verilator predates a
CC-mode change of several years ago which overrides the defaults with GNU
style indentation; the `c-set-style` undoes that.)
* Use 4 spaces per level, and no tabs.
* Use 2 spaces between the end of source and the beginning of a comment.
* Use "mixedCapsSymbols" instead of "underlined_symbls".
* Comment every member variable.
=== The `astgen` script
Some of the code implementing passes is extremely repetitive, and must be
implemented for each sub-class of `AstNode`. However, while repetitive,
there is more variability than can be handled in C++ macros.
In Verilator this is implemented by using a Perl script, `astgen` to
pre-process the C++ code. For example in `V3Const.cpp` this 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 http://en.wikipedia.org/wiki/Visitor_pattern.
As noted above, all visitors are derived classes of `AstNVisitor`. All
derived classes of `AstNode` implement the `accept` method, which takes as
argument a reference to an instance or a `AstNVisitor` derived class and
applies the visit method of the `AstNVisitor` 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 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 `user5()` methods, or as a pointer (of type `AstNUser`)
using the `user1p()` through `user5p()` 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
`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 more messy 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
`AstNVisitor` provides a set of iterators to facilitate walking over the
tree. Each operates on the current `AstNVisitor` 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) {
<code specific to 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
For an overview of how to write a test see the BUGS section of the
Verilator primary 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
=== Controlling the Test Driver
Test drivers are written in PERL. All invoke the main test driver script,
which can provide detailed help on all the features available when writing
a test driver.
test_regress/t/driver.pl --help
For convenience, a summary of the most commonly used features is provided
here. All drivers require a call to `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 a hash
table as argument specifying additional options.
The test driver assumes by default that the source Verilog file name
matches the PERL driver 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,
);
=== Regression Testing for Developers
Developers will also want to call ./configure with two extra flags:
`--enable-ccwarn`::
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 Unix::Processors
There are some traps to avoid when running regression tests
* When checking the MANIFEST, the test will barf 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.
=== Continuous Integration
Verilator has a https://travis-ci.com/verilator/verilator[Travis CI environment]
which automatically tests the master branch for test failures on new commits. It
also runs a daily cron job to validate all of the tests against different OS and
compiler versions.
Developers can connect Travis CI to their GitHub account so that the CI
enviroment can check their branches too by doing the following:
* Go to https://github.com/marketplace/travis-ci and follow the prompts
* Only the Open Source (FREE) version of Travis CI is required
* Under a Travis CI project click More options > Settings in order to set up a
cron job on a particular branch
== Debugging
=== --debug
When you run with `--debug` there are two primary output file types placed
into the obj_dir, .tree and .dot files.
=== .dot output
Dot files are dumps of internal graphs in
http://www.graphviz.org/[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 can be more useful with large graphs.
For dynamic graph viewing consider ZGRViewer
http://zvtm.sourceforge.net/zgrviewer.html. If you know of better
viewers let us know; ZGRViewer isn't great for large graphs.
=== .tree output
Tree files are dumps of the AST Tree and are produced between every major
algorithmic stage. An example:
NETLIST 0x90fb00 <e1> {a0}
1: MODULE 0x912b20 <e8822> {a8} top L2 [P]
*1:2: VAR 0x91a780 <e74#> {a22} @dt=0xa2e640(w32) out_wide [O] WIRE
1:2:1: BASICDTYPE 0xa2e640 <e2149> {e24} @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.
[cols="20%,80%"]
|===
|`1:2:` | indicates the hierarchy of the `VAR` is the `op2p` pointer under
the `MODULE`, which in turn is the `op1p` pointer under the `NETLIST`
|`VAR` | is the AstNodeType.
| `0x91a780` | is the address of this node.
| `<e74>` | means the 74th edit to the netlist was the last modification to
this node.
| `{a22}` | indicates this node is related to line 22 in the source filename
"a", where "a" is the first file read, "z" the 26th, and "aa" the 27th.
| `@dt=0x...` | indicates the address of the data type this node contains.
| `w32` | indicates the width is 32 bits.
| `out_wide` | is the name of the node, in this case the name of the variable.
| `[O]` | are 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 <e1> {a0} w0
1: MODULE 0x92bac80 <e3144> {e14} w0 TOP_t L1 [P]
1:1: CELLINLINE 0x92bab18 <e3686#> {e14} w0 v -> t
1:1: CELLINLINE 0x92bc1d8 <e3688#> {e24} w0 v__DOT__i_test_gen -> test_gen
...
1: MODULE 0x92b9bb0 <e503> {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.
Last edit number::
Of the form `<ennnn>` or `<ennnn#>` , 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 (which typically means 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...user5p, 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` it 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 <e509> {e24} w0 clk [RV] <- VAR 0x92a2e90 <e79> {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.
=== Debugging with GDB
The test_regress/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 <e####> line in the tree dumps):
watch AstNode::s_editCntGbl==####
To print a node:
pn nodep
# or: call nodep->dumpGdb() # aliased to "pn" in src/.gdbinit
pnt nodep
# or: call nodep->dumpTreeGdb() # 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?
. File an issue (if there isn't already) so others know what you're working on.
. Make a testcase in the test_regress/t/t_EXAMPLE format, see << /TESTING >>.
. 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.
. If a new Ast type is needed, add it to V3AstNodes.h.
. Now you can run "test_regress/t/t_{new testcase}.pl --debug" and it'll
probably fail but you'll see a test_regress/obj_dir/t_{newtestcase}/*.tree
file which you can examine to see if the parsing worked. See also the
sections above on debugging.
. 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.
== Distribution
Copyright 2008-2019 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.
+1 -1
View File
@@ -24,7 +24,7 @@ endif
# e.g. examples/tracing_c.
# If $VERILATOR_ROOT isn't in the environment, we assume it is part of a
# package inatall, and verilator is in your path. Otherwise find the
# 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
+1 -1
View File
@@ -24,7 +24,7 @@ endif
# e.g. examples/tracing_sc.
# If $VERILATOR_ROOT isn't in the environment, we assume it is part of a
# package inatall, and verilator is in your path. Otherwise find the
# 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
+1 -1
View File
@@ -21,7 +21,7 @@ endif
# Set up variables
# If $VERILATOR_ROOT isn't in the environment, we assume it is part of a
# package inatall, and verilator is in your path. Otherwise find the
# 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
+6 -6
View File
@@ -14,18 +14,18 @@ module top
input fastclk,
input reset_l,
output [1:0] out_small,
output [39:0] out_quad,
output [69:0] out_wide,
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
wire [1:0] out_small = ~reset_l ? '0 : (in_small + 2'b1);
wire [39:0] out_quad = ~reset_l ? '0 : (in_quad + 40'b1);
wire [69:0] out_wide = ~reset_l ? '0 : (in_wide + 70'b1);
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*/
+1 -1
View File
@@ -21,7 +21,7 @@ endif
# Set up variables
# If $VERILATOR_ROOT isn't in the environment, we assume it is part of a
# package inatall, and verilator is in your path. Otherwise find the
# 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
+6 -6
View File
@@ -14,18 +14,18 @@ module top
input fastclk,
input reset_l,
output [1:0] out_small,
output [39:0] out_quad,
output [69:0] out_wide,
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
wire [1:0] out_small = ~reset_l ? '0 : (in_small + 2'b1);
wire [39:0] out_quad = ~reset_l ? '0 : (in_quad + 40'b1);
wire [69:0] out_wide = ~reset_l ? '0 : (in_wide + 70'b1);
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*/
+25 -9
View File
@@ -22,7 +22,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//=========================================================================
#define _VERILATED_CPP_
#include "verilatedos.h"
@@ -43,9 +43,13 @@
// Static sanity checks (when get C++11 can use static_assert)
typedef union {
// cppcheck-suppress unusedStructMember // Unused as is assertion
char vluint8_incorrect[(sizeof(vluint8_t) == 1) ? 1:-1];
// cppcheck-suppress unusedStructMember // Unused as is assertion
char vluint16_incorrect[(sizeof(vluint16_t) == 2) ? 1:-1];
// cppcheck-suppress unusedStructMember // Unused as is assertion
char vluint32_incorrect[(sizeof(vluint32_t) == 4) ? 1:-1];
// cppcheck-suppress unusedStructMember // Unused as is assertion
char vluint64_incorrect[(sizeof(vluint64_t) == 8) ? 1:-1];
} vl_static_checks_t;
@@ -285,6 +289,7 @@ IData VL_RANDOM_I(int obits) VL_MT_SAFE {
QData VL_RANDOM_Q(int obits) VL_MT_SAFE {
return vl_rand64() & VL_MASK_Q(obits);
}
// VL_RANDOM_W currently unused as $random always 32 bits
WDataOutP VL_RANDOM_W(int obits, WDataOutP outwp) VL_MT_SAFE {
for (int i=0; i<VL_WORDS_I(obits); ++i) {
if (i<(VL_WORDS_I(obits)-1)) {
@@ -1093,8 +1098,8 @@ IData VL_FGETS_IXI(int obits, void* destp, IData fpi) VL_MT_SAFE {
IData bytes = VL_BYTES_I(obits);
char buffer[VL_TO_STRING_MAX_WORDS*VL_WORDSIZE+1];
// V3Emit has static check that bytes < VL_TO_STRING_MAX_WORDS, but be safe
if (VL_UNLIKELY(bytes > VL_TO_STRING_MAX_WORDS*VL_WORDSIZE)) {
VL_FATAL_MT(__FILE__, __LINE__, "", "Internal: fgets buffer overrun");
if (VL_UNCOVERABLE(bytes > VL_TO_STRING_MAX_WORDS*VL_WORDSIZE)) {
VL_FATAL_MT(__FILE__, __LINE__, "", "Internal: fgets buffer overrun"); // LCOV_EXCL_LINE
}
// We don't use fgets, as we must read \0s.
@@ -1317,7 +1322,7 @@ const char* memhFormat(int nBits) {
case 5: VL_SNPRINTF(buf, 32, "%%06x"); break;
case 6: VL_SNPRINTF(buf, 32, "%%07x"); break;
case 7: VL_SNPRINTF(buf, 32, "%%08x"); break;
default: assert(false); break;
default: assert(false); break; // LCOV_EXCL_LINE
}
return buf;
}
@@ -1373,6 +1378,7 @@ void VL_WRITEMEM_N(
FILE* fp = fopen(filename.c_str(), "w");
if (VL_UNLIKELY(!fp)) {
VL_FATAL_MT(filename.c_str(), 0, "", "$writemem file not found");
// cppcheck-suppress resourceLeak // fp is NULL - bug in cppcheck
return;
}
@@ -1510,6 +1516,7 @@ void VL_READMEM_N(
if (VL_UNLIKELY(!fp)) {
// We don't report the Verilog source filename as it slow to have to pass it down
VL_FATAL_MT(filename.c_str(), 0, "", "$readmem file not found");
// cppcheck-suppress resourceLeak // fp is NULL - bug in cppcheck
return;
}
// Prep for reading
@@ -1842,9 +1849,9 @@ void Verilated::flushCb(VerilatedVoidCb cb) VL_MT_SAFE {
VerilatedLockGuard lock(m_mutex);
if (s_flushCb == cb) {} // Ok - don't duplicate
else if (!s_flushCb) { s_flushCb=cb; }
else {
else { // LCOV_EXCL_LINE
// Someday we may allow multiple callbacks ala atexit(), but until then
VL_FATAL_MT("unknown", 0, "",
VL_FATAL_MT("unknown", 0, "", // LCOV_EXCL_LINE
"Verilated::flushCb called twice with different callbacks");
}
}
@@ -2100,9 +2107,11 @@ void* VerilatedVarProps::datapAdjustIndex(void* datap, int dim, int indx) const
VerilatedScope::VerilatedScope() {
m_callbacksp = NULL;
m_namep = NULL;
m_identifierp = NULL;
m_funcnumMax = 0;
m_symsp = NULL;
m_varsp = NULL;
m_type = SCOPE_OTHER;
}
VerilatedScope::~VerilatedScope() {
@@ -2115,15 +2124,18 @@ VerilatedScope::~VerilatedScope() {
}
void VerilatedScope::configure(VerilatedSyms* symsp, const char* prefixp,
const char* suffixp) VL_MT_UNSAFE {
const char* suffixp, const char* identifier,
const Type type) VL_MT_UNSAFE {
// Slowpath - called once/scope at construction
// We don't want the space and reference-count access overhead of strings.
m_symsp = symsp;
m_type = type;
char* namep = new char[strlen(prefixp)+strlen(suffixp)+2];
strcpy(namep, prefixp);
if (*prefixp && *suffixp) strcat(namep, ".");
strcat(namep, suffixp);
m_namep = namep;
m_identifierp = identifier;
VerilatedImp::scopeInsert(this);
}
@@ -2136,8 +2148,8 @@ void VerilatedScope::exportInsert(int finalize, const char* namep, void* cb) VL_
// Alternative is to dynamically stretch the array, which is more code, and slower.
if (funcnum >= m_funcnumMax) { m_funcnumMax = funcnum+1; }
} else {
if (VL_UNLIKELY(funcnum >= m_funcnumMax)) {
VL_FATAL_MT(__FILE__, __LINE__, "",
if (VL_UNCOVERABLE(funcnum >= m_funcnumMax)) {
VL_FATAL_MT(__FILE__, __LINE__, "", // LCOV_EXCL_LINE
"Internal: Bad funcnum vs. pre-finalize maximum");
}
if (VL_UNLIKELY(!m_callbacksp)) { // First allocation
@@ -2228,6 +2240,10 @@ void VerilatedScope::scopeDump() const {
}
}
void VerilatedHierarchy::add(VerilatedScope* fromp, VerilatedScope* top) {
VerilatedImp::hierarchyAdd(fromp, top);
}
//===========================================================================
// VerilatedOneThreaded:: Methods
+24 -7
View File
@@ -23,7 +23,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//*************************************************************************
#ifndef _VERILATED_H_
#define _VERILATED_H_ 1 ///< Header Guard
@@ -189,8 +189,8 @@ public:
// METHODS
/// Check that the current thread ID is the same as the construction thread ID
void check() VL_MT_UNSAFE_ONE {
if (!VL_LIKELY(m_threadid == VL_THREAD_ID())) {
fatal_different();
if (VL_UNCOVERABLE(m_threadid != VL_THREAD_ID())) {
fatal_different(); // LCOV_EXCL_LINE
}
}
static void fatal_different() VL_MT_SAFE;
@@ -203,6 +203,8 @@ public:
//=========================================================================
/// Base class for all Verilated module classes
class VerilatedScope;
class VerilatedModule {
VL_UNCOPYABLE(VerilatedModule);
private:
@@ -290,6 +292,11 @@ public: // But for internal use only
/// This class is initialized by main thread only. Reading post-init is thread safe.
class VerilatedScope {
public:
typedef enum {
SCOPE_MODULE, SCOPE_OTHER
} Type; // Type of a scope, currently module is only interesting
private:
// Fastpath:
VerilatedSyms* m_symsp; ///< Symbol table
void** m_callbacksp; ///< Callback table pointer (Fastpath)
@@ -297,16 +304,20 @@ class VerilatedScope {
// 4 bytes padding (on -m64), for rent.
VerilatedVarNameMap* m_varsp; ///< Variable map
const char* m_namep; ///< Scope name (Slowpath)
const char* m_identifierp; ///< Identifier of scope (with escapes removed)
Type m_type; ///< Type of the scope
public: // But internals only - called from VerilatedModule's
VerilatedScope();
~VerilatedScope();
void configure(VerilatedSyms* symsp, const char* prefixp, const char* suffixp) VL_MT_UNSAFE;
void configure(VerilatedSyms* symsp, const char* prefixp, const char* suffix,
const char* identifier, const Type type) VL_MT_UNSAFE;
void exportInsert(int finalize, const char* namep, void* cb) VL_MT_UNSAFE;
void varInsert(int finalize, const char* namep, void* datap,
VerilatedVarType vltype, int vlflags, int dims, ...) VL_MT_UNSAFE;
// ACCESSORS
const char* name() const { return m_namep; }
const char* identifier() const { return m_identifierp; }
inline VerilatedSyms* symsp() const { return m_symsp; }
VerilatedVar* varFind(const char* namep) const VL_MT_SAFE_POSTINIT;
VerilatedVarNameMap* varsp() const VL_MT_SAFE_POSTINIT { return m_varsp; }
@@ -318,10 +329,16 @@ public: // But internals only - called from VerilatedModule's
if (VL_LIKELY(funcnum < scopep->m_funcnumMax)) {
// m_callbacksp must be declared, as Max'es are > 0
return scopep->m_callbacksp[funcnum];
} else {
return scopep->exportFindError(funcnum);
} else { // LCOV_EXCL_LINE
return scopep->exportFindError(funcnum); // LCOV_EXCL_LINE
}
}
Type type() const { return m_type; }
};
class VerilatedHierarchy {
public:
void add(VerilatedScope* fromp, VerilatedScope* top);
};
//===========================================================================
@@ -736,7 +753,7 @@ extern double sc_time_stamp();
# define SP_AUTO_COVER3(what,file,line)
#endif
//=========================================================================
// Functional macros/routines
// These all take the form
+1 -1
View File
@@ -17,7 +17,7 @@
//=========================================================================
//
// DESCRIPTION: Verilator: Include in verilog files to hide verilator defines
`ifdef _VERILATED_V_ `else
`define _VERILATED_V_ 1
+1 -1
View File
@@ -19,7 +19,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//*************************************************************************
///**** Product and Version name
+1 -1
View File
@@ -22,7 +22,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//=========================================================================
#define _VERILATED_DPI_CPP_
#include "verilatedos.h"
+1 -1
View File
@@ -23,7 +23,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//*************************************************************************
#ifndef _VERILATED_DPI_H_
#define _VERILATED_DPI_H_ 1 ///< Header Guard
+1 -1
View File
@@ -24,7 +24,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//*************************************************************************
#ifndef _VERILATED_HEAVY_H_
#define _VERILATED_HEAVY_H_ 1 ///< Header Guard
+18 -2
View File
@@ -19,12 +19,12 @@
/// Code available from: http://www.veripool.org/verilator
///
//=========================================================================
#ifndef _VERILATED_IMP_H_
#define _VERILATED_IMP_H_ 1 ///< Header Guard
#if !defined(_VERILATED_CPP_) && !defined(_VERILATED_DPI_CPP_)
#if !defined(_VERILATED_CPP_) && !defined(_VERILATED_DPI_CPP_) && !defined(_VERILATED_VPI_CPP_)
# error "verilated_imp.h only to be included by verilated*.cpp internals"
#endif
@@ -187,6 +187,10 @@ class VerilatedImp {
VerilatedMutex m_nameMutex; ///< Protect m_nameMap
VerilatedScopeNameMap m_nameMap VL_GUARDED_BY(m_nameMutex); ///< Map of <scope_name, scope pointer>
VerilatedMutex m_hierMapMutex; ///< Protect m_hierMap
VerilatedHierarchyMap m_hierMap VL_GUARDED_BY(m_hierMapMutex); ///< Map the represents scope hierarchy
// Slow - somewhat static:
VerilatedMutex m_exportMutex; ///< Protect m_nameMap
ExportNameMap m_exportMap VL_GUARDED_BY(m_exportMutex); ///< Map of <export_func_proto, func number>
@@ -321,6 +325,18 @@ public: // But only for verilated*.cpp
return &s_s.m_nameMap;
}
public: // But only for verilated*.cpp
// METHODS - hierarchy
static void hierarchyAdd(const VerilatedScope* fromp, const VerilatedScope* top) VL_MT_SAFE {
// Slow ok - called at construction for VPI accessible elements
VerilatedLockGuard lock(s_s.m_hierMapMutex);
s_s.m_hierMap[fromp].push_back(top);
}
static const VerilatedHierarchyMap* hierarchyMap() VL_MT_SAFE_POSTINIT {
// Thread save only assuming this is called only after model construction completed
return &s_s.m_hierMap;
}
public: // But only for verilated*.cpp
// METHODS - export names
+6 -3
View File
@@ -65,7 +65,8 @@ VerilatedDeserialize& VerilatedDeserialize::readAssert(const void* __restrict da
size_t size) VL_MT_UNSAFE_ONE {
if (VL_UNLIKELY(readDiffers(datap, size))) {
std::string fn = filename();
std::string msg = "Can't deserialize save-restore file as was made from different model";
std::string msg = "Can't deserialize save-restore file as was made from different model:"
+filename();
VL_FATAL_MT(fn.c_str(), 0, "", msg.c_str());
close();
}
@@ -86,7 +87,8 @@ void VerilatedDeserialize::header() VL_MT_UNSAFE_ONE {
VerilatedDeserialize& os = *this; // So can cut and paste standard >> code below
if (VL_UNLIKELY(os.readDiffers(VLTSAVE_HEADER_STR, strlen(VLTSAVE_HEADER_STR)))) {
std::string fn = filename();
std::string msg = std::string("Can't deserialize; file has wrong header signature");
std::string msg = std::string("Can't deserialize; file has wrong header signature: ")
+filename();
VL_FATAL_MT(fn.c_str(), 0, "", msg.c_str());
close();
}
@@ -103,7 +105,8 @@ void VerilatedDeserialize::trailer() VL_MT_UNSAFE_ONE {
VerilatedDeserialize& os = *this; // So can cut and paste standard >> code below
if (VL_UNLIKELY(os.readDiffers(VLTSAVE_TRAILER_STR, strlen(VLTSAVE_TRAILER_STR)))) {
std::string fn = filename();
std::string msg = std::string("Can't deserialize; file has wrong end-of-file signature");
std::string msg = std::string("Can't deserialize; file has wrong end-of-file signature: ")
+filename();
VL_FATAL_MT(fn.c_str(), 0, "", msg.c_str());
close();
}
+1 -1
View File
@@ -22,7 +22,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//*************************************************************************
#ifndef _VERILATED_SC_H_
#define _VERILATED_SC_H_ 1 ///< Header Guard
+1 -1
View File
@@ -27,7 +27,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//*************************************************************************
#ifndef _VERILATED_SYM_PROPS_H_
#define _VERILATED_SYM_PROPS_H_ 1 ///< Header Guard
+11 -1
View File
@@ -26,7 +26,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//*************************************************************************
#ifndef _VERILATED_SYMS_H_
#define _VERILATED_SYMS_H_ 1 ///< Header Guard
@@ -36,6 +36,7 @@
#include "verilated_sym_props.h"
#include <map>
#include <vector>
//======================================================================
/// Types
@@ -63,4 +64,13 @@ public:
~VerilatedVarNameMap() {}
};
typedef std::vector<const VerilatedScope*> VerilatedScopeVector;
class VerilatedHierarchyMap
: public std::map<const VerilatedScope*, VerilatedScopeVector> {
public:
VerilatedHierarchyMap() {}
~VerilatedHierarchyMap() {}
};
#endif // Guard
+1 -2
View File
@@ -221,8 +221,7 @@ void VlThreadPool::profileDump(const char* filenamep, vluint64_t ticksElapsed) {
eit->m_cpu,
thread_id);
break;
default: assert(false);
break;
default: assert(false); break; // LCOV_EXCL_LINE
}
}
}
+1
View File
@@ -186,6 +186,7 @@ public:
m_mtaskId = 0;
m_predictTime = 0;
m_startTime = 0;
m_endTime = 0;
m_cpu = getcpu();
}
void startRecord(vluint64_t time, uint32_t mtask, uint32_t predict) {
+1 -1
View File
@@ -325,7 +325,7 @@ void VerilatedVcd::printQuad(vluint64_t n) {
void VerilatedVcd::printTime(vluint64_t timeui) {
// VCD file format specification does not allow non-integers for timestamps
// Dinotrace doesn't mind, but Cadence vvision seems to choke
// Dinotrace doesn't mind, but Cadence Vision seems to choke
if (VL_UNLIKELY(timeui < m_timeLastDump)) {
timeui = m_timeLastDump;
static VL_THREAD_LOCAL bool backTime = false;
+85 -13
View File
@@ -24,17 +24,20 @@
/// Code available from: http://www.veripool.org/verilator
///
//=========================================================================
#define _VERILATED_VPI_CPP_
#if VM_SC
# include "verilated_sc.h"
#endif
#include "verilated.h"
#include "verilated_vpi.h"
#include "verilated_imp.h"
#include <list>
#include <map>
#include <set>
#include <sstream>
//======================================================================
// Internal constants
@@ -74,7 +77,7 @@ public:
// We reserve word zero for the next pointer, as that's safer in case a
// dangling reference to the original remains around.
static const size_t chunk = 96;
if (VL_UNLIKELY(size>chunk)) VL_FATAL_MT(__FILE__, __LINE__, "", "increase chunk");
if (VL_UNCOVERABLE(size>chunk)) VL_FATAL_MT(__FILE__, __LINE__, "", "increase chunk");
if (VL_LIKELY(t_freeHead)) {
vluint8_t* newp = t_freeHead;
t_freeHead = *((vluint8_t**)newp);
@@ -161,6 +164,7 @@ public:
};
class VerilatedVpioScope : public VerilatedVpio {
protected:
const VerilatedScope* m_scopep;
public:
explicit VerilatedVpioScope(const VerilatedScope* scopep)
@@ -210,7 +214,6 @@ public:
vluint32_t entSize() const { return m_entSize; }
vluint32_t index() { return m_index; }
virtual vluint32_t type() const {
if (varp()->vldir() != vpiNoDirection) return vpiPort;
return (varp()->dims()>1) ? vpiMemory : vpiReg; // but might be wire, logic
}
virtual vluint32_t size() const { return get_range().elements(); }
@@ -308,6 +311,43 @@ public:
}
};
class VerilatedVpioModule : public VerilatedVpioScope {
const char* m_name;
const char* m_fullname;
public:
explicit VerilatedVpioModule(const VerilatedScope* modulep)
: VerilatedVpioScope(modulep) {
m_fullname = m_scopep->name();
if (strncmp(m_fullname, "TOP.", 4) == 0) m_fullname += 4;
m_name = m_scopep->identifier();
}
static inline VerilatedVpioModule* castp(vpiHandle h) {
return dynamic_cast<VerilatedVpioModule*>((VerilatedVpio*)h); }
virtual vluint32_t type() const { return vpiModule; }
virtual const char* name() const { return m_name; }
virtual const char* fullname() const { return m_fullname; }
};
class VerilatedVpioModuleIter : public VerilatedVpio {
const std::vector<const VerilatedScope*> *m_vec;
std::vector<const VerilatedScope*>::const_iterator m_it;
public:
explicit VerilatedVpioModuleIter(const std::vector<const VerilatedScope*>& vec) : m_vec(&vec) {
m_it = m_vec->begin();
}
virtual ~VerilatedVpioModuleIter() {}
static inline VerilatedVpioModuleIter* castp(vpiHandle h) {
return dynamic_cast<VerilatedVpioModuleIter*>((VerilatedVpio*) h); }
virtual vluint32_t type() const { return vpiIterator; }
virtual vpiHandle dovpi_scan() {
if (m_it == m_vec->end()) {
return 0;
}
const VerilatedScope* modp = *m_it++;
return (new VerilatedVpioModule(modp))->castVpiHandle();
}
};
//======================================================================
struct VerilatedVpiTimedCbsCmp {
@@ -348,7 +388,7 @@ public:
varop->createPrevDatap();
}
}
if (VL_UNLIKELY(vop->reason() >= CB_ENUM_MAX_VALUE)) {
if (VL_UNCOVERABLE(vop->reason() >= CB_ENUM_MAX_VALUE)) {
VL_FATAL_MT(__FILE__, __LINE__, "", "vpi bb reason too large");
}
s_s.m_cbObjLists[vop->reason()].push_back(vop);
@@ -390,8 +430,9 @@ public:
}
return ~VL_ULL(0); // maxquad
}
static void callCbs(vluint32_t reason) {
static bool callCbs(vluint32_t reason) VL_MT_UNSAFE_ONE {
VpioCbList& cbObjList = s_s.m_cbObjLists[reason];
bool called = false;
for (VpioCbList::iterator it=cbObjList.begin(); it!=cbObjList.end();) {
if (VL_UNLIKELY(!*it)) { // Deleted earlier, cleanup
it = cbObjList.erase(it);
@@ -400,7 +441,9 @@ public:
VerilatedVpioCb* vop = *it++;
VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: reason_callback %d %p\n", reason, vop););
(vop->cb_rtnp()) (vop->cb_datap());
called = true;
}
return called;
}
static void callValueCbs() VL_MT_UNSAFE_ONE {
assertOneCheck();
@@ -521,6 +564,10 @@ void VerilatedVpi::callValueCbs() VL_MT_UNSAFE_ONE {
VerilatedVpiImp::callValueCbs();
}
bool VerilatedVpi::callCbs(vluint32_t reason) VL_MT_UNSAFE_ONE {
return VerilatedVpiImp::callCbs(reason);
}
//======================================================================
// VerilatedVpiImp implementation
@@ -992,9 +1039,9 @@ vpiHandle vpi_handle_by_name(PLI_BYTE8* namep, vpiHandle scope) {
_VL_VPI_ERROR_RESET();
if (VL_UNLIKELY(!namep)) return NULL;
VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_handle_by_name %s %p\n", namep, scope););
VerilatedVpioScope* voScopep = VerilatedVpioScope::castp(scope);
const VerilatedVar* varp;
const VerilatedVar* varp = NULL;
const VerilatedScope* scopep;
VerilatedVpioScope* voScopep = VerilatedVpioScope::castp(scope);
std::string scopeAndName = namep;
if (voScopep) {
scopeAndName = std::string(voScopep->fullname()) + "." + namep;
@@ -1004,7 +1051,11 @@ vpiHandle vpi_handle_by_name(PLI_BYTE8* namep, vpiHandle scope) {
// This doesn't yet follow the hierarchy in the proper way
scopep = Verilated::scopeFind(namep);
if (scopep) { // Whole thing found as a scope
return (new VerilatedVpioScope(scopep))->castVpiHandle();
if (scopep->type() == VerilatedScope::SCOPE_MODULE) {
return (new VerilatedVpioModule(scopep))->castVpiHandle();
} else {
return (new VerilatedVpioScope(scopep))->castVpiHandle();
}
}
const char* baseNamep = scopeAndName.c_str();
std::string scopename;
@@ -1013,9 +1064,19 @@ vpiHandle vpi_handle_by_name(PLI_BYTE8* namep, vpiHandle scope) {
baseNamep = dotp+1;
scopename = std::string(namep, dotp-namep);
}
scopep = Verilated::scopeFind(scopename.c_str());
if (!scopep) return NULL;
varp = scopep->varFind(baseNamep);
if (scopename.find(".") == std::string::npos) {
// This is a toplevel, hence search in our TOP ports first.
scopep = Verilated::scopeFind("TOP");
if (scopep) {
varp = scopep->varFind(baseNamep);
}
}
if (!varp) {
scopep = Verilated::scopeFind(scopename.c_str());
if (!scopep) return NULL;
varp = scopep->varFind(baseNamep);
}
}
if (!varp) return NULL;
return (new VerilatedVpioVar(varp, scopep))->castVpiHandle();
@@ -1127,6 +1188,14 @@ vpiHandle vpi_iterate(PLI_INT32 type, vpiHandle object) {
return ((new VerilatedVpioVarIter(vop->scopep()))
->castVpiHandle());
}
case vpiModule: {
VerilatedVpioModule* vop = VerilatedVpioModule::castp(object);
const VerilatedHierarchyMap* map = VerilatedImp::hierarchyMap();
const VerilatedScope *mod = vop ? vop->scopep() : NULL;
VerilatedHierarchyMap::const_iterator it = map->find((VerilatedScope*) mod);
if (it == map->end()) return 0;
return ((new VerilatedVpioModuleIter(it->second))->castVpiHandle());
}
default:
_VL_VPI_WARNING(__FILE__, __LINE__, "%s: Unsupported type %s, nothing will be returned",
VL_FUNC, VerilatedVpiError::strFromVpiObjType(type));
@@ -1154,7 +1223,7 @@ PLI_INT32 vpi_get(PLI_INT32 property, vpiHandle object) {
return VL_TIME_PRECISION;
}
case vpiType: {
VerilatedVpio* vop = VerilatedVpioVar::castp(object);
VerilatedVpio* vop = VerilatedVpio::castp(object);
if (VL_UNLIKELY(!vop)) return 0;
return vop->type();
}
@@ -1203,6 +1272,9 @@ PLI_BYTE8 *vpi_get_str(PLI_INT32 property, vpiHandle object) {
case vpiDefName: {
return (PLI_BYTE8*)vop->defname();
}
case vpiType: {
return (PLI_BYTE8*) VerilatedVpiError::strFromVpiObjType(vop->type());
}
default:
_VL_VPI_WARNING(__FILE__, __LINE__, "%s: Unsupported type %s, nothing will be returned",
VL_FUNC, VerilatedVpiError::strFromVpiProp(property));
@@ -1255,7 +1327,7 @@ void vpi_get_value(vpiHandle object, p_vpi_value value_p) {
return;
case VLVT_WDATA: {
int words = VL_WORDS_I(vop->varp()->packed().elements());
if (VL_UNLIKELY(words >= VL_MULS_MAX_WORDS)) {
if (VL_UNCOVERABLE(words >= VL_MULS_MAX_WORDS)) {
VL_FATAL_MT(__FILE__, __LINE__, "",
"vpi_get_value with more than VL_MULS_MAX_WORDS; increase and recompile");
}
+4 -1
View File
@@ -22,7 +22,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//=========================================================================
#ifndef _VERILATED_VPI_H_
#define _VERILATED_VPI_H_ 1 ///< Header Guard
@@ -45,6 +45,9 @@ public:
/// Call value based callbacks
/// Users should call this from their main loops
static void callValueCbs() VL_MT_UNSAFE_ONE;
/// Call callbacks of arbitrary types
/// Users can call this from their application code
static bool callCbs(vluint32_t reason) VL_MT_UNSAFE_ONE;
/// Self test, for internal use only
static void selfTest() VL_MT_UNSAFE_ONE;
};
+3 -2
View File
@@ -25,7 +25,7 @@
/// Code available from: http://www.veripool.org/verilator
///
//*************************************************************************
#ifndef _VERILATEDOS_H_
#define _VERILATEDOS_H_ 1 ///< Header Guard
@@ -110,6 +110,7 @@
# define VL_LIKELY(x) (!!(x)) ///< Boolean expression more often true than false
# define VL_UNLIKELY(x) (!!(x)) ///< Boolean expression more often false than true
#endif
#define VL_UNCOVERABLE(x) VL_UNLIKELY(x) ///< Boolean expression never hit by users (no coverage)
#ifndef VL_UNREACHABLE
# define VL_UNREACHABLE ///< Point that may never be reached
#endif
@@ -406,4 +407,4 @@ typedef unsigned long long vluint64_t; ///< 64-bit unsigned type
//=========================================================================
#endif /*guard*/
#endif // Guard
-1006
View File
File diff suppressed because it is too large Load Diff
+263
View File
@@ -0,0 +1,263 @@
#!/usr/bin/perl -w
# See copyright, etc in below POD section.
######################################################################
use Cwd;
use File::Copy qw(cp);
use File::Path qw(mkpath);
use Getopt::Long;
use IO::File;
use Pod::Usage;
use strict;
use vars qw($Debug);
our $Exclude_Line_Regexp;
our @Remove_Sources;
our @Source_Globs;
#======================================================================
# main
our $Opt_Stage = 0;
autoflush STDOUT 1;
autoflush STDERR 1;
Getopt::Long::config("no_auto_abbrev");
if (! GetOptions(
"debug" => sub { $Debug = 1; },
"<>" => sub { die "%Error: Unknown parameter: $_[0]\n"; },
"stage=i" => \$Opt_Stage,
)) {
die "%Error: Bad usage, try 'install_test --help'\n";
}
test();
exit(0);
#######################################################################
sub test {
-r "nodist/code_coverage.dat" or die "%Error: Run from the top of the verilator kit,";
require "./nodist/code_coverage.dat";
if ($Opt_Stage <= 0) {
print "Stage 0: configure (coverage on)\n";
run("make distclean");
run("./configure --enable-longtests CXX='g++ --coverage'");
run("make -k");
# 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");
}
if ($Opt_Stage <= 1) {
print "Stage 1: make examples (with coverage on)\n";
run("make examples");
run("make test_regress");
}
my $cc_dir = "nodist/obj_dir/coverage";
if ($Opt_Stage <= 2) {
print "Stage 2: Create info files under $cc_dir\n";
mkpath($cc_dir);
mkpath("$cc_dir/info");
my $dats = `find . -print | grep .gcda`;
my %dirs;
foreach my $dat (split '\n', $dats) {
$dat =~ s!/[^/]+$!!;
$dirs{$dat} = 1;
}
foreach my $dir (sort keys %dirs) {
(my $outname = $dir) =~ s![^a-zA-Z0-9]+!_!g;
run("cd $cc_dir/info ; lcov -c -d ../../../../$dir -o app_test_${outname}.info");
}
}
if ($Opt_Stage <= 3) {
# lcov doesn't have a control file to override single lines, so replicate the sources
print "Stage 3: Clone sources under $cc_dir\n";
clone_sources($cc_dir);
}
if ($Opt_Stage <= 4) {
print "Stage 4: Copy .gcno files\n";
my $dats = `find . -print | grep .gcno`;
foreach my $dat (split '\n', $dats) {
next if $dat =~ /$cc_dir/;
my $outdat = $cc_dir."/".$dat;
#print "cp $dat, $outdat);\n";
cp($dat, $outdat);
}
}
if ($Opt_Stage <= 5) {
print "Stage 5: Combine data files\n";
run("cd $cc_dir ; lcov -c -i -d src/obj_dbg -o app_base.info");
run("cd $cc_dir ; lcov -a app_base.info -o app_total.info");
my $infos = `cd $cc_dir ; find info -print | grep .info`;
my $comb = "";
my @infos = (split /\n/, $infos);
foreach my $info (@infos) {
$comb .= " -a $info";
# Need to batch them to avoid overrunning shell command length limit
if (length($comb) > 10000 || $info eq $infos[$#infos]) {
run("cd $cc_dir ; lcov -a app_total.info $comb -o app_total.info");
$comb = "";
}
}
}
if ($Opt_Stage <= 6) {
print "Stage 6: Filter processed source files\n";
my $cmd = '';
foreach my $glob (@Remove_Sources) {
$cmd .= " '$glob'";
}
run("cd $cc_dir ; lcov --remove app_total.info $cmd -o app_total.info");
}
if ($Opt_Stage <= 7) {
print "Stage 7: Create HTML\n";
cleanup_abs_paths($cc_dir, "$cc_dir/app_total.info", "$cc_dir/app_total.info");
run("cd $cc_dir ; genhtml app_total.info --demangle-cpp"
." --rc lcov_branch_coverage=1 --rc genhtml_hi_limit=100 --output-directory html");
}
if ($Opt_Stage <= 9) {
print "*-* All Finished *-*\n";
}
}
sub clone_sources {
my $cc_dir = shift;
my $excluded_lines = 0;
foreach my $glob (@Source_Globs) {
foreach my $infile (glob $glob) {
$infile !~ m!^/!
or die "%Error: source globs should be relative not absolute filenames,";
my $outfile = $cc_dir."/".$infile;
(my $outpath = $outfile) =~ s!/[^/]*$!!;
mkpath($outpath);
my $fh = IO::File->new("<$infile") or die "%Error: $! $infile,";
my $ofh = IO::File->new(">$outfile") or die "%Error: $! $outfile,";
my $lineno = 0;
while (defined(my $line = $fh->getline)) {
$lineno++;
chomp $line;
if ($line !~ m!// LCOV_EXCL_LINE!
&& $line =~ /$Exclude_Line_Regexp/) {
$line .= " //code_coverage: // LCOV_EXCL_LINE";
$excluded_lines++;
#print "$infile:$lineno: $line";
} else {
}
$ofh->print("$line\n");
}
}
}
print "Source code lines automatically LCOV_EXCL_LINE'ed: $excluded_lines\n";
}
sub cleanup_abs_paths {
my $cc_dir = shift;
my $infile = shift;
my $outfile = shift;
my $fh = IO::File->new("<$infile") or die "%Error: $! $infile,";
my @lines;
while (defined(my $line = $fh->getline)) {
if ($line =~ m!^SF:!) {
$line =~ s!$ENV{VERILATOR_ROOT}/!!;
$line =~ s!$cc_dir/!!;
$line =~ s!obj_dbg/verilog.y$!verilog.y!;
#print "Remaining SF: ",$line;
}
push @lines, $line;
}
my $ofh = IO::File->new(">$outfile") or die "%Error: $! $outfile,";
$ofh->print(@lines);
}
#######################################################################
# .dat file callbacks
sub exclude_line_regexp {
$Exclude_Line_Regexp = shift;
}
sub remove_source {
my @srcs = @_;
push @Remove_Sources, @srcs;
}
sub source_globs {
my @dirs = @_;
push @Source_Globs, @dirs;
}
#######################################################################
sub run {
# Run a system command, check errors
my $command = shift;
print "\t$command\n";
system "$command";
my $status = $?;
($status == 0) or die "%Error: Command Failed $command, $status, stopped";
}
#######################################################################
__END__
=pod
=head1 NAME
code_coverage - Build and collect Verilator coverage
=head1 SYNOPSIS
cd $VERILATOR_ROOT
nodist/code_coverage
=head1 DESCRIPTION
code_coverage builds Verilator with C++ coverage support and runs tests
with coverage enabled.
This will rebuild the current object files.
=head1 ARGUMENTS
=over 4
=item --help
Displays this message and program version and exits.
=item -stage I<stage>
Runs a specific stage (see the script).
=back
=head1 DISTRIBUTION
Copyright 2019-2019 by Wilson Snyder. This package 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.
=head1 AUTHORS
Wilson Snyder <[email protected]>
=head1 SEE ALSO
C<lcov>
=cut
######################################################################
### Local Variables:
### compile-command: "cd .. ; nodist/code_coverage "
### End:
+42
View File
@@ -0,0 +1,42 @@
# -*- Perl -*-
# DESCRIPTION: Verilator: Internal C++ code lcov control file
#
# Copyright 2019-2019 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.
source_globs("src/*.cpp",
"src/*.h",
"src/*.l",
"src/*.y",
"src/obj_dbg/*.h",
"src/obj_dbg/*.cpp",
"include/*.c",
"include/*.cpp",
"include/*.h",
"include/*/*.h",
"include/*/*.cpp",
"include/*/*.c",
);
remove_source("/usr/include/*");
remove_source("*/include/sysc/*");
remove_source("*/V3ClkGater.cpp");
remove_source("*/V3ClkGater.h");
remove_source("*/V3GraphDfa.cpp");
remove_source("*/V3GraphDfa.h");
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/*");
exclude_line_regexp(qr/(\bv3fatalSrc\b|\bVL_UNCOVERABLE\b)/);
1;
+2 -2
View File
@@ -38,8 +38,8 @@ cwrite("graph_export.cpp");
#----------------------------------------------------------------------
sub usage {
pod2usage(-verbose=>2, -exitval=>2, -output=>\*STDOUT);
exit(1);
pod2usage(-verbose=>2, -exitval=>0, -output=>\*STDOUT);
exit(1); # Unreachable
}
sub debug {
+2 -2
View File
@@ -43,8 +43,8 @@ dotwrite();
#----------------------------------------------------------------------
sub usage {
pod2usage(-verbose=>2, -exitval=>2, -output=>\*STDOUT);
exit(1);
pod2usage(-verbose=>2, -exitval=>0, -output=>\*STDOUT);
exit(1); # Unreachable
}
sub debug {
+3 -2
View File
@@ -22,7 +22,8 @@ Getopt::Long::config("no_auto_abbrev");
if (! GetOptions (
"debug" => sub { $Debug = 1; },
"help" => sub { print "Version $VERSION\n";
pod2usage(-verbose=>2, -exitval => 2, output=>\*STDOUT, -noperldoc=>1); },
pod2usage(-verbose=>2, -exitval => 0,
output=>\*STDOUT, -noperldoc=>1); },
"narrow!" => sub { $Opt_Widen = 0; },
"version" => sub { print "Version $VERSION\n"; exit(0); },
"widen!" => sub { $Opt_Widen = 1; }, # Default, undocumented
@@ -132,7 +133,7 @@ sub edit_file {
foreach my $lineno (sort {$a <=> $b} keys %$editlines) {
push @editits, $lineno if $editlines->{$lineno}{editit};
}
return if $#editits < 0;
if (ignore($filename)) {
print "%Warning: Ignoring $filename\n";
+2 -2
View File
@@ -40,8 +40,8 @@ print '(query-replace-regexp "(\\([0-9a-z_]+\\))" "\\1" nil nil nil)',"\n";
#----------------------------------------------------------------------
sub usage {
pod2usage(-verbose=>2, -exitval=>2, -output=>\*STDOUT);
exit(1);
pod2usage(-verbose=>2, -exitval=>0, -output=>\*STDOUT);
exit(1); # Unreachable
}
sub debug {
+9 -8
View File
@@ -60,6 +60,8 @@ pkgdatadir = @pkgdatadir@
CFG_WITH_CCWARN = @CFG_WITH_CCWARN@
CFG_WITH_DEFENV = @CFG_WITH_DEFENV@
CPPFLAGS += @CPPFLAGS@
CFLAGS += @CFLAGS@
CXXFLAGS += @CXXFLAGS@
LDFLAGS += @LDFLAGS@
EXEEXT = @EXEEXT@
CFG_CXXFLAGS_SRC = @CFG_CXXFLAGS_SRC@
@@ -135,7 +137,7 @@ VLCOVGEN = $(srcdir)/vlcovgen
all: make_info $(TGT)
make_info:
@echo " Compile flags: " $(CXX) ${CPPFLAGS}
@echo " Compile flags: " $(CXX) ${CFLAGS} ${CXXFLAGS} ${CPPFLAGS}
clean mostlyclean distclean maintainer-clean::
-rm -f *.o *.d perlxsi.c *_gen_*
@@ -167,7 +169,6 @@ RAW_OBJS = \
V3Cdc.o \
V3Changed.o \
V3Clean.o \
V3ClkGater.o \
V3Clock.o \
V3Combine.o \
V3Config.o \
@@ -280,21 +281,21 @@ V3Number_test: V3Number_test.o
$(PERL) $(ASTGEN) -I$(srcdir) $*.cpp
%.o: %.cpp
$(OBJCACHE) ${CXX} ${CPPFLAGSWALL} -c $<
$(OBJCACHE) ${CXX} ${CXXFLAGS} ${CPPFLAGSWALL} -c $<
%.o: %.c
$(OBJCACHE) ${CC} ${CPPFLAGSWALL} -c $<
$(OBJCACHE) ${CC} ${CFLAGS} ${CPPFLAGSWALL} -c $<
V3ParseLex.o: V3ParseLex.cpp V3Lexer.yy.cpp V3ParseBison.c
$(OBJCACHE) ${CXX} ${CPPFLAGSPARSER} -c $<
$(OBJCACHE) ${CXX} ${CXXFLAGS} ${CPPFLAGSPARSER} -c $<
V3ParseGrammar.o: V3ParseGrammar.cpp V3ParseBison.c
$(OBJCACHE) ${CXX} ${CPPFLAGSPARSER} -c $<
$(OBJCACHE) ${CXX} ${CXXFLAGS} ${CPPFLAGSPARSER} -c $<
V3ParseImp.o: V3ParseImp.cpp V3ParseBison.c
$(OBJCACHE) ${CXX} ${CPPFLAGSPARSER} -c $<
$(OBJCACHE) ${CXX} ${CXXFLAGS} ${CPPFLAGSPARSER} -c $<
V3PreProc.o: V3PreProc.cpp V3PreLex.yy.cpp
$(OBJCACHE) ${CXX} ${CPPFLAGSPARSER} -c $<
$(OBJCACHE) ${CXX} ${CXXFLAGS} ${CPPFLAGSPARSER} -c $<
#### Generated files
+24 -24
View File
@@ -29,7 +29,7 @@
// WIRE: Move into SACTIVE(combo)
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -66,7 +66,7 @@ private:
// METHODS
void addActive(AstActive* nodep) {
if (!m_scopep) nodep->v3fatalSrc("NULL scope");
UASSERT_OBJ(m_scopep, nodep, "NULL scope");
m_scopep->addActivep(nodep);
}
// VISITORS
@@ -140,7 +140,7 @@ public:
return activep;
}
public:
// CONSTUCTORS
// CONSTRUCTORS
ActiveNamer() {
m_scopep = NULL;
m_iActivep = NULL;
@@ -168,13 +168,14 @@ private:
// Convert to a non-delayed assignment
UINFO(5," ASSIGNDLY "<<nodep<<endl);
if (m_check == CT_INITIAL) {
nodep->v3warn(INITIALDLY, "Delayed assignments (<=) in initial"
" or final block; suggest blocking assignments (=).");
nodep->v3warn(INITIALDLY, "Delayed assignments (<=) in initial or final block\n"
<<nodep->warnMore()<<"... Suggest blocking assignments (=)");
} else if (m_check == CT_LATCH) {
// Suppress. Shouldn't matter that the interior of the latch races
} else {
nodep->v3warn(COMBDLY, "Delayed assignments (<=) in non-clocked"
" (non flop or latch) block; suggest blocking assignments (=).");
" (non flop or latch) block\n"
<<nodep->warnMore()<<"... Suggest blocking assignments (=)");
}
AstNode* newp = new AstAssign(nodep->fileline(),
nodep->lhsp()->unlinkFrBack(),
@@ -195,17 +196,16 @@ private:
AstVar* varp = nodep->varp();
if (m_check == CT_SEQ
&& m_assignp
&& !varp->isUsedLoopIdx() // Ignore loop indicies
&& !varp->isTemp()
) {
&& !varp->isUsedLoopIdx() // Ignore loop indices
&& !varp->isTemp()) {
// Allow turning off warnings on the always, or the variable also
if (!m_alwaysp->fileline()->warnIsOff(V3ErrorCode::BLKSEQ)
&& !m_assignp->fileline()->warnIsOff(V3ErrorCode::BLKSEQ)
&& !varp->fileline()->warnIsOff(V3ErrorCode::BLKSEQ)
) {
&& !varp->fileline()->warnIsOff(V3ErrorCode::BLKSEQ)) {
m_assignp->v3warn(BLKSEQ, "Blocking assignments (=) in sequential (flop or latch) block\n"
<<m_assignp->warnMore()<<"... Suggest delayed assignments (<=)");
m_alwaysp->fileline()->modifyWarnOff(V3ErrorCode::BLKSEQ, true); // Complain just once for the entire always
varp->fileline()->modifyWarnOff(V3ErrorCode::BLKSEQ, true);
nodep->v3warn(BLKSEQ, "Blocking assignments (=) in sequential (flop or latch) block; suggest delayed assignments (<=).");
}
}
}
@@ -214,7 +214,7 @@ private:
iterateChildren(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
ActiveDlyVisitor(AstNode* nodep, CheckType check) {
m_alwaysp = nodep;
m_check = check;
@@ -301,7 +301,7 @@ private:
m_namer.scopep()->addActivep(m_scopeFinalp);
}
nodep->unlinkFrBack();
m_scopeFinalp->addStmtsp(new AstComment(nodep->fileline(), nodep->typeName()));
m_scopeFinalp->addStmtsp(new AstComment(nodep->fileline(), nodep->typeName(), true));
m_scopeFinalp->addStmtsp(nodep->bodysp()->unlinkFrBackWithNext());
nodep->deleteTree(); VL_DANGLING(nodep);
}
@@ -314,12 +314,13 @@ private:
&& VN_IS(oldsensesp->sensesp(), SenItem)
&& VN_CAST(oldsensesp->sensesp(), SenItem)->isNever()) {
// Never executing. Kill it.
if (oldsensesp->sensesp()->nextp()) nodep->v3fatalSrc("Never senitem should be alone, else the never should be eliminated.");
UASSERT_OBJ(!oldsensesp->sensesp()->nextp(), nodep,
"Never senitem should be alone, else the never should be eliminated.");
nodep->unlinkFrBack()->deleteTree(); VL_DANGLING(nodep);
return;
}
// Read sensitivitues
// Read sensitivities
m_itemCombo = false;
m_itemSequent = false;
iterateAndNextNull(oldsensesp);
@@ -391,15 +392,14 @@ private:
}
virtual void visit(AstSenGate* nodep) {
AstSenItem* subitemp = nodep->sensesp();
if (subitemp->edgeType() != AstEdgeType::ET_ANYEDGE
&& subitemp->edgeType() != AstEdgeType::ET_POSEDGE
&& subitemp->edgeType() != AstEdgeType::ET_NEGEDGE) {
nodep->v3fatalSrc("Strange activity type under SenGate");
}
UASSERT_OBJ(subitemp->edgeType() == VEdgeType::ET_ANYEDGE
|| subitemp->edgeType() == VEdgeType::ET_POSEDGE
|| subitemp->edgeType() == VEdgeType::ET_NEGEDGE,
nodep, "Strange activity type under SenGate");
iterateChildren(nodep);
}
virtual void visit(AstSenItem* nodep) {
if (nodep->edgeType() == AstEdgeType::ET_ANYEDGE) {
if (nodep->edgeType() == VEdgeType::ET_ANYEDGE) {
m_itemCombo = true;
// Delete the sensitivity
// We'll add it as a generic COMBO SenItem in a moment.
@@ -408,7 +408,7 @@ private:
// V3LinkResolve should have cleaned most of these up
if (!nodep->varrefp()->width1()) {
nodep->v3error("Unsupported: Non-single bit wide signal pos/negedge sensitivity: "
<<nodep->varrefp()->prettyName());
<<nodep->varrefp()->prettyNameQ());
}
m_itemSequent = true;
nodep->varrefp()->varp()->usedClock(true);
@@ -423,7 +423,7 @@ private:
iterateChildren(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit ActiveVisitor(AstNetlist* nodep) {
m_scopeFinalp = NULL;
m_itemCombo = false;
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3ACTIVE_H_
#define _V3ACTIVE_H_ 1
+13 -15
View File
@@ -26,7 +26,7 @@
// Move SenTree the global SenTree
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -72,14 +72,13 @@ private:
UINFO(4," ACTIVE "<<nodep<<endl);
V3Const::constifyExpensiveEdit(nodep); // Remove duplicate clocks and such; sensesp() may change!
AstSenTree* sensesp = nodep->sensesp();
if (!sensesp) nodep->v3fatalSrc("NULL");
UASSERT_OBJ(sensesp, nodep, "NULL");
if (sensesp->sensesp()
&& VN_IS(sensesp->sensesp(), SenItem)
&& VN_CAST(sensesp->sensesp(), SenItem)->isNever()) {
// Never executing. Kill it.
if (sensesp->sensesp()->nextp()) {
nodep->v3fatalSrc("Never senitem should be alone, else the never should be eliminated.");
}
UASSERT_OBJ(!sensesp->sensesp()->nextp(), nodep,
"Never senitem should be alone, else the never should be eliminated.");
nodep->unlinkFrBack()->deleteTree(); VL_DANGLING(nodep);
return;
}
@@ -101,9 +100,8 @@ private:
// Move the active's contents to the other active
UINFO(4," merge active "<<sensesp<<" into "<<wantp<<endl);
if (nodep->sensesStorep()) {
if (sensesp != nodep->sensesStorep()) {
nodep->v3fatalSrc("sensesStore should have been deleted earlier if different");
}
UASSERT_OBJ(sensesp == nodep->sensesStorep(), nodep,
"sensesStore should have been deleted earlier if different");
sensesp->unlinkFrBack();
// There may be other references to same sense tree,
// we'll be removing all references when we get to them,
@@ -115,22 +113,22 @@ private:
// No need to do statements under it, they're already moved.
//iterateChildren(nodep);
}
virtual void visit(AstInitial* nodep) {
virtual void visit(AstInitial* nodep) { // LCOV_EXCL_LINE
nodep->v3fatalSrc("Node should have been under ACTIVE");
}
virtual void visit(AstAssignAlias* nodep) {
virtual void visit(AstAssignAlias* nodep) { // LCOV_EXCL_LINE
nodep->v3fatalSrc("Node should have been under ACTIVE");
}
virtual void visit(AstAssignW* nodep) {
virtual void visit(AstAssignW* nodep) { // LCOV_EXCL_LINE
nodep->v3fatalSrc("Node should have been under ACTIVE");
}
virtual void visit(AstAlways* nodep) {
virtual void visit(AstAlways* nodep) { // LCOV_EXCL_LINE
nodep->v3fatalSrc("Node should have been under ACTIVE");
}
virtual void visit(AstAlwaysPublic* nodep) {
virtual void visit(AstAlwaysPublic* nodep) { // LCOV_EXCL_LINE
nodep->v3fatalSrc("Node should have been under ACTIVE");
}
virtual void visit(AstFinal* nodep) {
virtual void visit(AstFinal* nodep) { // LCOV_EXCL_LINE
nodep->v3fatalSrc("Node should have been deleted");
}
// Empty visitors, speed things up
@@ -141,7 +139,7 @@ private:
iterateChildren(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit ActiveTopVisitor(AstNetlist* nodep) {
m_topscopep = NULL;
iterate(nodep);
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3ACTIVETOP_H_
#define _V3ACTIVETOP_H_ 1
+13 -12
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -44,10 +44,10 @@ private:
AstNodeModule* m_modp; // Last module
AstBegin* m_beginp; // Last begin
unsigned m_modPastNum; // Module past numbering
V3Double0 m_statAsCover; // Statistic tracking
V3Double0 m_statAsPsl; // Statistic tracking
V3Double0 m_statAsFull; // Statistic tracking
V3Double0 m_statAsSV; // Statistic tracking
VDouble0 m_statAsCover; // Statistic tracking
VDouble0 m_statAsPsl; // Statistic tracking
VDouble0 m_statAsFull; // Statistic tracking
VDouble0 m_statAsSV; // Statistic tracking
// METHODS
string assertDisplayMessage(AstNode* nodep, const string& prefix, const string& message) {
@@ -120,7 +120,7 @@ private:
} else {
// V3Coverage assigned us a bucket to increment.
AstCoverInc* covincp = VN_CAST(snodep->coverincp(), CoverInc);
if (!covincp) snodep->v3fatalSrc("Missing AstCoverInc under assertion");
UASSERT_OBJ(covincp, snodep, "Missing AstCoverInc under assertion");
covincp->unlinkFrBack();
if (message!="") covincp->declp()->comment(message);
bodysp = covincp;
@@ -143,7 +143,7 @@ private:
ifp = new AstIf(nodep->fileline(), propp, NULL, stmtsp);
// It's more LIKELY that we'll take the NULL if clause
// than the sim-killing else clause:
ifp->branchPred(AstBranchPred::BP_LIKELY);
ifp->branchPred(VBranchPred::BP_LIKELY);
bodysp = newIfAssertOn(ifp);
} else if (VN_IS(nodep, PslRestrict)) {
// IEEE says simulator ignores these
@@ -182,7 +182,7 @@ private:
AstIf* ifp = new AstIf(nodep->fileline(), propp, passsp, failsp);
AstNode* newp = ifp;
if (VN_IS(nodep, VAssert)) ifp->branchPred(AstBranchPred::BP_UNLIKELY);
if (VN_IS(nodep, VAssert)) ifp->branchPred(VBranchPred::BP_UNLIKELY);
//
// Install it
nodep->replaceWith(newp);
@@ -242,7 +242,7 @@ private:
new AstLogNot(nodep->fileline(), ohot),
newFireAssert(nodep, "'unique if' statement violated"),
newifp);
checkifp->branchPred(AstBranchPred::BP_UNLIKELY);
checkifp->branchPred(VBranchPred::BP_UNLIKELY);
nodep->replaceWith(checkifp);
pushDeletep(nodep);
} else {
@@ -305,7 +305,7 @@ private:
new AstLogNot(nodep->fileline(), ohot),
newFireAssert(nodep, "synthesis parallel_case, but multiple matches found"),
NULL);
ifp->branchPred(AstBranchPred::BP_UNLIKELY);
ifp->branchPred(VBranchPred::BP_UNLIKELY);
nodep->addNotParallelp(ifp);
}
}
@@ -317,10 +317,11 @@ private:
iterateChildren(nodep);
uint32_t ticks = 1;
if (nodep->ticksp()) {
if (!VN_IS(nodep->ticksp(), Const)) nodep->v3fatalSrc("Expected constant ticks, checked in V3Width");
UASSERT_OBJ(VN_IS(nodep->ticksp(), Const), nodep,
"Expected constant ticks, checked in V3Width");
ticks = VN_CAST(nodep->ticksp(), Const)->toUInt();
}
if (ticks<1) nodep->v3fatalSrc("0 tick should have been checked in V3Width");
UASSERT_OBJ(ticks>=1, nodep, "0 tick should have been checked in V3Width");
AstNode* inp = nodep->exprp()->unlinkFrBack();
AstVar* invarp = NULL;
AstSenTree* sentreep = nodep->sentreep(); sentreep->unlinkFrBack();
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3ASSERT_H_
#define _V3ASSERT_H_ 1
+2 -2
View File
@@ -20,7 +20,7 @@
// Pre steps:
// Attach clocks to each assertion
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -95,7 +95,7 @@ private:
virtual void visit(AstNodePslCoverOrAssert* nodep) {
if (nodep->sentreep()) return; // Already processed
clearAssertInfo();
// Find PslClocking's burried under nodep->exprsp
// Find PslClocking's buried under nodep->exprsp
iterateChildren(nodep);
nodep->sentreep(newSenTree(nodep));
clearAssertInfo();
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3ASSERTPRE_H_
#define _V3ASSERTPRE_H_ 1
+97 -53
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -113,7 +113,8 @@ string AstNode::encodeName(const string& namein) {
// a user identifier nor a temp we create in Verilator.
// We also do *NOT* use __DOT__ etc, as we search for those
// in some replacements, and don't want to mangle the user's names.
char hex[10]; sprintf(hex, "__0%02X", pos[0]);
unsigned val = pos[0] & 0xff; // Mask to avoid sign extension
char hex[10]; sprintf(hex, "__0%02X", val);
out += hex;
}
}
@@ -248,7 +249,7 @@ inline void AstNode::debugTreeChange(const char* prefix, int lineno, bool next)
AstNode* AstNode::addNext(AstNode* nodep, AstNode* newp) {
// Add to m_nextp, returns this
UDEBUGONLY(if (!newp) nodep->v3fatalSrc("Null item passed to addNext"););
UDEBUGONLY(UASSERT_OBJ(newp, nodep, "Null item passed to addNext"););
nodep->debugTreeChange("-addNextThs: ", __LINE__, false);
newp->debugTreeChange("-addNextNew: ", __LINE__, true);
if (!nodep) { // verilog.y and lots of other places assume this
@@ -259,9 +260,10 @@ AstNode* AstNode::addNext(AstNode* nodep, AstNode* newp) {
if (oldtailp->m_nextp) {
if (oldtailp->m_headtailp) {
oldtailp = oldtailp->m_headtailp; // This=beginning of list, jump to end
UDEBUGONLY(if (oldtailp->m_nextp) nodep->v3fatalSrc("Node had next, but headtail says it shouldn't"););
UDEBUGONLY(UASSERT_OBJ(!oldtailp->m_nextp, nodep,
"Node had next, but headtail says it shouldn't"););
} else {
// Though inefficent, we are occasionally passed a addNext in the middle of a list.
// Though inefficient, we are occasionally passed a addNext in the middle of a list.
while (oldtailp->m_nextp != NULL) oldtailp = oldtailp->m_nextp;
}
}
@@ -337,9 +339,9 @@ void AstNode::addNextHere(AstNode* newp) {
void AstNode::setOp1p(AstNode* newp) {
UASSERT(newp, "Null item passed to setOp1p");
UDEBUGONLY(if (m_op1p) this->v3fatalSrc("Adding to non-empty, non-list op1"););
UDEBUGONLY(if (newp->m_backp) newp->v3fatalSrc("Adding already linked node"););
UDEBUGONLY(if (newp->m_nextp) newp->v3fatalSrc("Adding list to non-list op1"););
UDEBUGONLY(UASSERT_OBJ(!m_op1p, this, "Adding to non-empty, non-list op1"););
UDEBUGONLY(UASSERT_OBJ(!newp->m_backp, newp, "Adding already linked node"););
UDEBUGONLY(UASSERT_OBJ(!newp->m_nextp, newp, "Adding list to non-list op1"););
this->debugTreeChange("-setOp1pThs: ", __LINE__, false);
newp->debugTreeChange("-setOp1pNew: ", __LINE__, true);
m_op1p = newp;
@@ -350,9 +352,9 @@ void AstNode::setOp1p(AstNode* newp) {
void AstNode::setOp2p(AstNode* newp) {
UASSERT(newp, "Null item passed to setOp2p");
UDEBUGONLY(if (m_op2p) this->v3fatalSrc("Adding to non-empty, non-list op2"););
UDEBUGONLY(if (newp->m_backp) newp->v3fatalSrc("Adding already linked node"););
UDEBUGONLY(if (newp->m_nextp) newp->v3fatalSrc("Adding list to non-list op2"););
UDEBUGONLY(UASSERT_OBJ(!m_op2p, this, "Adding to non-empty, non-list op2"););
UDEBUGONLY(UASSERT_OBJ(!newp->m_backp, newp, "Adding already linked node"););
UDEBUGONLY(UASSERT_OBJ(!newp->m_nextp, newp, "Adding list to non-list op2"););
this->debugTreeChange("-setOp2pThs: ", __LINE__, false);
newp->debugTreeChange("-setOp2pNew: ", __LINE__, true);
m_op2p = newp;
@@ -363,9 +365,9 @@ void AstNode::setOp2p(AstNode* newp) {
void AstNode::setOp3p(AstNode* newp) {
UASSERT(newp, "Null item passed to setOp3p");
UDEBUGONLY(if (m_op3p) this->v3fatalSrc("Adding to non-empty, non-list op3"););
UDEBUGONLY(if (newp->m_backp) newp->v3fatalSrc("Adding already linked node"););
UDEBUGONLY(if (newp->m_nextp) newp->v3fatalSrc("Adding list to non-list op3"););
UDEBUGONLY(UASSERT_OBJ(!m_op3p, this, "Adding to non-empty, non-list op3"););
UDEBUGONLY(UASSERT_OBJ(!newp->m_backp, newp, "Adding already linked node"););
UDEBUGONLY(UASSERT_OBJ(!newp->m_nextp, newp, "Adding list to non-list op3"););
this->debugTreeChange("-setOp3pThs: ", __LINE__, false);
newp->debugTreeChange("-setOp3pNew: ", __LINE__, true);
m_op3p = newp;
@@ -376,9 +378,9 @@ void AstNode::setOp3p(AstNode* newp) {
void AstNode::setOp4p(AstNode* newp) {
UASSERT(newp, "Null item passed to setOp4p");
UDEBUGONLY(if (m_op4p) this->v3fatalSrc("Adding to non-empty, non-list op4"););
UDEBUGONLY(if (newp->m_backp) newp->v3fatalSrc("Adding already linked node"););
UDEBUGONLY(if (newp->m_nextp) newp->v3fatalSrc("Adding list to non-list op4"););
UDEBUGONLY(UASSERT_OBJ(!m_op4p, this, "Adding to non-empty, non-list op4"););
UDEBUGONLY(UASSERT_OBJ(!newp->m_backp, newp, "Adding already linked node"););
UDEBUGONLY(UASSERT_OBJ(!newp->m_nextp, newp, "Adding list to non-list op4"););
this->debugTreeChange("-setOp4pThs: ", __LINE__, false);
newp->debugTreeChange("-setOp4pNew: ", __LINE__, true);
m_op4p = newp;
@@ -580,9 +582,11 @@ void AstNode::relinkOneLink(AstNode*& pointpr, // Ref to pointer that gets set
// Insert the whole old list following the new node's list.
// Thus a unlink without next, followed by relink, gives the same list.
AstNode* newlistlastp = newp->m_headtailp;
if (newlistlastp->m_nextp && newlistlastp!=newp) newp->v3fatalSrc("Headtailp tail isn't at the tail");
UASSERT_OBJ(!(newlistlastp->m_nextp && newlistlastp!=newp), newp,
"Headtailp tail isn't at the tail");
AstNode* oldlistlastp = pointpr->m_headtailp;
if (oldlistlastp->m_nextp && oldlistlastp!=pointpr) newp->v3fatalSrc("Old headtailp tail isn't at the tail");
UASSERT_OBJ(!(oldlistlastp->m_nextp && oldlistlastp!=pointpr), newp,
"Old headtailp tail isn't at the tail");
// Next links
newlistlastp->m_nextp = pointpr;
pointpr->m_backp = newlistlastp;
@@ -772,14 +776,15 @@ void AstNode::iterateAndNext(AstNVisitor& v) {
// there's no lower level reason yet though the back must exist.
AstNode* nodep = this;
#ifdef VL_DEBUG // Otherwise too hot of a function for debug
if (VL_UNLIKELY(nodep && !nodep->m_backp)) nodep->v3fatalSrc("iterateAndNext node has no back");
UASSERT_OBJ(!(nodep && !nodep->m_backp), nodep,
"iterateAndNext node has no back");
#endif
if (nodep) ASTNODE_PREFETCH(nodep->m_nextp);
while (nodep) { // effectively: if (!this) return; // Callers rely on this
if (nodep->m_nextp) ASTNODE_PREFETCH(nodep->m_nextp->m_nextp);
AstNode* niterp = nodep; // This address may get stomped via m_iterpp if the node is edited
// Desirable check, but many places where multiple iterations are OK
//if (VL_UNLIKELY(niterp->m_iterpp)) niterp->v3fatalSrc("IterateAndNext under iterateAndNext may miss edits");
// UASSERT_OBJ(!niterp->m_iterpp, niterp, "IterateAndNext under iterateAndNext may miss edits");
// Optimization note: Doing PREFETCH_RW on m_iterpp is a net even
// cppcheck-suppress nullPointer
niterp->m_iterpp = &niterp;
@@ -856,7 +861,7 @@ AstNode* AstNode::iterateSubtreeReturnEdits(AstNVisitor& v) {
else if (this->m_backp->m_op3p == this) nextnodepp = &(this->m_backp->m_op3p);
else if (this->m_backp->m_op4p == this) nextnodepp = &(this->m_backp->m_op4p);
else if (this->m_backp->m_nextp == this) nextnodepp = &(this->m_backp->m_nextp);
if (!nextnodepp) this->v3fatalSrc("Node's back doesn't point to forward to node itself");
UASSERT_OBJ(nextnodepp, this, "Node's back doesn't point to forward to node itself");
{
nodep->accept(v); VL_DANGLING(nodep); // nodep to null as may be replaced
}
@@ -934,13 +939,11 @@ V3Hash::V3Hash(const string& name) {
void AstNode::checkTreeIter(AstNode* backp) {
// private: Check a tree and children
if (backp != this->backp()) {
this->v3fatalSrc("Back node inconsistent");
}
UASSERT_OBJ(backp == this->backp(), this, "Back node inconsistent");
if (VN_IS(this, NodeTermop) || VN_IS(this, NodeVarRef)) {
// Termops have a short-circuited iterateChildren, so check usage
if (op1p()||op2p()||op3p()||op4p())
this->v3fatalSrc("Terminal operation with non-terminals");
UASSERT_OBJ(!(op1p()||op2p()||op3p()||op4p()), this,
"Terminal operation with non-terminals");
}
if (m_op1p) m_op1p->checkTreeIterList(this);
if (m_op2p) m_op2p->checkTreeIterList(this);
@@ -955,12 +958,13 @@ void AstNode::checkTreeIterList(AstNode* backp) {
AstNode* tailp = this;
for (AstNode* nodep=headp; nodep; nodep=nodep->nextp()) {
nodep->checkTreeIter(backp);
if (headp!=this && nextp()) this->v3fatalSrc("Headtailp should be null in middle of lists");
UASSERT_OBJ(headp==this || !nextp(), this,
"Headtailp should be null in middle of lists");
tailp = nodep;
backp = nodep;
}
if (headp->m_headtailp != tailp) headp->v3fatalSrc("Tail in headtailp is inconsistent");
if (tailp->m_headtailp != headp) tailp->v3fatalSrc("Head in headtailp is inconsistent");
UASSERT_OBJ(headp->m_headtailp == tailp, headp, "Tail in headtailp is inconsistent");
UASSERT_OBJ(tailp->m_headtailp == headp, tailp, "Head in headtailp is inconsistent");
}
void AstNode::checkTree() {
@@ -973,23 +977,28 @@ void AstNode::checkTree() {
}
}
void AstNode::dumpGdb() { // For GDB only
dumpGdbHeader();
cout<<" "; dump(cout); cout<<endl;
// cppcheck-suppress unusedFunction // Debug only
void AstNode::dumpGdb() { // For GDB only // LCOV_EXCL_LINE
dumpGdbHeader(); // LCOV_EXCL_LINE
cout<<" "; dump(cout); cout<<endl; // LCOV_EXCL_LINE
}
void AstNode::dumpGdbHeader() const { // For GDB only
dumpPtrs(cout);
cout<<" Fileline = "<<fileline()<<endl;
// cppcheck-suppress unusedFunction // Debug only
void AstNode::dumpGdbHeader() const { // For GDB only // LCOV_EXCL_LINE
dumpPtrs(cout); // LCOV_EXCL_LINE
cout<<" Fileline = "<<fileline()<<endl; // LCOV_EXCL_LINE
}
void AstNode::dumpTreeGdb() { // For GDB only
dumpGdbHeader();
dumpTree(cout);
// cppcheck-suppress unusedFunction // Debug only
void AstNode::dumpTreeGdb() { // For GDB only // LCOV_EXCL_LINE
dumpGdbHeader(); // LCOV_EXCL_LINE
dumpTree(cout); // LCOV_EXCL_LINE
}
void AstNode::dumpTreeFileGdb(const char* filenamep) { // For GDB only
string filename = filenamep ? filenamep : v3Global.debugFilename("debug.tree", 98);
v3Global.rootp()->dumpTreeFile(filename);
// cppcheck-suppress unusedFunction // Debug only
void AstNode::dumpTreeFileGdb(const char* filenamep) { // For GDB only // LCOV_EXCL_LINE
string filename = filenamep ? filenamep : v3Global.debugFilename("debug.tree", 98); // LCOV_EXCL_LINE
v3Global.rootp()->dumpTreeFile(filename); // LCOV_EXCL_LINE
}
// cppcheck-suppress unusedFunction // Debug only
void AstNode::checkIter() const {
if (m_iterpp) {
dumpPtrs(cout);
@@ -1021,8 +1030,12 @@ void AstNode::dumpPtrs(std::ostream& os) const {
}
void AstNode::dumpTree(std::ostream& os, const string& indent, int maxDepth) {
static int s_debugFileline = v3Global.opt.debugSrcLevel("fileline"); // --debugi-fileline 9
os<<indent<<" "<<this<<endl;
if (debug()>8) { os<<indent<<" "; dumpPtrs(os); }
if (s_debugFileline >= 9) {
os<<fileline()->warnContextSecondary();
}
if (maxDepth==1) {
if (op1p()||op2p()||op3p()||op4p()) { os<<indent<<"1: ...(maxDepth)"<<endl; }
} else {
@@ -1076,9 +1089,43 @@ void AstNode::v3errorEndFatal(std::ostringstream& str) const {
v3errorEnd(str); assert(0); VL_UNREACHABLE
}
string AstNode::locationStr() const {
string str = "... In instance ";
const AstNode* backp = this;
while (backp) {
const AstScope* scopep;
if ((scopep = VN_CAST_CONST(backp, Scope))) {
// The design is flattened and there are no useful scopes
// This is probably because of inlining
if (scopep->isTop()) break;
str += scopep->prettyName();
return str;
}
backp = backp->backp();
}
backp = this;
while (backp) {
const AstModule* modp;
const AstNodeVarRef* nvrp;
if ((modp = VN_CAST_CONST(backp, Module)) && !modp->hierName().empty()) {
str += modp->hierName();
return str;
} else if ((nvrp = VN_CAST_CONST(backp, NodeVarRef))) {
string prettyName = nvrp->prettyName();
// VarRefs have not been flattened yet and do not contain location information
if (prettyName != nvrp->name()) {
str += prettyName;
return str;
}
}
backp = backp->backp();
}
return "";
}
void AstNode::v3errorEnd(std::ostringstream& str) const {
if (!m_fileline) {
V3Error::v3errorEnd(str);
V3Error::v3errorEnd(str, locationStr());
} else {
std::ostringstream nsstr;
nsstr<<str.str();
@@ -1088,31 +1135,28 @@ void AstNode::v3errorEnd(std::ostringstream& str) const {
const_cast<AstNode*>(this)->dump(nsstr);
nsstr<<endl;
}
m_fileline->v3errorEnd(nsstr);
m_fileline->v3errorEnd(nsstr, locationStr());
}
}
string AstNode::warnMore() const {
return fileline()->warnMore();
}
//======================================================================
// Data type conversion
void AstNode::dtypeChgSigned(bool flag) {
if (!dtypep()) this->v3fatalSrc("No dtype when changing to (un)signed");
UASSERT_OBJ(dtypep(), this, "No dtype when changing to (un)signed");
dtypeChgWidthSigned(dtypep()->width(), dtypep()->widthMin(),
flag ? AstNumeric::SIGNED : AstNumeric::UNSIGNED);
AstNumeric::fromBool(flag));
}
void AstNode::dtypeChgWidth(int width, int widthMin) {
if (!dtypep()) this->v3fatalSrc("No dtype when changing width"); // Use ChgWidthSigned(...UNSIGNED) otherwise
UASSERT_OBJ(dtypep(), this,
"No dtype when changing width"); // Use ChgWidthSigned(...UNSIGNED) otherwise
dtypeChgWidthSigned(width, widthMin, dtypep()->numeric());
}
void AstNode::dtypeChgWidthSigned(int width, int widthMin, AstNumeric numeric) {
if (!dtypep()) {
// We allow dtypep() to be null, as before/during widthing dtypes are not resolved
dtypeSetLogicSized(width, widthMin, numeric);
dtypeSetLogicUnsized(width, widthMin, numeric);
} else {
if (width==dtypep()->width()
&& widthMin==dtypep()->widthMin()
@@ -1122,7 +1166,7 @@ void AstNode::dtypeChgWidthSigned(int width, int widthMin, AstNumeric numeric) {
// work OK but this assumption may break in the future.
// Note we can't just clone and do a widthForce, as if it's a BasicDType
// the msb() indications etc will be incorrect.
dtypeSetLogicSized(width, widthMin, numeric);
dtypeSetLogicUnsized(width, widthMin, numeric);
}
}
+90 -61
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3AST_H_
#define _V3AST_H_ 1
@@ -51,16 +51,19 @@ typedef std::set<int> MTaskIdSet; // Set of mtaskIds for Var sorting
//######################################################################
// For broken() function, return error string if have a match
#define BROKEN_RTN(test) do { if (VL_UNLIKELY(test)) return # test; } while(0)
#define BROKEN_RTN(test) do { if (VL_UNCOVERABLE(test)) return # test; } while(0)
// (V)erilator (N)ode is: True if AstNode is of a a given AstType
#define VN_IS(nodep,nodetypename) (AstNode::privateIs ## nodetypename(nodep))
// (V)erilator (N)ode cast: Cast to given type if can; effectively
// dynamic_cast(nodep)(nodetypename)
// dynamic_cast<nodetypename>(nodep)
#define VN_CAST(nodep,nodetypename) (AstNode::privateCast ## nodetypename(nodep))
#define VN_CAST_CONST(nodep,nodetypename) (AstNode::privateConstCast ## nodetypename(nodep) )
// (V)erilator (N)ode deleted: Reference to deleted child (for assertions only)
#define VN_DELETED(nodep) VL_UNLIKELY((vluint64_t)(nodep) == 0x1)
//######################################################################
class AstType {
@@ -70,7 +73,7 @@ public:
// enum en {...};
// const char* ascii() const {...};
enum en m_e;
// cppcheck-suppress uninitVar // responsiblity of each subclass
// cppcheck-suppress uninitVar // responsibility of each subclass
inline AstType() {}
// cppcheck-suppress noExplicitConstructor
inline AstType(en _e) : m_e(_e) {}
@@ -182,7 +185,7 @@ public:
//######################################################################
class AstEdgeType {
class VEdgeType {
public:
// REMEMBER to edit the strings below too
enum en {
@@ -210,7 +213,7 @@ public:
};
return clocked[m_e];
}
AstEdgeType invert() const {
VEdgeType invert() const {
switch (m_e) {
case ET_ANYEDGE: return ET_ANYEDGE;
case ET_BOTHEDGE: return ET_BOTHEDGE;
@@ -220,7 +223,7 @@ public:
case ET_LOWEDGE: return ET_HIGHEDGE;
default: UASSERT_STATIC(0, "Inverting bad edgeType()");
};
return AstEdgeType::ET_ILLEGAL;
return VEdgeType::ET_ILLEGAL;
}
const char* ascii() const {
static const char* const names[] = {
@@ -237,20 +240,20 @@ public:
return names[m_e];
}
// Return true iff this and the other have mutually exclusive transitions
bool exclusiveEdge(const AstEdgeType& other) const {
bool exclusiveEdge(const VEdgeType& other) const {
switch (m_e) {
case AstEdgeType::ET_POSEDGE:
case VEdgeType::ET_POSEDGE:
switch (other.m_e) {
case AstEdgeType::ET_NEGEDGE: // FALLTHRU
case AstEdgeType::ET_LOWEDGE:
case VEdgeType::ET_NEGEDGE: // FALLTHRU
case VEdgeType::ET_LOWEDGE:
return true;
default: {}
}
break;
case AstEdgeType::ET_NEGEDGE:
case VEdgeType::ET_NEGEDGE:
switch (other.m_e) {
case AstEdgeType::ET_POSEDGE: // FALLTHRU
case AstEdgeType::ET_HIGHEDGE:
case VEdgeType::ET_POSEDGE: // FALLTHRU
case VEdgeType::ET_HIGHEDGE:
return true;
default: {}
}
@@ -259,15 +262,15 @@ public:
}
return false;
}
inline AstEdgeType() : m_e(ET_ILLEGAL) {}
inline VEdgeType() : m_e(ET_ILLEGAL) {}
// cppcheck-suppress noExplicitConstructor
inline AstEdgeType(en _e) : m_e(_e) {}
explicit inline AstEdgeType(int _e) : m_e(static_cast<en>(_e)) {}
inline VEdgeType(en _e) : m_e(_e) {}
explicit inline VEdgeType(int _e) : m_e(static_cast<en>(_e)) {}
operator en() const { return m_e; }
};
inline bool operator==(AstEdgeType lhs, AstEdgeType rhs) { return (lhs.m_e == rhs.m_e); }
inline bool operator==(AstEdgeType lhs, AstEdgeType::en rhs) { return (lhs.m_e == rhs); }
inline bool operator==(AstEdgeType::en lhs, AstEdgeType rhs) { return (lhs == rhs.m_e); }
inline bool operator==(VEdgeType lhs, VEdgeType rhs) { return (lhs.m_e == rhs.m_e); }
inline bool operator==(VEdgeType lhs, VEdgeType::en rhs) { return (lhs.m_e == rhs); }
inline bool operator==(VEdgeType::en lhs, VEdgeType rhs) { return (lhs == rhs.m_e); }
//######################################################################
@@ -610,7 +613,7 @@ public:
//######################################################################
class AstBranchPred {
class VBranchPred {
public:
enum en {
BP_UNKNOWN=0,
@@ -620,12 +623,15 @@ public:
};
enum en m_e;
// CONSTRUCTOR - note defaults to *UNKNOWN*
inline AstBranchPred() : m_e(BP_UNKNOWN) {}
inline VBranchPred() : m_e(BP_UNKNOWN) {}
// cppcheck-suppress noExplicitConstructor
inline AstBranchPred(en _e) : m_e(_e) {}
explicit inline AstBranchPred(int _e) : m_e(static_cast<en>(_e)) {}
inline VBranchPred(en _e) : m_e(_e) {}
explicit inline VBranchPred(int _e) : m_e(static_cast<en>(_e)) {}
operator en() const { return m_e; }
AstBranchPred invert() const {
bool unknown() const { return m_e == BP_UNKNOWN; }
bool likely() const { return m_e == BP_LIKELY; }
bool unlikely() const { return m_e == BP_UNLIKELY; }
VBranchPred invert() const {
if (m_e==BP_UNLIKELY) return BP_LIKELY;
else if (m_e==BP_LIKELY) return BP_UNLIKELY;
else return m_e;
@@ -635,14 +641,14 @@ public:
"", "VL_LIKELY", "VL_UNLIKELY"};
return names[m_e]; }
};
inline bool operator==(AstBranchPred lhs, AstBranchPred rhs) { return (lhs.m_e == rhs.m_e); }
inline bool operator==(AstBranchPred lhs, AstBranchPred::en rhs) { return (lhs.m_e == rhs); }
inline bool operator==(AstBranchPred::en lhs, AstBranchPred rhs) { return (lhs == rhs.m_e); }
inline std::ostream& operator<<(std::ostream& os, const AstBranchPred& rhs) { return os<<rhs.ascii(); }
inline bool operator==(VBranchPred lhs, VBranchPred rhs) { return (lhs.m_e == rhs.m_e); }
inline bool operator==(VBranchPred lhs, VBranchPred::en rhs) { return (lhs.m_e == rhs); }
inline bool operator==(VBranchPred::en lhs, VBranchPred rhs) { return (lhs == rhs.m_e); }
inline std::ostream& operator<<(std::ostream& os, const VBranchPred& rhs) { return os<<rhs.ascii(); }
//######################################################################
class AstVarAttrClocker {
class VVarAttrClocker {
public:
enum en {
CLOCKER_UNKNOWN=0,
@@ -652,13 +658,13 @@ public:
};
enum en m_e;
// CONSTRUCTOR - note defaults to *UNKNOWN*
inline AstVarAttrClocker() : m_e(CLOCKER_UNKNOWN) {}
inline VVarAttrClocker() : m_e(CLOCKER_UNKNOWN) {}
// cppcheck-suppress noExplicitConstructor
inline AstVarAttrClocker(en _e) : m_e(_e) {}
explicit inline AstVarAttrClocker(int _e) : m_e(static_cast<en>(_e)) {}
inline VVarAttrClocker(en _e) : m_e(_e) {}
explicit inline VVarAttrClocker(int _e) : m_e(static_cast<en>(_e)) {}
operator en() const { return m_e; }
bool unknown() const { return m_e==CLOCKER_UNKNOWN; }
AstVarAttrClocker invert() const {
VVarAttrClocker invert() const {
if (m_e==CLOCKER_YES) return CLOCKER_NO;
else if (m_e==CLOCKER_NO) return CLOCKER_YES;
else return m_e;
@@ -668,10 +674,10 @@ public:
"", "clker", "non_clker"};
return names[m_e]; }
};
inline bool operator==(AstVarAttrClocker lhs, AstVarAttrClocker rhs) { return (lhs.m_e == rhs.m_e); }
inline bool operator==(AstVarAttrClocker lhs, AstVarAttrClocker::en rhs) { return (lhs.m_e == rhs); }
inline bool operator==(AstVarAttrClocker::en lhs, AstVarAttrClocker rhs) { return (lhs == rhs.m_e); }
inline std::ostream& operator<<(std::ostream& os, const AstVarAttrClocker& rhs) { return os<<rhs.ascii(); }
inline bool operator==(VVarAttrClocker lhs, VVarAttrClocker rhs) { return (lhs.m_e == rhs.m_e); }
inline bool operator==(VVarAttrClocker lhs, VVarAttrClocker::en rhs) { return (lhs.m_e == rhs); }
inline bool operator==(VVarAttrClocker::en lhs, VVarAttrClocker rhs) { return (lhs == rhs.m_e); }
inline std::ostream& operator<<(std::ostream& os, const VVarAttrClocker& rhs) { return os<<rhs.ascii(); }
//######################################################################
@@ -750,33 +756,34 @@ public:
//######################################################################
class AstParseRefExp {
class VParseRefExp {
public:
enum en {
PX_NONE, // Used in V3LinkParse only
PX_TEXT // Unknown ID component
};
enum en m_e;
inline AstParseRefExp() : m_e(PX_NONE) {}
inline VParseRefExp() : m_e(PX_NONE) {}
// cppcheck-suppress noExplicitConstructor
inline AstParseRefExp(en _e) : m_e(_e) {}
explicit inline AstParseRefExp(int _e) : m_e(static_cast<en>(_e)) {}
inline VParseRefExp(en _e) : m_e(_e) {}
explicit inline VParseRefExp(int _e) : m_e(static_cast<en>(_e)) {}
operator en() const { return m_e; }
const char* ascii() const {
static const char* const names[] = {
"", "TEXT", "PREDOT"};
return names[m_e]; }
};
inline bool operator==(AstParseRefExp lhs, AstParseRefExp rhs) { return (lhs.m_e == rhs.m_e); }
inline bool operator==(AstParseRefExp lhs, AstParseRefExp::en rhs) { return (lhs.m_e == rhs); }
inline bool operator==(AstParseRefExp::en lhs, AstParseRefExp rhs) { return (lhs == rhs.m_e); }
inline std::ostream& operator<<(std::ostream& os, const AstParseRefExp& rhs) { return os<<rhs.ascii(); }
inline bool operator==(VParseRefExp lhs, VParseRefExp rhs) { return (lhs.m_e == rhs.m_e); }
inline bool operator==(VParseRefExp lhs, VParseRefExp::en rhs) { return (lhs.m_e == rhs); }
inline bool operator==(VParseRefExp::en lhs, VParseRefExp rhs) { return (lhs == rhs.m_e); }
inline std::ostream& operator<<(std::ostream& os, const VParseRefExp& rhs) { return os<<rhs.ascii(); }
//######################################################################
// VNumRange - Structure containing numberic range information
// VNumRange - Structure containing numeric range information
// See also AstRange, which is a symbolic version of this
struct VNumRange {
class VNumRange {
public:
int m_hi; // HI part, HI always >= LO
int m_lo; // LO
union {
@@ -831,7 +838,8 @@ inline std::ostream& operator<<(std::ostream& os, const VNumRange& rhs) { rhs.du
//######################################################################
struct VBasicTypeKey {
class VBasicTypeKey {
public:
int m_width; // From AstNodeDType: Bit width of operation
int m_widthMin; // From AstNodeDType: If unsized, bitwidth of minimum implementation
AstNumeric m_numeric; // From AstNodeDType: Node is signed
@@ -907,7 +915,7 @@ public:
//
// AstUser2InUse m_userres;
//
// This will clear the tree, and prevent another visitor from clobering
// This will clear the tree, and prevent another visitor from clobbering
// user2. When the member goes out of scope it will be automagically
// freed up.
@@ -1114,6 +1122,14 @@ public:
};
std::ostream& operator<<(std::ostream& os, const V3Hash& rhs);
//######################################################################
// Callback base class to determine if node matches some formula
class VNodeMatcher {
public:
virtual bool nodeMatch(const AstNode* nodep) const { return true; }
};
//######################################################################
// AstNode -- Base type of all Ast types
@@ -1180,13 +1196,14 @@ private:
bool ignNext, bool gateOnly);
void deleteTreeIter();
void deleteNode();
string locationStr() const;
public:
static void relinkOneLink(AstNode*& pointpr, AstNode* newp);
// cppcheck-suppress functionConst
void debugTreeChange(const char* prefix, int lineno, bool next);
protected:
// CONSTUCTORS
// CONSTRUCTORS
AstNode() {init(); }
explicit AstNode(FileLine* fileline) {init(); m_fileline = fileline; }
virtual AstNode* clone() = 0; // Generally, cloneTree is what you want instead
@@ -1250,7 +1267,7 @@ public:
static int instrCountPli() { return 20; } ///< Instruction cycles to call pli routines
static int instrCountDouble() { return 8; } ///< Instruction cycles to convert or do floats
static int instrCountDoubleDiv() { return 40; } ///< Instruction cycles to divide floats
static int instrCountDoubleTrig() { return 200; } ///< Instruction cycles to do triganomics
static int instrCountDoubleTrig() { return 200; } ///< Instruction cycles to do trigonomics
static int instrCountString() { return 100; } ///< Instruction cycles to do string ops
static int instrCountCall() { return instrCountBranch()+10; } ///< Instruction cycles to call subroutine
static int instrCountTime() { return instrCountCall()+5; } ///< Instruction cycles to determine simulation time
@@ -1264,10 +1281,13 @@ public:
string shortName() const; // Name with __PVT__ removed for concatenating scopes
static string dedotName(const string& namein); // Name with dots removed
static string prettyName(const string& namein); // Name for printing out to the user
static string prettyNameQ(const string& namein) { // Quoted pretty name (for errors)
return string("'")+prettyName(namein)+"'"; }
static string encodeName(const string& namein); // Encode user name into internal C representation
static string encodeNumber(vlsint64_t num); // Encode number into internal C representation
static string vcdName(const string& namein); // Name for printing out to vcd files
string prettyName() const { return prettyName(name()); }
string prettyNameQ() const { return prettyNameQ(name()); }
string prettyTypeName() const; // "VARREF" for error messages
virtual string prettyOperatorName() const { return "operator "+prettyTypeName(); }
FileLine* fileline() const { return m_fileline; }
@@ -1381,10 +1401,12 @@ public:
void dtypeChgSigned(bool flag=true);
void dtypeChgWidth(int width, int widthMin);
void dtypeChgWidthSigned(int width, int widthMin, AstNumeric numeric);
void dtypeSetBitSized(int width, int widthMin, AstNumeric numeric) {
void dtypeSetBitUnsized(int width, int widthMin, AstNumeric numeric) {
dtypep(findBitDType(width, widthMin, numeric)); }
void dtypeSetLogicSized(int width, int widthMin, AstNumeric numeric) {
void dtypeSetLogicUnsized(int width, int widthMin, AstNumeric numeric) {
dtypep(findLogicDType(width, widthMin, numeric)); }
void dtypeSetLogicSized(int width, AstNumeric numeric) {
dtypep(findLogicDType(width, width, numeric)); } // Since sized, widthMin is width
void dtypeSetLogicBool() { dtypep(findLogicBoolDType()); }
void dtypeSetDouble() { dtypep(findDoubleDType()); }
void dtypeSetString() { dtypep(findStringDType()); }
@@ -1408,7 +1430,11 @@ public:
// METHODS - dump and error
void v3errorEnd(std::ostringstream& str) const;
void v3errorEndFatal(std::ostringstream& str) const VL_ATTR_NORETURN;
string warnMore() const;
string warnContextPrimary() const { return fileline()->warnContextPrimary(); }
string warnContextSecondary() const { return fileline()->warnContextSecondary(); }
string warnMore() const { return fileline()->warnMore(); }
string warnOther() const { return fileline()->warnOther(); }
virtual void dump(std::ostream& str=std::cout);
void dumpGdb(); // For GDB only
void dumpGdbHeader() const;
@@ -1733,7 +1759,7 @@ public:
class AstNodeIf : public AstNodeStmt {
private:
AstBranchPred m_branchPred; // Branch prediction as taken/untaken?
VBranchPred m_branchPred; // Branch prediction as taken/untaken?
public:
AstNodeIf(FileLine* fl, AstNode* condp, AstNode* ifsp, AstNode* elsesp)
: AstNodeStmt(fl) {
@@ -1751,8 +1777,8 @@ public:
virtual int instrCount() const { return instrCountBranch(); }
virtual V3Hash sameHash() const { return V3Hash(); }
virtual bool same(const AstNode* samep) const { return true; }
void branchPred(AstBranchPred flag) { m_branchPred = flag; }
AstBranchPred branchPred() const { return m_branchPred; }
void branchPred(VBranchPred flag) { m_branchPred = flag; }
VBranchPred branchPred() const { return m_branchPred; }
};
class AstNodeCase : public AstNodeStmt {
@@ -1884,7 +1910,7 @@ public:
//
// Changing the width may confuse the data type resolution, so must clear
// TypeTable cache after use.
void widthForce(int width, int sized) { m_width = width; m_widthMin = sized; }
void widthForce(int width, int widthMin) { m_width = width; m_widthMin = widthMin; }
// For backward compatibility inherit width and signing from the subDType/base type
void widthFromSub(AstNodeDType* nodep) { m_width = nodep->m_width; m_widthMin = nodep->m_widthMin; m_numeric = nodep->m_numeric; }
//
@@ -1923,7 +1949,7 @@ public:
// AstNumeric::NOSIGN overloaded to indicate not packed
m_packed = (numericUnpack != AstNumeric::NOSIGN);
m_isFourstate = false; // V3Width computes
numeric(numericUnpack.isSigned() ? AstNumeric::SIGNED : AstNumeric::UNSIGNED);
numeric(AstNumeric::fromBool(numericUnpack.isSigned()));
}
ASTNODE_BASE_FUNCS(NodeClassDType)
virtual const char* broken() const;
@@ -2036,7 +2062,7 @@ class AstNodeStream : public AstNodeBiop {
public:
AstNodeStream(FileLine* fl, AstNode* lhsp, AstNode* rhsp) : AstNodeBiop(fl, lhsp, rhsp) {
if (lhsp->dtypep()) {
dtypeSetLogicSized(lhsp->dtypep()->width(), lhsp->dtypep()->width(), AstNumeric::UNSIGNED);
dtypeSetLogicSized(lhsp->dtypep()->width(), AstNumeric::UNSIGNED);
}
}
ASTNODE_BASE_FUNCS(NodeStream)
@@ -2168,6 +2194,7 @@ class AstNodeModule : public AstNode {
private:
string m_name; // Name of the module
string m_origName; // Name of the module, ignoring name() changes, for dot lookup
string m_hierName; // Hierarchical name for errors, etc.
bool m_modPublic:1; // Module has public references
bool m_modTrace:1; // Tracing this module
bool m_inLibrary:1; // From a library, no error if not used, never top level
@@ -2198,6 +2225,8 @@ public:
// ACCESSORS
virtual void name(const string& name) { m_name = name; }
string origName() const { return m_origName; }
string hierName() const { return m_hierName; }
void hierName(const string& hierName) { m_hierName = hierName; }
bool inLibrary() const { return m_inLibrary; }
void inLibrary(bool flag) { m_inLibrary = flag; }
void level(int level) { m_level = level; }
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3ASTCONSTONLY_H_
#define _V3ASTCONSTONLY_H_ 1
+30 -54
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -65,7 +65,7 @@ void AstNodeClassDType::repairMemberCache() {
clearCache();
for (AstMemberDType* itemp = membersp(); itemp; itemp=VN_CAST(itemp->nextp(), MemberDType)) {
if (m_members.find(itemp->name())!=m_members.end()) {
itemp->v3error("Duplicate declaration of member name: "<<itemp->prettyName()); }
itemp->v3error("Duplicate declaration of member name: "<<itemp->prettyNameQ()); }
else m_members.insert(make_pair(itemp->name(), itemp));
}
}
@@ -76,7 +76,7 @@ const char* AstNodeClassDType::broken() const {
exists.insert(itemp);
}
for (MemberNameMap::const_iterator it=m_members.begin(); it!=m_members.end(); ++it) {
if (VL_UNLIKELY(exists.find(it->second) == exists.end())) {
if (VL_UNCOVERABLE(exists.find(it->second) == exists.end())) {
this->v3error("Internal: Structure member broken: "<<it->first);
return "member broken";
}
@@ -120,7 +120,9 @@ int AstNodeClassDType::widthAlignBytes() const {
}
AstNodeBiop* AstEq::newTyped(FileLine* fl, AstNode* lhsp, AstNode* rhsp) {
if (lhsp->isDouble() && rhsp->isDouble()) {
if (lhsp->isString() && rhsp->isString()) {
return new AstEqN(fl, lhsp, rhsp);
} else if (lhsp->isDouble() && rhsp->isDouble()) {
return new AstEqD(fl, lhsp, rhsp);
} else {
return new AstEq(fl, lhsp, rhsp);
@@ -128,7 +130,9 @@ AstNodeBiop* AstEq::newTyped(FileLine* fl, AstNode* lhsp, AstNode* rhsp) {
}
AstNodeBiop* AstGte::newTyped(FileLine* fl, AstNode* lhsp, AstNode* rhsp) {
if (lhsp->isDouble() && rhsp->isDouble()) {
if (lhsp->isString() && rhsp->isString()) {
return new AstGteN(fl, lhsp, rhsp);
} else if (lhsp->isDouble() && rhsp->isDouble()) {
return new AstGteD(fl, lhsp, rhsp);
} else if (lhsp->isSigned() && rhsp->isSigned()) {
return new AstGteS(fl, lhsp, rhsp);
@@ -138,7 +142,9 @@ AstNodeBiop* AstGte::newTyped(FileLine* fl, AstNode* lhsp, AstNode* rhsp) {
}
AstNodeBiop* AstLte::newTyped(FileLine* fl, AstNode* lhsp, AstNode* rhsp) {
if (lhsp->isDouble() && rhsp->isDouble()) {
if (lhsp->isString() && rhsp->isString()) {
return new AstLteN(fl, lhsp, rhsp);
} else if (lhsp->isDouble() && rhsp->isDouble()) {
return new AstLteD(fl, lhsp, rhsp);
} else if (lhsp->isSigned() && rhsp->isSigned()) {
return new AstLteS(fl, lhsp, rhsp);
@@ -148,7 +154,9 @@ AstNodeBiop* AstLte::newTyped(FileLine* fl, AstNode* lhsp, AstNode* rhsp) {
}
AstNodeBiop* AstEqWild::newTyped(FileLine* fl, AstNode* lhsp, AstNode* rhsp) {
if (lhsp->isDouble() && rhsp->isDouble()) {
if (lhsp->isString() && rhsp->isString()) {
return new AstEqN(fl, lhsp, rhsp);
} else if (lhsp->isDouble() && rhsp->isDouble()) {
return new AstEqD(fl, lhsp, rhsp);
} else {
return new AstEqWild(fl, lhsp, rhsp);
@@ -215,8 +223,8 @@ string AstVar::verilogKwd() const {
}
string AstVar::vlArgType(bool named, bool forReturn, bool forFunc) const {
if (forReturn) named = false;
if (forReturn) v3fatalSrc("verilator internal data is never passed as return, but as first argument");
UASSERT_OBJ(!forReturn, this,
"Internal data is never passed as return, but as first argument");
string otype;
AstBasicDType* bdtypep = basicp();
bool strtype = bdtypep && bdtypep->keyword()==AstBasicDTypeKwd::STRING;
@@ -465,7 +473,7 @@ AstVar* AstVar::scVarRecurse(AstNode* nodep) {
string AstVar::mtasksString() const {
std::ostringstream os;
os<<" all: ";
os<<"all: ";
for (MTaskIdSet::const_iterator it = m_mtaskIds.begin();
it != m_mtaskIds.end(); ++it) {
os<<*it<<" ";
@@ -642,28 +650,28 @@ string AstScopeName::scopeNameFormatter(AstText* scopeTextp) const {
}
bool AstSenTree::hasClocked() const {
if (!sensesp()) this->v3fatalSrc("SENTREE without any SENITEMs under it");
UASSERT_OBJ(sensesp(), this, "SENTREE without any SENITEMs under it");
for (AstNodeSenItem* senp = sensesp(); senp; senp=VN_CAST(senp->nextp(), NodeSenItem)) {
if (senp->isClocked()) return true;
}
return false;
}
bool AstSenTree::hasSettle() const {
if (!sensesp()) this->v3fatalSrc("SENTREE without any SENITEMs under it");
UASSERT_OBJ(sensesp(), this, "SENTREE without any SENITEMs under it");
for (AstNodeSenItem* senp = sensesp(); senp; senp=VN_CAST(senp->nextp(), NodeSenItem)) {
if (senp->isSettle()) return true;
}
return false;
}
bool AstSenTree::hasInitial() const {
if (!sensesp()) this->v3fatalSrc("SENTREE without any SENITEMs under it");
UASSERT_OBJ(sensesp(), this, "SENTREE without any SENITEMs under it");
for (AstNodeSenItem* senp = sensesp(); senp; senp=VN_CAST(senp->nextp(), NodeSenItem)) {
if (senp->isInitial()) return true;
}
return false;
}
bool AstSenTree::hasCombo() const {
if (!sensesp()) this->v3fatalSrc("SENTREE without any SENITEMs under it");
UASSERT_OBJ(sensesp(), this, "SENTREE without any SENITEMs under it");
for (AstNodeSenItem* senp = sensesp(); senp; senp=VN_CAST(senp->nextp(), NodeSenItem)) {
if (senp->isCombo()) return true;
}
@@ -676,12 +684,6 @@ void AstTypeTable::clearCache() {
for (int i=0; i < static_cast<int>(AstBasicDTypeKwd::_ENUM_MAX); ++i) {
m_basicps[i] = NULL;
}
for (int isbit=0; isbit<_IDX0_MAX; ++isbit) {
for (int numer=0; numer<AstNumeric::_ENUM_MAX; ++numer) {
LogicMap& mapr = m_logicMap[isbit][numer];
mapr.clear();
}
}
m_detailedMap.clear();
// Clear generic()'s so dead detection will work
for (AstNode* nodep = typesp(); nodep; nodep=nodep->nextp()) {
@@ -718,24 +720,10 @@ AstBasicDType* AstTypeTable::findBasicDType(FileLine* fl, AstBasicDTypeKwd kwd)
AstBasicDType* AstTypeTable::findLogicBitDType(FileLine* fl, AstBasicDTypeKwd kwd,
int width, int widthMin, AstNumeric numeric) {
int idx = IDX0_LOGIC;
if (kwd == AstBasicDTypeKwd::LOGIC) idx = IDX0_LOGIC;
else if (kwd == AstBasicDTypeKwd::BIT) idx = IDX0_BIT;
else fl->v3fatalSrc("Bad kwd for findLogicBitDType");
std::pair<int,int> widths = make_pair(width, widthMin);
LogicMap& mapr = m_logicMap[idx][static_cast<int>(numeric)];
LogicMap::const_iterator it = mapr.find(widths);
if (it != mapr.end()) return it->second;
//
AstBasicDType* new1p = new AstBasicDType(fl, kwd, numeric, width, widthMin);
// Because the detailed map doesn't update this map,
// check the detailed map for this same node, and if found update this map
// Also adds this new node to the detailed map
AstBasicDType* newp = findInsertSameDType(new1p);
if (newp != new1p) new1p->deleteTree();
else addTypesp(newp);
//
mapr.insert(make_pair(widths, newp));
return newp;
}
@@ -764,12 +752,12 @@ AstBasicDType* AstTypeTable::findInsertSameDType(AstBasicDType* nodep) {
// Special walking tree inserters
void AstNode::addBeforeStmt(AstNode* newp, AstNode*) {
if (!backp()) newp->v3fatalSrc("Can't find current statement to addBeforeStmt");
UASSERT_OBJ(backp(), newp, "Can't find current statement to addBeforeStmt");
// Look up; virtual call will find where to put it
this->backp()->addBeforeStmt(newp, this);
}
void AstNode::addNextStmt(AstNode* newp, AstNode*) {
if (!backp()) newp->v3fatalSrc("Can't find current statement to addNextStmt");
UASSERT_OBJ(backp(), newp, "Can't find current statement to addNextStmt");
// Look up; virtual call will find where to put it
this->backp()->addNextStmt(newp, this);
}
@@ -832,7 +820,7 @@ void AstNode::dump(std::ostream& str) {
//<<" "<<cvtToHex(this)->m_backp
<<" <e"<<std::dec<<editCount()
<<((editCount()>=editCountLast())?"#>":">")
<<" {"<<fileline()->filenameLetters()<<std::dec<<fileline()->lineno()<<"}";
<<" {"<<fileline()->filenameLetters()<<std::dec<<fileline()->lastLineno()<<"}";
if (user1p()) str<<" u1="<<cvtToHex(user1p());
if (user2p()) str<<" u2="<<cvtToHex(user2p());
if (user3p()) str<<" u3="<<cvtToHex(user3p());
@@ -939,9 +927,9 @@ void AstRange::dump(std::ostream& str) {
if (littleEndian()) str<<" [LITTLE]";
}
void AstRefDType::dump(std::ostream& str) {
static bool s_recursing = false;
this->AstNodeDType::dump(str);
if (defp()) {
static bool s_recursing = false;
if (!s_recursing) { // Prevent infinite dump if circular typedefs
s_recursing = true;
str<<" -> "; defp()->dump(str);
@@ -1030,22 +1018,6 @@ void AstTypeTable::dump(std::ostream& str) {
subnodep->dump(str);
}
}
for (int isbit=0; isbit<2; ++isbit) {
for (int issigned=0; issigned<AstNumeric::_ENUM_MAX; ++issigned) {
LogicMap& mapr = m_logicMap[isbit][issigned];
for (LogicMap::const_iterator it = mapr.begin(); it != mapr.end(); ++it) {
AstBasicDType* dtypep = it->second;
str<<endl; // Newline from caller, so newline first
std::stringstream nsstr;
nsstr<<(isbit?"bw":"lw")
<<it->first.first<<"/"<<it->first.second;
str<<"\t\t"<<std::setw(8)<<nsstr.str();
if (issigned) str<<" s"; else str<<" u";
str<<" -> ";
dtypep->dump(str);
}
}
}
{
DetailedMap& mapr = m_detailedMap;
for (DetailedMap::const_iterator it = mapr.begin(); it != mapr.end(); ++it) {
@@ -1191,6 +1163,10 @@ void AstNodeText::dump(std::ostream& str) {
str<<" \""<<out<<"\"";
}
void AstVFile::dump(std::ostream& str) {
this->AstNode::dump(str);
}
void AstCFile::dump(std::ostream& str) {
this->AstNode::dump(str);
if (source()) str<<" [SRC]";
+268 -110
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3ASTNODES_H_
#define _V3ASTNODES_H_ 1
@@ -55,10 +55,10 @@ private:
} else if (m_num.isString()) {
dtypeSetString();
} else {
dtypeSetLogicSized(m_num.width(), (m_num.sized() ? 0 : m_num.widthMin()),
m_num.isSigned() ? AstNumeric::SIGNED
: AstNumeric::UNSIGNED);
dtypeSetLogicUnsized(m_num.width(), (m_num.sized() ? 0 : m_num.widthMin()),
AstNumeric::fromBool(m_num.isSigned()));
}
m_num.nodep(this);
}
public:
AstConst(FileLine* fl, const V3Number& num)
@@ -72,6 +72,12 @@ public:
, m_num(this, width, value) {
initWithNumber();
}
class DtypedValue{}; // for creator type-overload selection
AstConst(FileLine* fl, DtypedValue, AstNodeDType* nodedtypep, uint32_t value)
: AstNodeMath(fl)
, m_num(this, nodedtypep->width(), value, nodedtypep->widthSized()) {
initWithNumber();
}
class StringToParse {}; // for creator type-overload selection
AstConst(FileLine* fl, StringToParse, const char* sourcep)
: AstNodeMath(fl)
@@ -86,44 +92,43 @@ public:
}
AstConst(FileLine* fl, uint32_t num)
: AstNodeMath(fl)
, m_num(V3Number(this, 32, num)) {
dtypeSetLogicSized(m_num.width(),
m_num.sized() ? 0 : m_num.widthMin(),
AstNumeric::UNSIGNED);
, m_num(this, 32, num) {
dtypeSetLogicUnsized(m_num.width(), 0, AstNumeric::UNSIGNED);
}
class Unsized32 {}; // for creator type-overload selection
AstConst(FileLine* fl, Unsized32, uint32_t num) // Unsized 32-bit integer of specified value
: AstNodeMath(fl)
, m_num(V3Number(this, 32, num)) {
, m_num(this, 32, num) {
m_num.width(32, false);
dtypeSetLogicSized(32, m_num.widthMin(), AstNumeric::UNSIGNED);
dtypeSetLogicUnsized(32, m_num.widthMin(), AstNumeric::UNSIGNED);
}
class Signed32 {}; // for creator type-overload selection
AstConst(FileLine* fl, Signed32, int32_t num) // Signed 32-bit integer of specified value
: AstNodeMath(fl)
, m_num(V3Number(this, 32, num)) {
, m_num(this, 32, num) {
m_num.width(32, 32);
dtypeSetLogicSized(32, m_num.widthMin(), AstNumeric::SIGNED);
dtypeSetLogicUnsized(32, m_num.widthMin(), AstNumeric::SIGNED);
}
class RealDouble {}; // for creator type-overload selection
AstConst(FileLine* fl, RealDouble, double num)
: AstNodeMath(fl)
, m_num(V3Number(this, 64)) { m_num.setDouble(num); dtypeSetDouble(); }
, m_num(this, 64) { m_num.setDouble(num); dtypeSetDouble(); }
class String {}; // for creator type-overload selection
AstConst(FileLine* fl, String, const string& num)
: AstNodeMath(fl)
, m_num(V3Number(V3Number::String(), this, num)) { dtypeSetString(); }
, m_num(V3Number::String(), this, num) { dtypeSetString(); }
class LogicFalse {};
AstConst(FileLine* fl, LogicFalse) // Shorthand const 0, dtype should be a logic of size 1
: AstNodeMath(fl)
, m_num(V3Number(this, 1, 0)) { dtypeSetLogicBool(); }
, m_num(this, 1, 0) { dtypeSetLogicBool(); }
class LogicTrue {};
AstConst(FileLine* fl, LogicTrue) // Shorthand const 1, dtype should be a logic of size 1
: AstNodeMath(fl)
, m_num(V3Number(this, 1, 1)) { dtypeSetLogicBool(); }
, m_num(this, 1, 1) { dtypeSetLogicBool(); }
ASTNODE_NODE_FUNCS(Const)
virtual string name() const { return num().ascii(); } // * = Value
virtual const V3Number& num() const { return m_num; } // * = Value
const V3Number& num() const { return m_num; } // * = Value
V3Number& num() { return m_num; } // * = Value
uint32_t toUInt() const { return num().toUInt(); }
vlsint32_t toSInt() const { return num().toSInt(); }
vluint64_t toUQuad() const { return num().toUQuad(); }
@@ -329,7 +334,7 @@ public:
};
class AstPackArrayDType : public AstNodeArrayDType {
// Array data type, ie "some_dtype var_name [2:0]"
// Packed array data type, ie "some_dtype [2:0] var_name"
// Children: DTYPE (moved to refDTypep() in V3Width)
// Children: RANGE (array bounds)
public:
@@ -533,7 +538,7 @@ public:
bool littleEndian() const { return (rangep() ? rangep()->littleEndian() : m.m_nrange.littleEndian()); }
bool implicit() const { return keyword() == AstBasicDTypeKwd::LOGIC_IMPLICIT; }
VNumRange declRange() const { return isRanged() ? VNumRange(msb(), lsb(), littleEndian()) : VNumRange(); }
void cvtRangeConst() { // Convert to smaller represenation
void cvtRangeConst() { // Convert to smaller representation
if (rangep() && VN_IS(rangep()->msbp(), Const) && VN_IS(rangep()->lsbp(), Const)) {
m.m_nrange.init(rangep()->msbConst(), rangep()->lsbConst(),
rangep()->littleEndian());
@@ -588,6 +593,7 @@ public:
class AstIfaceRefDType : public AstNodeDType {
// Reference to an interface, either for a port, or inside parent cell
private:
FileLine* m_modportFileline; // Where modport token was
string m_cellName; // "" = no cell, such as when connects to 'input' iface
string m_ifaceName; // Interface name
string m_modportName; // "" = no modport
@@ -595,11 +601,15 @@ private:
AstCell* m_cellp; // When exact parent cell known; not a guess
AstModport* m_modportp; // NULL = unlinked or no modport
public:
AstIfaceRefDType(FileLine* fl, const string& cellName, const string& ifaceName)
: AstNodeDType(fl), m_cellName(cellName), m_ifaceName(ifaceName), m_modportName(""),
AstIfaceRefDType(FileLine* fl,
const string& cellName, const string& ifaceName)
: AstNodeDType(fl), m_modportFileline(NULL),
m_cellName(cellName), m_ifaceName(ifaceName), m_modportName(""),
m_ifacep(NULL), m_cellp(NULL), m_modportp(NULL) { }
AstIfaceRefDType(FileLine* fl, const string& cellName, const string& ifaceName, const string& modport)
: AstNodeDType(fl), m_cellName(cellName), m_ifaceName(ifaceName), m_modportName(modport),
AstIfaceRefDType(FileLine* fl, FileLine* modportFl,
const string& cellName, const string& ifaceName, const string& modport)
: AstNodeDType(fl), m_modportFileline(modportFl),
m_cellName(cellName), m_ifaceName(ifaceName), m_modportName(modport),
m_ifacep(NULL), m_cellp(NULL), m_modportp(NULL) { }
ASTNODE_NODE_FUNCS(IfaceRefDType)
// METHODS
@@ -615,6 +625,7 @@ public:
virtual V3Hash sameHash() const { return V3Hash(m_cellp); }
virtual int widthAlignBytes() const { return 1; }
virtual int widthTotalBytes() const { return 1; }
FileLine* modportFileline() const { return m_modportFileline; }
string cellName() const { return m_cellName; }
void cellName(const string& name) { m_cellName = name; }
string ifaceName() const { return m_ifaceName; }
@@ -953,8 +964,8 @@ class AstSelBit : public AstNodePreSel {
public:
AstSelBit(FileLine* fl, AstNode* fromp, AstNode* bitp)
:AstNodePreSel(fl, fromp, bitp, NULL) {
if (v3Global.assertDTypesResolved()) { v3fatalSrc("not coded to create after dtypes resolved"); }
}
UASSERT_OBJ(!v3Global.assertDTypesResolved(), this,
"not coded to create after dtypes resolved"); }
ASTNODE_NODE_FUNCS(SelBit)
AstNode* bitp() const { return rhsp(); }
};
@@ -996,7 +1007,6 @@ public:
m_declElWidth = 1;
if (VN_IS(widthp, Const)) {
dtypeSetLogicSized(VN_CAST(widthp, Const)->toUInt(),
VN_CAST(widthp, Const)->toUInt(),
AstNumeric::UNSIGNED);
}
}
@@ -1004,7 +1014,7 @@ public:
: AstNodeTriop(fl, fromp,
new AstConst(fl, lsb), new AstConst(fl, bitwidth)) {
m_declElWidth = 1;
dtypeSetLogicSized(bitwidth, bitwidth, AstNumeric::UNSIGNED);
dtypeSetLogicSized(bitwidth, AstNumeric::UNSIGNED);
}
ASTNODE_NODE_FUNCS(Sel)
virtual void dump(std::ostream& str);
@@ -1139,6 +1149,8 @@ private:
VDirection m_direction; // Direction input/output etc
VDirection m_declDirection; // Declared direction input/output etc
AstBasicDTypeKwd m_declKwd; // Keyword at declaration time
bool m_ansi:1; // ANSI port list variable (for dedup check)
bool m_declTyped:1; // Declared as type (for dedup check)
bool m_tristate:1; // Inout or triwire or trireg
bool m_primaryIO:1; // In/out to top level (or directly assigned from same)
bool m_sc:1; // SystemC variable
@@ -1167,10 +1179,11 @@ private:
bool m_noReset:1; // Do not do automated reset/randomization
bool m_noSubst:1; // Do not substitute out references
bool m_trace:1; // Trace this variable
AstVarAttrClocker m_attrClocker;
VVarAttrClocker m_attrClocker;
MTaskIdSet m_mtaskIds; // MTaskID's that read or write this var
void init() {
m_ansi = false; m_declTyped = false;
m_tristate = false; m_primaryIO = false;
m_sc = false; m_scClocked = false; m_scSensitive = false;
m_usedClock = false; m_usedParam = false; m_usedLoopIdx = false;
@@ -1183,7 +1196,7 @@ private:
m_isStatic = false; m_isPulldown = false; m_isPullup = false;
m_isIfaceParent = false; m_isDpiOpenArray = false;
m_noReset = false; m_noSubst = false; m_trace = false;
m_attrClocker = AstVarAttrClocker::CLOCKER_UNKNOWN;
m_attrClocker = VVarAttrClocker::CLOCKER_UNKNOWN;
}
public:
AstVar(FileLine* fl, AstVarType type, const string& name, VFlagChildDType, AstNodeDType* dtp)
@@ -1211,7 +1224,7 @@ public:
, m_name(name), m_origName(name) {
init();
combineType(type);
dtypeSetLogicSized(wantwidth, wantwidth, AstNumeric::UNSIGNED);
dtypeSetLogicSized(wantwidth, AstNumeric::UNSIGNED);
m_declKwd = AstBasicDTypeKwd::LOGIC;
}
AstVar(FileLine* fl, AstVarType type, const string& name, VFlagBitPacked, int wantwidth)
@@ -1219,7 +1232,7 @@ public:
, m_name(name), m_origName(name) {
init();
combineType(type);
dtypeSetLogicSized(wantwidth, wantwidth, AstNumeric::UNSIGNED);
dtypeSetLogicSized(wantwidth, AstNumeric::UNSIGNED);
m_declKwd = AstBasicDTypeKwd::BIT;
}
AstVar(FileLine* fl, AstVarType type, const string& name, AstVar* examplep)
@@ -1273,8 +1286,10 @@ public:
AstNode* attrsp() const { return op4p(); } // op4 = Attributes during early parse
void childDTypep(AstNodeDType* nodep) { setOp1p(nodep); }
virtual AstNodeDType* subDTypep() const { return dtypep() ? dtypep() : childDTypep(); }
void ansi(bool flag) { m_ansi = flag; }
void declTyped(bool flag) { m_declTyped = flag; }
void attrClockEn(bool flag) { m_attrClockEn = flag; }
void attrClocker(AstVarAttrClocker flag) { m_attrClocker = flag; }
void attrClocker(VVarAttrClocker flag) { m_attrClocker = flag; }
void attrFileDescr(bool flag) { m_fileDescr = flag; }
void attrScClocked(bool flag) { m_scClocked = flag; }
void attrScBv(bool flag) { m_attrScBv = flag; }
@@ -1306,6 +1321,8 @@ public:
virtual void name(const string& name) { m_name = name; }
virtual void tag(const string& text) { m_tag = text;}
virtual string tag() const { return m_tag; }
bool isAnsi() const { return m_ansi; }
bool isDeclTyped() const { return m_declTyped; }
bool isInoutish() const { return m_direction.isInoutish(); }
bool isNonOutput() const { return m_direction.isNonOutput(); }
bool isReadOnly() const { return m_direction.isReadOnly(); }
@@ -1357,7 +1374,7 @@ public:
bool attrScClocked() const { return m_scClocked; }
bool attrSFormat() const { return m_attrSFormat; }
bool attrIsolateAssign() const { return m_attrIsolateAssign; }
AstVarAttrClocker attrClocker() const { return m_attrClocker; }
VVarAttrClocker attrClocker() const { return m_attrClocker; }
virtual string verilogKwd() const;
void propagateAttrFrom(AstVar* fromp) {
// This is getting connected to fromp; keep attributes
@@ -1629,7 +1646,7 @@ public:
return modVarp() ? ((modVarp()->direction().isAny()
? modVarp()->direction().prettyName()+" "
: "")
+"port connection '"+modVarp()->prettyName()+"'")
+"port connection "+modVarp()->prettyNameQ())
: "port connection"; }
bool dotStar() const { return name() == ".*"; } // Fake name for .* connections until linked
int pinNum() const { return m_pinNum; }
@@ -1815,6 +1832,7 @@ public:
class AstCell : public AstNode {
// A instantiation cell or interface call (don't know which until link)
private:
FileLine* m_modNameFileline; // Where module the cell instances token was
string m_name; // Cell name
string m_origName; // Original name before dot addition
string m_modName; // Module the cell instances
@@ -1823,9 +1841,11 @@ private:
bool m_recursive:1; // Self-recursive module
bool m_trace:1; // Trace this cell
public:
AstCell(FileLine* fl, const string& instName, const string& modName,
AstCell(FileLine* fl, FileLine* mfl,
const string& instName, const string& modName,
AstPin* pinsp, AstPin* paramsp, AstRange* rangep)
: AstNode(fl)
, m_modNameFileline(mfl)
, m_name(instName), m_origName(instName), m_modName(modName)
, m_modp(NULL), m_hasIfaceVar(false), m_recursive(false), m_trace(true) {
addNOp1p(pinsp); addNOp2p(paramsp); setNOp3p(rangep); }
@@ -1841,6 +1861,7 @@ public:
void origName(const string& name) { m_origName = name; }
string modName() const { return m_modName; } // * = Instance name
void modName(const string& name) { m_modName = name; }
FileLine* modNameFileline() const { return m_modNameFileline; }
AstPin* pinsp() const { return VN_CAST(op1p(), Pin); } // op1 = List of cell ports
AstPin* paramsp() const { return VN_CAST(op2p(), Pin); } // op2 = List of parameter #(##) values
AstRange* rangep() const { return VN_CAST(op3p(), Range); } // op3 = Range of arrayed instants (NULL=not ranged)
@@ -1858,21 +1879,27 @@ public:
class AstCellInline : public AstNode {
// A instantiation cell that was removed by inlining
// For communication between V3Inline and V3LinkDot only
// For communication between V3Inline and V3LinkDot,
// except for VPI runs where it exists until the end.
// It is augmented with the scope in V3Scope for VPI.
// Children: When 2 levels inlined, other CellInline under this
private:
string m_name; // Cell name, possibly {a}__DOT__{b}...
string m_origModName; // Original name of the module, ignoring name() changes, for dot lookup
AstScope* m_scopep; // The scope that the cell is inlined into
public:
AstCellInline(FileLine* fl, const string& name, const string& origModName)
: AstNode(fl)
, m_name(name), m_origModName(origModName) {}
, m_name(name), m_origModName(origModName), m_scopep(NULL) {}
ASTNODE_NODE_FUNCS(CellInline)
virtual void dump(std::ostream& str);
virtual const char* broken() const { BROKEN_RTN(m_scopep && !m_scopep->brokeExists()); return NULL; }
// ACCESSORS
virtual string name() const { return m_name; } // * = Cell name
string origModName() const { return m_origModName; } // * = modp()->origName() before inlining
virtual void name(const string& name) { m_name = name; }
void scopep(AstScope* scp) { m_scopep = scp; }
AstScope* scopep() const { return m_scopep; }
};
class AstCellRef : public AstNode {
@@ -1934,7 +1961,7 @@ public:
AstBind(FileLine* fl, const string& name, AstNode* cellsp)
: AstNode(fl)
, m_name(name) {
if (!VN_IS(cellsp, Cell)) cellsp->v3fatalSrc("Only cells allowed to be bound");
UASSERT_OBJ(VN_IS(cellsp, Cell), cellsp, "Only cells allowed to be bound");
addNOp1p(cellsp);
}
ASTNODE_NODE_FUNCS(Bind)
@@ -1983,10 +2010,11 @@ class AstParseRef : public AstNode {
// Parents: math|stmt
// Children: TEXT|DOT|SEL*|TASK|FUNC (or expression under sel)
private:
AstParseRefExp m_expect; // Type we think it should resolve to
string m_name;
VParseRefExp m_expect; // Type we think it should resolve to
string m_name;
public:
AstParseRef(FileLine* fl, AstParseRefExp expect, const string& name, AstNode* lhsp, AstNodeFTaskRef* ftaskrefp)
AstParseRef(FileLine* fl, VParseRefExp expect, const string& name,
AstNode* lhsp, AstNodeFTaskRef* ftaskrefp)
: AstNode(fl), m_expect(expect), m_name(name) { setNOp1p(lhsp); setNOp2p(ftaskrefp); }
ASTNODE_NODE_FUNCS(ParseRef)
virtual void dump(std::ostream& str);
@@ -1999,8 +2027,8 @@ public:
virtual string emitVerilog() { V3ERROR_NA; return ""; }
virtual string emitC() { V3ERROR_NA; return ""; }
virtual void name(const string& name) { m_name = name; }
AstParseRefExp expect() const { return m_expect; }
void expect(AstParseRefExp exp) { m_expect = exp; }
VParseRefExp expect() const { return m_expect; }
void expect(VParseRefExp exp) { m_expect = exp; }
// op1 = Components
AstNode* lhsp() const { return op1p(); } // op1 = List of statements
AstNode* ftaskrefp() const { return op2p(); } // op2 = Function/task reference
@@ -2112,53 +2140,53 @@ class AstSenItem : public AstNodeSenItem {
// Parents: SENTREE
// Children: (optional) VARREF SENGATE
private:
AstEdgeType m_edgeType; // Edge type
VEdgeType m_edgeType; // Edge type
public:
class Combo {}; // for creator type-overload selection
class Illegal {}; // for creator type-overload selection
class Initial {}; // for creator type-overload selection
class Settle {}; // for creator type-overload selection
class Never {}; // for creator type-overload selection
AstSenItem(FileLine* fl, AstEdgeType edgeType, AstNode* varrefp)
AstSenItem(FileLine* fl, VEdgeType edgeType, AstNode* varrefp)
: AstNodeSenItem(fl), m_edgeType(edgeType) {
setOp1p(varrefp);
}
AstSenItem(FileLine* fl, Combo)
: AstNodeSenItem(fl) {
m_edgeType = AstEdgeType::ET_COMBO;
m_edgeType = VEdgeType::ET_COMBO;
}
AstSenItem(FileLine* fl, Illegal)
: AstNodeSenItem(fl) {
m_edgeType = AstEdgeType::ET_ILLEGAL;
m_edgeType = VEdgeType::ET_ILLEGAL;
}
AstSenItem(FileLine* fl, Initial)
: AstNodeSenItem(fl) {
m_edgeType = AstEdgeType::ET_INITIAL;
m_edgeType = VEdgeType::ET_INITIAL;
}
AstSenItem(FileLine* fl, Settle)
: AstNodeSenItem(fl) {
m_edgeType = AstEdgeType::ET_SETTLE;
m_edgeType = VEdgeType::ET_SETTLE;
}
AstSenItem(FileLine* fl, Never)
: AstNodeSenItem(fl) {
m_edgeType = AstEdgeType::ET_NEVER;
m_edgeType = VEdgeType::ET_NEVER;
}
ASTNODE_NODE_FUNCS(SenItem)
virtual void dump(std::ostream& str);
virtual V3Hash sameHash() const { return V3Hash(edgeType()); }
virtual bool same(const AstNode* samep) const {
return edgeType()==static_cast<const AstSenItem*>(samep)->edgeType(); }
AstEdgeType edgeType() const { return m_edgeType; } // * = Posedge/negedge
void edgeType(AstEdgeType type) { m_edgeType = type; editCountInc(); } // * = Posedge/negedge
VEdgeType edgeType() const { return m_edgeType; } // * = Posedge/negedge
void edgeType(VEdgeType type) { m_edgeType = type; editCountInc(); } // * = Posedge/negedge
AstNode* sensp() const { return op1p(); } // op1 = Signal sensitized
AstNodeVarRef* varrefp() const { return VN_CAST(op1p(), NodeVarRef); } // op1 = Signal sensitized
//
virtual bool isClocked() const { return edgeType().clockedStmt(); }
virtual bool isCombo() const { return edgeType()==AstEdgeType::ET_COMBO; }
virtual bool isInitial() const { return edgeType()==AstEdgeType::ET_INITIAL; }
virtual bool isIllegal() const { return edgeType()==AstEdgeType::ET_ILLEGAL; }
virtual bool isSettle() const { return edgeType()==AstEdgeType::ET_SETTLE; }
virtual bool isNever() const { return edgeType()==AstEdgeType::ET_NEVER; }
virtual bool isCombo() const { return edgeType()==VEdgeType::ET_COMBO; }
virtual bool isInitial() const { return edgeType()==VEdgeType::ET_INITIAL; }
virtual bool isIllegal() const { return edgeType()==VEdgeType::ET_ILLEGAL; }
virtual bool isSettle() const { return edgeType()==VEdgeType::ET_SETTLE; }
virtual bool isNever() const { return edgeType()==VEdgeType::ET_NEVER; }
bool hasVar() const { return !(isCombo()||isInitial()||isSettle()||isNever()); }
};
@@ -2366,15 +2394,17 @@ class AstComment : public AstNodeStmt {
// Parents: {statement list}
// Children: none
private:
bool m_showAt; // Show "at <fileline>"
string m_name; // Text of comment
public:
AstComment(FileLine* fl, const string& name)
AstComment(FileLine* fl, const string& name, bool showAt=false)
: AstNodeStmt(fl)
, m_name(name) {}
, m_showAt(showAt), m_name(name) {}
ASTNODE_NODE_FUNCS(Comment)
virtual string name() const { return m_name; } // * = Text
virtual V3Hash sameHash() const { return V3Hash(); } // Ignore name in comments
virtual bool same(const AstNode* samep) const { return true; } // Ignore name in comments
virtual bool showAt() const { return m_showAt; }
};
class AstCond : public AstNodeCond {
@@ -2659,6 +2689,35 @@ public:
void filep(AstNodeVarRef* nodep) { setNOp3p(nodep); }
};
class AstElabDisplay : public AstNode {
// Parents: stmtlist
// Children: SFORMATF to generate print string
private:
AstDisplayType m_displayType;
public:
AstElabDisplay(FileLine* fileline, AstDisplayType dispType, AstNode* exprsp)
: AstNode(fileline) {
setOp1p(new AstSFormatF(fileline, AstSFormatF::NoFormat(), exprsp));
m_displayType = dispType;
}
ASTNODE_NODE_FUNCS(ElabDisplay)
virtual const char* broken() const { BROKEN_RTN(!fmtp()); return NULL; }
virtual string verilogKwd() const { return (string("$")+string(displayType().ascii())); }
virtual bool isGateOptimizable() const { return false; }
virtual bool isPredictOptimizable() const { return false; }
virtual bool isPure() const { return false; } // SPECIAL: $display has 'visual' ordering
virtual bool isOutputter() const { return true; } // SPECIAL: $display makes output
virtual bool isUnlikely() const { return true; }
virtual V3Hash sameHash() const { return V3Hash(displayType()); }
virtual bool same(const AstNode* samep) const {
return displayType()==static_cast<const AstElabDisplay*>(samep)->displayType(); }
virtual int instrCount() const { return instrCountPli(); }
AstDisplayType displayType() const { return m_displayType; }
void displayType(AstDisplayType type) { m_displayType = type; }
void fmtp(AstSFormatF* nodep) { addOp1p(nodep); } // op1 = To-String formatter
AstSFormatF* fmtp() const { return VN_CAST(op1p(), SFormatF); }
};
class AstSFormat : public AstNodeStmt {
// Parents: statement container
// Children: string to load
@@ -2826,6 +2885,86 @@ public:
void countp(AstNode* nodep) { setNOp4p(nodep); }
};
class AstFRewind : public AstNodeMath {
// Parents: stmtlist
// Children: file which must be a varref
public:
AstFRewind(FileLine* fileline, AstNode* filep)
: AstNodeMath(fileline) {
setNOp2p(filep);
}
ASTNODE_NODE_FUNCS(FRewind)
virtual string verilogKwd() const { return "$frewind"; }
virtual string emitVerilog() { V3ERROR_NA; return ""; }
virtual string emitC() { V3ERROR_NA; return ""; }
virtual bool isGateOptimizable() const { return false; }
virtual bool isPredictOptimizable() const { return false; }
virtual bool isPure() const { return false; }
virtual bool isOutputter() const { return true; }
virtual bool isUnlikely() const { return true; }
virtual bool cleanOut() { return false; }
virtual V3Hash sameHash() const { return V3Hash(); }
virtual bool same(const AstNode* samep) const { return true; }
AstNode* filep() const { return op2p(); }
void filep(AstNodeVarRef* nodep) { setNOp2p(nodep); }
};
class AstFTell : public AstNodeMath {
// Parents: stmtlist
// Children: file which must be a varref
public:
AstFTell(FileLine* fileline, AstNode* filep)
: AstNodeMath(fileline) {
setNOp2p(filep);
}
ASTNODE_NODE_FUNCS(FTell)
virtual string verilogKwd() const { return "$ftell"; }
virtual string emitVerilog() { V3ERROR_NA; return ""; }
virtual string emitC() { V3ERROR_NA; return ""; }
virtual bool isGateOptimizable() const { return false; }
virtual bool isPredictOptimizable() const { return false; }
virtual bool isPure() const { return false; }
virtual bool isOutputter() const { return true; }
virtual bool isUnlikely() const { return true; }
virtual bool cleanOut() { return false; }
virtual V3Hash sameHash() const { return V3Hash(); }
virtual bool same(const AstNode* samep) const { return true; }
AstNode* filep() const { return op2p(); }
void filep(AstNodeVarRef* nodep) { setNOp2p(nodep); }
};
class AstFSeek : public AstNodeMath {
// Parents: expr
// Children: file which must be a varref
// Children: offset
// Children: operation
public:
AstFSeek(FileLine* fileline, AstNode* filep,
AstNode* offset, AstNode* operation)
: AstNodeMath(fileline) {
setOp2p(filep);
setNOp3p(offset);
setNOp4p(operation);
}
ASTNODE_NODE_FUNCS(FSeek)
virtual string verilogKwd() const { return "$fseek"; }
virtual string emitVerilog() { V3ERROR_NA; return ""; }
virtual string emitC() { V3ERROR_NA; return ""; }
virtual bool isGateOptimizable() const { return false; }
virtual bool isPredictOptimizable() const { return false; }
virtual bool isPure() const { return false; } // SPECIAL: has 'visual' ordering
virtual bool isOutputter() const { return true; } // SPECIAL: makes output
virtual bool cleanOut() { return false; }
virtual V3Hash sameHash() const { return V3Hash(); }
virtual bool same(const AstNode* samep) const { return true; }
AstNode* filep() const { return op2p(); }
void filep(AstNode* nodep) { setOp2p(nodep); }
AstNode* offset() const { return op3p(); }
void offset(AstNode* nodep) { setNOp3p(nodep); }
AstNode* operation() const { return op4p(); }
void operation(AstNode* nodep) { setNOp4p(nodep); }
};
class AstFScanF : public AstNodeMath {
// Parents: expr
// Children: file which must be a varref
@@ -3062,7 +3201,7 @@ public:
ASTNODE_NODE_FUNCS(Repeat)
AstNode* countp() const { return op2p(); } // op2 = condition to continue
AstNode* bodysp() const { return op3p(); } // op3 = body of loop
virtual bool isGateOptimizable() const { return false; } // Not releavant - converted to FOR
virtual bool isGateOptimizable() const { return false; } // Not relevant - converted to FOR
virtual int instrCount() const { return instrCountBranch(); }
virtual V3Hash sameHash() const { return V3Hash(); }
virtual bool same(const AstNode* samep) const { return true; }
@@ -3209,27 +3348,6 @@ public:
AstJumpLabel* labelp() const { return m_labelp; }
};
class AstUntilStable : public AstNodeStmt {
// Quasi-while loop until given signals are stable
// Parents: CFUNC (generally)
// Children: VARREF, statements
public:
AstUntilStable(FileLine* fileline, AstVarRef* stablesp, AstNode* bodysp)
: AstNodeStmt(fileline) {
addNOp2p(stablesp); addNOp3p(bodysp);
}
ASTNODE_NODE_FUNCS(UntilStable)
AstVarRef* stablesp() const { return VN_CAST(op2p(), VarRef); } // op2 = list of variables that must become stable
AstNode* bodysp() const { return op3p(); } // op3 = body of loop
void addStablesp(AstVarRef* newp) { addOp2p(newp); }
void addBodysp(AstNode* newp) { addOp3p(newp); }
virtual bool isGateOptimizable() const { return false; } // Not relevant
virtual bool isPredictOptimizable() const { return false; } // Not relevant
virtual int instrCount() const { return instrCountBranch(); }
virtual V3Hash sameHash() const { return V3Hash(); }
virtual bool same(const AstNode* samep) const { return true; }
};
class AstChangeXor : public AstNodeBiComAsv {
// A comparison to determine change detection, common & must be fast.
// Returns 32-bit or 64-bit value where 0 indicates no change.
@@ -3843,7 +3961,7 @@ class AstExtend : public AstNodeUniop {
public:
AstExtend(FileLine* fl, AstNode* lhsp) : AstNodeUniop(fl, lhsp) {}
AstExtend(FileLine* fl, AstNode* lhsp, int width) : AstNodeUniop(fl, lhsp) {
dtypeSetLogicSized(width, width, AstNumeric::UNSIGNED); }
dtypeSetLogicSized(width, AstNumeric::UNSIGNED); }
ASTNODE_NODE_FUNCS(Extend)
virtual void numberOperate(V3Number& out, const V3Number& lhs) { out.opAssign(lhs); }
virtual string emitVerilog() { return "%l"; }
@@ -3859,7 +3977,7 @@ public:
AstExtendS(FileLine* fl, AstNode* lhsp) : AstNodeUniop(fl, lhsp) {}
AstExtendS(FileLine* fl, AstNode* lhsp, int width) : AstNodeUniop(fl, lhsp) {
// Important that widthMin be correct, as opExtend requires it after V3Expand
dtypeSetLogicSized(width, width, AstNumeric::UNSIGNED); }
dtypeSetLogicSized(width, AstNumeric::UNSIGNED); }
ASTNODE_NODE_FUNCS(ExtendS)
virtual void numberOperate(V3Number& out, const V3Number& lhs) {
out.opExtendS(lhs, lhsp()->widthMinV());
@@ -3876,8 +3994,8 @@ class AstSigned : public AstNodeUniop {
// $signed(lhs)
public:
AstSigned(FileLine* fl, AstNode* lhsp) : AstNodeUniop(fl, lhsp) {
if (v3Global.assertDTypesResolved()) { v3fatalSrc("not coded to create after dtypes resolved"); }
}
UASSERT_OBJ(!v3Global.assertDTypesResolved(), this,
"not coded to create after dtypes resolved"); }
ASTNODE_NODE_FUNCS(Signed)
virtual void numberOperate(V3Number& out, const V3Number& lhs) { out.opAssign(lhs); out.isSigned(false); }
virtual string emitVerilog() { return "%f$signed(%l)"; }
@@ -3891,8 +4009,8 @@ class AstUnsigned : public AstNodeUniop {
// $unsigned(lhs)
public:
AstUnsigned(FileLine* fl, AstNode* lhsp) : AstNodeUniop(fl, lhsp) {
if (v3Global.assertDTypesResolved()) { v3fatalSrc("not coded to create after dtypes resolved"); }
}
UASSERT_OBJ(!v3Global.assertDTypesResolved(), this,
"not coded to create after dtypes resolved"); }
ASTNODE_NODE_FUNCS(Unsigned)
virtual void numberOperate(V3Number& out, const V3Number& lhs) { out.opAssign(lhs); out.isSigned(false); }
virtual string emitVerilog() { return "%f$unsigned(%l)"; }
@@ -4097,7 +4215,7 @@ public:
m_size = setwidth;
if (setwidth) {
if (minwidth==-1) minwidth = setwidth;
dtypeSetLogicSized(setwidth, minwidth, AstNumeric::UNSIGNED);
dtypeSetLogicUnsized(setwidth, minwidth, AstNumeric::UNSIGNED);
}
}
AstCCast(FileLine* fl, AstNode* lhsp, AstNode* typeFromp) : AstNodeUniop(fl, lhsp) {
@@ -4865,7 +4983,7 @@ class AstShiftL : public AstNodeBiop {
public:
AstShiftL(FileLine* fl, AstNode* lhsp, AstNode* rhsp, int setwidth=0)
: AstNodeBiop(fl, lhsp, rhsp) {
if (setwidth) { dtypeSetLogicSized(setwidth, setwidth, AstNumeric::UNSIGNED); }
if (setwidth) { dtypeSetLogicSized(setwidth, AstNumeric::UNSIGNED); }
}
ASTNODE_NODE_FUNCS(ShiftL)
virtual AstNode* cloneType(AstNode* lhsp, AstNode* rhsp) { return new AstShiftL(this->fileline(), lhsp, rhsp); }
@@ -4883,7 +5001,7 @@ class AstShiftR : public AstNodeBiop {
public:
AstShiftR(FileLine* fl, AstNode* lhsp, AstNode* rhsp, int setwidth=0)
: AstNodeBiop(fl, lhsp, rhsp) {
if (setwidth) { dtypeSetLogicSized(setwidth, setwidth, AstNumeric::UNSIGNED); }
if (setwidth) { dtypeSetLogicSized(setwidth, AstNumeric::UNSIGNED); }
}
ASTNODE_NODE_FUNCS(ShiftR)
virtual AstNode* cloneType(AstNode* lhsp, AstNode* rhsp) { return new AstShiftR(this->fileline(), lhsp, rhsp); }
@@ -4905,7 +5023,7 @@ public:
AstShiftRS(FileLine* fl, AstNode* lhsp, AstNode* rhsp, int setwidth=0)
: AstNodeBiop(fl, lhsp, rhsp) {
// Important that widthMin be correct, as opExtend requires it after V3Expand
if (setwidth) { dtypeSetLogicSized(setwidth, setwidth, AstNumeric::SIGNED); }
if (setwidth) { dtypeSetLogicSized(setwidth, AstNumeric::SIGNED); }
}
ASTNODE_NODE_FUNCS(ShiftRS)
virtual AstNode* cloneType(AstNode* lhsp, AstNode* rhsp) { return new AstShiftRS(this->fileline(), lhsp, rhsp); }
@@ -5282,7 +5400,6 @@ public:
AstConcat(FileLine* fl, AstNode* lhsp, AstNode* rhsp) : AstNodeBiop(fl, lhsp, rhsp) {
if (lhsp->dtypep() && rhsp->dtypep()) {
dtypeSetLogicSized(lhsp->dtypep()->width()+rhsp->dtypep()->width(),
lhsp->dtypep()->width()+rhsp->dtypep()->width(),
AstNumeric::UNSIGNED);
}
}
@@ -5325,7 +5442,6 @@ private:
if (lhsp()) {
if (const AstConst* constp = VN_CAST(rhsp(), Const)) {
dtypeSetLogicSized(lhsp()->width()*constp->toUInt(),
lhsp()->width()*constp->toUInt(),
AstNumeric::UNSIGNED);
}
}
@@ -5663,6 +5779,23 @@ public:
bool tracking() const { return m_tracking; }
};
class AstTextBlock : public AstText {
private:
bool m_commas; // Comma separate emitted children
public:
AstTextBlock(FileLine* fl, const string& textp="", bool tracking=false,
bool commas=false)
: AstText(fl, textp, tracking), m_commas(commas) {}
ASTNODE_NODE_FUNCS(TextBlock)
void commas(bool flag) { m_commas = flag; }
bool commas() const { return m_commas; }
AstNode* nodesp() const { return op1p(); }
void addNodep(AstNode* nodep) { addOp1p(nodep); }
void addText(FileLine* fl, const string& textp, bool tracking=false) {
addNodep(new AstText(fl, textp, tracking));
}
};
class AstScCtor : public AstNodeText {
public:
AstScCtor(FileLine* fl, const string& textp)
@@ -5735,29 +5868,58 @@ public:
};
//======================================================================
// Emit C nodes
// Emitted file nodes
class AstCFile : public AstNode {
// C++ output file
class AstFile : public AstNode {
// Emitted Otput file
// Parents: NETLIST
// Children: nothing yet
// Children: AstTextBlock
private:
string m_name; ///< Filename
public:
AstFile(FileLine* fl, const string& name)
: AstNode(fl) {
m_name = name;
}
ASTNODE_BASE_FUNCS(File)
virtual string name() const { return m_name; }
virtual V3Hash sameHash() const { return V3Hash(); }
virtual bool same(const AstNode* samep) const { return true; }
void tblockp(AstTextBlock* tblockp) { setOp1p(tblockp); }
AstTextBlock* tblockp() { return VN_CAST(op1p(), TextBlock); }
};
//======================================================================
// Emit V nodes
class AstVFile : public AstFile {
// Verilog output file
// Parents: NETLIST
public:
AstVFile(FileLine* fl, const string& name)
: AstFile(fl, name) { }
ASTNODE_NODE_FUNCS(VFile)
virtual void dump(std::ostream& str=std::cout);
};
//======================================================================
// Emit C nodes
class AstCFile : public AstFile {
// C++ output file
// Parents: NETLIST
private:
bool m_slow:1; ///< Compile w/o optimization
bool m_source:1; ///< Source file (vs header file)
bool m_support:1; ///< Support file (non systemc)
public:
AstCFile(FileLine* fl, const string& name)
: AstNode(fl) {
m_name = name;
: AstFile(fl, name) {
m_slow = false;
m_source = false;
m_support = false;
}
ASTNODE_NODE_FUNCS(CFile)
virtual string name() const { return m_name; }
virtual V3Hash sameHash() const { return V3Hash(); }
virtual bool same(const AstNode* samep) const { return true; }
virtual void dump(std::ostream& str=std::cout);
bool slow() const { return m_slow; }
void slow(bool flag) { m_slow = flag; }
@@ -5969,7 +6131,7 @@ public:
AstCMath(FileLine* fl, const string& textStmt, int setwidth, bool cleanOut=true)
: AstNodeMath(fl), m_cleanOut(cleanOut) {
addNOp1p(new AstText(fl, textStmt, true));
if (setwidth) { dtypeSetLogicSized(setwidth, setwidth, AstNumeric::UNSIGNED); }
if (setwidth) { dtypeSetLogicSized(setwidth, AstNumeric::UNSIGNED); }
}
ASTNODE_NODE_FUNCS(CMath)
virtual bool isGateOptimizable() const { return false; }
@@ -6071,12 +6233,8 @@ public:
class AstTypeTable : public AstNode {
// Container for hash of standard data types
// Children: NODEDTYPEs
typedef std::map<std::pair<int,int>,AstBasicDType*> LogicMap;
AstBasicDType* m_basicps[AstBasicDTypeKwd::_ENUM_MAX];
//
enum { IDX0_LOGIC, IDX0_BIT, _IDX0_MAX };
LogicMap m_logicMap[_IDX0_MAX][AstNumeric::_ENUM_MAX]; // uses above IDX enums
//
typedef std::map<VBasicTypeKey,AstBasicDType*> DetailedMap;
DetailedMap m_detailedMap;
public:
@@ -6111,7 +6269,7 @@ private:
AstExecGraph* m_execGraphp; // Execution MTask graph for threads>1 mode
public:
AstNetlist()
: AstNode(new FileLine("AstRoot", 0))
: AstNode(new FileLine(FileLine::builtInFilename()))
, m_typeTablep(NULL)
, m_dollarUnitPkgp(NULL)
, m_evalp(NULL)
@@ -6127,8 +6285,8 @@ public:
AstNodeModule* topModulep() const { // * = Top module in hierarchy (first one added, for now)
return VN_CAST(op1p(), NodeModule); }
void addModulep(AstNodeModule* modulep) { addOp1p(modulep); }
AstCFile* filesp() const { return VN_CAST(op2p(), CFile);} // op2 = List of files
void addFilesp(AstCFile* filep) { addOp2p(filep); }
AstFile* filesp() const { return VN_CAST(op2p(), File);} // op2 = List of files
void addFilesp(AstFile* filep) { addOp2p(filep); }
AstNode* miscsp() const { return op3p(); } // op3 = List of dtypes etc
void addMiscsp(AstNode* nodep) { addOp3p(nodep); }
AstTypeTable* typeTablep() { return m_typeTablep; }
+4 -4
View File
@@ -28,7 +28,7 @@
// Unnamed BEGINs change only variable, not $display("%m") scope.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -141,7 +141,7 @@ private:
// Remap var names and replace lower Begins
iterateAndNextNull(nodep->stmtsp());
if (nodep->genforp()) nodep->v3fatalSrc("GENFORs should have been expanded earlier");
UASSERT_OBJ(!nodep->genforp(), nodep, "GENFORs should have been expanded earlier");
}
m_namedScope = oldScope;
m_unnamedScope = oldUnnamed;
@@ -227,7 +227,7 @@ private:
iterateChildren(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
BeginVisitor(AstNetlist* nodep, BeginState* statep) {
m_statep = statep;
m_modp = NULL;
@@ -276,7 +276,7 @@ private:
iterateChildren(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
BeginRelinkVisitor(AstNetlist* nodep, BeginState*) {
iterate(nodep);
}
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3BEGIN_H_
#define _V3BEGIN_H_ 1
+6 -6
View File
@@ -26,7 +26,7 @@
// Then, if FTASK is called only once, add inline attribute
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -87,10 +87,10 @@ private:
int elseUnlikely = m_unlikely;
// Compute
int likeness = ifLikely - ifUnlikely - (elseLikely - elseUnlikely);
if (likeness>0) {
nodep->branchPred(AstBranchPred::BP_LIKELY);
} else if (likeness<0) {
nodep->branchPred(AstBranchPred::BP_UNLIKELY);
if (likeness > 0) {
nodep->branchPred(VBranchPred::BP_LIKELY);
} else if (likeness < 0) {
nodep->branchPred(VBranchPred::BP_UNLIKELY);
} // else leave unknown
}
m_likely = lastLikely;
@@ -122,7 +122,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit BranchVisitor(AstNetlist* nodep) {
reset();
iterateChildren(nodep);
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3BRANCH_H_
#define _V3BRANCH_H_ 1
+37 -46
View File
@@ -24,7 +24,7 @@
// Check all links point to marked nodes
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -60,10 +60,9 @@ public:
// Called by operator delete on any node - only if VL_LEAK_CHECKS
if (debug()>=9) cout<<"-nodeDel: "<<cvtToHex(nodep)<<endl;
NodeMap::iterator iter = s_nodes.find(nodep);
if (iter==s_nodes.end() || !(iter->second & FLAG_ALLOCATED)) {
reinterpret_cast<const AstNode*>(nodep)
->v3fatalSrc("Deleting AstNode object that was never tracked or already deleted");
}
UASSERT_OBJ(!(iter==s_nodes.end() || !(iter->second & FLAG_ALLOCATED)),
reinterpret_cast<const AstNode*>(nodep),
"Deleting AstNode object that was never tracked or already deleted");
if (iter!=s_nodes.end()) s_nodes.erase(iter);
}
#if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 4
@@ -74,9 +73,8 @@ public:
// Called by operator new on any node - only if VL_LEAK_CHECKS
if (debug()>=9) cout<<"-nodeNew: "<<cvtToHex(nodep)<<endl;
NodeMap::iterator iter = s_nodes.find(nodep);
if (iter !=s_nodes.end() && (iter->second & FLAG_ALLOCATED)) {
nodep->v3fatalSrc("Newing AstNode object that is already allocated");
}
UASSERT_OBJ(!(iter !=s_nodes.end() && (iter->second & FLAG_ALLOCATED)),
nodep, "Newing AstNode object that is already allocated");
if (iter == s_nodes.end()) {
int flags = FLAG_ALLOCATED; // This int needed to appease GCC 4.1.2
s_nodes.insert(make_pair(nodep, flags));
@@ -96,19 +94,17 @@ public:
if (!linkable) return; // save some time, else the map will get huge!
#endif
NodeMap::iterator iter = s_nodes.find(nodep);
if (iter == s_nodes.end()) {
if (VL_UNCOVERABLE(iter == s_nodes.end())) {
#ifdef VL_LEAK_CHECKS
nodep->v3fatalSrc("AstNode is in tree, but not allocated");
#endif
} else {
if (!(iter->second & FLAG_ALLOCATED)) {
#ifdef VL_LEAK_CHECKS
nodep->v3fatalSrc("AstNode is in tree, but not allocated");
UASSERT_OBJ(iter->second & FLAG_ALLOCATED, nodep,
"AstNode is in tree, but not allocated");
#endif
}
if (iter->second & FLAG_IN_TREE) {
nodep->v3fatalSrc("AstNode is already in tree at another location");
}
UASSERT_OBJ(!(iter->second & FLAG_IN_TREE), nodep,
"AstNode is already in tree at another location");
}
int or_flags = FLAG_IN_TREE | (linkable?FLAG_LINKABLE:0);
if (iter == s_nodes.end()) {
@@ -183,7 +179,7 @@ public:
}
}
public:
// CONSTUCTORS
// CONSTRUCTORS
BrokenTable() {}
virtual ~BrokenTable() {}
};
@@ -217,7 +213,7 @@ private:
processAndIterate(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit BrokenMarkVisitor(AstNetlist* nodep) {
iterate(nodep);
}
@@ -230,35 +226,31 @@ public:
class BrokenCheckVisitor : public AstNVisitor {
private:
void checkWidthMin(const AstNode* nodep) {
if (nodep->width() != nodep->widthMin()
&& v3Global.widthMinUsage()==VWidthMinUsage::MATCHES_WIDTH) {
nodep->v3fatalSrc("Width != WidthMin");
}
UASSERT_OBJ(nodep->width() == nodep->widthMin()
|| v3Global.widthMinUsage() != VWidthMinUsage::MATCHES_WIDTH,
nodep, "Width != WidthMin");
}
void processAndIterate(AstNode* nodep) {
BrokenTable::setUnder(nodep, true);
if (const char* whyp=nodep->broken()) {
nodep->v3fatalSrc("Broken link in node (or something without maybePointedTo): "<<whyp);
}
const char* whyp = nodep->broken();
UASSERT_OBJ(!whyp, nodep,
"Broken link in node (or something without maybePointedTo): "<<whyp);
if (nodep->dtypep()) {
if (!nodep->dtypep()->brokeExists()) {
nodep->v3fatalSrc("Broken link in node->dtypep() to "
<<cvtToHex(nodep->dtypep()));
} else if (!VN_IS(nodep->dtypep(), NodeDType)) {
nodep->v3fatalSrc("Non-dtype link in node->dtypep() to "
<<cvtToHex(nodep->dtypep()));
}
UASSERT_OBJ(nodep->dtypep()->brokeExists(), nodep,
"Broken link in node->dtypep() to "<<cvtToHex(nodep->dtypep()));
UASSERT_OBJ(VN_IS(nodep->dtypep(), NodeDType), nodep,
"Non-dtype link in node->dtypep() to "<<cvtToHex(nodep->dtypep()));
}
if (v3Global.assertDTypesResolved()) {
if (nodep->hasDType()) {
if (!nodep->dtypep()) nodep->v3fatalSrc(
"No dtype on node with hasDType(): "<<nodep->prettyTypeName());
UASSERT_OBJ(nodep->dtypep(), nodep,
"No dtype on node with hasDType(): "<<nodep->prettyTypeName());
} else {
if (nodep->dtypep()) nodep->v3fatalSrc(
"DType on node without hasDType(): "<<nodep->prettyTypeName());
UASSERT_OBJ(!nodep->dtypep(), nodep,
"DType on node without hasDType(): "<<nodep->prettyTypeName());
}
if (nodep->getChildDTypep()) nodep->v3fatalSrc(
"childDTypep() non-null on node after should have removed");
UASSERT_OBJ(!nodep->getChildDTypep(), nodep,
"childDTypep() non-null on node after should have removed");
if (const AstNodeDType* dnodep = VN_CAST(nodep, NodeDType)) checkWidthMin(dnodep);
}
checkWidthMin(nodep);
@@ -267,18 +259,17 @@ private:
}
virtual void visit(AstNodeAssign* nodep) {
processAndIterate(nodep);
if (v3Global.assertDTypesResolved()
&& nodep->brokeLhsMustBeLvalue()
&& VN_IS(nodep->lhsp(), NodeVarRef)
&& !VN_CAST(nodep->lhsp(), NodeVarRef)->lvalue()) {
nodep->v3fatalSrc("Assignment LHS is not an lvalue");
}
UASSERT_OBJ(!(v3Global.assertDTypesResolved()
&& nodep->brokeLhsMustBeLvalue()
&& VN_IS(nodep->lhsp(), NodeVarRef)
&& !VN_CAST(nodep->lhsp(), NodeVarRef)->lvalue()),
nodep, "Assignment LHS is not an lvalue");
}
virtual void visit(AstNode* nodep) {
processAndIterate(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit BrokenCheckVisitor(AstNetlist* nodep) {
iterate(nodep);
}
@@ -291,9 +282,9 @@ public:
void V3Broken::brokenAll(AstNetlist* nodep) {
//UINFO(9,__FUNCTION__<<": "<<endl);
static bool inBroken = false;
if (inBroken) {
if (VL_UNCOVERABLE(inBroken)) {
// A error called by broken can recurse back into broken; avoid this
UINFO(1,"Broken called under broken, skipping recursion.\n");
UINFO(1,"Broken called under broken, skipping recursion.\n"); // LCOV_EXCL_LINE
} else {
inBroken = true;
BrokenTable::prepForTree();
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3BROKEN_H_
#define _V3BROKEN_H_ 1
+2 -2
View File
@@ -106,7 +106,7 @@ private:
//######################################################################
void V3CCtors::evalAsserts() {
AstNodeModule* modp = v3Global.rootp()->modulesp(); // Top module
AstNodeModule* modp = v3Global.rootp()->modulesp(); // Top module wrapper
AstCFunc* funcp = new AstCFunc(modp->fileline(), "_eval_debug_assertions", NULL, "void");
funcp->declPrivate(true);
funcp->isStatic(false);
@@ -134,7 +134,7 @@ void V3CCtors::evalAsserts() {
AstNodeIf* ifp = new AstIf(varp->fileline(), newp,
new AstCStmt(varp->fileline(),
"Verilated::overWidthError(\""+varp->prettyName()+"\");"));
ifp->branchPred(AstBranchPred::BP_UNLIKELY);
ifp->branchPred(VBranchPred::BP_UNLIKELY);
newp = ifp;
funcp->addStmtsp(newp);
}
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CCTORS_H_
#define _V3CCTORS_H_ 1
+11 -11
View File
@@ -37,7 +37,7 @@
// <000000001_000000000 at midpoint.)
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -72,7 +72,7 @@ private:
itemp; itemp=VN_CAST(itemp->nextp(), CaseItem)) {
if (itemp->isDefault()) {
if (hitDefault) {
nodep->v3error("Multiple default statements in case statement.");
itemp->v3error("Multiple default statements in case statement.");
}
hitDefault = true;
}
@@ -110,7 +110,7 @@ private:
iterateChildren(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit CaseLintVisitor(AstNodeCase* nodep) {
m_caseExprp = NULL;
iterate(nodep);
@@ -129,8 +129,8 @@ private:
AstUser3InUse m_inuser3;
// STATE
V3Double0 m_statCaseFast; // Statistic tracking
V3Double0 m_statCaseSlow; // Statistic tracking
VDouble0 m_statCaseFast; // Statistic tracking
VDouble0 m_statCaseSlow; // Statistic tracking
// Per-CASE
int m_caseWidth; // Width of valueItems
@@ -171,7 +171,7 @@ private:
for (AstNode* icondp = itemp->condsp(); icondp!=NULL; icondp=icondp->nextp()) {
//if (debug()>=9) icondp->dumpTree(cout, " caseitem: ");
AstConst* iconstp = VN_CAST(icondp, Const);
if (!iconstp) nodep->v3fatalSrc("above 'can't parse' should have caught this");
UASSERT_OBJ(iconstp, nodep, "above 'can't parse' should have caught this");
if (neverItem(nodep, iconstp)) {
// X in casez can't ever be executed
} else {
@@ -186,8 +186,8 @@ private:
if (!m_valueItem[i]) {
m_valueItem[i] = itemp;
} else if (!itemp->ignoreOverlap() && !bitched) {
itemp->v3warn(CASEOVERLAP, "Case values overlap (example pattern 0x"
<<std::hex<<i<<")");
icondp->v3warn(CASEOVERLAP, "Case values overlap (example pattern 0x"
<<std::hex<<i<<")");
bitched = true;
m_caseNoOverlapsAllCovered = false;
}
@@ -210,7 +210,7 @@ private:
return false;
}
}
if (m_caseItems <= 3) return false; // Not worth simplifing
if (m_caseItems <= 3) return false; // Not worth simplifying
// Convert valueItem from AstCaseItem* to the expression
// Not done earlier, as we may now have a NULL because it's just a ";" NOP branch
for (uint32_t i=0; i<(1UL<<m_caseWidth); ++i) {
@@ -223,7 +223,7 @@ private:
if (msb<0) {
// There's no space for a IF. We know upperValue is thus down to a specific
// exact value, so just return the tree value
// Note can't clone here, as we're going to check for equivelence above
// Note can't clone here, as we're going to check for equivalence above
return m_valueItem[upperValue];
}
else {
@@ -474,7 +474,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit CaseVisitor(AstNetlist* nodep) {
m_caseWidth = 0;
m_caseItems = 0;
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CASE_H_
#define _V3CASE_H_ 1
+4 -4
View File
@@ -40,7 +40,7 @@
// even if assigning to a unsigned.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -94,7 +94,7 @@ private:
// If we have uint64 = CAST(uint64(x)) then the upcasting
// really needs to be CAST(uint64(CAST(uint32(x))).
// Otherwise a (uint64)(a>b) would return wrong value, as
// less than has undeterministic signedness.
// less than has nondeterministic signedness.
if (nodep->isQuad() && !nodep->lhsp()->isQuad()
&& !VN_IS(nodep->lhsp(), CCast)) {
insertCast(nodep->lhsp(), VL_WORDSIZE);
@@ -154,7 +154,7 @@ private:
nodep->user1(1);
}
virtual void visit(AstConst* nodep) {
// Constants are of unknown size if smaller than 33 bits, becase
// Constants are of unknown size if smaller than 33 bits, because
// we're too lazy to wrap every constant in the universe in
// ((IData)#).
nodep->user1(nodep->isQuad() || nodep->isWide());
@@ -170,7 +170,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit CastVisitor(AstNetlist* nodep) {
iterate(nodep);
}
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CAST_H_
#define _V3CAST_H_ 1
+9 -9
View File
@@ -24,7 +24,7 @@
// Trace back to previous flop
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -154,7 +154,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
CdcDumpVisitor(AstNode* nodep, std::ofstream* ofp, const string& prefix) {
m_ofp = ofp;
m_prefix = prefix;
@@ -181,7 +181,7 @@ private:
}
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit CdcWidthVisitor(AstNode* nodep) {
m_maxLineno = 0;
m_maxFilenameLen = 0;
@@ -303,7 +303,7 @@ private:
}
}
string spaces(int level) { string out; while (level--) out += " "; return out; }
string spaces(int level) { string out; while (level--) out += " "; return out; } // LCOV_EXCL_LINE
string pad(unsigned column, const string& in) {
string out = in;
@@ -424,7 +424,7 @@ private:
}
//UINFO(9," finalflop "<<targetp->name()<<" "<<targetp->nodep()->fileline()<<endl);
warnAndFile(markp->nodep(), V3ErrorCode::CDCRSTLOGIC,
"Logic in path that feeds async reset, via signal: "+nodep->prettyName());
"Logic in path that feeds async reset, via signal: "+nodep->prettyNameQ());
dumpAsyncRecurse(targetp, "", " ", 0);
}
bool dumpAsyncRecurse(CdcEitherVertex* vertexp, const string& prefix,
@@ -633,9 +633,9 @@ private:
}
virtual void visit(AstNodeVarRef* nodep) {
if (m_scopep) {
if (!m_logicVertexp) nodep->v3fatalSrc("Var ref not under a logic block");
UASSERT_OBJ(m_logicVertexp, nodep, "Var ref not under a logic block");
AstVarScope* varscp = nodep->varScopep();
if (!varscp) nodep->v3fatalSrc("Var didn't get varscoped in V3Scope.cpp");
UASSERT_OBJ(varscp, nodep, "Var didn't get varscoped in V3Scope.cpp");
CdcVarVertex* varvertexp = makeVarVertex(varscp);
UINFO(5," VARREF to "<<varscp<<endl);
// We use weight of one for normal edges,
@@ -682,7 +682,7 @@ private:
}
virtual void visit(AstSenGate* nodep) {
// First handle the clock part will be handled in a minute by visit AstSenItem
// The logic gating term is delt with as logic
// The logic gating term is dealt with as logic
iterateNewStmt(nodep);
}
virtual void visit(AstAssignAlias* nodep) {
@@ -729,7 +729,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit CdcVisitor(AstNode* nodep) {
m_logicVertexp = NULL;
m_scopep = NULL;
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CDC_H_
#define _V3CDC_H_ 1
+9 -9
View File
@@ -29,7 +29,7 @@
// we need to indicate a new clock has been created.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -87,7 +87,7 @@ public:
m_tlChgFuncp->addStmtsp(new AstCReturn(m_scopetopp->fileline(), callp));
} else {
AstCReturn* returnp = VN_CAST(m_tlChgFuncp->stmtsp(), CReturn);
if (!returnp) m_scopetopp->v3fatalSrc("Lost CReturn in top change function");
UASSERT_OBJ(returnp, m_scopetopp, "Lost CReturn in top change function");
// This is currently using AstLogOr which will shortcut the
// evaluation if any function returns true. This is likely what
// we want and is similar to the logic already in use inside
@@ -182,7 +182,7 @@ private:
if (debug()) nodep->dumpTree(cout, "-DETECTARRAY-class-");
m_vscp->v3warn(E_DETECTARRAY, "Unsupported: Can't detect changes on complex variable"
" (probably with UNOPTFLAT warning suppressed): "
<<m_vscp->varp()->prettyName());
<<m_vscp->varp()->prettyNameQ());
}
}
virtual void visit(AstNode* nodep) {
@@ -190,10 +190,10 @@ private:
if (debug()) nodep->dumpTree(cout, "-DETECTARRAY-general-");
m_vscp->v3warn(E_DETECTARRAY, "Unsupported: Can't detect changes on complex variable"
" (probably with UNOPTFLAT warning suppressed): "
<<m_vscp->varp()->prettyName());
<<m_vscp->varp()->prettyNameQ());
}
public:
// CONSTUCTORS
// CONSTRUCTORS
ChangedInsertVisitor(AstVarScope* vscp, ChangedState* statep) {
m_statep = statep;
m_vscp = vscp;
@@ -241,7 +241,7 @@ private:
VL_DEBUG_FUNC; // Declare debug()
void genChangeDet(AstVarScope* vscp) {
vscp->v3warn(IMPERFECTSCH, "Imperfect scheduling of variable: "<<vscp->prettyName());
vscp->v3warn(IMPERFECTSCH, "Imperfect scheduling of variable: "<<vscp->prettyNameQ());
ChangedInsertVisitor visitor (vscp, m_statep);
}
@@ -260,8 +260,8 @@ private:
AstNode::user1ClearTree();
// Create the change detection function
AstScope* scopep = nodep->scopep();
if (!scopep) nodep->v3fatalSrc("No scope found on top level,"
" perhaps you have no statements?");
UASSERT_OBJ(scopep, nodep,
"No scope found on top level, perhaps you have no statements?");
m_statep->m_scopetopp = scopep;
// Create a wrapper change detection function that calls each change detection function
@@ -296,7 +296,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
ChangedVisitor(AstNetlist* nodep, ChangedState* statep) {
m_statep = statep;
iterate(nodep);
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CHANGED_H_
#define _V3CHANGED_H_ 1
+5 -4
View File
@@ -26,7 +26,7 @@
// Copy all width() values to widthMin() so RANGE, etc can still see orig widths
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -72,13 +72,14 @@ private:
int width = cppWidth(nodep); // widthMin is unchanged
if (old_dtypep->width() != width) {
// Since any given dtype's cppWidth() is the same, we can just
// remember one convertion for each, and reuse it
// remember one conversion for each, and reuse it
if (AstNodeDType* new_dtypep = VN_CAST(old_dtypep->user3p(), NodeDType)) {
nodep->dtypep(new_dtypep);
} else {
nodep->dtypeChgWidth(width, nodep->widthMin());
AstNodeDType* new_dtypep2 = nodep->dtypep();
if (new_dtypep2 == old_dtypep) nodep->v3fatalSrc("Dtype didn't change when width changed");
UASSERT_OBJ(new_dtypep2 != old_dtypep, nodep,
"Dtype didn't change when width changed");
old_dtypep->user3p(new_dtypep2); // Remember for next time
}
}
@@ -284,7 +285,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit CleanVisitor(AstNetlist* nodep) {
m_modp = NULL;
iterate(nodep);
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CLEAN_H_
#define _V3CLEAN_H_ 1
-924
View File
@@ -1,924 +0,0 @@
// -*- mode: C++; c-file-style: "cc-mode" -*-
//*************************************************************************
// DESCRIPTION: Verilator: Break always into sensitivity active domains
//
// Code available from: http://www.veripool.org/verilator
//
//*************************************************************************
//
// Copyright 2008-2019 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.
//
// Verilator is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//*************************************************************************
// V3ClkGater's Transformations:
//
// Look for clock gaters
// Note there's overlap between this process and V3Split's
// ALWAYS: Build graph
// IF: Form vertex pointing to any IFs or ALWAYS above
// VARREF: Form vertex pointing to IFs it is under
// ASSIGN: If under normal assignment, disable optimization
// FUTURE OPTIMIZE: If signal is set to itself, consider that OK for gating.
// !splitable: Mark all VARREFs in this statement as comming from it
// Optimize graph so if signal is referenced under multiple IF branches it moves up
// Make ALWAYS for each new gating term, and move statements there
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
#include "V3Global.h"
#include "V3Ast.h"
#include "V3Stats.h"
#include "V3Graph.h"
#include "V3ClkGater.h"
#include <algorithm>
#include <cstdarg>
#include <map>
#include <vector>
//######################################################################
// Base for debug
class GaterBaseVisitor : public AstNVisitor {
protected:
VL_DEBUG_FUNC; // Declare debug()
};
//######################################################################
// Support classes
class GaterVarVertex;
class GaterVertex : public V3GraphVertex {
static uint32_t s_rankNum;
public:
explicit GaterVertex(V3Graph* graphp)
: V3GraphVertex(graphp) {
s_rankNum++; rank(s_rankNum);
}
virtual ~GaterVertex() {}
virtual int typeNum() const = 0;
static void clearRank() { s_rankNum = 0; }
virtual int sortCmp(const V3GraphVertex* rhsp) const;
};
uint32_t GaterVertex::s_rankNum = 0;
class GaterHeadVertex : public GaterVertex {
public:
explicit GaterHeadVertex(V3Graph* graphp)
: GaterVertex(graphp) {}
virtual ~GaterHeadVertex() {}
virtual int typeNum() const { return __LINE__; } // C++ typeof() equivelent
virtual string name() const { return "*HEAD*"; }
virtual string dotColor() const { return "green"; }
};
class GaterPliVertex : public GaterVertex {
public:
explicit GaterPliVertex(V3Graph* graphp)
: GaterVertex(graphp) {}
virtual ~GaterPliVertex() {}
virtual int typeNum() const { return __LINE__; } // C++ typeof() equivelent
virtual string name() const { return "*PLI*"; }
virtual string dotColor() const { return "red"; }
};
class GaterIfVertex : public GaterVertex {
AstNodeIf* m_nodep;
public:
AstNodeIf* nodep() const { return m_nodep; }
GaterIfVertex(V3Graph* graphp, AstNodeIf* nodep)
: GaterVertex(graphp), m_nodep(nodep) { }
virtual ~GaterIfVertex() {}
virtual int typeNum() const { return __LINE__; } // C++ typeof() equivelent
virtual string name() const {
return cvtToHex(m_nodep)+" {"+cvtToStr(m_nodep->fileline()->lineno())+"}"; }
};
class GaterVarVertex : public GaterVertex {
AstVarScope* m_nodep;
public:
AstVarScope* nodep() const { return m_nodep; }
GaterVarVertex(V3Graph* graphp, AstVarScope* nodep)
: GaterVertex(graphp), m_nodep(nodep) { }
virtual ~GaterVarVertex() {}
virtual int typeNum() const { return __LINE__; } // C++ typeof() equivelent
virtual string name() const { return nodep()->name(); }
virtual string dotColor() const { return "skyblue"; }
};
//######################################################################
// Edge types
class GaterEdge : public V3GraphEdge {
uint32_t m_ifelse; // True branch of if
public:
// These are used as shift amounts into node's user()
#define VU_DEFINE enum VarUsage { VU_NONE=0, VU_IF=1, VU_ELSE=2, VU_PLI=4, VU_MADE=8}
VU_DEFINE;
uint32_t ifelse() const { return m_ifelse; }
bool ifelseTrue() const { return m_ifelse & VU_IF; }
bool ifelseFalse() const { return m_ifelse & VU_ELSE; }
bool ifelseBoth() const { return ifelseTrue() && ifelseFalse(); }
GaterEdge(V3Graph* graphp, V3GraphVertex* fromp, V3GraphVertex* top, uint32_t ifelse)
: V3GraphEdge(graphp, fromp, top, 10, false), m_ifelse(ifelse) {}
virtual ~GaterEdge() {}
virtual string dotColor() const { return ((ifelse() & VU_PLI) ? "red"
: (ifelseBoth() ? "blue"
: (ifelseTrue() ? "green"
: "darkgreen"))); }
virtual int sortCmp(const V3GraphEdge* rEdgep) const {
// Our master sort sorts by edges first, so we don't want to
// consider the upstream vertex::sortCmp when sorting by edges.
// We do want to order by something though; rank works
if (fromp()->rank() < rEdgep->fromp()->rank()) return -1;
if (fromp()->rank() > rEdgep->fromp()->rank()) return 1;
// If same, resolve by ifelse
const GaterEdge* crEdgep = static_cast<const GaterEdge*>(rEdgep);
if (m_ifelse < crEdgep->m_ifelse) return -1;
if (m_ifelse > crEdgep->m_ifelse) return 1;
return 0;
}
};
int GaterVertex::sortCmp(const V3GraphVertex* rhsp) const {
const GaterVertex* crhsp = static_cast<const GaterVertex*>(rhsp);
// We really only care about ordering Var's together, but...
// First put same type together
if (typeNum() < crhsp->typeNum()) return -1;
if (typeNum() > crhsp->typeNum()) return 1;
// If variable, group by same input fanin
// (know they're the same type based on above compare)
if (dynamic_cast<const GaterVarVertex*>(this)) {
// We've already sorted by edges, so just see if same tree
// If this gets too slow, we could compute a hash up front
V3GraphEdge* lEdgep = this->inBeginp();
V3GraphEdge* rEdgep = rhsp->inBeginp();
while (lEdgep && rEdgep) {
const GaterEdge* clEdgep = static_cast<const GaterEdge*>(lEdgep);
const GaterEdge* crEdgep = static_cast<const GaterEdge*>(rEdgep);
if (lEdgep->fromp()->rank() < rEdgep->fromp()->rank()) return -1;
if (lEdgep->fromp()->rank() > rEdgep->fromp()->rank()) return 1;
if (clEdgep->ifelse() < crEdgep->ifelse()) return -1;
if (clEdgep->ifelse() > crEdgep->ifelse()) return 1;
lEdgep = lEdgep->inNextp();
rEdgep = rEdgep->inNextp();
}
if (!lEdgep && !rEdgep) return 0;
return lEdgep ? -1 : 1;
}
// Finally by rank of this vertex
if (rank() < rhsp->rank()) return -1;
if (rank() > rhsp->rank()) return 1;
return 0;
}
//######################################################################
// Check for non-simple gating equations
class GaterCondVisitor : public GaterBaseVisitor {
private:
// RETURN STATE
bool m_isSimple; // Set false when we know it isn't simple
// METHODS
inline void okIterate(AstNode* nodep) {
if (m_isSimple) iterateChildren(nodep);
}
// VISITORS
virtual void visit(AstOr* nodep) { okIterate(nodep); }
virtual void visit(AstAnd* nodep) { okIterate(nodep); }
virtual void visit(AstNot* nodep) { okIterate(nodep); }
virtual void visit(AstLogOr* nodep) { okIterate(nodep); }
virtual void visit(AstLogAnd* nodep) { okIterate(nodep); }
virtual void visit(AstLogNot* nodep) { okIterate(nodep); }
virtual void visit(AstVarRef* nodep) { okIterate(nodep); }
// Other possibilities are equals, etc
// But, we don't want to get too complicated or it will take too much
// effort to calculate the gater
virtual void visit(AstNode* nodep) {
m_isSimple = false;
//iterateChildren(nodep);
}
public:
// CONSTUCTORS
explicit GaterCondVisitor(AstNode* nodep) {
m_isSimple = true;
iterate(nodep);
}
virtual ~GaterCondVisitor() {}
// PUBLIC METHODS
bool isSimple() const { return m_isSimple; }
};
//######################################################################
// Check for non-simple gating equations
class GaterBodyVisitor : public GaterBaseVisitor {
// NODE STATE
// Input state
// AstVarScope::user2p() -> AstAlways* moving this variable to
enum State {
// This is used as a bitmask
STATE_UNKNOWN = 0,
STATE_KEEP = 1, // Seen a variable we need, keep this statement
STATE_DELETE = 2 // Seen a variable we need, delete this statement
// 3=keep & delete
};
bool m_original; // Deleting original statements, vs deleting new var statements
AstNode* m_exprp; // New gater expression we are building
bool m_cloning; // Clone this object 0=not sure yet, 1=do
uint32_t m_state; // Parsing state
// VISITORS
virtual void visit(AstVarRef* nodep) {
if (nodep->lvalue()) {
AstVarScope* vscp = nodep->varScopep();
if (vscp->user2p() == m_exprp) {
// This variable's block needs to move to the new always
if (m_original) {
UINFO(9," VARREF delete in old: "<<nodep<<endl);
m_state |= STATE_DELETE;
} else {
UINFO(9," VARREF stays in new: "<<nodep<<endl);
m_state |= STATE_KEEP;
}
} else {
if (m_original) {
UINFO(9," VARREF other stays in old\n");
m_state |= STATE_KEEP;
} else {
UINFO(9," VARREF other delete in new\n");
m_state |= STATE_DELETE;
}
}
}
}
//virtual void visit(AstNodeIf* nodep) { ... }
// Not needed, it's the same handling as any other statement. Cool, huh?
// (We may get empty IFs but the constant propagater will rip them up for us)
virtual void visit(AstNodeStmt* nodep) {
if (!nodep->isStatement()) {
iterateChildren(nodep);
return;
}
uint32_t oldstate = m_state;
// Find if children want to delete this or not.
// Note children may bicker, and want to both keep and delete (branches on a if)
uint32_t childstate;
{
m_state = STATE_UNKNOWN;
iterateChildren(nodep);
childstate = m_state;
}
m_state = oldstate;
UINFO(9," Did state="<<childstate<<" "<<nodep<<endl);
// Indeterminate (statement with no lvalue), so keep only in original
if (childstate == STATE_UNKNOWN) {
if (m_original) childstate |= STATE_KEEP;
else childstate |= STATE_DELETE;
}
if ((childstate & STATE_DELETE) && !(childstate & STATE_KEEP)) {
nodep->unlinkFrBack()->deleteTree(); VL_DANGLING(nodep);
// Pass upwards we did delete
m_state |= STATE_DELETE;
} else {
// Pass upwards we must keep
m_state |= STATE_KEEP;
}
}
virtual void visit(AstNode* nodep) {
iterateChildren(nodep);
}
public:
// CONSTUCTORS
GaterBodyVisitor(AstAlways* nodep, AstNode* exprp, bool original) {
m_exprp = exprp;
m_original = original;
m_state = STATE_UNKNOWN;
m_cloning = false;
if (debug()>=9) nodep->dumpTree(cout, " GateBodyIn: ");
iterateAndNextNull(nodep->bodysp());
if (debug()>=9) nodep->dumpTree(cout, " GateBodyOut: ");
// If there's no statements we shouldn't have had a resulting graph
// vertex asking for this creation
}
virtual ~GaterBodyVisitor() {}
};
//######################################################################
// Create clock gaters
class GaterVisitor : public GaterBaseVisitor {
// NODE STATE
// Cleared on Always
// AstVarScope::user1p() -> GaterVarVertex*
// AstAlways::user4() -> bool. True indicates processed
// Cleared on each new Always
// AstVarScope::user2p() -> AstAlways* moving this variable to
AstUser1InUse m_inuser1;
AstUser2InUse m_inuser2;
AstUser4InUse m_inuser4;
// GRAPH STATE
// Cleared on simplify
// Vertex::user() -> VarUsage: Mark of which if/else edges are hit
// TYPES
VU_DEFINE;
enum MiscConsts {
IF_DEPTH_MAX = 4, // IFs deep we bother to analyze
DOMAINS_MAX = 32 // Clock domains before avoiding O(N^2) blowup
};
// MEMBERS
string m_nonopt; // Reason block is not optimizable
V3Double0 m_statGaters; // Statistic tracking
V3Double0 m_statBits; // Statistic tracking
bool m_directlyUnderAlw; // Immediately under Always or If
int m_ifDepth; // Depth of IF statements
int m_numIfs; // Number of IF statements
V3Graph m_graph; // Scoreboard of var usages/dependencies
GaterPliVertex* m_pliVertexp; // Element specifying PLI ordering
GaterHeadVertex* m_headVertexp; // Top vertex
V3GraphVertex* m_aboveVertexp; // Vertex above this point in tree
uint32_t m_aboveTrue; // Vertex above this point is true branch
AstVarScope* m_stmtVscp; // Current statement had variable assigned
bool m_stmtInPli; // Current statement has PLI
// METHODS
void nonOptimizable(AstNode* nodep, const char* reasonp) {
if (m_nonopt=="") {
UINFO(9," Nonopt: "<<reasonp<<": "<<nodep<<endl);
m_nonopt = reasonp;
}
}
void scoreboardPli(AstNode* nodep) {
// Order all PLI statements with other PLI statements
// This ensures $display's and such remain in proper order
// We don't prevent splitting out other non-pli statements, however,
// because it is common to have $uasserts sprinkled about.
if (!m_pliVertexp) {
m_pliVertexp = new GaterPliVertex(&m_graph);
}
if (m_stmtVscp) { // Already saw a variable, be sure to mark it!
GaterVarVertex* varVtxp = reinterpret_cast<GaterVarVertex*>(m_stmtVscp->user1p());
new GaterEdge(&m_graph, m_pliVertexp, varVtxp, VU_PLI);
}
m_stmtInPli = true; // Mark all followon variables too
}
// METHODS -- GRAPH stuff
void simplifyGraph() {
if (debug()>=9) m_graph.dumpDotFilePrefixed("gater_init", false);
// We now have all PLI variables with edges FROM the pli vertex
simplifyPli();
if (debug()>=9) m_graph.dumpDotFilePrefixed("gater_pli", false);
// Any vertex that points along both true & false path to variable
// can be simplfied so parent points to that vertex. Any vertex
// that points to a (great...) grandparent of a variable can just
// point to the edge.
m_graph.userClearVertices(); // user() will contain VarUsage
simplifyIfElseRecurse(m_headVertexp);
if (debug()>=9) m_graph.dumpDotFilePrefixed("gater_ifelse", false);
m_graph.userClearVertices(); // user() will contain VarUsage
simplifyGrandRecurse(m_headVertexp, 1);
if (debug()>=9) m_graph.dumpDotFilePrefixed("gater_grand", false);
simplifyRemoveUngated(m_headVertexp);
// Give all signals with same gating term same color
graphColorSameFeeder();
if (debug()>=9) m_graph.dumpDotFilePrefixed("gater_done", false);
}
void simplifyPli() {
// For now, we'll not gate any logic with PLI lvariables in it. In
// the future we may move PLI statements. One way to do so is to
// all below pli VARs to go IfVertex -> PliVertex -> VarVertex then
// they all must get colored the same. There may be a lot of
// duplicated edges to the PLI; they'll need cleanup. All of the
// later optimizations need to deal, and the GaterBodyVisitor needs
// to know how to move them.
if (m_pliVertexp) {
// Follow PLI out edges to find all relevant variables
for (V3GraphEdge* nextp,* edgep = m_pliVertexp->outBeginp(); edgep; edgep = nextp) {
nextp = edgep->outNextp(); // We may edit the list
if (GaterVarVertex* vVxp = dynamic_cast<GaterVarVertex*>(edgep->top())) {
vVxp->unlinkDelete(&m_graph); VL_DANGLING(vVxp); VL_DANGLING(edgep);
} else {
m_graph.dump();
v3fatalSrc("PLI vertex points to non-signal");
}
}
m_pliVertexp->unlinkDelete(&m_graph); m_pliVertexp = NULL;
}
}
void simplifyIfElseRecurse(V3GraphVertex* vertexp) {
// From bottom-up, propagate duplicate IF/ELSE branches to grandparent
for (V3GraphEdge* edgep = vertexp->outBeginp(); edgep; edgep=edgep->outNextp()) {
simplifyIfElseRecurse(edgep->top());
}
//UINFO(9,"IERecurse "<<vertexp<<endl);
if (dynamic_cast<GaterIfVertex*>(vertexp)) {
// Clear indications
for (V3GraphEdge* edgep = vertexp->outBeginp(); edgep; edgep=edgep->outNextp()) {
edgep->top()->user(VU_NONE);
}
// Mark nodes on to/from side
for (V3GraphEdge* edgep = vertexp->outBeginp(); edgep; edgep=edgep->outNextp()) {
V3GraphVertex* toVxp = edgep->top();
GaterEdge* cedgep = static_cast<GaterEdge*>(edgep);
// We may mark this twice in one pass - if so it's duplicated; no worries
if (cedgep->ifelseTrue()) toVxp->user(toVxp->user() | VU_IF);
if (cedgep->ifelseFalse()) toVxp->user(toVxp->user() | VU_ELSE);
//UINFO(9," mark "<<edgep<<" "<<toVxp<<endl);
}
// Any with both IF & ELSE mark get removal mark, and new parent edge
for (V3GraphEdge* nextp,* edgep = vertexp->outBeginp(); edgep; edgep = nextp) {
nextp = edgep->outNextp(); // We may edit the list
V3GraphVertex* toVxp = edgep->top();
//UINFO(9," to "<<toVxp->user()<<" "<<toVxp<<endl);
if ((toVxp->user() & VU_IF) && (toVxp->user() & VU_ELSE)) {
edgep->unlinkDelete(); VL_DANGLING(edgep);
if (!(toVxp->user() & VU_MADE)) { // Make an edge only once
toVxp->user(toVxp->user() | VU_MADE);
GaterEdge* inedgep = static_cast<GaterEdge*>(vertexp->inBeginp());
V3GraphVertex* grandparent = inedgep->fromp();
new GaterEdge(&m_graph, grandparent, toVxp, inedgep->ifelse());
}
}
}
}
}
void simplifyGrandRecurse(V3GraphVertex* vertexp, uint32_t depth) {
// From top-down delete any vars that grandparents source
// IE A -> B -> C -> VAR
// \----------^
//UINFO(9,"GRecurse "<<depth<<" "<<vertexp<<endl);
// Mark all variables to be swept
for (V3GraphEdge *nextp, *edgep = vertexp->outBeginp(); edgep; edgep=nextp) {
nextp = edgep->outNextp(); // We may edit the list
if (GaterVarVertex* toVxp = dynamic_cast<GaterVarVertex*>(edgep->top())) {
if (toVxp->user() && toVxp->user() < depth) {
// A recursion "above" us marked it,
// Remove this edge, it's redundant with the upper edge
edgep->unlinkDelete(); VL_DANGLING(edgep);
} else {
GaterEdge* cedgep = static_cast<GaterEdge*>(edgep);
if (cedgep->ifelseBoth()) {
toVxp->user(depth);
}
}
}
}
// Recurse
for (V3GraphEdge* edgep = vertexp->outBeginp(); edgep; edgep=edgep->outNextp()) {
simplifyGrandRecurse(edgep->top(), depth+1);
}
// Clean our marks
for (V3GraphEdge* edgep = vertexp->outBeginp(); edgep; edgep=edgep->outNextp()) {
V3GraphVertex* toVxp = edgep->top();
if (toVxp->user() && toVxp->user() < depth) { // A recursion "above" us marked it; don't mess with it
} else {
toVxp->user(0); // We marked it originally, so unmark now
}
}
// Delete any If nodes with no children
// Last, as want bottom-up cleanup
for (V3GraphEdge *nextp, *edgep = vertexp->outBeginp(); edgep; edgep=nextp) {
nextp = edgep->outNextp(); // We may edit the list
if (GaterIfVertex* toVxp = dynamic_cast<GaterIfVertex*>(edgep->top())) {
if (!toVxp->outBeginp()) {
if (!nextp || nextp->top() != edgep->top()) { // Else next would disappear; we'll do it next loop
toVxp->unlinkDelete(&m_graph); VL_DANGLING(toVxp); VL_DANGLING(edgep);
}
}
}
}
}
void simplifyRemoveUngated(V3GraphVertex* vertexp) {
// Remove variables that are ungated
// At this point, any variable under the head is ungated
for (V3GraphEdge *nextp, *edgep = vertexp->outBeginp(); edgep; edgep=nextp) {
nextp = edgep->outNextp(); // We may edit the list
if (GaterVarVertex* toVxp = dynamic_cast<GaterVarVertex*>(edgep->top())) {
if (!nextp || nextp->top() != edgep->top()) { // Else next would disappear; we'll do it next loop
toVxp->unlinkDelete(&m_graph); VL_DANGLING(toVxp); VL_DANGLING(edgep);
}
}
}
}
void graphColorSameFeeder() {
// Assign same color to all destination vertices that have same
// subgraph feeding into them
// (I.E. all "from" nodes are common within each color)
// We could hash, but instead it's faster to sort edges, so we know
// the same edge list is always adjacent. The result is a
// O(vertices*edges) loop, but we'd need that to hash too.
if (debug()>9) { cout<<"PreColor:\n"; m_graph.dump(); }
m_graph.sortEdges();
// Now sort vertices, so same inbound edge set ends up adjacent
m_graph.sortVertices();
// Now walk and assign colors; same color is adjacent
m_graph.clearColors();
m_graph.userClearEdges(); // Used by newExprFromGraph
uint32_t color = 1;
GaterVarVertex* lastVxp = NULL;
for (V3GraphVertex* vertexp = m_graph.verticesBeginp();
vertexp; vertexp=vertexp->verticesNextp()) {
if (GaterVarVertex* vVxp = dynamic_cast<GaterVarVertex*>(vertexp)) {
if (!vVxp->inBeginp()) {
// At this point, any variable not linked is an error
// (It should have at least landed under the Head node)
vVxp->nodep()->v3fatalSrc("Variable became stranded in clk gate detection");
}
if (!lastVxp || vVxp->sortCmp(lastVxp)) {
// Different sources for this new node
color++;
}
vVxp->color(color);
lastVxp = vVxp;
}
}
if (debug()>9) { cout<<"PostColor:\n"; m_graph.dump(); }
}
AstNode* newExprFromGraph(GaterVarVertex* vertexp) {
// Recurse backwards, then form equation on return path
// We could use user()!=0, but zeroing it is slow, so instead we'll mark with a generation
// We get equations like "a | (!a & b)" which obviously could be reduced here,
// instead out of generality, there's a V3Const::matchOrAndNot that'll clean it up
static uint32_t s_generation = 0;
++s_generation;
nafgMarkRecurse(vertexp, s_generation);
AstNode* nodep = nafgCreateRecurse(m_headVertexp, s_generation);
if (debug()>=9) nodep->dumpTree(cout, " GateExpr: ");
return nodep;
}
void nafgMarkRecurse(V3GraphVertex* vertexp, uint32_t generation) {
// Backwards mark user() on the path we recurse
//UINFO(9," nafgMark: v "<<cvtToHex(vertexp)<<" "<<vertexp->name()<<endl);
for (V3GraphEdge* edgep = vertexp->inBeginp(); edgep; edgep = edgep->inNextp()) {
//UINFO(9," nafgMark: "<<cvtToHex(edgep)<<" "<<edgep->name()<<endl);
edgep->user(generation);
nafgMarkRecurse(edgep->fromp(), generation);
}
}
AstNode* nafgCreateRecurse(V3GraphVertex* vertexp, uint32_t generation) {
// Forewards follow user() marked previously and build tree
AstNode* nodep = NULL;
// OR across all edges found at this level
//UINFO(9," nafgEnter: v "<<cvtToHex(vertexp)<<" "<<vertexp->name()<<endl);
for (V3GraphEdge* edgep = vertexp->outBeginp(); edgep; edgep = edgep->outNextp()) {
if (edgep->user() == generation) {
GaterEdge* cedgep = static_cast<GaterEdge*>(edgep);
AstNode* eqnp = NULL;
//UINFO(9," nafgFollow: "<<cvtToHex(edgep)<<" "<<edgep->name()<<endl);
if (dynamic_cast<GaterHeadVertex*>(edgep->fromp())) {
// Just OR in all lower terms
eqnp = nafgCreateRecurse(edgep->top(), generation);
} else if (GaterIfVertex* cVxp = dynamic_cast<GaterIfVertex*>(edgep->fromp())) {
// Edges from IFs represent a real IF branch in the equation tree
//UINFO(9," ifver "<<cvtToHex(edgep)<<" cc"<<edgep->dotColor()<<endl);
eqnp = cVxp->nodep()->condp()->cloneTree(true);
if (!eqnp) cVxp->nodep()->v3fatalSrc("null condition");
if (cedgep->ifelseFalse()) {
eqnp = new AstNot(eqnp->fileline(), eqnp);
}
// We need to AND this term onto whatever was found below it
AstNode* belowp = nafgCreateRecurse(edgep->top(), generation);
if (belowp) eqnp = new AstAnd(eqnp->fileline(), eqnp, belowp);
}
// Top level we could choose to make multiple gaters, or ORs under the gater
// Right now we'll put OR lower down and let other optimizations deal
if (nodep) nodep = new AstOr(nodep->fileline(), nodep, eqnp);
else nodep = eqnp;
//if (debug()>=9) nodep->dumpTree(cout, " followExpr: ");
}
}
//UINFO(9," nafgExit: "<<cvtToHex(vertexp)<<" "<<vertexp->name()<<endl);
return nodep;
}
void newAlwaysTrees(AstAlways* nodep) {
// Across all variables we're moving
uint32_t lastColor = 0;
AstNode* lastExprp = NULL;
for (V3GraphVertex* vertexp = m_graph.verticesBeginp();
vertexp; vertexp=vertexp->verticesNextp()) {
if (GaterVarVertex* vVxp = dynamic_cast<GaterVarVertex*>(vertexp)) {
if (!lastExprp || lastColor != vVxp->color()) {
lastColor = vVxp->color();
// Create the block we've just finished
if (lastExprp) newAlwaysTree(nodep, lastExprp); // Duplicate below
// New expression for this color
lastExprp = newExprFromGraph(vVxp);
}
// Mark variable to move
if (vVxp->nodep()->user2p()) vVxp->nodep()->v3fatalSrc("One variable got marked under two gaters");
vVxp->nodep()->user2p(lastExprp);
m_statBits += vVxp->nodep()->width(); // Moving a wide bus counts more!
// There shouldn't be two possibilities we want to
// move to, IE {A,B} <= Z because we marked such
// things as unoptimizable
}
}
// Create the final block we've just finished
if (lastExprp) newAlwaysTree(nodep, lastExprp); // Duplicate above
}
void newAlwaysTree(AstAlways* nodep, AstNode* exprp) {
// Create new always with specified gating expression
// Relevant vars are already marked with user2p
// Should we put the gater under the always itself,
// or make a new signal?
// New signal: May cause replicated logic until we can combine
// Need way to toggle signal on complicated pos/negedge
// Under Always: More complicated, may not propagate logic with gateer
// Untill we get better gate optimization, we'll go this route.
//#define GATER_NOP
#ifdef GATER_NOP
// For testing only, don't clock gate but still make new always
AstSenTree* sensesp = nodep->sensesp()->cloneTree(true);
#else
// Make a SenGate
AstSenItem* oldsenitemsp = VN_CAST(nodep->sensesp()->sensesp(), SenItem);
if (!oldsenitemsp) nodep->v3fatalSrc("SenTree doesn't have any SenItem under it");
AstSenTree* sensesp = new AstSenTree(nodep->fileline(),
new AstSenGate(nodep->fileline(),
oldsenitemsp->cloneTree(true),
exprp));
#endif
// Make new body; note clone will preserve user2p() indicating moving vars
AstNode* bodyp = nodep->bodysp()->cloneTree(true);
AstAlways* alwp = new AstAlways(nodep->fileline(),
nodep->keyword(),
sensesp,
bodyp);
alwp->user4(1); // No need to process the new always again!
nodep->addNextHere(alwp);
// Blow moved statements from old body
{ GaterBodyVisitor vis(nodep, exprp, true); }
// Blow old statements from new body
{ GaterBodyVisitor vis(alwp, exprp, false); }
++m_statGaters;
if (debug()>=9) alwp->dumpTree(cout, " new: ");
}
// VISITORS
virtual void visit(AstAlways* nodep) {
if (debug()>=9) cout<<endl<<endl<<endl;
UINFO(5, "Gater: ALWAYS: "<<nodep<<endl);
if (nodep->user4SetOnce()) return;
clear();
if (debug()>=9) nodep->dumpTree(cout, " Alwin: ");
// Look for constructs we can't optimize
// Form graph with Vertices at each IF, and each Variable
m_aboveTrue = VU_IF | VU_ELSE;
iterateChildrenAlw(nodep, true);
// Other reasons to not optimize
if (!m_numIfs) nonOptimizable(nodep, "No if statements");
// Something to optimize, oh my!
if (m_nonopt!="") {
UINFO(5, " Gater non-opt: "<<m_nonopt<<endl);
} else {
// Process it
simplifyGraph();
// See how much moves
uint32_t lastColor = 0;
for (V3GraphVertex* vertexp = m_graph.verticesBeginp();
vertexp; vertexp=vertexp->verticesNextp()) {
if (GaterVarVertex* vVxp = dynamic_cast<GaterVarVertex*>(vertexp)) {
if (lastColor < vVxp->color()) {
lastColor = vVxp->color();
}
}
}
if (lastColor == 0) { // Nothing we moved!
nonOptimizable(nodep, "Nothing moved");
}
else if (lastColor > DOMAINS_MAX) {
// Our move algorithm is fairly slow and if we're splitting
// up too much it'll get really nasty. It's probably a bad
// move for performance to split too much, anyhow, as the
// number of gaters will result in calling many small c functions.
nonOptimizable(nodep, "Too much moved");
}
if (m_nonopt=="") {
newAlwaysTrees(nodep);
if (debug()>=9) nodep->dumpTree(cout, " Gaterout: ");
}
}
UINFO(5, " Gater done"<<endl);
}
virtual void visit(AstVarRef* nodep) {
if (nodep->lvalue()) {
AstVarScope* vscp = nodep->varScopep();
if (nodep->varp()->isSigPublic()) {
// Public signals shouldn't be changed, pli code might be messing with them
scoreboardPli(nodep);
}
// If another lvalue in this node, give up optimizing.
// We could just not optimize this variable, but we've already marked the
// other variable as optimizable, so we can instead pretend it's a PLI node.
if (m_stmtVscp) {
UINFO(5, " Multiple lvalues in one statement: "<<nodep<<endl);
scoreboardPli(nodep); // This will set m_stmtInPli
}
m_stmtVscp = vscp;
// Find, or make new Vertex
GaterVarVertex* vertexp = reinterpret_cast<GaterVarVertex*>(vscp->user1p());
if (!vertexp) {
vertexp = new GaterVarVertex(&m_graph, vscp);
vscp->user1p(vertexp);
}
new GaterEdge(&m_graph, m_aboveVertexp, vertexp, m_aboveTrue);
if (m_stmtInPli) {
new GaterEdge(&m_graph, m_pliVertexp, vertexp, VU_PLI);
}
}
}
virtual void visit(AstNodeIf* nodep) {
m_ifDepth++;
bool allowGater = m_directlyUnderAlw && m_ifDepth <= IF_DEPTH_MAX;
if (allowGater) {
GaterCondVisitor condVisitor(nodep->condp());
if (!condVisitor.isSimple()) {
// Don't clear optimization, simply drop this IF as part of the gating
UINFO(5," IFnon-simple-condition: "<<nodep<<endl);
allowGater = false;
}
}
if (!allowGater) {
// IF burried under something complicated
iterateChildrenAlw(nodep, true);
} else {
UINFO(5, " IF: "<<nodep<<endl);
m_numIfs++;
// Recurse to next level of if.
V3GraphVertex* lastabovep = m_aboveVertexp;
uint32_t lasttrue = m_aboveTrue;
GaterIfVertex* vertexp = new GaterIfVertex(&m_graph, nodep);
new GaterEdge(&m_graph, m_aboveVertexp, vertexp, m_aboveTrue);
{
iterateAndNextNull(nodep->condp()); // directlyUnder stays as-is
}
{
m_aboveVertexp = vertexp; // Vars will point at this edge
m_aboveTrue = VU_IF;
iterateAndNextNull(nodep->ifsp()); // directlyUnder stays as-is (true)
}
{
m_aboveVertexp = vertexp; // Vars will point at this edge
m_aboveTrue = VU_ELSE;
iterateAndNextNull(nodep->elsesp()); // directlyUnder stays as-is (true)
}
m_aboveVertexp = lastabovep;
m_aboveTrue = lasttrue;
}
m_ifDepth--;
}
virtual void visit(AstAssignDly* nodep) {
// iterateChildrenAlw will detect this is a statement for us
iterateChildrenAlw(nodep, false);
}
virtual void visit(AstNodeAssign* nodep) {
// Note NOT AssignDly; handled above, We'll just mark this block as
// not optimizable.
//
// A future alternative is to look for any lvalues that are also
// variables in the sensitivity list, or rvalues in this block. If
// any hit, disable optimization. Unlikely to be useful (For loops
// being an exception, but they're already unrolled.)
nonOptimizable(nodep, "Non-delayed assignment");
// No reason to iterate.
}
virtual void visit(AstSenItem* nodep) {
if (!nodep->isClocked()) {
nonOptimizable(nodep, "Non-clocked sensitivity");
}
iterateChildrenAlw(nodep, false);
}
//--------------------
virtual void visit(AstNode* nodep) {
if (m_nonopt=="") { // Else accelerate
iterateChildrenAlw(nodep, false);
}
}
inline void iterateChildrenAlw(AstNode* nodep, bool under) {
// **** USE THIS INSTEAD OF iterateChildren!
// Note If visitor doesn't call here; does it its own way
bool lastdua = m_directlyUnderAlw;
AstVarScope* lastvscp = m_stmtVscp;
bool lastpli = m_stmtInPli;
m_directlyUnderAlw = under;
if (VN_IS(nodep, NodeStmt)) { // Restored below
UINFO(9," Stmt: "<<nodep<<endl);
m_stmtVscp = NULL;
m_stmtInPli = false;
}
if (!nodep->isPure() || nodep->isBrancher()) {
// May also be a new statement (above if); if so we mark it immediately
UINFO(9," NotPure "<<nodep<<endl);
scoreboardPli(nodep);
}
{
iterateChildren(nodep);
}
m_directlyUnderAlw = lastdua;
if (VN_IS(nodep, NodeStmt)) { // Reset what set above; else propagate up to above statement
m_stmtVscp = lastvscp;
m_stmtInPli = lastpli;
}
}
public:
// CONSTUCTORS
explicit GaterVisitor(AstNetlist* nodep) {
// AstAlways visitor does the real work, so most zeroing needs to be in clear()
clear();
iterate(nodep);
}
void clear() {
m_nonopt = "";
m_directlyUnderAlw = false;
m_ifDepth = 0;
m_numIfs = 0;
AstNode::user1ClearTree();
AstNode::user2ClearTree();
// Prepare graph
m_graph.clear();
GaterVertex::clearRank();
m_pliVertexp = NULL;
m_headVertexp = new GaterHeadVertex(&m_graph);
m_aboveVertexp = m_headVertexp;
m_aboveTrue = false;
m_stmtVscp = NULL;
m_stmtInPli = false;
}
virtual ~GaterVisitor() {
V3Stats::addStat("Optimizations, Gaters inserted", m_statGaters);
V3Stats::addStat("Optimizations, Gaters impacted bits", m_statBits);
}
};
//######################################################################
// Active class functions
void V3ClkGater::clkGaterAll(AstNetlist* nodep) {
UINFO(2,__FUNCTION__<<": "<<endl);
{
// While the gater does well at some modules, it seems to slow down many others
UINFO(5,"ClkGater is disabled due to performance issues\n");
} // Destruct before checking
//GaterVisitor visitor (nodep);
V3Global::dumpCheckGlobalTree("clkgater", 0, v3Global.opt.dumpTreeLevel(__FILE__) >= 3);
}
-37
View File
@@ -1,37 +0,0 @@
// -*- mode: C++; c-file-style: "cc-mode" -*-
//*************************************************************************
// DESCRIPTION: Verilator: Break always into clock gated blocks
//
// Code available from: http://www.veripool.org/verilator
//
//*************************************************************************
//
// Copyright 2003-2019 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.
//
// Verilator is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CLKGATER_H_
#define _V3CLKGATER_H_ 1
#include "config_build.h"
#include "verilatedos.h"
#include "V3Error.h"
#include "V3Ast.h"
//============================================================================
class V3ClkGater {
public:
static void clkGaterAll(AstNetlist* nodep);
};
#endif // Guard
+22 -19
View File
@@ -30,7 +30,7 @@
// Create global calling function for any per-scope functions. (For FINALs).
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -74,7 +74,7 @@ private:
if (vscp->user1p()) return static_cast<AstVarScope*>(vscp->user1p());
AstVar* varp = vscp->varp();
if (!varp->width1()) varp->v3error("Unsupported: Clock edge on non-single bit signal: "
<<varp->prettyName());
<<varp->prettyNameQ());
string newvarname = (string("__Vclklast__")
+vscp->scopep()->nameDotless()+"__"+varp->name());
AstVar* newvarp = new AstVar(vscp->fileline(),
@@ -110,14 +110,14 @@ private:
// HIGHEDGE: var
// LOWEDGE: ~var
AstNode* newp = NULL;
if (nodep->edgeType()==AstEdgeType::ET_ILLEGAL) {
if (nodep->edgeType()==VEdgeType::ET_ILLEGAL) {
if (!v3Global.opt.bboxUnsup()) {
nodep->v3error("Unsupported: Complicated event expression in sensitive activity list");
}
return NULL;
}
AstVarScope* clkvscp = nodep->varrefp()->varScopep();
if (nodep->edgeType()==AstEdgeType::ET_POSEDGE) {
if (nodep->edgeType() == VEdgeType::ET_POSEDGE) {
AstVarScope* lastVscp = getCreateLastClk(clkvscp);
newp = new AstAnd(nodep->fileline(),
new AstVarRef(nodep->fileline(),
@@ -125,23 +125,23 @@ private:
new AstNot(nodep->fileline(),
new AstVarRef(nodep->fileline(),
lastVscp, false)));
} else if (nodep->edgeType()==AstEdgeType::ET_NEGEDGE) {
} else if (nodep->edgeType() == VEdgeType::ET_NEGEDGE) {
AstVarScope* lastVscp = getCreateLastClk(clkvscp);
newp = new AstAnd(nodep->fileline(),
new AstNot(nodep->fileline(),
new AstVarRef(nodep->fileline(),
nodep->varrefp()->varScopep(), false)),
new AstVarRef(nodep->fileline(), lastVscp, false));
} else if (nodep->edgeType()==AstEdgeType::ET_BOTHEDGE) {
} else if (nodep->edgeType() == VEdgeType::ET_BOTHEDGE) {
AstVarScope* lastVscp = getCreateLastClk(clkvscp);
newp = new AstXor(nodep->fileline(),
new AstVarRef(nodep->fileline(),
nodep->varrefp()->varScopep(), false),
new AstVarRef(nodep->fileline(), lastVscp, false));
} else if (nodep->edgeType()==AstEdgeType::ET_HIGHEDGE) {
} else if (nodep->edgeType() == VEdgeType::ET_HIGHEDGE) {
newp = new AstVarRef(nodep->fileline(),
clkvscp, false);
} else if (nodep->edgeType()==AstEdgeType::ET_LOWEDGE) {
} else if (nodep->edgeType() == VEdgeType::ET_LOWEDGE) {
newp = new AstNot(nodep->fileline(),
new AstVarRef(nodep->fileline(),
clkvscp, false));
@@ -179,7 +179,7 @@ private:
}
AstIf* makeActiveIf(AstSenTree* sensesp) {
AstNode* senEqnp = createSenseEquation(sensesp->sensesp());
if (!senEqnp) sensesp->v3fatalSrc("No sense equation, shouldn't be in sequent activation.");
UASSERT_OBJ(senEqnp, sensesp, "No sense equation, shouldn't be in sequent activation.");
AstIf* newifp = new AstIf(sensesp->fileline(), senEqnp, NULL, NULL);
return (newifp);
}
@@ -193,7 +193,8 @@ private:
UINFO(4," TOPSCOPE "<<nodep<<endl);
m_topScopep = nodep;
m_scopep = nodep->scopep();
if (!m_scopep) nodep->v3fatalSrc("No scope found on top level, perhaps you have no statements?");
UASSERT_OBJ(m_scopep, nodep,
"No scope found on top level, perhaps you have no statements?");
//VV***** We reset all user1p()
AstNode::user1ClearTree();
// Make top functions
@@ -263,14 +264,14 @@ private:
m_scopep = nodep;
iterateChildren(nodep);
if (AstNode* movep = nodep->finalClksp()) {
if (!m_topScopep) nodep->v3fatalSrc("Final clocks under non-top scope");
UASSERT_OBJ(m_topScopep, nodep, "Final clocks under non-top scope");
movep->unlinkFrBackWithNext();
m_evalFuncp->addFinalsp(movep);
}
m_scopep = NULL;
}
virtual void visit(AstAlways* nodep) {
AstNode* cmtp = new AstComment(nodep->fileline(), nodep->typeName());
AstNode* cmtp = new AstComment(nodep->fileline(), nodep->typeName(), true);
nodep->replaceWith(cmtp);
if (AstNode* stmtsp = nodep->bodysp()) {
stmtsp->unlinkFrBackWithNext();
@@ -279,7 +280,7 @@ private:
nodep->deleteTree(); VL_DANGLING(nodep);
}
virtual void visit(AstAlwaysPost* nodep) {
AstNode* cmtp = new AstComment(nodep->fileline(), nodep->typeName());
AstNode* cmtp = new AstComment(nodep->fileline(), nodep->typeName(), true);
nodep->replaceWith(cmtp);
if (AstNode* stmtsp = nodep->bodysp()) {
stmtsp->unlinkFrBackWithNext();
@@ -300,7 +301,7 @@ private:
changep),
incp, NULL);
// We could add another IF to detect posedges, and only increment if so.
// It's another whole branch though verus a potential memory miss.
// It's another whole branch though versus a potential memory miss.
// We'll go with the miss.
newp->addIfsp(new AstAssign(nodep->fileline(),
changep->cloneTree(false),
@@ -308,7 +309,7 @@ private:
nodep->replaceWith(newp); nodep->deleteTree(); VL_DANGLING(nodep);
}
virtual void visit(AstInitial* nodep) {
AstNode* cmtp = new AstComment(nodep->fileline(), nodep->typeName());
AstNode* cmtp = new AstComment(nodep->fileline(), nodep->typeName(), true);
nodep->replaceWith(cmtp);
if (AstNode* stmtsp = nodep->bodysp()) {
stmtsp->unlinkFrBackWithNext();
@@ -346,13 +347,14 @@ private:
if (!m_topScopep || !nodep->stmtsp()) {
// Not at the top or empty block...
// Only empty blocks should be leftover on the non-top. Killem.
if (nodep->stmtsp()) nodep->v3fatalSrc("Non-empty lower active");
UASSERT_OBJ(!nodep->stmtsp(), nodep, "Non-empty lower active");
nodep->unlinkFrBack()->deleteTree(); VL_DANGLING(nodep);
} else if (m_mtaskBodyp) {
UINFO(4," TR ACTIVE "<<nodep<<endl);
AstNode* stmtsp = nodep->stmtsp()->unlinkFrBackWithNext();
if (nodep->hasClocked()) {
if (nodep->hasInitial()) nodep->v3fatalSrc("Initial block should not have clock sensitivity");
UASSERT_OBJ(!nodep->hasInitial(), nodep,
"Initial block should not have clock sensitivity");
if (m_lastSenp && nodep->sensesp()->sameTree(m_lastSenp)) {
UINFO(4," sameSenseTree\n");
} else {
@@ -377,7 +379,8 @@ private:
AstNode* stmtsp = nodep->stmtsp()->unlinkFrBackWithNext();
if (nodep->hasClocked()) {
// Remember the latest sensitivity so we can compare it next time
if (nodep->hasInitial()) nodep->v3fatalSrc("Initial block should not have clock sensitivity");
UASSERT_OBJ(!nodep->hasInitial(), nodep,
"Initial block should not have clock sensitivity");
if (m_lastSenp && nodep->sensesp()->sameTree(m_lastSenp)) {
UINFO(4," sameSenseTree\n");
} else {
@@ -428,7 +431,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit ClockVisitor(AstNetlist* nodep) {
m_modp = NULL;
m_evalFuncp = NULL;
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CLOCK_H_
#define _V3CLOCK_H_ 1
+6 -5
View File
@@ -68,7 +68,7 @@ protected:
// Note this is disabled, it still needed work
// Also repair it for DPI functions; when make __common need to insure proper
// flags get inherited from the old to new AstCFunc, and that AstText doesn't
// get split between functions causing the text to have a danginling reference.
// get split between functions causing the text to have a dangling reference.
bool statementCombine() { return false; } // duplicateFunctionCombine();
};
@@ -96,7 +96,8 @@ public:
AstCCall* callp = eqit->second;
if (!callp->user3()) { // !already done
UINFO(4, " Called "<<callp<<endl);
if (callp->funcp() != oldfuncp) callp->v3fatalSrc("Call list broken, points to call w/different func");
UASSERT_OBJ(callp->funcp() == oldfuncp, callp,
"Call list broken, points to call w/different func");
if (newfuncp) {
AstCCall* newp = new AstCCall(callp, newfuncp);
// Special new AstCCall form above transfers children of callp to newfuncp
@@ -188,7 +189,7 @@ private:
// STATE
typedef enum {STATE_IDLE, STATE_HASH, STATE_DUP} CombineState;
V3Double0 m_statCombs; // Statistic tracking
VDouble0 m_statCombs; // Statistic tracking
CombineState m_state; // Major state
AstNodeModule* m_modp; // Current module
AstCFunc* m_funcp; // Current function
@@ -236,7 +237,7 @@ private:
V3Hash hashval = it->first;
AstNode* node1p = it->second;
if (!VN_IS(node1p, CFunc)) continue;
if (hashval.isIllegal()) node1p->v3fatalSrc("Illegal (unhashed) nodes");
UASSERT_OBJ(!hashval.isIllegal(), node1p, "Illegal (unhashed) nodes");
for (V3Hashed::iterator eqit = it; eqit != m_hashed.end(); ++eqit) {
AstNode* node2p = eqit->second;
if (!(eqit->first == hashval)) break;
@@ -460,7 +461,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit CombineVisitor(AstNetlist* nodep) {
m_state = STATE_IDLE;
m_modp = NULL;
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3COMBINE_H_
#define _V3COMBINE_H_ 1
+5 -5
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -35,7 +35,7 @@ class V3ConfigLine {
public:
int m_lineno; // Line number to make change at
V3ErrorCode m_code; // Error code
bool m_on; // True to enaable message
bool m_on; // True to enable message
V3ConfigLine(V3ErrorCode code, int lineno, bool on)
: m_lineno(lineno), m_code(code), m_on(on) {}
~V3ConfigLine() {}
@@ -119,7 +119,7 @@ public:
}
inline void applyIgnores(FileLine* filelinep) {
// HOT routine, called each parsed token line
if (m_lastLineno != filelinep->lineno()
if (m_lastLineno != filelinep->lastLineno()
|| m_lastFilename != filelinep->filename()) {
//UINFO(9," ApplyIgnores for "<<filelinep->ascii()<<endl);
if (VL_UNLIKELY(m_lastFilename != filelinep->filename())) {
@@ -127,7 +127,7 @@ public:
m_lastFilename = filelinep->filename();
}
// Process all on/offs for lines up to and including the current line
int curlineno = filelinep->lineno();
int curlineno = filelinep->lastLineno();
for (; m_lastIt != m_lastEnd; ++m_lastIt) {
if (m_lastIt->m_lineno > curlineno) break;
//UINFO(9," Hit "<<*m_lastIt<<endl);
@@ -138,7 +138,7 @@ public:
UINFO(9," NXT "<<*it<<endl);
}
}
m_lastLineno = filelinep->lineno();
m_lastLineno = filelinep->lastLineno();
}
}
};
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CONFIG_H_
#define _V3CONFIG_H_ 1
+45 -45
View File
@@ -23,7 +23,7 @@
// Attempt to convert operands to constants
// If operands are constant, replace this node with constant.
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -53,7 +53,7 @@ private:
iterateChildren(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit ConstVarMarkVisitor(AstNode* nodep) {
AstNode::user4ClearTree(); // Check marked InUse before we're called
iterate(nodep);
@@ -75,7 +75,7 @@ private:
iterateChildren(nodep);
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit ConstVarFindVisitor(AstNode* nodep) {
m_found = false;
iterateAndNextNull(nodep);
@@ -97,7 +97,7 @@ private:
// AstJumpLabel::user4 -> bool. Set when AstJumpGo uses this label
// STATE
bool m_params; // If true, propogate parameterized and true numbers only
bool m_params; // If true, propagate parameterized and true numbers only
bool m_required; // If true, must become a constant
bool m_wremove; // Inside scope, no assignw removal
bool m_warn; // Output warnings
@@ -557,7 +557,7 @@ private:
return false;
}
bool concatMergeable(const AstNode* lhsp, const AstNode* rhsp) {
// determine if {a OP b, c OP d} => {a, c} OP {b, d} is advantagous
// determine if {a OP b, c OP d} => {a, c} OP {b, d} is advantageous
if (!v3Global.opt.oAssemble()) return false; // opt disabled
if (lhsp->type() != rhsp->type()) return false;
if (!ifConcatMergeableBiop(lhsp)) return false;
@@ -589,9 +589,8 @@ private:
void replaceNum(AstNode* oldp, const V3Number& num) {
// Replace oldp node with a constant set to specified value
UASSERT(oldp, "Null old");
if (VN_IS(oldp, Const) && !VN_CAST(oldp, Const)->num().isFourState()) {
oldp->v3fatalSrc("Already constant??");
}
UASSERT_OBJ(!(VN_IS(oldp, Const) && !VN_CAST(oldp, Const)->num().isFourState()),
oldp, "Already constant??");
AstNode* newp = new AstConst(oldp->fileline(), num);
newp->dtypeFrom(oldp);
if (debug()>5) oldp->dumpTree(cout, " const_old: ");
@@ -678,21 +677,21 @@ private:
// NODE(..., CHILD(...)) -> CHILD(...)
childp->unlinkFrBackWithNext();
// If replacing a SEL for example, the data type comes from the parent (is less wide).
// This may adversly affect the operation of the node being replaced.
// This may adversely affect the operation of the node being replaced.
childp->dtypeFrom(nodep);
nodep->replaceWith(childp);
nodep->deleteTree(); VL_DANGLING(nodep);
}
//! Replace a ternary node with its RHS after iterating
//! Used with short-circuting, where the RHS has not yet been iterated.
//! Used with short-circuiting, where the RHS has not yet been iterated.
void replaceWIteratedRhs(AstNodeTriop* nodep) {
if (AstNode* rhsp = nodep->rhsp()) iterateAndNextNull(rhsp);
replaceWChild(nodep, nodep->rhsp()); // May have changed
}
//! Replace a ternary node with its THS after iterating
//! Used with short-circuting, where the THS has not yet been iterated.
//! Used with short-circuiting, where the THS has not yet been iterated.
void replaceWIteratedThs(AstNodeTriop* nodep) {
if (AstNode* thsp = nodep->thsp()) iterateAndNextNull(thsp);
replaceWChild(nodep, nodep->thsp()); // May have changed
@@ -810,7 +809,8 @@ private:
int rstart = rselp->lsbConst();
int rwidth = rselp->widthConst();
if ((rstart + rwidth) != lstart) nodep->v3fatalSrc("tried to merge two selects which are not adjacent");
UASSERT_OBJ((rstart + rwidth) == lstart, nodep,
"tried to merge two selects which are not adjacent");
AstSel* newselp = new AstSel(lselp->fromp()->fileline(),
rselp->fromp()->cloneTree(false), rstart, lwidth+rwidth);
UINFO(5, "merged two adjacent sel "<<lselp <<" and "<<rselp<< " to one "<<newselp<<endl);
@@ -833,7 +833,7 @@ private:
// use the lhs to replace the parent concat
lp->lhsp()->replaceWith(newlp);
lp->rhsp()->replaceWith(newrp);
lp->dtypeChgWidthSigned(newlp->width(), newlp->width(), AstNumeric::fromBool(true));
lp->dtypeChgWidthSigned(newlp->width(), newlp->width(), AstNumeric::UNSIGNED);
UINFO(5, "merged "<< nodep <<endl);
rp->unlinkFrBack()->deleteTree(); VL_DANGLING(rp);
nodep->replaceWith(lp->unlinkFrBack()); nodep->deleteTree(); VL_DANGLING(nodep);
@@ -1066,7 +1066,7 @@ private:
int msb2 = lsb2+lc2p->width()-1;
int lsb1 = msb2+1;
int msb1 = lsb1+lc1p->width()-1;
if (msb1!=(conp->width()-1)) nodep->v3fatalSrc("Width calc mismatch");
UASSERT_OBJ(msb1 == (conp->width()-1), nodep, "Width calc mismatch");
// Form ranges
AstSel* sel1p = new AstSel(conp->fileline(), rhsp, lsb1, msb1-lsb1+1);
AstSel* sel2p = new AstSel(conp->fileline(), rhs2p, lsb2, msb2-lsb2+1);
@@ -1081,7 +1081,7 @@ private:
newp = AstNode::addNext(newp, asn1ap);
newp = AstNode::addNext(newp, asn2ap);
} else {
if (!m_modp) nodep->v3fatalSrc("Not under module");
UASSERT_OBJ(m_modp, nodep, "Not under module");
// We could create just one temp variable, but we'll get better optimization
// if we make one per term.
string name1 = (string("__Vconcswap")+cvtToStr(m_modp->varNumGetInc()));
@@ -1150,9 +1150,8 @@ private:
AstNode* srcp = nodep->rhsp()->unlinkFrBack();
// Connect the rhs to the stream operator and update its width
VN_CAST(streamp, StreamL)->lhsp(srcp);
streamp->dtypeSetLogicSized((srcp->width()),
(srcp->widthMin()),
AstNumeric::UNSIGNED);
streamp->dtypeSetLogicUnsized(srcp->width(), srcp->widthMin(),
AstNumeric::UNSIGNED);
// Shrink the RHS if necessary
if (sWidth > dWidth) {
streamp = new AstSel(streamp->fileline(), streamp, sWidth-dWidth, dWidth);
@@ -1214,7 +1213,7 @@ private:
new AstConst(nodep->fileline(), val),
fromp);
// widthMin no longer applicable if different C-expanded width
newp->dtypeSetLogicSized(nodep->width(), nodep->width(), AstNumeric::UNSIGNED);
newp->dtypeSetLogicSized(nodep->width(), AstNumeric::UNSIGNED);
nodep->replaceWith(newp);
nodep->deleteTree(); VL_DANGLING(nodep);
if (debug()>=9) newp->dumpTree(cout, " _new: ");
@@ -1228,13 +1227,13 @@ private:
AstNode* errorp = simvis.whyNotNodep(); if (!errorp) errorp = nodep;
nodep->v3error("Expecting expression to be constant, but can't determine constant for "
<<nodep->prettyTypeName()<<endl
<<errorp->warnMore()<<"... Location of non-constant "
<<errorp->warnOther()<<"... Location of non-constant "
<<errorp->prettyTypeName()<<": "<<simvis.whyNotMessage());
replaceZero(nodep); VL_DANGLING(nodep);
} else {
// Fetch the result
V3Number* outnump = simvis.fetchNumberNull(nodep);
if (!outnump) nodep->v3fatalSrc("No number returned from simulation");
UASSERT_OBJ(outnump, nodep, "No number returned from simulation");
// Replace it
replaceNum(nodep,*outnump); VL_DANGLING(nodep);
}
@@ -1269,7 +1268,7 @@ private:
}
void swapSides(AstNodeBiCom* nodep) {
// COMMUNATIVE({a},CONST) -> COMMUNATIVE(CONST,{a})
// COMMUTATIVE({a},CONST) -> COMMUTATIVE(CONST,{a})
// This simplifies later optimizations
AstNode* lhsp = nodep->lhsp()->unlinkFrBackWithNext();
AstNode* rhsp = nodep->rhsp()->unlinkFrBackWithNext();
@@ -1440,7 +1439,7 @@ private:
AstNode* fromp = repp->lhsp();
AstConst* lsbp = VN_CAST(nodep->lsbp(), Const); if (!lsbp) return false;
AstNode* widthp = nodep->widthp(); if (!VN_IS(widthp, Const)) return false;
if (!fromp->width()) nodep->v3fatalSrc("Not widthed");
UASSERT_OBJ(fromp->width(), nodep, "Not widthed");
if ((lsbp->toUInt() / fromp->width())
!= ((lsbp->toUInt()+nodep->width()-1) / fromp->width())) return false;
//
@@ -1500,7 +1499,7 @@ private:
void replaceSelIntoBiop(AstSel* nodep) {
// SEL(BUFIF1(a,b),1,bit) => BUFIF1(SEL(a,1,bit),SEL(b,1,bit))
AstNodeBiop* fromp = VN_CAST(nodep->fromp()->unlinkFrBack(), NodeBiop);
if (!fromp) nodep->v3fatalSrc("Called on non biop");
UASSERT_OBJ(fromp, nodep, "Called on non biop");
AstNode* lsbp = nodep->lsbp()->unlinkFrBack();
AstNode* widthp = nodep->widthp()->unlinkFrBack();
//
@@ -1517,7 +1516,7 @@ private:
void replaceSelIntoUniop(AstSel* nodep) {
// SEL(NOT(a),1,bit) => NOT(SEL(a,bit))
AstNodeUniop* fromp = VN_CAST(nodep->fromp()->unlinkFrBack(), NodeUniop);
if (!fromp) nodep->v3fatalSrc("Called on non biop");
UASSERT_OBJ(fromp, nodep, "Called on non biop");
AstNode* lsbp = nodep->lsbp()->unlinkFrBack();
AstNode* widthp = nodep->widthp()->unlinkFrBack();
//
@@ -1564,7 +1563,7 @@ private:
}
virtual void visit(AstNodeVarRef* nodep) {
iterateChildren(nodep);
if (!nodep->varp()) nodep->v3fatalSrc("Not linked");
UASSERT_OBJ(nodep->varp(), nodep, "Not linked");
bool did = false;
if (m_doV && nodep->varp()->valuep() && !m_attrp) {
//if (debug()) valuep->dumpTree(cout, " visitvaref: ");
@@ -1598,7 +1597,7 @@ private:
if (initarp->defaultp()) {
itemp = initarp->defaultp();
} else {
initarp->v3fatalSrc("Not enough values in array initalizement");
initarp->v3fatalSrc("Not enough values in array initialization");
}
}
}
@@ -1622,15 +1621,15 @@ private:
}
if (!did && m_required) {
nodep->v3error("Expecting expression to be constant, but variable isn't const: "
<<nodep->varp()->prettyName());
<<nodep->varp()->prettyNameQ());
}
}
virtual void visit(AstEnumItemRef* nodep) {
iterateChildren(nodep);
if (!nodep->itemp()) nodep->v3fatalSrc("Not linked");
UASSERT_OBJ(nodep->itemp(), nodep, "Not linked");
bool did = false;
if (nodep->itemp()->valuep()) {
//if (debug()) nodep->varp()->valuep()->dumpTree(cout, " visitvaref: ");
//if (debug()) nodep->itemp()->valuep()->dumpTree(cout, " visitvaref: ");
iterateAndNextNull(nodep->itemp()->valuep());
if (AstConst* valuep = VN_CAST(nodep->itemp()->valuep(), Const)) {
const V3Number& num = valuep->num();
@@ -1640,7 +1639,7 @@ private:
}
if (!did && m_required) {
nodep->v3error("Expecting expression to be constant, but variable isn't const: "
<<nodep->itemp()->prettyName());
<<nodep->itemp()->prettyNameQ());
}
}
@@ -1659,7 +1658,7 @@ private:
|| VN_IS(nodep->sensp(), EnumItemRef)
|| (nodep->varrefp() && nodep->varrefp()->varp()->isParam()))) {
// Constants in sensitivity lists may be removed (we'll simplify later)
if (nodep->isClocked()) { // A constant can never get a pos/negexge
if (nodep->isClocked()) { // A constant can never get a pos/negedge
if (onlySenItemInSenTree(nodep)) {
nodep->replaceWith(new AstSenItem(nodep->fileline(), AstSenItem::Never()));
nodep->deleteTree(); VL_DANGLING(nodep);
@@ -1682,7 +1681,7 @@ private:
UINFO(8,"senItem(NOT...) "<<nodep<<" "<<invert<<endl);
if (invert) nodep->edgeType( nodep->edgeType().invert() );
AstNodeVarRef* senvarp = VN_CAST(lastSensp->unlinkFrBack(), NodeVarRef);
if (!senvarp) sensp->v3fatalSrc("Non-varref sensitivity variable");
UASSERT_OBJ(senvarp, sensp, "Non-varref sensitivity variable");
sensp->replaceWith(senvarp);
sensp->deleteTree(); VL_DANGLING(sensp);
} else if (!m_doNConst // Deal with later when doNConst missing
@@ -1690,7 +1689,8 @@ private:
|| VN_IS(nodep->sensp(), Const))) {
} else if (nodep->isIllegal()) { // Deal with later
} else {
if (nodep->hasVar() && !nodep->varrefp()) nodep->v3fatalSrc("Null sensitivity variable");
UASSERT_OBJ(!(nodep->hasVar() && !nodep->varrefp()), nodep,
"Null sensitivity variable");
}
}
virtual void visit(AstSenGate* nodep) {
@@ -1830,16 +1830,16 @@ private:
|| (!litemp->varrefp() && !ritemp->varrefp())) {
// We've sorted in the order ANY, BOTH, POS, NEG,
// so we don't need to try opposite orders
if (( litemp->edgeType()==AstEdgeType::ET_ANYEDGE) // ANY or {BOTH|POS|NEG} -> ANY
|| (litemp->edgeType()==AstEdgeType::ET_BOTHEDGE) // BOTH or {POS|NEG} -> BOTH
|| (litemp->edgeType()==AstEdgeType::ET_POSEDGE // POS or NEG -> BOTH
&& ritemp->edgeType()==AstEdgeType::ET_NEGEDGE)
|| (litemp->edgeType()==ritemp->edgeType()) // Identical edges
if (( litemp->edgeType() == VEdgeType::ET_ANYEDGE) // ANY or {BOTH|POS|NEG} -> ANY
|| (litemp->edgeType() == VEdgeType::ET_BOTHEDGE) // BOTH or {POS|NEG} -> BOTH
|| (litemp->edgeType() == VEdgeType::ET_POSEDGE // POS or NEG -> BOTH
&& ritemp->edgeType() == VEdgeType::ET_NEGEDGE)
|| (litemp->edgeType() == ritemp->edgeType()) // Identical edges
) {
// Fix edge of old node
if (litemp->edgeType()==AstEdgeType::ET_POSEDGE
&& ritemp->edgeType()==AstEdgeType::ET_NEGEDGE)
litemp->edgeType(AstEdgeType::ET_BOTHEDGE);
if (litemp->edgeType() == VEdgeType::ET_POSEDGE
&& ritemp->edgeType() == VEdgeType::ET_NEGEDGE)
litemp->edgeType(VEdgeType::ET_BOTHEDGE);
// Remove redundant node
ritemp->unlinkFrBack()->deleteTree(); VL_DANGLING(ritemp); VL_DANGLING(cmpp);
// Try to collapse again
@@ -2192,7 +2192,7 @@ private:
// v--- *1* These ops are always first, as we warn before replacing
// v--- *V* This op is a verilog op, only in m_doV mode
// v--- *C* This op works on all constant children, allowed in m_doConst mode
// v--- *S* This op specifies a type should use short-circuting of its lhs op
// v--- *S* This op specifies a type should use short-circuiting of its lhs op
TREEOP1("AstSel{warnSelect(nodep)}", "NEVER");
// Generic constants on both side. Do this first to avoid other replacements
@@ -2518,7 +2518,7 @@ public:
PROC_CPP
};
// CONSTUCTORS
// CONSTRUCTORS
explicit ConstVisitor(ProcMode pmode) {
m_params = false;
m_required = false;
@@ -2586,7 +2586,7 @@ AstNode* V3Const::constifyParamsEdit(AstNode* nodep) {
//! trigger warnings when we deal with the width. It is possible that these
//! are spurious, existing within sub-expressions that will not actually be
//! generated. Since such occurrences, must be constant, in order to be
//! someting a generate block can depend on, we can wait until later to do the
//! something a generate block can depend on, we can wait until later to do the
//! width check.
//! @return Pointer to the edited node.
AstNode* V3Const::constifyGenerateParamsEdit(AstNode* nodep) {
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3CONST_H_
#define _V3CONST_H_ 1
+3 -3
View File
@@ -27,7 +27,7 @@
// for that if/else/case.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -262,7 +262,7 @@ private:
}
}
else if (AstUnionDType* adtypep = VN_CAST(dtypep, UnionDType)) {
// Arbitrarially handle only the first member of the union
// Arbitrarily handle only the first member of the union
if (AstMemberDType* itemp = adtypep->membersp()) {
AstNodeDType* subtypep = itemp->subDTypep()->skipRefp();
ToggleEnt newent (above.m_comment+string(".")+itemp->name(),
@@ -380,7 +380,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit CoverageVisitor(AstNetlist* rootp) {
// Operate on all modules
m_checkBlock = true;
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3COVERAGE_H_
#define _V3COVERAGE_H_ 1
+4 -4
View File
@@ -20,7 +20,7 @@
// COVERAGEJOIN TRANSFORMATIONS:
// If two COVERTOGGLEs have same VARSCOPE, combine them
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -50,7 +50,7 @@ private:
// STATE
ToggleList m_toggleps; // List of of all AstCoverToggle's
V3Double0 m_statToggleJoins; // Statistic tracking
VDouble0 m_statToggleJoins; // Statistic tracking
// METHODS
VL_DEBUG_FUNC; // Declare debug()
@@ -81,7 +81,7 @@ private:
// duplicated), not the covertoggle, but we need to get back to the
// covertoggle which is immediately above, so:
AstCoverToggle* removep = VN_CAST(duporigp->backp(), CoverToggle);
if (!removep) nodep->v3fatalSrc("CoverageJoin duplicate of wrong type");
UASSERT_OBJ(removep, nodep, "CoverageJoin duplicate of wrong type");
UINFO(8," Orig "<<nodep<<" -->> "<<nodep->incp()->declp()<<endl);
UINFO(8," dup "<<removep<<" -->> "<<removep->incp()->declp()<<endl);
// The CoverDecl the duplicate pointed to now needs to point to the
@@ -119,7 +119,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit CoverageJoinVisitor(AstNetlist* nodep) {
iterate(nodep);
}
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3COVERAGEJOIN_H_
#define _V3COVERAGEJOIN_H_ 1
+2 -2
View File
@@ -37,7 +37,7 @@
// here after scoping to allow more dead node
// removal.
// *************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -407,7 +407,7 @@ public:
iterate(nodep);
deadCheckVar();
// We only elimate scopes when in a flattened structure
// We only eliminate scopes when in a flattened structure
// Otherwise we have no easy way to know if a scope is used
if (elimScopes) deadCheckScope();
if (elimCells) deadCheckCells();
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3DEAD_H_
#define _V3DEAD_H_ 1
+22 -19
View File
@@ -51,7 +51,7 @@
// ASSIGNW (BITSEL(ARRAYSEL(VARREF(x), __Vdlyvdim_x), __Vdlyvlsb_x), __Vdlyvval_x)
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -99,10 +99,10 @@ private:
AstAssignDly* m_nextDlyp; // Next delayed assignment in a list of assignments
bool m_inDly; // True in delayed assignments
bool m_inLoop; // True in for loops
bool m_inInitial; // True in intial blocks
bool m_inInitial; // True in initial blocks
typedef std::map<std::pair<AstNodeModule*,string>,AstVar*> VarMap;
VarMap m_modVarMap; // Table of new var names created under module
V3Double0 m_statSharedSet;// Statistic tracking
VDouble0 m_statSharedSet; // Statistic tracking
typedef std::map<AstVarScope*,int> ScopeVecMap;
ScopeVecMap m_scopeVecMap; // Next var number for each scope
@@ -114,13 +114,13 @@ private:
nodep->user5( nodep->user5() | flags );
if ((nodep->user5() & VU_DLY) && (nodep->user5() & VU_NONDLY)) {
nodep->v3warn(BLKANDNBLK, "Unsupported: Blocked and non-blocking assignments to same variable: "
<<nodep->varp()->prettyName());
<<nodep->varp()->prettyNameQ());
}
}
AstVarScope* createVarSc(AstVarScope* oldvarscp, const string& name,
int width/*0==fromoldvar*/, AstNodeDType* newdtypep) {
// Because we've already scoped it, we may need to add both the AstVar and the AstVarScope
if (!oldvarscp->scopep()) oldvarscp->v3fatalSrc("Var unscoped");
UASSERT_OBJ(oldvarscp->scopep(), oldvarscp, "Var unscoped");
AstVar* varp;
AstNodeModule* addmodp = oldvarscp->scopep()->modp();
// We need a new AstVar, but only one for all scopes, to match the new AstVarScope
@@ -158,15 +158,18 @@ private:
}
void checkActivePost(AstVarRef* varrefp, AstActive* oldactivep) {
// Check for MULTIDRIVEN, and if so make new sentree that joins old & new sentree
if (!oldactivep) varrefp->v3fatalSrc("<= old dly assignment not put under sensitivity block");
UASSERT_OBJ(oldactivep, varrefp, "<= old dly assignment not put under sensitivity block");
if (oldactivep->sensesp() != m_activep->sensesp()) {
if (!varrefp->varp()->fileline()->warnIsOff(V3ErrorCode::MULTIDRIVEN)
&& !varrefp->varp()->user2()) {
varrefp->varp()->v3warn(
MULTIDRIVEN, "Signal has multiple driving blocks with different clocking: "
<<varrefp->varp()->prettyName()<<endl
<<varrefp->warnMore()<<"... Location of first driving block"<<endl
<<oldactivep->warnMore()<<"... Location of other driving block");
<<varrefp->varp()->prettyNameQ()<<endl
<<varrefp->warnOther()<<"... Location of first driving block"<<endl
<<varrefp->warnContextPrimary()<<endl
<<oldactivep->warnOther()<<"... Location of other driving block"<<endl
<<oldactivep->warnContextSecondary()
);
varrefp->varp()->user2(true);
}
UINFO(4,"AssignDupDlyVar: "<<varrefp<<endl);
@@ -200,10 +203,9 @@ private:
} else {
arrayselp = VN_CAST(lhsp, ArraySel);
}
if (!arrayselp) nodep->v3fatalSrc("No arraysel under bitsel?");
if (VN_IS(arrayselp->dtypep()->skipRefp(), UnpackArrayDType)) {
nodep->v3fatalSrc("ArraySel with unpacked arrays should have been removed in V3Slice");
}
UASSERT_OBJ(arrayselp, nodep, "No arraysel under bitsel?");
UASSERT_OBJ(!VN_IS(arrayselp->dtypep()->skipRefp(), UnpackArrayDType), nodep,
"ArraySel with unpacked arrays should have been removed in V3Slice");
UINFO(4,"AssignDlyArray: "<<nodep<<endl);
//
//=== Dimensions: __Vdlyvdim__
@@ -214,8 +216,8 @@ private:
dimvalp.push_front(valp);
}
AstVarRef* varrefp = VN_CAST(dimselp, VarRef);
if (!varrefp) nodep->v3fatalSrc("No var underneath arraysels");
if (!varrefp->varScopep()) varrefp->v3fatalSrc("Var didn't get varscoped in V3Scope.cpp");
UASSERT_OBJ(varrefp, nodep, "No var underneath arraysels");
UASSERT_OBJ(varrefp->varScopep(), varrefp, "Var didn't get varscoped in V3Scope.cpp");
varrefp->unlinkFrBack();
AstVar* oldvarp = varrefp->varp();
int modVecNum = m_scopeVecMap[varrefp->varScopep()]++;
@@ -330,7 +332,8 @@ private:
// Optimize as above; if sharing Vdlyvset *ON SAME VARIABLE*,
// we can share the IF statement too
postLogicp = VN_CAST(finalp->user4p(), If);
if (!postLogicp) nodep->v3fatalSrc("Delayed assignment misoptimized; prev var found w/o associated IF");
UASSERT_OBJ(postLogicp, nodep,
"Delayed assignment misoptimized; prev var found w/o associated IF");
} else {
postLogicp = new AstIf(nodep->fileline(),
new AstVarRef(nodep->fileline(), setvscp, false),
@@ -397,12 +400,12 @@ private:
if (m_inDly && nodep->lvalue()) {
UINFO(4,"AssignDlyVar: "<<nodep<<endl);
markVarUsage(nodep->varScopep(), VU_DLY);
if (!m_activep) nodep->v3fatalSrc("<= not under sensitivity block");
UASSERT_OBJ(m_activep, nodep, "<= not under sensitivity block");
if (!m_activep->hasClocked()) {
nodep->v3error("Internal: Blocking <= assignment in non-clocked block, should have converted in V3Active");
}
AstVarScope* oldvscp = nodep->varScopep();
if (!oldvscp) nodep->v3fatalSrc("Var didn't get varscoped in V3Scope.cpp");
UASSERT_OBJ(oldvscp, nodep, "Var didn't get varscoped in V3Scope.cpp");
AstVarScope* dlyvscp = VN_CAST(oldvscp->user1p(), VarScope);
if (dlyvscp) { // Multiple use of delayed variable
AstActive* oldactivep = VN_CAST(dlyvscp->user2p(), Active);
@@ -458,7 +461,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit DelayedVisitor(AstNetlist* nodep) {
m_inDly = false;
m_activep = NULL;
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3DELAYED_H_
#define _V3DELAYED_H_ 1
+5 -5
View File
@@ -26,7 +26,7 @@
// Any statements that need "this" are marked non-static
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -66,7 +66,7 @@ private:
// bitmask instead of widths....)
// See t_func_crc for an example test that requires this
VFlagLogicPacked(), nodep->width());
if (!m_funcp) nodep->v3fatalSrc("Deep expression not under a function");
UASSERT_OBJ(m_funcp, nodep, "Deep expression not under a function");
m_funcp->addInitsp(varp);
// Replace node tree with reference to var
AstVarRef* newp = new AstVarRef(nodep->fileline(), varp, false);
@@ -132,9 +132,9 @@ private:
//--------------------
// Marking of non-static functions (because they might need "this")
// (Here instead of new vistor after V3Descope just to avoid another visitor)
// (Here instead of new visitor after V3Descope just to avoid another visitor)
void needNonStaticFunc(AstNode* nodep) {
if (!m_funcp) nodep->v3fatalSrc("Non-static accessor not under a function");
UASSERT_OBJ(m_funcp, nodep, "Non-static accessor not under a function");
if (m_funcp->isStatic().trueU()) {
UINFO(5,"Mark non-public due to "<<nodep<<endl);
m_funcp->isStatic(false);
@@ -157,7 +157,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit DepthVisitor(AstNetlist* nodep) {
m_modp = NULL;
m_funcp = NULL;
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3DEPTH_H_
#define _V3DEPTH_H_ 1
+2 -2
View File
@@ -23,7 +23,7 @@
// For each deep block, create cfunc including that block.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
@@ -123,7 +123,7 @@ private:
}
public:
// CONSTUCTORS
// CONSTRUCTORS
explicit DepthBlockVisitor(AstNetlist* nodep) {
m_modp = NULL;
m_funcp = NULL;
+1 -1
View File
@@ -17,7 +17,7 @@
// GNU General Public License for more details.
//
//*************************************************************************
#ifndef _V3DEPTHBLOCK_H_
#define _V3DEPTHBLOCK_H_ 1

Some files were not shown because too many files have changed in this diff Show More