From 31757df22978ef3f1be804e68cada44a22b17929 Mon Sep 17 00:00:00 2001 From: Wilson Snyder Date: Fri, 27 Mar 2026 23:14:18 -0400 Subject: [PATCH] Internals: clangtidy cleanups. No functional change intended (#7343) --- Makefile.in | 4 +- include/verilated.cpp | 189 ++++++++++++++++----------------- include/verilated.h | 4 +- include/verilated_cov.cpp | 6 +- include/verilated_dpi.cpp | 4 +- include/verilated_fst_c.cpp | 5 +- include/verilated_funcs.h | 177 ++++++++++++++---------------- include/verilated_imp.h | 5 +- include/verilated_probdist.cpp | 24 +++-- include/verilated_profiler.cpp | 2 +- include/verilated_random.cpp | 19 ++-- include/verilated_random.h | 27 +++-- include/verilated_saif_c.cpp | 26 ++--- include/verilated_saif_c.h | 4 +- include/verilated_save.cpp | 4 +- include/verilated_sym_props.h | 9 +- include/verilated_threads.cpp | 11 +- include/verilated_threads.h | 15 ++- include/verilated_timing.h | 2 +- include/verilated_types.h | 31 ++---- include/verilated_vcd_c.cpp | 11 +- include/verilated_vpi.cpp | 126 +++++++++++----------- include/verilatedos.h | 10 +- include/verilatedos_c.h | 8 +- src/V3Assert.cpp | 10 +- src/V3AssertProp.cpp | 5 +- src/V3Ast.cpp | 88 +++++++-------- src/V3Ast.h | 4 +- src/V3AstAttr.h | 18 ++-- src/V3AstInlines.h | 24 ++--- src/V3AstNodeDType.h | 33 +++--- src/V3AstNodeExpr.h | 15 +-- src/V3AstNodeOther.h | 2 +- src/V3AstNodes.cpp | 32 ++---- src/V3Begin.cpp | 5 +- src/V3Broken.cpp | 6 +- src/V3CUse.cpp | 2 +- src/V3Const.cpp | 15 ++- src/V3Control.cpp | 86 +++++++-------- src/V3Coverage.cpp | 16 +-- src/V3Dead.cpp | 2 +- src/V3DebugBisect.h | 2 +- src/V3Delayed.cpp | 6 +- src/V3Descope.cpp | 4 +- src/V3Dfg.h | 9 +- src/V3DfgBreakCycles.cpp | 2 +- src/V3DfgCache.h | 10 +- src/V3DfgCse.cpp | 2 +- src/V3DfgDecomposition.cpp | 2 +- src/V3DfgPasses.cpp | 2 +- src/V3DfgPeephole.cpp | 2 +- src/V3DfgPushDownSels.cpp | 6 +- src/V3DfgRegularize.cpp | 2 +- src/V3DfgSynthesize.cpp | 4 +- src/V3EmitCFunc.cpp | 6 +- src/V3EmitCFunc.h | 4 +- src/V3EmitCHeaders.cpp | 2 +- src/V3EmitCMain.cpp | 2 +- src/V3EmitCPch.cpp | 1 - src/V3EmitCSyms.cpp | 2 +- src/V3EmitMk.cpp | 6 +- src/V3EmitV.cpp | 4 +- src/V3Error.cpp | 42 +++----- src/V3Error.h | 20 ++-- src/V3ExecGraph.cpp | 128 +++++++++++----------- src/V3Expand.cpp | 4 +- src/V3File.cpp | 9 +- src/V3File.h | 11 +- src/V3FileLine.cpp | 2 +- src/V3FileLine.h | 2 +- src/V3Force.cpp | 2 +- src/V3Gate.cpp | 6 +- src/V3Global.h | 2 +- src/V3Graph.cpp | 4 +- src/V3Graph.h | 1 - src/V3GraphPathChecker.cpp | 2 +- src/V3GraphStream.h | 7 +- src/V3HierBlock.cpp | 2 +- src/V3InlineCFuncs.cpp | 4 +- src/V3Inst.cpp | 8 +- src/V3InstrCount.cpp | 4 +- src/V3LibMap.cpp | 2 +- src/V3LiftExpr.cpp | 2 +- src/V3LinkCells.cpp | 2 +- src/V3LinkDot.cpp | 44 ++++---- src/V3LinkDotIfaceCapture.cpp | 4 +- src/V3LinkLevel.cpp | 2 +- src/V3Mutex.h | 2 +- src/V3Number.cpp | 55 +++++----- src/V3Number.h | 3 +- src/V3OptionParser.cpp | 3 +- src/V3Options.cpp | 34 +++--- src/V3Options.h | 7 +- src/V3OrderParallel.cpp | 16 +-- src/V3Os.cpp | 129 +++++++++++----------- src/V3PairingHeap.h | 9 +- src/V3Param.cpp | 100 ++++++++--------- src/V3ParseGrammar.h | 65 ++++++------ src/V3ParseImp.cpp | 17 +-- src/V3ParseImp.h | 6 +- src/V3PreExpr.h | 12 +-- src/V3PreLex.l | 2 +- src/V3PreProc.cpp | 36 +++---- src/V3PreShell.cpp | 2 +- src/V3Premit.cpp | 4 +- src/V3ProtectLib.cpp | 4 +- src/V3RandSequence.cpp | 4 +- src/V3Randomize.cpp | 58 +++++----- src/V3Randomize.h | 2 +- src/V3Sched.h | 2 +- src/V3SchedAcyclic.cpp | 2 +- src/V3SchedPartition.cpp | 2 +- src/V3SchedTiming.cpp | 6 +- src/V3SchedTrigger.cpp | 9 +- src/V3Simulate.h | 27 +++-- src/V3Split.cpp | 4 +- src/V3Stats.h | 4 +- src/V3StatsReport.cpp | 10 +- src/V3String.cpp | 62 +++++------ src/V3String.h | 7 +- src/V3Subst.cpp | 12 ++- src/V3SymTable.h | 4 +- src/V3Task.h | 2 +- src/V3ThreadPool.cpp | 6 +- src/V3Timing.cpp | 2 +- src/V3TraceDecl.cpp | 9 +- src/V3Tristate.cpp | 18 ++-- src/V3Udp.cpp | 8 +- src/V3Undriven.cpp | 6 +- src/V3UniqueNames.h | 3 +- src/V3Width.cpp | 3 +- src/V3WidthCommit.cpp | 2 +- src/V3WidthCommit.h | 3 +- src/V3WidthSel.cpp | 6 +- src/Verilator.cpp | 10 +- src/VlcBucket.h | 23 ++-- src/VlcPoint.h | 2 +- src/VlcSource.h | 9 +- src/VlcTop.cpp | 12 +-- 139 files changed, 1089 insertions(+), 1238 deletions(-) diff --git a/Makefile.in b/Makefile.in index 48f2c6390..fa81074c9 100644 --- a/Makefile.in +++ b/Makefile.in @@ -444,7 +444,9 @@ cppcheck: CLANGTIDY = clang-tidy CLANGTIDY_FLAGS = -config='' \ -header-filter='.*' \ - -checks='-fuchsia-*,-cppcoreguidelines-avoid-c-arrays,-cppcoreguidelines-init-variables,-cppcoreguidelines-avoid-goto,-modernize-avoid-c-arrays,-readability-magic-numbers,-readability-simplify-boolean-expr,-cppcoreguidelines-macro-usage' \ + -checks='*,-abseil-*,-fuchsia-*,-cppcoreguidelines-avoid-c-arrays,-cppcoreguidelines-init-variables,-cppcoreguidelines-avoid-goto,-modernize-avoid-c-arrays,-readability-magic-numbers,-readability-simplify-boolean-expr,-cppcoreguidelines-macro-usage' \ + +# Good checks: -checks='-*,bugprone-assignment-in-if-condition,google-build-using-namespace,google-readability-casting,modernize-use-default-member-init,modernize-use-emplace,modernize-use-equals-default,modernize-use-equals-delete,modernize-use-nullptr,performance-faster-string-find,readability-isolate-declaration,readability-redundant-control-flow,readability-redundant-member-init,readability-redundant-string-cstr,readability-uppercase-literal-suffix CLANGTIDY_DEP = $(subst .cpp,.cpp.tidy,$(CHECK_CPP)) CLANGTIDY_DEFS = -DVL_DEBUG=1 -DVL_CPPCHECK=1 diff --git a/include/verilated.cpp b/include/verilated.cpp index 008323ffc..922385126 100644 --- a/include/verilated.cpp +++ b/include/verilated.cpp @@ -316,14 +316,14 @@ static size_t _vl_snprintf_string(std::string& str, const char* format, snprintf_args_ts... args) VL_MT_SAFE { constexpr size_t FIRST_TRY_SIZE = 128; str.resize(FIRST_TRY_SIZE); - size_t req_size = VL_SNPRINTF(&str[0], FIRST_TRY_SIZE + 1, format, args...); + const size_t req_size = VL_SNPRINTF(&str[0], FIRST_TRY_SIZE + 1, format, args...); if (VL_LIKELY(req_size <= FIRST_TRY_SIZE)) { str.resize(req_size); // Resize the string down to the real size, // otherwise it will break things later return req_size; } str.resize(req_size); - VL_SNPRINTF(&str[0], req_size + 1, format, args...); + (void)VL_SNPRINTF(&str[0], req_size + 1, format, args...); return req_size; } @@ -685,9 +685,9 @@ WDataOutP _vl_moddiv_w(int lbits, WDataOutP owp, const WDataInP lwp, const WData } for (int i = vw; i < words; ++i) owp[i] = 0; return owp; - } else { // division - return owp; } + // division + return owp; } WDataOutP VL_POW_WWW(int obits, int, int rbits, WDataOutP owp, const WDataInP lwp, @@ -745,16 +745,18 @@ WDataOutP VL_POWSS_WWW(int obits, int, int rbits, WDataOutP owp, const WDataInP lor |= ((lwp[words - 1] == VL_MASK_E(rbits)) ? ~VL_EUL(0) : 0); if (lor == 0 && lwp[0] == 0) { // "X" so return 0 return owp; - } else if (lor == 0 && lwp[0] == 1) { // 1 + } + if (lor == 0 && lwp[0] == 1) { // 1 owp[0] = 1; return owp; - } else if (lsign && lor == ~VL_EUL(0) && lwp[0] == ~VL_EUL(0)) { // -1 + } + if (lsign && lor == ~VL_EUL(0) && lwp[0] == ~VL_EUL(0)) { // -1 if (rwp[0] & 1) { // -1^odd=-1 return VL_ALLONES_W(obits, owp); - } else { // -1^even=1 - owp[0] = 1; - return owp; } + // -1^even=1 + owp[0] = 1; + return owp; } return owp; } @@ -770,16 +772,11 @@ QData VL_POWSS_QQW(int obits, int, int rbits, QData lhs, const WDataInP rwp, boo bool rsign) VL_MT_SAFE { // Skip check for rhs == 0, as short-circuit doesn't save time if (rsign && VL_SIGN_W(rbits, rwp)) { - if (lhs == 0) { - return 0; // "X" - } else if (lhs == 1) { - return 1; - } else if (lsign && lhs == VL_MASK_Q(obits)) { // -1 - if (rwp[0] & 1) { - return VL_MASK_Q(obits); // -1^odd=-1 - } else { - return 1; // -1^even=1 - } + if (lhs == 0) return 0; // "X" + if (lhs == 1) return 1; + if (lsign && lhs == VL_MASK_Q(obits)) { // -1 + if (rwp[0] & 1) return VL_MASK_Q(obits); // -1^odd=-1 + return 1; // -1^even=1 } return 0; } @@ -1145,17 +1142,17 @@ void _vl_vsformat(std::string& output, const std::string& format, int argc, if (width > strp->size()) padding.append(width - strp->size(), ' '); output += left ? (*strp + padding) : (padding + *strp); break; - } else { // Number-based string - std::string field; - for (; lsb >= 0; --lsb) { - lsb = (lsb / 8) * 8; // Next digit - const IData charval = VL_BITRSHIFT_W(lwp, lsb) & 0xff; - field += (charval == 0) ? ' ' : charval; - } - std::string padding; - if (width > field.size()) padding.append(width - field.size(), ' '); - output += left ? (field + padding) : (padding + field); } + // Number-based string + std::string field; + for (; lsb >= 0; --lsb) { + lsb = (lsb / 8) * 8; // Next digit + const IData charval = VL_BITRSHIFT_W(lwp, lsb) & 0xff; + field += (charval == 0) ? ' ' : charval; + } + std::string padding; + if (width > field.size()) padding.append(width - field.size(), ' '); + output += left ? (field + padding) : (padding + field); break; } case 'p': { // Pattern @@ -1208,7 +1205,7 @@ void _vl_vsformat(std::string& output, const std::string& format, int argc, // + 1.0 rounding bias. double dchars = mantissabits / 3.321928094887362 + 1.0; if (formatAttr == VL_VFORMATATTR_SIGNED) ++dchars; // space for sign - width = int(dchars); + width = static_cast(dchars); } const int needmore = static_cast(width) - digits; if (needmore > 0) { @@ -1248,7 +1245,7 @@ void _vl_vsformat(std::string& output, const std::string& format, int argc, // V3Width errors on const %x of string, but V3Randomize may make a %x on a // string, or may have a runtime format const std::string* const strp = static_cast(thingp); - int chars = static_cast(strp->size()); + const int chars = static_cast(strp->size()); int truncFront = widthSet ? (chars - (static_cast(width) / 2)) : 0; if (truncFront < 0) truncFront = 0; lbits = chars * 8; @@ -1348,13 +1345,12 @@ void _vl_vsformat(std::string& output, const std::string& format, int argc, static bool _vl_vsss_eof(FILE* fp, int floc) VL_MT_SAFE { if (VL_LIKELY(fp)) { return std::feof(fp) ? true : false; // true : false to prevent MSVC++ warning - } else { - return floc < 0; } + return floc < 0; } static void _vl_vsss_advance(FILE* fp, int& floc) VL_MT_SAFE { if (VL_LIKELY(fp)) { - std::fgetc(fp); + (void)std::fgetc(fp); } else { floc -= 8; } @@ -1365,17 +1361,13 @@ static int _vl_vsss_peek(FILE* fp, int& floc, const WDataInP fromp, if (VL_LIKELY(fp)) { const int data = std::fgetc(fp); if (data == EOF) return EOF; - ungetc(data, fp); + ungetc(data, fp); // No (void), might be macro return data; - } else { - if (floc < 0) return EOF; - floc = floc & ~7; // Align to closest character - if (fromp == nullptr) { - return fstr[fstr.length() - 1 - (floc >> 3)]; - } else { - return VL_BITRSHIFT_W(fromp, floc) & 0xff; - } } + if (floc < 0) return EOF; + floc = floc & ~7; // Align to closest character + if (!fromp) return fstr[fstr.length() - 1 - (floc >> 3)]; + return VL_BITRSHIFT_W(fromp, floc) & 0xff; } static void _vl_vsss_skipspace(FILE* fp, int& floc, const WDataInP fromp, const std::string& fstr) VL_MT_SAFE { @@ -1532,11 +1524,11 @@ IData _vl_vsscanf(FILE* fp, // If a fscanf if (!formatAttrValid) formatAttr = va_arg(ap, int); // char promoted to int formatAttrValid = false; } - int obits = (!inIgnore - && (formatAttr == VL_VFORMATATTR_UNSIGNED - || formatAttr == VL_VFORMATATTR_SIGNED)) - ? va_arg(ap, int) - : 0; + const int obits = (!inIgnore + && (formatAttr == VL_VFORMATATTR_UNSIGNED + || formatAttr == VL_VFORMATATTR_SIGNED)) + ? va_arg(ap, int) + : 0; void* const thingp = inIgnore ? nullptr : va_arg(ap, void*); double real = 0; @@ -1995,13 +1987,14 @@ uint64_t VL_MURMUR64_HASH(const char* key) VL_PURE { const unsigned char* data2 = reinterpret_cast(data); switch (len & 7) { - case 7: h ^= uint64_t(data2[6]) << 48; /* fallthrough */ - case 6: h ^= uint64_t(data2[5]) << 40; /* fallthrough */ - case 5: h ^= uint64_t(data2[4]) << 32; /* fallthrough */ - case 4: h ^= uint64_t(data2[3]) << 24; /* fallthrough */ - case 3: h ^= uint64_t(data2[2]) << 16; /* fallthrough */ - case 2: h ^= uint64_t(data2[1]) << 8; /* fallthrough */ - case 1: h ^= uint64_t(data2[0]); h *= m; /* fallthrough */ + case 7: h ^= static_cast(data2[6]) << 48; // FALLTHRU + case 6: h ^= static_cast(data2[5]) << 40; // FALLTHRU + case 5: h ^= static_cast(data2[4]) << 32; // FALLTHRU + case 4: h ^= static_cast(data2[3]) << 24; // FALLTHRU + case 3: h ^= static_cast(data2[2]) << 16; // FALLTHRU + case 2: h ^= static_cast(data2[1]) << 8; // FALLTHRU + case 1: h ^= static_cast(data2[0]); h *= m; // FALLTHRU + default:; }; h ^= h >> r; @@ -2082,7 +2075,7 @@ static std::string _vl_stacktrace_demangle(const std::string& input) VL_MT_SAFE // abi::__cxa_demangle mallocs demangled_name int status = 0; char* const demangled_name - = abi::__cxa_demangle(word.c_str(), NULL, NULL, &status); + = abi::__cxa_demangle(word.c_str(), nullptr, nullptr, &status); if (status == 0) { result += std::string{demangled_name}; std::free(demangled_name); // Free the allocated memory @@ -2386,14 +2379,14 @@ static const char* memhFormat(int nBits) { static thread_local char t_buf[32]; switch ((nBits - 1) / 4) { - case 0: VL_SNPRINTF(t_buf, 32, "%%01x"); break; - case 1: VL_SNPRINTF(t_buf, 32, "%%02x"); break; - case 2: VL_SNPRINTF(t_buf, 32, "%%03x"); break; - case 3: VL_SNPRINTF(t_buf, 32, "%%04x"); break; - case 4: VL_SNPRINTF(t_buf, 32, "%%05x"); break; - case 5: VL_SNPRINTF(t_buf, 32, "%%06x"); break; - case 6: VL_SNPRINTF(t_buf, 32, "%%07x"); break; - case 7: VL_SNPRINTF(t_buf, 32, "%%08x"); break; + case 0: (void)VL_SNPRINTF(t_buf, 32, "%%01x"); break; + case 1: (void)VL_SNPRINTF(t_buf, 32, "%%02x"); break; + case 2: (void)VL_SNPRINTF(t_buf, 32, "%%03x"); break; + case 3: (void)VL_SNPRINTF(t_buf, 32, "%%04x"); break; + case 4: (void)VL_SNPRINTF(t_buf, 32, "%%05x"); break; + case 5: (void)VL_SNPRINTF(t_buf, 32, "%%06x"); break; + case 6: (void)VL_SNPRINTF(t_buf, 32, "%%07x"); break; + case 7: (void)VL_SNPRINTF(t_buf, 32, "%%08x"); break; default: assert(false); break; // LCOV_EXCL_LINE } return t_buf; @@ -2764,28 +2757,27 @@ double vl_time_multiplier(int scale) VL_PURE { 0.00000000000000001, 0.000000000000000001}; return neg10[-scale]; - } else { - static const double pow10[] = {1.0, - 10.0, - 100.0, - 1000.0, - 10000.0, - 100000.0, - 1000000.0, - 10000000.0, - 100000000.0, - 1000000000.0, - 10000000000.0, - 100000000000.0, - 1000000000000.0, - 10000000000000.0, - 100000000000000.0, - 1000000000000000.0, - 10000000000000000.0, - 100000000000000000.0, - 1000000000000000000.0}; - return pow10[scale]; } + static const double pow10[] = {1.0, + 10.0, + 100.0, + 1000.0, + 10000.0, + 100000.0, + 1000000.0, + 10000000.0, + 100000000.0, + 1000000000.0, + 10000000000.0, + 100000000000.0, + 1000000000000.0, + 10000000000000.0, + 100000000000000.0, + 1000000000000000.0, + 10000000000000000.0, + 100000000000000000.0, + 1000000000000000000.0}; + return pow10[scale]; } uint64_t vl_time_pow10(int n) { static const uint64_t pow10[20] = { @@ -2824,7 +2816,7 @@ std::string vl_timescaled_double(double value, const char* format) VL_PURE { else if (value >= 1e-18) { suffixp = "as"; value *= 1e18; } // clang-format on char valuestr[100]; - VL_SNPRINTF(valuestr, 100, format, value, suffixp); + (void)VL_SNPRINTF(valuestr, 100, format, value, suffixp); return std::string{valuestr}; // Gets converted to string, so no ref to stack } @@ -3075,7 +3067,7 @@ const char* VerilatedContext::commandArgsPlusMatch(const char* prefixp) const std::string& match = impp()->argPlusMatch(prefixp); static thread_local std::string t_outstr; if (match.empty()) return ""; - t_outstr = match.c_str(); + t_outstr = match; return t_outstr.c_str(); } void VerilatedContext::internalsDump() const VL_MT_SAFE { @@ -3267,9 +3259,8 @@ bool VerilatedContextImp::commandArgVlString(const std::string& arg, const std:: if (0 == std::strncmp(prefix.c_str(), arg.c_str(), len)) { valuer = arg.substr(len); return true; - } else { - return false; } + return false; } bool VerilatedContextImp::commandArgVlUint64(const std::string& arg, const std::string& prefix, @@ -3312,10 +3303,9 @@ void VerilatedContext::randSeed(int val) VL_MT_SAFE { uint64_t VerilatedContextImp::randSeedDefault64() const VL_MT_SAFE { if (randSeed() != 0) { return ((static_cast(randSeed()) << 32) ^ (static_cast(randSeed()))); - } else { - return ((static_cast(vl_sys_rand32()) << 32) - ^ (static_cast(vl_sys_rand32()))); } + return ((static_cast(vl_sys_rand32()) << 32) + ^ (static_cast(vl_sys_rand32()))); } //====================================================================== @@ -3343,7 +3333,8 @@ void VerilatedContext::statsPrintSummary() VL_MT_UNSAFE { = vl_timescaled_double((cputime != 0.0) ? (simtimeInUnits / cputime) : 0, "%0.3f %s"); VL_PRINTF("- Verilator: %s at %s; walltime %0.3f s; speed %s/s\n", endwhy.c_str(), simtime.c_str(), walltime, simtimePerf.c_str()); - uint64_t memPeak, memCurrent; + uint64_t memPeak; + uint64_t memCurrent; VlOs::memUsageBytes(memPeak /*ref*/, memCurrent /*ref*/); const double modelMB = memPeak / 1024.0 / 1024.0; VL_PRINTF("- Verilator: cpu %0.3f s on %u threads; allocated %0.0f MB\n", cputime, @@ -3484,27 +3475,27 @@ static struct { static void addCbFlush(Verilated::VoidPCb cb, void* datap) VL_MT_SAFE_EXCLUDES(VlCbStatic.s_flushMutex) { const VerilatedLockGuard lock{VlCbStatic.s_flushMutex}; - std::pair pair(cb, datap); + const std::pair pair(cb, datap); VlCbStatic.s_flushCbs.remove(pair); // Just in case it's a duplicate VlCbStatic.s_flushCbs.push_back(pair); } static void addCbExit(Verilated::VoidPCb cb, void* datap) VL_MT_SAFE_EXCLUDES(VlCbStatic.s_exitMutex) { const VerilatedLockGuard lock{VlCbStatic.s_exitMutex}; - std::pair pair(cb, datap); + const std::pair pair(cb, datap); VlCbStatic.s_exitCbs.remove(pair); // Just in case it's a duplicate VlCbStatic.s_exitCbs.push_back(pair); } static void removeCbFlush(Verilated::VoidPCb cb, void* datap) VL_MT_SAFE_EXCLUDES(VlCbStatic.s_flushMutex) { const VerilatedLockGuard lock{VlCbStatic.s_flushMutex}; - std::pair pair(cb, datap); + const std::pair pair(cb, datap); VlCbStatic.s_flushCbs.remove(pair); } static void removeCbExit(Verilated::VoidPCb cb, void* datap) VL_MT_SAFE_EXCLUDES(VlCbStatic.s_exitMutex) { const VerilatedLockGuard lock{VlCbStatic.s_exitMutex}; - std::pair pair(cb, datap); + const std::pair pair(cb, datap); VlCbStatic.s_exitCbs.remove(pair); } static void runCallbacks(const VoidPCbList& cbs) VL_MT_SAFE { @@ -3589,7 +3580,7 @@ void Verilated::stackCheck(QData needSize) VL_MT_UNSAFE { } // VL_PRINTF_MT("-Info: stackCheck(%" PRIu64 ") have %" PRIu64 "\n", needSize, haveSize); // Check and request for 1.5x need. This is automated so the user doesn't need to do anything. - QData requestSize = needSize + needSize / 2; + const QData requestSize = needSize + needSize / 2; if (VL_UNLIKELY(haveSize && needSize && haveSize < requestSize)) { // Try to increase the stack limit to the requested size rlim.rlim_cur = requestSize; @@ -3894,7 +3885,7 @@ void VerilatedAssertOneThread::fatal_different() VL_MT_SAFE { void VlDeleter::deleteAll() VL_EXCLUDES(m_mutex) VL_EXCLUDES(m_deleteMutex) VL_MT_SAFE { while (true) { { - VerilatedLockGuard lock{m_mutex}; + const VerilatedLockGuard lock{m_mutex}; if (m_newGarbage.empty()) break; m_deleteMutex.lock(); std::swap(m_newGarbage, m_deleteNow); diff --git a/include/verilated.h b/include/verilated.h index 909956d82..b7f70bda7 100644 --- a/include/verilated.h +++ b/include/verilated.h @@ -392,7 +392,7 @@ protected: int m_errorLimit = 1; // Stop on error number int m_randReset = 0; // Random reset: 0=all 0s, 1=all 1s, 2=random int m_randSeed = 0; // Random seed: 0=random - enum { UNITS_NONE = 99 }; // Default based on precision + static constexpr int UNITS_NONE = 99; // Default based on precision int m_timeFormatUnits = UNITS_NONE; // $timeformat units int m_timeFormatPrecision = 0; // $timeformat number of decimal places int m_timeFormatWidth = 20; // $timeformat character width @@ -540,7 +540,7 @@ public: /// Enable quiet (also prevents need for OS calls to get CPU time) void quiet(bool flag) VL_MT_SAFE; /// Return randReset value - int randReset() VL_MT_SAFE { return m_s.m_randReset; } + int randReset() const VL_MT_SAFE { return m_s.m_randReset; } /// Select initial value of otherwise uninitialized signals. /// 0 = Set to zeros /// 1 = Set all bits to one diff --git a/include/verilated_cov.cpp b/include/verilated_cov.cpp index 123fa6dbe..0f8eced98 100644 --- a/include/verilated_cov.cpp +++ b/include/verilated_cov.cpp @@ -147,7 +147,7 @@ private: if (!std::isprint(*pos) || *pos == '%' || *pos == '"') { constexpr size_t LEN_MAX_HEX = 20; char hex[LEN_MAX_HEX]; - VL_SNPRINTF(hex, LEN_MAX_HEX, "%%%02X", pos[0]); + (void)VL_SNPRINTF(hex, LEN_MAX_HEX, "%%%02X", pos[0]); rtn += hex; } else { rtn += *pos; @@ -344,9 +344,9 @@ public: // Insert the values int addKeynum = 0; for (int i = 0; i < VerilatedCovConst::MAX_KEYS; ++i) { - const std::string key = keys[i]; + const std::string& key = keys[i]; if (!keys[i].empty()) { - const std::string val = valps[i]; + const std::string& val = valps[i]; // std::cout << " " << __FUNCTION__ << " " << key << " = " << val << "\n"; m_insertp->m_keys[addKeynum] = valueIndex(key); m_insertp->m_vals[addKeynum] = valueIndex(val); diff --git a/include/verilated_dpi.cpp b/include/verilated_dpi.cpp index d8f75f577..c97c56640 100644 --- a/include/verilated_dpi.cpp +++ b/include/verilated_dpi.cpp @@ -775,7 +775,7 @@ int svGetCallerInfo(const char** fileNamepp, int* lineNumberp) { //====================================================================== // Time -int svGetTime(const svScope scope, svTimeVal* time) { +int svGetTime(const svScope /*scope*/, svTimeVal* time) { if (VL_UNLIKELY(!time)) return -1; const QData qtime = VL_TIME_Q(); VlWide<2> itime; @@ -796,7 +796,7 @@ int svGetTimeUnit(const svScope scope, int32_t* time_unit) { return 0; } -int svGetTimePrecision(const svScope scope, int32_t* time_precision) { +int svGetTimePrecision(const svScope /*scope*/, int32_t* time_precision) { if (VL_UNLIKELY(!time_precision)) return -1; *time_precision = Verilated::threadContextp()->timeprecision(); return 0; diff --git a/include/verilated_fst_c.cpp b/include/verilated_fst_c.cpp index a0f636dc4..3096765a5 100644 --- a/include/verilated_fst_c.cpp +++ b/include/verilated_fst_c.cpp @@ -152,7 +152,8 @@ void VerilatedFst::pushPrefix(const char* namep, VerilatedTracePrefixType type, // Upper has name, we can suppress inserting $rootio, but still push so popPrefix works m_prefixStack.emplace_back(prevPrefix, VerilatedTracePrefixType::ROOTIO_WRAPPER); return; - } else if (name.empty()) { + } + if (name.empty()) { m_prefixStack.emplace_back(prevPrefix, VerilatedTracePrefixType::ROOTIO_WRAPPER); return; } @@ -352,7 +353,7 @@ void VerilatedFst::declDoubleArray(uint32_t code, const char* name, int dtypenum //============================================================================= // Get/commit trace buffer -VerilatedFst::Buffer* VerilatedFst::getTraceBuffer(uint32_t fidx) { +VerilatedFst::Buffer* VerilatedFst::getTraceBuffer(uint32_t /*fidx*/) { if (offload()) return new OffloadBuffer{*this}; return new Buffer{*this}; } diff --git a/include/verilated_funcs.h b/include/verilated_funcs.h index ce9643084..2dacc5af8 100644 --- a/include/verilated_funcs.h +++ b/include/verilated_funcs.h @@ -98,10 +98,9 @@ inline IData VL_URANDOM_RANGE_I(IData hi, IData lo) { if (VL_UNLIKELY(hi - lo + 1 == 0)) return rnd; // Modulus isn't very fast but it's common that hi-low is power-of-two return (rnd % (hi - lo + 1)) + lo; - } else { - if (VL_UNLIKELY(lo - hi + 1 == 0)) return rnd; - return (rnd % (lo - hi + 1)) + hi; } + if (VL_UNLIKELY(lo - hi + 1 == 0)) return rnd; + return (rnd % (lo - hi + 1)) + hi; } /// Random reset a signal of given width (init time only, var-specific PRNG) @@ -306,7 +305,7 @@ extern void _vl_debug_print_w(int lbits, WDataInP const iwp) VL_MT_SAFE; // clang-format off -#if defined(SYSTEMC_VERSION) +#ifdef SYSTEMC_VERSION /// Return current simulation time // Already defined: extern sc_time sc_time_stamp(); inline uint64_t vl_time_stamp64() VL_MT_SAFE { return sc_core::sc_time_stamp().value(); } @@ -500,15 +499,15 @@ static inline void VL_ASSIGNBIT_WO(int bit, WDataOutP owp) VL_MT_SAFE { sc_dt::sc_biguint<(obits)> _butemp = (svar).read(); \ uint32_t* chunkp = _butemp.get_raw(); \ int32_t lsb = 0; \ - while (lsb < obits - BITS_PER_DIGIT) { \ + while (lsb < (obits) - BITS_PER_DIGIT) { \ const uint32_t data = *chunkp; \ ++chunkp; \ - _vl_insert_WI(owp.data(), data, lsb + BITS_PER_DIGIT - 1, lsb); \ + _vl_insert_WI((owp).data(), data, lsb + BITS_PER_DIGIT - 1, lsb); \ lsb += BITS_PER_DIGIT; \ } \ - if (lsb < obits) { \ + if (lsb < (obits)) { \ const uint32_t msb_data = *chunkp; \ - _vl_insert_WI(owp.data(), msb_data, obits - 1, lsb); \ + _vl_insert_WI((owp).data(), msb_data, (obits) - 1, lsb); \ } \ (owp)[words - 1] &= VL_MASK_E(obits); \ } @@ -762,14 +761,12 @@ static inline IData VL_COUNTONES_W(int words, WDataInP const lwp) VL_PURE { static inline IData VL_COUNTBITS_I(int lbits, IData lhs, IData ctrl0, IData ctrl1, IData ctrl2) VL_PURE { const int ctrlSum = (ctrl0 & 0x1) + (ctrl1 & 0x1) + (ctrl2 & 0x1); - if (ctrlSum == 3) { - return VL_COUNTONES_I(lhs); - } else if (ctrlSum == 0) { + if (ctrlSum == 3) return VL_COUNTONES_I(lhs); + if (ctrlSum == 0) { const IData mask = (lbits == 32) ? -1 : ((1 << lbits) - 1); return VL_COUNTONES_I(~lhs & mask); - } else { - return (lbits == 32) ? 32 : lbits; } + return (lbits == 32) ? 32 : lbits; } static inline IData VL_COUNTBITS_Q(int lbits, QData lhs, IData ctrl0, IData ctrl1, IData ctrl2) VL_PURE { @@ -1018,17 +1015,17 @@ static inline void VL_NEGATE_INPLACE_W(int words, WDataOutP owp_lwp) VL_MT_SAFE // EMIT_RULE: VL_MUL: oclean=dirty; lclean==clean; rclean==clean; // EMIT_RULE: VL_DIV: oclean=dirty; lclean==clean; rclean==clean; // EMIT_RULE: VL_MODDIV: oclean=dirty; lclean==clean; rclean==clean; -static inline IData VL_DIV_III(int lbits, IData lhs, IData rhs) { +static inline IData VL_DIV_III(int /*lbits*/, IData lhs, IData rhs) { return (rhs == 0) ? 0 : lhs / rhs; } -static inline QData VL_DIV_QQQ(int lbits, QData lhs, QData rhs) { +static inline QData VL_DIV_QQQ(int /*lbits*/, QData lhs, QData rhs) { return (rhs == 0) ? 0 : lhs / rhs; } #define VL_DIV_WWW(lbits, owp, lwp, rwp) (_vl_moddiv_w(lbits, owp, lwp, rwp, 0)) -static inline IData VL_MODDIV_III(int lbits, IData lhs, IData rhs) { +static inline IData VL_MODDIV_III(int /*lbits*/, IData lhs, IData rhs) { return (rhs == 0) ? 0 : lhs % rhs; } -static inline QData VL_MODDIV_QQQ(int lbits, QData lhs, QData rhs) { +static inline QData VL_MODDIV_QQQ(int /*lbits*/, QData lhs, QData rhs) { return (rhs == 0) ? 0 : lhs % rhs; } #define VL_MODDIV_WWW(lbits, owp, lwp, rwp) (_vl_moddiv_w(lbits, owp, lwp, rwp, 1)) @@ -1176,9 +1173,8 @@ static inline WDataOutP VL_DIVS_WWW(int lbits, WDataOutP owp, WDataInP const lwp VL_DIV_WWW(lbits, qNoSign, ltup, rtup); _vl_clean_inplace_w(lbits, VL_NEGATE_W(lwords, owp, qNoSign)); return owp; - } else { - return VL_DIV_WWW(lbits, owp, ltup, rtup); } + return VL_DIV_WWW(lbits, owp, ltup, rtup); } static inline WDataOutP VL_MODDIVS_WWW(int lbits, WDataOutP owp, WDataInP const lwp, WDataInP const rwp) VL_MT_SAFE { @@ -1199,9 +1195,8 @@ static inline WDataOutP VL_MODDIVS_WWW(int lbits, WDataOutP owp, WDataInP const VL_MODDIV_WWW(lbits, qNoSign, ltup, rtup); _vl_clean_inplace_w(lbits, VL_NEGATE_W(lwords, owp, qNoSign)); return owp; - } else { - return VL_MODDIV_WWW(lbits, owp, ltup, rtup); } + return VL_MODDIV_WWW(lbits, owp, ltup, rtup); } #define VL_POW_IIQ(obits, lbits, rbits, lhs, rhs) VL_POW_QQQ(obits, lbits, rbits, lhs, rhs) @@ -1255,14 +1250,11 @@ static inline IData VL_POWSS_III(int obits, int, int rbits, IData lhs, IData rhs if (rsign && VL_SIGN_I(rbits, rhs)) { if (lhs == 0) { return 0; // "X" - } else if (lhs == 1) { - return 1; - } else if (lsign && lhs == VL_MASK_I(obits)) { // -1 - if (rhs & 1) { - return VL_MASK_I(obits); // -1^odd=-1 - } else { - return 1; // -1^even=1 - } + } + if (lhs == 1) { return 1; } + if (lsign && lhs == VL_MASK_I(obits)) { // -1 + if (rhs & 1) return VL_MASK_I(obits); // -1^odd=-1 + return 1; // -1^even=1 } return 0; } @@ -1272,16 +1264,12 @@ static inline QData VL_POWSS_QQQ(int obits, int, int rbits, QData lhs, QData rhs bool rsign) VL_MT_SAFE { if (VL_UNLIKELY(rhs == 0)) return 1; if (rsign && VL_SIGN_Q(rbits, rhs)) { - if (lhs == 0) { - return 0; // "X" - } else if (lhs == 1) { - return 1; - } else if (lsign && lhs == VL_MASK_Q(obits)) { // -1 - if (rhs & 1) { - return VL_MASK_Q(obits); // -1^odd=-1 - } else { - return 1; // -1^even=1 - } + if (lhs == 0) return 0; // "X" + + if (lhs == 1) return 1; + if (lsign && lhs == VL_MASK_Q(obits)) { // -1 + if (rhs & 1) return VL_MASK_Q(obits); // -1^odd=-1 + return 1; // -1^even=1 } return 0; } @@ -1614,28 +1602,28 @@ static inline WDataOutP VL_STREAML_WWI(int lbits, WDataOutP owp, WDataInP const return owp; } -static inline IData VL_PACK_I_RI(int obits, int lbits, const VlQueue& q) { +static inline IData VL_PACK_I_RI(int /*obits*/, int lbits, const VlQueue& q) { IData ret = 0; for (size_t i = 0; i < q.size(); ++i) ret |= static_cast(q.at(q.size() - 1 - i)) << (i * lbits); return ret; } -static inline IData VL_PACK_I_RI(int obits, int lbits, const VlQueue& q) { +static inline IData VL_PACK_I_RI(int /*obits*/, int lbits, const VlQueue& q) { IData ret = 0; for (size_t i = 0; i < q.size(); ++i) ret |= static_cast(q.at(q.size() - 1 - i)) << (i * lbits); return ret; } -static inline IData VL_PACK_I_RI(int obits, int lbits, const VlQueue& q) { +static inline IData VL_PACK_I_RI(int /*obits*/, int lbits, const VlQueue& q) { IData ret = 0; for (size_t i = 0; i < q.size(); ++i) ret |= q.at(q.size() - 1 - i) << (i * lbits); return ret; } template -static inline IData VL_PACK_I_UI(int obits, int lbits, const VlUnpacked& q) { +static inline IData VL_PACK_I_UI(int /*obits*/, int lbits, const VlUnpacked& q) { IData ret = 0; for (size_t i = 0; i < N_Depth; ++i) ret |= static_cast(q[N_Depth - 1 - i]) << (i * lbits); @@ -1643,7 +1631,7 @@ static inline IData VL_PACK_I_UI(int obits, int lbits, const VlUnpacked -static inline IData VL_PACK_I_UI(int obits, int lbits, const VlUnpacked& q) { +static inline IData VL_PACK_I_UI(int /*obits*/, int lbits, const VlUnpacked& q) { IData ret = 0; for (size_t i = 0; i < N_Depth; ++i) ret |= static_cast(q[N_Depth - 1 - i]) << (i * lbits); @@ -1651,27 +1639,27 @@ static inline IData VL_PACK_I_UI(int obits, int lbits, const VlUnpacked -static inline IData VL_PACK_I_UI(int obits, int lbits, const VlUnpacked& q) { +static inline IData VL_PACK_I_UI(int /*obits*/, int lbits, const VlUnpacked& q) { IData ret = 0; for (size_t i = 0; i < N_Depth; ++i) ret |= q[N_Depth - 1 - i] << (i * lbits); return ret; } -static inline QData VL_PACK_Q_RI(int obits, int lbits, const VlQueue& q) { +static inline QData VL_PACK_Q_RI(int /*obits*/, int lbits, const VlQueue& q) { QData ret = 0; for (size_t i = 0; i < q.size(); ++i) ret |= static_cast(q.at(q.size() - 1 - i)) << (i * lbits); return ret; } -static inline QData VL_PACK_Q_RI(int obits, int lbits, const VlQueue& q) { +static inline QData VL_PACK_Q_RI(int /*obits*/, int lbits, const VlQueue& q) { QData ret = 0; for (size_t i = 0; i < q.size(); ++i) ret |= static_cast(q.at(q.size() - 1 - i)) << (i * lbits); return ret; } -static inline QData VL_PACK_Q_RI(int obits, int lbits, const VlQueue& q) { +static inline QData VL_PACK_Q_RI(int /*obits*/, int lbits, const VlQueue& q) { QData ret = 0; for (size_t i = 0; i < q.size(); ++i) ret |= static_cast(q.at(q.size() - 1 - i)) << (i * lbits); @@ -1679,7 +1667,7 @@ static inline QData VL_PACK_Q_RI(int obits, int lbits, const VlQueue& q) } template -static inline QData VL_PACK_Q_UI(int obits, int lbits, const VlUnpacked& q) { +static inline QData VL_PACK_Q_UI(int /*obits*/, int lbits, const VlUnpacked& q) { QData ret = 0; for (size_t i = 0; i < N_Depth; ++i) ret |= static_cast(q[N_Depth - 1 - i]) << (i * lbits); @@ -1687,7 +1675,7 @@ static inline QData VL_PACK_Q_UI(int obits, int lbits, const VlUnpacked -static inline QData VL_PACK_Q_UI(int obits, int lbits, const VlUnpacked& q) { +static inline QData VL_PACK_Q_UI(int /*obits*/, int lbits, const VlUnpacked& q) { QData ret = 0; for (size_t i = 0; i < N_Depth; ++i) ret |= static_cast(q[N_Depth - 1 - i]) << (i * lbits); @@ -1695,21 +1683,21 @@ static inline QData VL_PACK_Q_UI(int obits, int lbits, const VlUnpacked -static inline QData VL_PACK_Q_UI(int obits, int lbits, const VlUnpacked& q) { +static inline QData VL_PACK_Q_UI(int /*obits*/, int lbits, const VlUnpacked& q) { QData ret = 0; for (size_t i = 0; i < N_Depth; ++i) ret |= static_cast(q[N_Depth - 1 - i]) << (i * lbits); return ret; } -static inline QData VL_PACK_Q_RQ(int obits, int lbits, const VlQueue& q) { +static inline QData VL_PACK_Q_RQ(int /*obits*/, int lbits, const VlQueue& q) { QData ret = 0; for (size_t i = 0; i < q.size(); ++i) ret |= q.at(q.size() - 1 - i) << (i * lbits); return ret; } template -static inline QData VL_PACK_Q_UQ(int obits, int lbits, const VlUnpacked& q) { +static inline QData VL_PACK_Q_UQ(int /*obits*/, int lbits, const VlUnpacked& q) { QData ret = 0; for (size_t i = 0; i < N_Depth; ++i) ret |= q[N_Depth - 1 - i] << (i * lbits); return ret; @@ -1922,7 +1910,7 @@ static inline void _vl_shiftl_inplace_w(int obits, WDataOutP iowp, // expression. Thus consider this when optimizing. (And perhaps have 2 funcs?) // If RHS (rd/rwp) is larger than the output, zeros (or all ones for >>>) must be returned // (This corresponds to AstShift*Ovr Ast nodes) -static inline IData VL_SHIFTL_III(int obits, int, int, IData lhs, IData rhs) VL_MT_SAFE { +static inline IData VL_SHIFTL_III(int /*obits*/, int, int, IData lhs, IData rhs) VL_MT_SAFE { if (VL_UNLIKELY(rhs >= VL_IDATASIZE)) return 0; return lhs << rhs; // Small is common so not clean return } @@ -1930,7 +1918,7 @@ static inline IData VL_SHIFTL_IIQ(int obits, int, int, IData lhs, QData rhs) VL_ if (VL_UNLIKELY(rhs >= VL_IDATASIZE)) return 0; return VL_CLEAN_II(obits, obits, lhs << rhs); } -static inline QData VL_SHIFTL_QQI(int obits, int, int, QData lhs, IData rhs) VL_MT_SAFE { +static inline QData VL_SHIFTL_QQI(int /*obits*/, int, int, QData lhs, IData rhs) VL_MT_SAFE { if (VL_UNLIKELY(rhs >= VL_QUADSIZE)) return 0; return lhs << rhs; // Small is common so not clean return } @@ -1991,19 +1979,19 @@ static inline QData VL_SHIFTL_QQW(int obits, int, int rbits, QData lhs, // EMIT_RULE: VL_SHIFTR: oclean=lclean; rclean==clean; // Important: Unlike most other funcs, the shift might well be a computed // expression. Thus consider this when optimizing. (And perhaps have 2 funcs?) -static inline IData VL_SHIFTR_III(int obits, int, int, IData lhs, IData rhs) VL_PURE { +static inline IData VL_SHIFTR_III(int /*obits*/, int, int, IData lhs, IData rhs) VL_PURE { if (VL_UNLIKELY(rhs >= VL_IDATASIZE)) return 0; return lhs >> rhs; } -static inline IData VL_SHIFTR_IIQ(int obits, int, int, IData lhs, QData rhs) VL_PURE { +static inline IData VL_SHIFTR_IIQ(int /*obits*/, int, int, IData lhs, QData rhs) VL_PURE { if (VL_UNLIKELY(rhs >= VL_IDATASIZE)) return 0; return lhs >> rhs; } -static inline QData VL_SHIFTR_QQI(int obits, int, int, QData lhs, IData rhs) VL_PURE { +static inline QData VL_SHIFTR_QQI(int /*obits*/, int, int, QData lhs, IData rhs) VL_PURE { if (VL_UNLIKELY(rhs >= VL_QUADSIZE)) return 0; return lhs >> rhs; } -static inline QData VL_SHIFTR_QQQ(int obits, int, int, QData lhs, QData rhs) VL_PURE { +static inline QData VL_SHIFTR_QQQ(int /*obits*/, int, int, QData lhs, QData rhs) VL_PURE { if (VL_UNLIKELY(rhs >= VL_QUADSIZE)) return 0; return lhs >> rhs; } @@ -2181,9 +2169,8 @@ static inline IData VL_BITSEL_IWII(int lbits, WDataInP const lwp, IData rd) VL_M if (VL_UNLIKELY(rd > static_cast(lbits))) { return ~0; // Spec says you can go outside the range of a array. Don't coredump if so. // We return all 1's as that's more likely to find bugs (?) than 0's. - } else { - return (lwp[word] >> VL_BITBIT_E(rd)); } + return (lwp[word] >> VL_BITBIT_E(rd)); } // EMIT_RULE: VL_RANGE: oclean=lclean; out=dirty @@ -2196,34 +2183,35 @@ static inline IData VL_SEL_IWII(int lbits, WDataInP const lwp, IData lsb, IData const int msb = lsb + width - 1; if (VL_UNLIKELY(msb >= lbits)) { return ~0; // Spec says you can go outside the range of a array. Don't coredump if so. - } else if (VL_BITWORD_E(msb) == VL_BITWORD_E(static_cast(lsb))) { - return VL_BITRSHIFT_W(lwp, lsb); - } else { - // 32 bit extraction may span two words - const int nbitsfromlow = VL_EDATASIZE - VL_BITBIT_E(lsb); // bits that come from low word - return ((lwp[VL_BITWORD_E(msb)] << nbitsfromlow) | VL_BITRSHIFT_W(lwp, lsb)); } + if (VL_BITWORD_E(msb) == VL_BITWORD_E(static_cast(lsb))) { + return VL_BITRSHIFT_W(lwp, lsb); + } + // 32 bit extraction may span two words + const int nbitsfromlow = VL_EDATASIZE - VL_BITBIT_E(lsb); // bits that come from low word + return ((lwp[VL_BITWORD_E(msb)] << nbitsfromlow) | VL_BITRSHIFT_W(lwp, lsb)); } static inline QData VL_SEL_QWII(int lbits, WDataInP const lwp, IData lsb, IData width) VL_MT_SAFE { const int msb = lsb + width - 1; if (VL_UNLIKELY(msb > lbits)) { return ~0; // Spec says you can go outside the range of a array. Don't coredump if so. - } else if (VL_BITWORD_E(msb) == VL_BITWORD_E(static_cast(lsb))) { + } + if (VL_BITWORD_E(msb) == VL_BITWORD_E(static_cast(lsb))) { return VL_BITRSHIFT_W(lwp, lsb); - } else if (VL_BITWORD_E(msb) == 1 + VL_BITWORD_E(static_cast(lsb))) { + } + if (VL_BITWORD_E(msb) == 1 + VL_BITWORD_E(static_cast(lsb))) { const int nbitsfromlow = VL_EDATASIZE - VL_BITBIT_E(lsb); const QData hi = (lwp[VL_BITWORD_E(msb)]); const QData lo = VL_BITRSHIFT_W(lwp, lsb); return (hi << nbitsfromlow) | lo; - } else { - // 64 bit extraction may span three words - const int nbitsfromlow = VL_EDATASIZE - VL_BITBIT_E(lsb); - const QData hi = (lwp[VL_BITWORD_E(msb)]); - const QData mid = (lwp[VL_BITWORD_E(lsb) + 1]); - const QData lo = VL_BITRSHIFT_W(lwp, lsb); - return (hi << (nbitsfromlow + VL_EDATASIZE)) | (mid << nbitsfromlow) | lo; } + // 64 bit extraction may span three words + const int nbitsfromlow = VL_EDATASIZE - VL_BITBIT_E(lsb); + const QData hi = (lwp[VL_BITWORD_E(msb)]); + const QData mid = (lwp[VL_BITWORD_E(lsb) + 1]); + const QData lo = VL_BITRSHIFT_W(lwp, lsb); + return (hi << (nbitsfromlow + VL_EDATASIZE)) | (mid << nbitsfromlow) | lo; } static inline WDataOutP VL_SEL_WWII(int obits, int lbits, WDataOutP owp, WDataInP const lwp, @@ -2277,13 +2265,11 @@ static inline bool VL_GET_QUEUE_BIT(const VlQueue& queue, int srcElementBits, if (VL_UNLIKELY(elemIdx >= queue.size())) return false; const T element = queue.at(elemIdx); - if (srcElementBits == 1) { - return element & 1; - } else { - const size_t bitInElem = bitIndex % srcElementBits; - const size_t actualBitPos = srcElementBits - 1 - bitInElem; - return (element >> actualBitPos) & 1; - } + if (srcElementBits == 1) return element & 1; + + const size_t bitInElem = bitIndex % srcElementBits; + const size_t actualBitPos = srcElementBits - 1 - bitInElem; + return (element >> actualBitPos) & 1; } // Helper function to set a bit in the destination queue @@ -2351,8 +2337,8 @@ static inline void VL_ZERO_INIT_QUEUE_ELEM(VlWide& elem) { // This specialization works for both VlQueue (and similar) as well // as VlQueue>. template -static inline void VL_COPY_Q(VlQueue& q, const VlQueue& from, int lbits, int srcElementBits, - int dstElementBits) { +static inline void VL_COPY_Q(VlQueue& q, const VlQueue& from, int /*lbits*/, + int srcElementBits, int dstElementBits) { if (srcElementBits == dstElementBits) { // Simple case: same element bit width, direct copy of each element if (VL_UNLIKELY(&q == &from)) return; // Skip self-assignment when it's truly a no-op @@ -2576,49 +2562,49 @@ static inline void VL_UNPACK_RW_W(int lbits, int rbits, VlQueue> } template -static inline void VL_UNPACK_UI_I(int lbits, int rbits, VlUnpacked& q, +static inline void VL_UNPACK_UI_I(int lbits, int /*rbits*/, VlUnpacked& q, IData from) { const IData mask = VL_MASK_I(lbits); for (size_t i = 0; i < N_Depth; ++i) q[i] = (from >> ((N_Depth - 1 - i) * lbits)) & mask; } template -static inline void VL_UNPACK_UI_I(int lbits, int rbits, VlUnpacked& q, +static inline void VL_UNPACK_UI_I(int lbits, int /*rbits*/, VlUnpacked& q, IData from) { const IData mask = VL_MASK_I(lbits); for (size_t i = 0; i < N_Depth; ++i) q[i] = (from >> ((N_Depth - 1 - i) * lbits)) & mask; } template -static inline void VL_UNPACK_UI_I(int lbits, int rbits, VlUnpacked& q, +static inline void VL_UNPACK_UI_I(int lbits, int /*rbits*/, VlUnpacked& q, IData from) { const IData mask = VL_MASK_I(lbits); for (size_t i = 0; i < N_Depth; ++i) q[i] = (from >> ((N_Depth - 1 - i) * lbits)) & mask; } template -static inline void VL_UNPACK_UI_Q(int lbits, int rbits, VlUnpacked& q, +static inline void VL_UNPACK_UI_Q(int lbits, int /*rbits*/, VlUnpacked& q, QData from) { const IData mask = VL_MASK_I(lbits); for (size_t i = 0; i < N_Depth; ++i) q[i] = (from >> ((N_Depth - 1 - i) * lbits)) & mask; } template -static inline void VL_UNPACK_UI_Q(int lbits, int rbits, VlUnpacked& q, +static inline void VL_UNPACK_UI_Q(int lbits, int /*rbits*/, VlUnpacked& q, QData from) { const IData mask = VL_MASK_I(lbits); for (size_t i = 0; i < N_Depth; ++i) q[i] = (from >> ((N_Depth - 1 - i) * lbits)) & mask; } template -static inline void VL_UNPACK_UI_Q(int lbits, int rbits, VlUnpacked& q, +static inline void VL_UNPACK_UI_Q(int lbits, int /*rbits*/, VlUnpacked& q, QData from) { const IData mask = VL_MASK_I(lbits); for (size_t i = 0; i < N_Depth; ++i) q[i] = (from >> ((N_Depth - 1 - i) * lbits)) & mask; } template -static inline void VL_UNPACK_UQ_Q(int lbits, int rbits, VlUnpacked& q, +static inline void VL_UNPACK_UQ_Q(int lbits, int /*rbits*/, VlUnpacked& q, QData from) { const QData mask = VL_MASK_Q(lbits); for (size_t i = 0; i < N_Depth; ++i) q[i] = (from >> ((N_Depth - 1 - i) * lbits)) & mask; @@ -2975,11 +2961,8 @@ extern std::string VL_SUBSTR_N(const std::string& lhs, IData rhs, IData ths) VL_ inline IData VL_CMP_NN(const std::string& lhs, const std::string& rhs, bool ignoreCase) VL_PURE { // SystemVerilog does not allow a string variable to contain '\0'. // So C functions such as strcmp() can correctly compare strings. - if (ignoreCase) { - return VL_STRCASECMP(lhs.c_str(), rhs.c_str()); - } else { - return std::strcmp(lhs.c_str(), rhs.c_str()); - } + if (ignoreCase) { return VL_STRCASECMP(lhs.c_str(), rhs.c_str()); } + return std::strcmp(lhs.c_str(), rhs.c_str()); } extern IData VL_ATOI_N(const std::string& str, int base) VL_PURE; diff --git a/include/verilated_imp.h b/include/verilated_imp.h index 6ee4e580e..b03b86d16 100644 --- a/include/verilated_imp.h +++ b/include/verilated_imp.h @@ -378,7 +378,7 @@ private: // MCD Case if (fdi & 1) fp.push_back(stdout); fdi >>= 1; - for (size_t i = 1; (fdi != 0) && (i < fp.capacity()); ++i, fdi >>= 1) { + for (size_t i = 1; (fdi != 0) && (i < VerilatedFpList::capacity()); ++i, fdi >>= 1) { if (fdi & VL_MASK_I(1)) fp.push_back(m_fdps[i]); } } @@ -553,9 +553,8 @@ private: if (it == s().m_exportMap.end()) { s().m_exportMap.emplace(namep, s().m_exportNext++); return s().m_exportNext++; - } else { - return it->second; } + return it->second; } public: diff --git a/include/verilated_probdist.cpp b/include/verilated_probdist.cpp index e2b75d3c7..a9a858d58 100644 --- a/include/verilated_probdist.cpp +++ b/include/verilated_probdist.cpp @@ -99,10 +99,11 @@ IData VL_DIST_CHI_SQUARE(IData& seedr, IData udf) VL_MT_SAFE { double r = _vl_dbase_chi_square(seedr, df); int32_t i; if (r >= 0) { - i = static_cast(r + 0.5); + i = static_cast(r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding } else { r = -r; // LCOV_EXCL_LINE - i = static_cast(r + 0.5); // LCOV_EXCL_LINE + i = static_cast( + r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding // LCOV_EXCL_LINE i = -i; // LCOV_EXCL_LINE } return static_cast(i); @@ -122,10 +123,10 @@ IData VL_DIST_ERLANG(IData& seedr, IData uk, IData umean) VL_MT_SAFE { double r = -a * log(x) / b; int32_t i; if (r >= 0) { - i = static_cast(r + 0.5); + i = static_cast(r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding } else { r = -r; - i = static_cast(r + 0.5); + i = static_cast(r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding i = -i; } return static_cast(i); @@ -140,10 +141,11 @@ IData VL_DIST_EXPONENTIAL(IData& seedr, IData umean) VL_MT_SAFE { int32_t i; double r = _vl_dbase_exponential(seedr, mean); if (r >= 0) { - i = static_cast(r + 0.5); + i = static_cast(r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding } else { r = -r; // LCOV_EXCL_LINE - i = static_cast(r + 0.5); // LCOV_EXCL_LINE + i = static_cast( + r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding // LCOV_EXCL_LINE i = -i; // LCOV_EXCL_LINE } return static_cast(i); @@ -155,10 +157,10 @@ IData VL_DIST_NORMAL(IData& seedr, IData umean, IData usd) VL_MT_SAFE { double r = _vl_dbase_normal(seedr, mean, sd); int32_t i; if (r >= 0) { - i = static_cast(r + 0.5); + i = static_cast(r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding } else { r = -r; - i = static_cast(r + 0.5); + i = static_cast(r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding i = -i; } return static_cast(i); @@ -172,7 +174,7 @@ IData VL_DIST_POISSON(IData& seedr, IData umean) VL_MT_SAFE { } int32_t i = 0; double q = -static_cast(mean); - double p = exp(q); + const double p = exp(q); q = _vl_dbase_uniform(seedr, 0, 1); while (p < q) { ++i; @@ -193,10 +195,10 @@ IData VL_DIST_T(IData& seedr, IData udf) VL_MT_SAFE { double r = _vl_dbase_normal(seedr, 0, 1) / root; int32_t i; if (r >= 0) { - i = static_cast(r + 0.5); + i = static_cast(r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding } else { r = -r; - i = static_cast(r + 0.5); + i = static_cast(r + 0.5); // cppcheck-suppress bugprone-incorrect-rounding i = -i; } return static_cast(i); diff --git a/include/verilated_profiler.cpp b/include/verilated_profiler.cpp index 621482bf0..609e66324 100644 --- a/include/verilated_profiler.cpp +++ b/include/verilated_profiler.cpp @@ -40,7 +40,7 @@ constexpr const char* const VlExecutionRecord::s_ascii[]; template static size_t roundUptoMultipleOf(size_t value) { static_assert((N & (N - 1)) == 0, "'N' must be a power of 2"); - size_t mask = N - 1; + const size_t mask = N - 1; return (value + mask) & ~mask; } diff --git a/include/verilated_random.cpp b/include/verilated_random.cpp index afc5e3eb1..3419b1506 100644 --- a/include/verilated_random.cpp +++ b/include/verilated_random.cpp @@ -274,7 +274,8 @@ static std::string readUntilBalanced(std::istream& stream) { static std::string parseNestedSelect(const std::string& nested_select_expr, std::vector& indices) { std::istringstream nestedStream(nested_select_expr); - std::string name, idx; + std::string name; + std::string idx; nestedStream >> name; if (name == "(select") { const std::string further_nested_expr = readUntilBalanced(nestedStream); @@ -566,7 +567,7 @@ bool VlRandomizer::parseSolution(std::iostream& os, bool log) { std::getline(os, sat); std::vector numbers; std::string currentNum; - for (char c : sat) { + for (const char c : sat) { if (std::isdigit(c)) { currentNum += c; numbers.push_back(std::stoi(currentNum)); @@ -574,14 +575,14 @@ bool VlRandomizer::parseSolution(std::iostream& os, bool log) { } } if (Verilated::threadContextp()->warnUnsatConstr()) { - for (int n : numbers) { + for (const int n : numbers) { if (n < m_constraints_line.size()) { const std::string& constraint_info = m_constraints_line[n]; // Parse "filename:linenum source" format - size_t colon_pos = constraint_info.find(':'); + const size_t colon_pos = constraint_info.find(':'); if (colon_pos != std::string::npos) { - std::string filename = constraint_info.substr(0, colon_pos); - size_t space_pos = constraint_info.find(" ", colon_pos); + const std::string filename = constraint_info.substr(0, colon_pos); + const size_t space_pos = constraint_info.find(" ", colon_pos); std::string linenum_str; std::string source; if (space_pos != std::string::npos) { @@ -595,7 +596,7 @@ bool VlRandomizer::parseSolution(std::iostream& os, bool log) { std::string msg = "UNSATCONSTR: Unsatisfied constraint"; if (!source.empty()) { // Trim leading whitespace and add quotes - size_t start = source.find_first_not_of(" \t"); + const size_t start = source.find_first_not_of(" \t"); if (start != std::string::npos) { msg += ": '" + source.substr(start) + "'"; } @@ -643,7 +644,9 @@ bool VlRandomizer::parseSolution(std::iostream& os, bool log) { "Internal: Unable to parse solver's response: invalid S-expression"); return false; } - std::string name, idx, value; + std::string name; + std::string idx; + std::string value; std::vector indices; os >> name; indices.clear(); diff --git a/include/verilated_random.h b/include/verilated_random.h index f45e7c8de..0d82b5d78 100644 --- a/include/verilated_random.h +++ b/include/verilated_random.h @@ -75,7 +75,7 @@ public: std::string name() const { return m_name; } int width() const { return m_width; } int dimension() const { return m_dimension; } - virtual void* datap(int idx) const { return m_datap; } + virtual void* datap(int /*idx*/) const { return m_datap; } std::uint32_t randModeIdx() const { return m_randModeIdx; } bool randModeIdxNone() const { return randModeIdx() == std::numeric_limits::max(); } bool set(const std::string& idx, const std::string& val) const; @@ -110,12 +110,9 @@ public: void* datap(int idx) const override { const std::string indexed_name = name() + std::to_string(idx); const auto it = m_arrVarsRefp->find(indexed_name); - if (it != m_arrVarsRefp->end()) { - return it->second->m_datap; - } else { - VL_FATAL_MT(__FILE__, __LINE__, "randomize", "indexed_name not found in m_arr_vars"); - return nullptr; // LCOV_EXCL_BR_LINE - } + if (VL_LIKELY(it != m_arrVarsRefp->end())) return it->second->m_datap; + VL_FATAL_MT(__FILE__, __LINE__, "randomize", "indexed_name not found in m_arr_vars"); + return nullptr; // LCOV_EXCL_BR_LINE } void emitHexs(std::ostream& s, const std::vector& indices, const size_t bit_width, size_t idx) const { @@ -229,7 +226,7 @@ class VlRandomizer VL_NOT_FINAL { // PRIVATE METHODS void randomConstraint(std::ostream& os, VlRNG& rngr, int bits); - bool parseSolution(std::iostream& file, bool log = false); + bool parseSolution(std::iostream& os, bool log = false); bool checkSat(std::iostream& os); void emitRandcExclusions(std::ostream& os) const; // Emit randc exclusion constraints void recordRandcValues(); // Record solved randc values for future exclusion @@ -413,7 +410,7 @@ public: // Register unpacked array of structs template typename std::enable_if::value, void>::type - write_var(VlUnpacked& var, int width, const char* name, int dimension, + write_var(VlUnpacked& var, int /*width*/, const char* name, int dimension, std::uint32_t randmodeIdx = std::numeric_limits::max()) { if (dimension > 0) record_struct_arr(var, name, dimension, {}, {}); } @@ -439,7 +436,7 @@ public: // Register associative array of structs template typename std::enable_if::value, void>::type - write_var(VlAssocArray& var, int width, const char* name, int dimension, + write_var(VlAssocArray& var, int /*width*/, const char* name, int dimension, std::uint32_t randmodeIdx = std::numeric_limits::max()) { if (dimension > 0) record_struct_arr(var, name, dimension, {}, {}); } @@ -449,8 +446,8 @@ public: // Record a flat (non-class) element into the array variable table template typename std::enable_if::value || VlIsVlWide::value, void>::type - record_arr_table(T& var, const std::string& name, int dimension, std::vector indices, - std::vector idxWidths) { + record_arr_table(T& var, const std::string& name, int /*dimension*/, + std::vector indices, std::vector idxWidths) { const std::string key = generateKey(name, m_index); m_arr_vars[key] = std::make_shared(name, &var, m_index, indices, idxWidths); ++m_index; @@ -525,8 +522,8 @@ public: // Register a single structArray element via write_var template typename std::enable_if::value, void>::type - record_struct_arr(T& var, const std::string& name, int dimension, std::vector indices, - std::vector idxWidths) { + record_struct_arr(T& var, const std::string& name, int /*dimension*/, + std::vector indices, std::vector idxWidths) { std::ostringstream oss; for (size_t i = 0; i < indices.size(); ++i) { oss << std::hex << std::setw(int(idxWidths[i] / 4)) << std::setfill('0') @@ -606,7 +603,7 @@ public: } // Helper: Generate unique variable key from name and index - std::string generateKey(const std::string& name, int idx) { + static std::string generateKey(const std::string& name, int idx) { if (!name.empty() && name[0] == '\\') { const size_t space_pos = name.find(' '); return (space_pos != std::string::npos ? name.substr(0, space_pos) : name) diff --git a/include/verilated_saif_c.cpp b/include/verilated_saif_c.cpp index abff785ce..d6632dca7 100644 --- a/include/verilated_saif_c.cpp +++ b/include/verilated_saif_c.cpp @@ -140,9 +140,9 @@ class VerilatedSaifActivityScope final { // Name of the activity scope std::string m_scopeName; // Array indices of child scopes - std::vector> m_childScopes{}; + std::vector> m_childScopes; // Children signals codes mapped to their names in the current scope - std::vector> m_childActivities{}; + std::vector> m_childActivities; // Parent scope pointer VerilatedSaifActivityScope* m_parentScope = nullptr; @@ -278,7 +278,7 @@ void VerilatedSaifActivityAccumulator::declare(uint32_t code, const std::string& //============================================================================= // VerilatedSaif implementation -VerilatedSaif::VerilatedSaif(void* filep) {} +VerilatedSaif::VerilatedSaif(void* /*filep*/) {} void VerilatedSaif::open(const char* filename) VL_MT_SAFE_EXCLUDES(m_mutex) { const VerilatedLockGuard lock{m_mutex}; @@ -378,8 +378,7 @@ bool VerilatedSaif::printScopeActivitiesFromAccumulatorIfPresent( for (const auto& childSignal : accumulator.m_scopeToActivities.at(absoluteScopePath)) { VerilatedSaifActivityVar& activityVariable = accumulator.m_activity.at(childSignal.first); - anyNetWritten - = printActivityStats(activityVariable, childSignal.second.c_str(), anyNetWritten); + anyNetWritten = printActivityStats(activityVariable, childSignal.second, anyNetWritten); } return anyNetWritten; @@ -488,7 +487,8 @@ void VerilatedSaif::pushPrefix(const char* namep, VerilatedTracePrefixType type) // Upper has name, we can suppress inserting $rootio, but still push so popPrefix works m_prefixStack.emplace_back(prevPrefix, VerilatedTracePrefixType::ROOTIO_WRAPPER); return; - } else if (name.empty()) { + } + if (name.empty()) { m_prefixStack.emplace_back(prevPrefix, VerilatedTracePrefixType::ROOTIO_WRAPPER); return; } @@ -513,9 +513,9 @@ void VerilatedSaif::pushPrefix(const char* namep, VerilatedTracePrefixType type) } const std::string newPrefix = prevPrefix + name; - bool properScope = (type != VerilatedTracePrefixType::ARRAY_UNPACKED - && type != VerilatedTracePrefixType::ARRAY_PACKED - && type != VerilatedTracePrefixType::ROOTIO_WRAPPER); + const bool properScope = (type != VerilatedTracePrefixType::ARRAY_UNPACKED + && type != VerilatedTracePrefixType::ARRAY_PACKED + && type != VerilatedTracePrefixType::ROOTIO_WRAPPER); m_prefixStack.emplace_back(newPrefix + (properScope ? " " : ""), type); } @@ -531,8 +531,8 @@ void VerilatedSaif::popPrefix() { } void VerilatedSaif::declare(const uint32_t code, uint32_t fidx, const char* name, - const char* wirep, const bool array, const int arraynum, - const bool bussed, const int msb, const int lsb) { + const char* /*wirep*/, const bool array, const int arraynum, + const bool /*bussed*/, const int msb, const int lsb) { assert(m_activityAccumulators.size() > fidx); VerilatedSaifActivityAccumulator& accumulator = *m_activityAccumulators.at(fidx); @@ -601,7 +601,9 @@ void VerilatedSaif::declDoubleArray(const uint32_t code, const uint32_t fidx, co //============================================================================= // Get/commit trace buffer -VerilatedSaif::Buffer* VerilatedSaif::getTraceBuffer(uint32_t fidx) { return new Buffer{*this}; } +VerilatedSaif::Buffer* VerilatedSaif::getTraceBuffer(uint32_t /*fidx*/) { + return new Buffer{*this}; +} void VerilatedSaif::commitTraceBuffer(VerilatedSaif::Buffer* bufp) { delete bufp; } diff --git a/include/verilated_saif_c.h b/include/verilated_saif_c.h index af7766b9e..11637d925 100644 --- a/include/verilated_saif_c.h +++ b/include/verilated_saif_c.h @@ -61,9 +61,9 @@ private: // Currently active scope VerilatedSaifActivityScope* m_currentScope = nullptr; // Array of declared scopes - std::vector> m_scopes{}; + std::vector> m_scopes; // Activity accumulators used to store variables statistics over simulation time - std::vector> m_activityAccumulators{}; + std::vector> m_activityAccumulators; // Total time of the currently traced simulation uint64_t m_time = 0; diff --git a/include/verilated_save.cpp b/include/verilated_save.cpp index 0569ba0aa..9b1c848b8 100644 --- a/include/verilated_save.cpp +++ b/include/verilated_save.cpp @@ -254,13 +254,13 @@ void VerilatedRestore::fill() VL_MT_UNSAFE_ONE { // Serialization of types VerilatedSerialize& operator<<(VerilatedSerialize& os, VerilatedContext* rhsp) { - os.write(rhsp->serialized1Ptr(), rhsp->serialized1Size()); + os.write(rhsp->serialized1Ptr(), VerilatedContext::serialized1Size()); os << rhsp->impp()->timeFormatSuffix(); os << rhsp->dumpfile(); return os; } VerilatedDeserialize& operator>>(VerilatedDeserialize& os, VerilatedContext* rhsp) { - os.read(rhsp->serialized1Ptr(), rhsp->serialized1Size()); + os.read(rhsp->serialized1Ptr(), VerilatedContext::serialized1Size()); std::string s; os >> s; rhsp->impp()->timeFormatSuffix(s); diff --git a/include/verilated_sym_props.h b/include/verilated_sym_props.h index d88a38cb0..da7199198 100644 --- a/include/verilated_sym_props.h +++ b/include/verilated_sym_props.h @@ -170,12 +170,9 @@ public: const std::vector& packedRanges() const VL_MT_SAFE { return m_packed; } const std::vector& unpackedRanges() const VL_MT_SAFE { return m_unpacked; } const VerilatedRange* range(int dim) const VL_MT_SAFE { - if (dim < udims()) - return &m_unpacked[dim]; - else if (dim < dims()) - return &m_packed[dim - udims()]; - else - return nullptr; + if (dim < udims()) return &m_unpacked[dim]; + if (dim < dims()) return &m_packed[dim - udims()]; + return nullptr; } // DPI accessors (with packed dimensions flattened!) int left(int dim) const VL_MT_SAFE { diff --git a/include/verilated_threads.cpp b/include/verilated_threads.cpp index d814b585c..c35c85512 100644 --- a/include/verilated_threads.cpp +++ b/include/verilated_threads.cpp @@ -148,12 +148,11 @@ VlThreadPool::~VlThreadPool() { std::string VlThreadPool::numaAssign(VerilatedContext* contextp) { #if defined(__linux) || defined(CPU_ZERO) || defined(VL_CPPCHECK) // Linux-like pthreads if (contextp && !contextp->useNumaAssign()) { return "NUMA assignment not requested"; } - std::string numa_strategy = VlOs::getenvStr("VERILATOR_NUMA_STRATEGY", "default"); - if (numa_strategy == "none") { - return "no NUMA assignment requested"; - } else if (numa_strategy != "default" && numa_strategy != "") { + const std::string numa_strategy = VlOs::getenvStr("VERILATOR_NUMA_STRATEGY", "default"); + if (numa_strategy == "none") return "no NUMA assignment requested"; + if (numa_strategy != "default" && numa_strategy != "") return "%Warning: unknown VERILATOR_NUMA_STRATEGY value '" + numa_strategy + "'"; - } + // Get number of processor available to the current process const unsigned num_proc = VlOs::getProcessAvailableParallelism(); if (!num_proc) return "Can't determine number of available threads"; @@ -184,7 +183,7 @@ std::string VlThreadPool::numaAssign(VerilatedContext* contextp) { while (!is.eof()) { std::string line; std::getline(is, line); - std::string::size_type pos = line.find(":"); + const std::string::size_type pos = line.find(':'); int number = -1; if (pos != std::string::npos) number = atoi(line.c_str() + pos + 1); if (line.compare(0, std::strlen("processor"), "processor") == 0) { diff --git a/include/verilated_threads.h b/include/verilated_threads.h index 9ac23392b..205761545 100644 --- a/include/verilated_threads.h +++ b/include/verilated_threads.h @@ -101,12 +101,11 @@ public: = 1 + m_upstreamDepsDone.fetch_add(1, std::memory_order_release); assert(upstreamDepsDone <= m_upstreamDepCount); return (upstreamDepsDone == m_upstreamDepCount); - } else { - const uint32_t upstreamDepsDone_prev - = m_upstreamDepsDone.fetch_sub(1, std::memory_order_release); - assert(upstreamDepsDone_prev > 0); - return (upstreamDepsDone_prev == 1); } + const uint32_t upstreamDepsDone_prev + = m_upstreamDepsDone.fetch_sub(1, std::memory_order_release); + assert(upstreamDepsDone_prev > 0); + return (upstreamDepsDone_prev == 1); } bool areUpstreamDepsDone(bool evenCycle) const { const uint32_t target = evenCycle ? m_upstreamDepCount : 0; @@ -158,7 +157,7 @@ class VlWorkerThread final { #ifdef VL_USE_PTHREADS pthread_t m_pthread{}; #else - std::thread m_cthread{}; + std::thread m_cthread; #endif // METHDOS @@ -182,7 +181,7 @@ public: VL_CPU_RELAX(); } } - VerilatedLockGuard lock{m_mutex}; + const VerilatedLockGuard lock{m_mutex}; while (m_ready.empty()) { m_waiting = true; m_cv.wait(m_mutex); @@ -239,7 +238,7 @@ public: } void freeWorkerIndexes(std::vector& indexes) { const VerilatedLockGuard lock{m_mutex}; - for (size_t index : indexes) m_unassignedWorkers.push(index); + for (const size_t index : indexes) m_unassignedWorkers.push(index); indexes.clear(); } unsigned assignTaskIndex() { return m_assignedTasks++; } diff --git a/include/verilated_timing.h b/include/verilated_timing.h index c87e216ef..157865499 100644 --- a/include/verilated_timing.h +++ b/include/verilated_timing.h @@ -33,7 +33,7 @@ // clang-format off // Some preprocessor magic to support both Clang and GCC coroutines with both libc++ and libstdc++ -#if defined _LIBCPP_VERSION // libc++ +#ifdef _LIBCPP_VERSION // libc++ # if defined(__has_include) && !__has_include() && __has_include() # if __clang_major__ > 13 // Clang > 13 warns that coroutine types in std::experimental are deprecated # pragma clang diagnostic push diff --git a/include/verilated_types.h b/include/verilated_types.h index a0f007d79..ac3ef8994 100644 --- a/include/verilated_types.h +++ b/include/verilated_types.h @@ -173,7 +173,7 @@ public: void randstate(const std::string& state) VL_MT_UNSAFE; }; -inline std::string VL_TO_STRING(const VlProcessRef& p) { return std::string("process"); } +inline std::string VL_TO_STRING(const VlProcessRef&) { return std::string("process"); } //=================================================================== // SystemVerilog event type @@ -611,11 +611,8 @@ public: // Accessing. Verilog: v = assoc[index] const T_Value& at(int32_t index) const { // Needs to work for dynamic arrays, so does not use N_MaxSize - if (VL_UNLIKELY(index < 0 || index >= m_deque.size())) { - return atDefault(); - } else { - return m_deque[index]; - } + if (VL_UNLIKELY(index < 0 || index >= m_deque.size())) return atDefault(); + return m_deque[index]; } // Access with an index counted from end (e.g. q[$]) T_Value& atWriteAppendBack(int32_t index) { return atWriteAppend(m_deque.size() - 1 - index); } @@ -1027,11 +1024,8 @@ public: // Accessing. Verilog: v = assoc[index] const T_Value& at(const T_Key& index) const { const auto it = m_map.find(index); - if (it == m_map.end()) { - return m_defaultValue; - } else { - return it->second; - } + if (it == m_map.end()) return m_defaultValue; + return it->second; } // Setting as a chained operation VlAssocArray& set(const T_Key& index, const T_Value& value) { @@ -1335,7 +1329,6 @@ public: // Default copy assignment operators are used. // METHODS -public: // Raw access WData* data() { return &m_storage[0]; } const WData* data() const { return &m_storage[0]; } @@ -1354,11 +1347,8 @@ public: template int find_length(int dimension, std::true_type) const { - if (dimension == N_CurrentDimension) { - return size(); - } else { - return m_storage[0].template find_length(dimension); - } + if (dimension == N_CurrentDimension) return size(); + return m_storage[0].template find_length(dimension); } template @@ -1941,7 +1931,7 @@ class VlClass VL_NOT_FINAL : public VlDeletable { public: // CONSTRUCTORS VlClass() {} - VlClass(const VlClass& copied) {} + VlClass(const VlClass& /*copied*/) {} ~VlClass() override = default; // Polymorphic shallow clone. Overridden in each generated concrete class. virtual VlClass* clone() const { return nullptr; } @@ -2125,13 +2115,12 @@ static inline bool VL_CAST_DYNAMIC(VlClassRef in, VlClassRef& outr if (VL_LIKELY(casted)) { outr = casted; return true; - } else { - return false; } + return false; } template -static inline bool VL_CAST_DYNAMIC(VlNull in, VlClassRef& outr) { +static inline bool VL_CAST_DYNAMIC(VlNull, VlClassRef& outr) { outr = VlNull{}; return true; } diff --git a/include/verilated_vcd_c.cpp b/include/verilated_vcd_c.cpp index d36cb85da..3e0552752 100644 --- a/include/verilated_vcd_c.cpp +++ b/include/verilated_vcd_c.cpp @@ -333,7 +333,8 @@ void VerilatedVcd::pushPrefix(const char* namep, VerilatedTracePrefixType type) // Upper has name, we can suppress inserting $rootio, but still push so popPrefix works m_prefixStack.emplace_back(prevPrefix, VerilatedTracePrefixType::ROOTIO_WRAPPER); return; - } else if (name.empty()) { + } + if (name.empty()) { m_prefixStack.emplace_back(prevPrefix, VerilatedTracePrefixType::ROOTIO_WRAPPER); return; } @@ -404,7 +405,7 @@ void VerilatedVcd::declare(uint32_t code, const char* name, const char* wirep, b char* vcdCodeWritep = vcdCode; uint32_t codeEnc = code; do { - *vcdCodeWritep++ = static_cast('!' + codeEnc % 94); + *vcdCodeWritep++ = static_cast('!' + (codeEnc % 94)); codeEnc /= 94; } while (codeEnc--); *vcdCodeWritep = '\0'; @@ -494,7 +495,7 @@ void VerilatedVcd::declDoubleArray(uint32_t code, const char* name, int arraynum //============================================================================= // Get/commit trace buffer -VerilatedVcd::Buffer* VerilatedVcd::getTraceBuffer(uint32_t fidx) { +VerilatedVcd::Buffer* VerilatedVcd::getTraceBuffer(uint32_t /*fidx*/) { VerilatedVcd::Buffer* const bufp = new Buffer{*this}; if (parallel()) { // Note: This is called from VerilatedVcd::dump, which already holds the lock @@ -503,7 +504,7 @@ VerilatedVcd::Buffer* VerilatedVcd::getTraceBuffer(uint32_t fidx) { // cppcheck-suppress unreadVariable // cppcheck bug, used below constexpr size_t pageSize = 4096; // 4 * m_maxSignalBytes, so we can reserve 2 * m_maxSignalBytes at the end for safety - size_t startingSize = vlstd::roundUpToMultipleOf(4 * m_maxSignalBytes); + const size_t startingSize = vlstd::roundUpToMultipleOf(4 * m_maxSignalBytes); m_freeBuffers.emplace_back(new char[startingSize], startingSize); ++m_numBuffers; } @@ -688,7 +689,7 @@ VL_ATTR_ALWINLINE void VerilatedVcdBuffer::emitDouble(uint32_t code, double newval) { char* wp = m_writep; // Buffer can't overflow before VL_SNPRINTF; we sized during declaration - VL_SNPRINTF(wp, m_maxSignalBytes, "r%.16g", newval); + (void)VL_SNPRINTF(wp, m_maxSignalBytes, "r%.16g", newval); wp += std::strlen(wp); finishLine(code, wp); } diff --git a/include/verilated_vpi.cpp b/include/verilated_vpi.cpp index 2432c33eb..8e2b5da05 100644 --- a/include/verilated_vpi.cpp +++ b/include/verilated_vpi.cpp @@ -221,10 +221,8 @@ public: // If the array is unpacked, returns the bitsize of a single underlying packed element. // If the array is packed, returns the bitsize of the whole array. uint32_t bitSize() const { - if (isIndexedDimUnpacked()) - return varp()->entBits(); - else - return size(); + if (isIndexedDimUnpacked()) return varp()->entBits(); + return size(); } const VerilatedRange* rangep() const override { return get_range(); } const char* name() const override { return m_varp->name(); } @@ -466,10 +464,8 @@ public: case VLVT_STRING: type = vpiStringVar; break; default: type = varp()->isBitVar() ? vpiBitVar : vpiReg; break; } - if (isIndexedDimUnpacked()) - return vpiRegArray; - else - return type; + if (isIndexedDimUnpacked()) return vpiRegArray; + return type; } const char* fullname() const override { static thread_local std::string t_out; @@ -533,16 +529,14 @@ public: if (const VerilatedVar* topvarp = m_topscopep->varFind(m_it->second.name())) { if (topvarp->isParam()) { return ((new VerilatedVpioParam{topvarp, m_topscopep})->castVpiHandle()); - } else { - return ((new VerilatedVpioVar{topvarp, m_topscopep})->castVpiHandle()); } + return ((new VerilatedVpioVar{topvarp, m_topscopep})->castVpiHandle()); } } if (m_it->second.isParam()) { return ((new VerilatedVpioParam{&(m_it->second), m_scopep})->castVpiHandle()); - } else { - return ((new VerilatedVpioVar{&(m_it->second), m_scopep})->castVpiHandle()); } + return ((new VerilatedVpioVar{&(m_it->second), m_scopep})->castVpiHandle()); } } }; @@ -589,8 +583,7 @@ public: if (m_nextIndex.at(it) <= m_ranges.at(it).high() && m_nextIndex.at(it) >= m_ranges.at(it).low()) break; - else if (it > 0) - m_nextIndex.at(it) = m_ranges.at(it).right(); + if (it > 0) m_nextIndex.at(it) = m_ranges.at(it).right(); } return ret->castVpiHandle(); @@ -833,6 +826,7 @@ public: m_value.value.vector = m_storage.vec.data(); break; } + default: break; } } @@ -852,6 +846,7 @@ public: new (&m_storage.vec) std::vector{o.m_storage.vec}; break; } + default: break; } } @@ -871,6 +866,7 @@ public: new (&m_storage.vec) std::vector{std::move(o.m_storage.vec)}; break; } + default: break; } } @@ -882,6 +878,7 @@ public: case vpiHexStrVal: // FALLTHRU case vpiStringVal: m_storage.str.~basic_string(); break; case vpiVectorVal: m_storage.vec.~vector(); break; + default: break; } } @@ -1279,7 +1276,7 @@ void VerilatedVpiImp::dumpCbs() VL_MT_UNSAFE_ONE { assertOneCheck(); VL_DBG_MSGF("- vpi: dumpCbs\n"); for (uint32_t reason = 0; reason < CB_ENUM_MAX_VALUE; ++reason) { - VpioCbList& cbObjList = s().m_cbCurrentLists[reason]; + const VpioCbList& cbObjList = s().m_cbCurrentLists[reason]; for (auto& ho : cbObjList) { if (VL_UNLIKELY(!ho.invalid())) { VL_DBG_MSGF("- vpi: reason=%d=%s id=%" PRId64 "\n", reason, @@ -1357,9 +1354,9 @@ auto VerilatedVpiImp::getForceControlSignals(const VerilatedVpioVar* const baseS VerilatedVpioVar* forceValueSignalVop = new VerilatedVpioVar{forceValueSignalVarp, baseSignalVop->scopep()}; - for (int idx : baseSignalVop->index()) { - VerilatedVpioVar* nextForceEnableSignalVop = forceEnableSignalVop->withIndex(idx); - VerilatedVpioVar* nextForceValueSignalVop = forceValueSignalVop->withIndex(idx); + for (const int idx : baseSignalVop->index()) { + VerilatedVpioVar* const nextForceEnableSignalVop = forceEnableSignalVop->withIndex(idx); + VerilatedVpioVar* const nextForceValueSignalVop = forceValueSignalVop->withIndex(idx); VL_DO_DANGLING(delete forceEnableSignalVop, forceEnableSignalVop); VL_DO_DANGLING(delete forceValueSignalVop, forceValueSignalVop); forceEnableSignalVop = nextForceEnableSignalVop; @@ -1394,8 +1391,8 @@ auto VerilatedVpiImp::getForceControlSignals(const VerilatedVpioVar* const baseS // Bits are stored left-to-right in memory, which can either be ascending or descending. To // match the bitOffset of the base signal, the distance to the rightmost bit, rather than // to the lowest indexed bit, must be determined - int currentDimRight = baseSignalVop->rangep()->right(); - int32_t offsetFromRight + const int currentDimRight = baseSignalVop->rangep()->right(); + const int32_t offsetFromRight = static_cast(static_cast(baseSignalVop->bitOffset()) - static_cast(forceValueSignalVop->bitOffset())); const bool isDescending @@ -1756,14 +1753,11 @@ const char* VerilatedVpiError::strFromVpiObjType(PLI_INT32 vpiVal) VL_PURE { "vpiPropFormalDecl", }; // clang-format on - if (VL_UNCOVERABLE(vpiVal < 0)) - return names[0]; - else if (vpiVal <= vpiAutomatics) - return names[vpiVal]; - else if (vpiVal >= vpiPackage && vpiVal <= vpiPropFormalDecl) + if (VL_UNCOVERABLE(vpiVal < 0)) return names[0]; + if (vpiVal <= vpiAutomatics) return names[vpiVal]; + if (vpiVal >= vpiPackage && vpiVal <= vpiPropFormalDecl) return sv_names1[(vpiVal - vpiPackage)]; - else - return names[0]; + return names[0]; } const char* VerilatedVpiError::strFromVpiMethod(PLI_INT32 vpiVal) VL_PURE { // clang-format off @@ -2434,11 +2428,11 @@ vpiHandle vpi_handle_by_name(PLI_BYTE8* namep, vpiHandle scope) { if (scopep) { // Whole thing found as a scope if (scopep->type() == VerilatedScope::SCOPE_MODULE) { return (new VerilatedVpioModule{scopep})->castVpiHandle(); - } else if (scopep->type() == VerilatedScope::SCOPE_PACKAGE) { - return (new VerilatedVpioPackage{scopep})->castVpiHandle(); - } else { - return (new VerilatedVpioScope{scopep})->castVpiHandle(); } + if (scopep->type() == VerilatedScope::SCOPE_PACKAGE) { + return (new VerilatedVpioPackage{scopep})->castVpiHandle(); + } + return (new VerilatedVpioScope{scopep})->castVpiHandle(); } std::string basename = scopeAndName; std::string scopename; @@ -2554,7 +2548,8 @@ vpiHandle vpi_handle(PLI_INT32 type, vpiHandle object) { if (const VerilatedVpioVarBase* const vop = VerilatedVpioVarBase::castp(object)) { if (VL_UNLIKELY(!vop->rangep())) return nullptr; return (new VerilatedVpioConst{vop->rangep()->left()})->castVpiHandle(); - } else if (const VerilatedVpioRange* const vop = VerilatedVpioRange::castp(object)) { + } + if (const VerilatedVpioRange* const vop = VerilatedVpioRange::castp(object)) { if (VL_UNLIKELY(!vop->rangep())) return nullptr; return (new VerilatedVpioConst{vop->rangep()->left()})->castVpiHandle(); } @@ -2567,7 +2562,8 @@ vpiHandle vpi_handle(PLI_INT32 type, vpiHandle object) { if (const VerilatedVpioVarBase* const vop = VerilatedVpioVarBase::castp(object)) { if (VL_UNLIKELY(!vop->rangep())) return nullptr; return (new VerilatedVpioConst{vop->rangep()->right()})->castVpiHandle(); - } else if (const VerilatedVpioRange* const vop = VerilatedVpioRange::castp(object)) { + } + if (const VerilatedVpioRange* const vop = VerilatedVpioRange::castp(object)) { if (VL_UNLIKELY(!vop->rangep())) return nullptr; return (new VerilatedVpioConst{vop->rangep()->right()})->castVpiHandle(); } @@ -2868,7 +2864,8 @@ PLI_INT32 vl_get_vltype_format(VerilatedVarType vlType) { } static void vl_strprintf(std::string& buffer, char const* fmt, ...) { - va_list args, args_copy; + va_list args; + va_list args_copy; va_start(args, fmt); buffer.clear(); // Make copy of args since we may need to call VL_VSNPRINTF more than once @@ -2960,8 +2957,7 @@ T vl_vpi_get_word_gen(const VerilatedVpioVarBase* vop, size_t bitCount, size_t a return ((info.m_datap[info.m_wordOffset] & info.m_maskLo) >> info.m_bitOffset) | ((info.m_datap[info.m_wordOffset + 1] & info.m_maskHi) << (wordBits - info.m_bitOffset)); - else - return (info.m_datap[info.m_wordOffset] & info.m_maskLo) >> info.m_bitOffset; + return (info.m_datap[info.m_wordOffset] & info.m_maskLo) >> info.m_bitOffset; } template @@ -3096,7 +3092,8 @@ void vl_vpi_get_value(const VerilatedVpioVarBase* vop, p_vpi_value valuep) { t_out[i].bval = 0; } return; - } else if (varp->vltype() == VLVT_UINT64 && varBits > 32) { + } + if (varp->vltype() == VLVT_UINT64 && varBits > 32) { t_out.resize(2); valuep->value.vector = t_out.data(); const QData data = get_word(vop, 64, 0); @@ -3105,13 +3102,12 @@ void vl_vpi_get_value(const VerilatedVpioVarBase* vop, p_vpi_value valuep) { t_out[0].aval = static_cast(data); t_out[0].bval = 0; return; - } else { - t_out.resize(1); - valuep->value.vector = t_out.data(); - t_out[0].aval = get_word(vop, 32, 0); - t_out[0].bval = 0; - return; } + t_out.resize(1); + valuep->value.vector = t_out.data(); + t_out[0].aval = get_word(vop, 32, 0); + t_out[0].bval = 0; + return; } else if (valuep->format == vpiBinStrVal) { t_outDynamicStr.resize(varBits); @@ -3172,11 +3168,10 @@ void vl_vpi_get_value(const VerilatedVpioVarBase* vop, p_vpi_value valuep) { if (varp->isParam()) { valuep->value.str = reinterpret_cast(varDatap); return; - } else { - t_outDynamicStr = *vop->varStringDatap(); - valuep->value.str = const_cast(t_outDynamicStr.c_str()); - return; } + t_outDynamicStr = *vop->varStringDatap(); + valuep->value.str = const_cast(t_outDynamicStr.c_str()); + return; } else { const int chars = VL_BYTES_I(varBits); t_outDynamicStr.resize(chars); @@ -3219,10 +3214,12 @@ void vpi_get_value(vpiHandle object, p_vpi_value valuep) { if (const VerilatedVpioVar* const vop = VerilatedVpioVar::castp(object)) { vl_vpi_get_value(vop, valuep); return; - } else if (const VerilatedVpioParam* const vop = VerilatedVpioParam::castp(object)) { + } + if (const VerilatedVpioParam* const vop = VerilatedVpioParam::castp(object)) { vl_vpi_get_value(vop, valuep); return; - } else if (const VerilatedVpioConst* const vop = VerilatedVpioConst::castp(object)) { + } + if (const VerilatedVpioConst* const vop = VerilatedVpioConst::castp(object)) { if (valuep->format == vpiIntVal) { valuep->value.integer = vop->num(); return; @@ -3484,15 +3481,15 @@ vpiHandle vpi_put_value(vpiHandle object, p_vpi_value valuep, p_vpi_time /*time_ // Does not use valueVop, because strings are not forceable anyway *(baseSignalVop->varStringDatap()) = valuep->value.str; return object; - } else { - const int chars = VL_BYTES_I(varBits); - const int len = std::strlen(valuep->value.str); - for (int i = 0; i < chars; ++i) { - // prepend with 0 values before placing string the least significant bytes - const char c = (i < len) ? valuep->value.str[len - i - 1] : 0; - vl_vpi_put_word(valueVop, c, 8, i * 8); - } } + const int chars = VL_BYTES_I(varBits); + const int len = std::strlen(valuep->value.str); + for (int i = 0; i < chars; ++i) { + // prepend with 0 values before placing string the least significant bytes + const char c = (i < len) ? valuep->value.str[len - i - 1] : 0; + vl_vpi_put_word(valueVop, c, 8, i * 8); + } + return object; } else if (valuep->format == vpiIntVal) { vl_vpi_put_word(valueVop, valuep->value.integer, 64, 0); @@ -3510,11 +3507,13 @@ vpiHandle vpi_put_value(vpiHandle object, p_vpi_value valuep, p_vpi_time /*time_ __func__, VerilatedVpiError::strFromVpiVal(valuep->format), valueVop->fullname()); return nullptr; - } else if (const VerilatedVpioParam* const vop = VerilatedVpioParam::castp(object)) { + } + if (const VerilatedVpioParam* const vop = VerilatedVpioParam::castp(object)) { VL_VPI_WARNING_(__FILE__, __LINE__, "%s: Ignoring vpi_put_value to vpiParameter '%s'", __func__, vop->fullname()); return nullptr; - } else if (const VerilatedVpioConst* const vop = VerilatedVpioConst::castp(object)) { + } + if (const VerilatedVpioConst* const vop = VerilatedVpioConst::castp(object)) { VL_VPI_WARNING_(__FILE__, __LINE__, "%s: Ignoring vpi_put_value to vpiConstant '%s'", __func__, vop->fullname()); return nullptr; @@ -3581,8 +3580,8 @@ bool vl_check_array_format(const VerilatedVar* varp, const p_vpi_arrayvalue arra template void vl_get_value_array_integrals(unsigned index, const unsigned num, const unsigned size, - const unsigned packedSize, const bool leftIsLow, const T* src, - K* dst) { + const unsigned /*packedSize*/, const bool leftIsLow, + const T* src, K* dst) { static_assert(sizeof(K) >= sizeof(T), "size of type K is less than size of type T"); for (int i = 0; i < num; ++i) { dst[i] = src[index]; @@ -3646,7 +3645,7 @@ void vl_get_value_array_vectors(unsigned index, const unsigned num, const unsign template void vl_put_value_array_vectors(unsigned index, const unsigned num, const unsigned size, const unsigned packedSize, const bool leftIsLow, - const bool fourState, const p_vpi_vecval src, T* dst) { + const bool /*fourState*/, const p_vpi_vecval src, T* dst) { static_assert(std::is_unsigned::value, "type T is not unsigned"); static_assert(std::is_integral::value, "type T is not an integral type"); const unsigned element_size_bytes VL_BYTES_I(packedSize); @@ -4148,7 +4147,8 @@ void vpi_get_time(vpiHandle object, p_vpi_time time_p) { time_p->low = itime[0]; time_p->high = itime[1]; return; - } else if (time_p->type == vpiScaledRealTime) { + } + if (time_p->type == vpiScaledRealTime) { double dtime = VL_TIME_D(); if (const VerilatedVpioScope* const vop = VerilatedVpioScope::castp(object)) { const int scalePow10 diff --git a/include/verilatedos.h b/include/verilatedos.h index af99f1aed..b93909309 100644 --- a/include/verilatedos.h +++ b/include/verilatedos.h @@ -37,7 +37,7 @@ //========================================================================= // Compiler pragma abstraction -#if defined(__clang__) +#ifdef __clang__ # define VL_CLANG_ATTR(attr) __attribute__(( attr )) #else # define VL_CLANG_ATTR(attr) @@ -127,7 +127,7 @@ VL_CLANG_ATTR(no_thread_safety_analysis) // Require mutex locks only in code units which work with enabled multi-threading. -#if !defined(VL_MT_DISABLED_CODE_UNIT) +#ifndef VL_MT_DISABLED_CODE_UNIT // Function requires not having a capability inbound (-fthread-safety) # define VL_REQUIRES(x) \ VL_CLANG_ATTR(annotate("REQUIRES")) \ @@ -384,7 +384,7 @@ using vlsint32_t = int32_t; ///< 32-bit signed type (backward compatibility) using vlsint64_t = int64_t; ///< 64-bit signed type (backward compatibility) #endif -#if defined(__CYGWIN__) +#ifdef __CYGWIN__ # include // __WORDSIZE # include // ssize_t @@ -485,12 +485,12 @@ using ssize_t = uint32_t; ///< signed size_t; returned from read() // Declare a class as uncopyable; put after a private: #define VL_UNCOPYABLE(Type) \ - Type(const Type& other) = delete; \ + Type(const Type& other) = delete; \ Type& operator=(const Type&) = delete // Declare a class as unmovable; put after a private: #define VL_UNMOVABLE(Type) \ - Type(Type&& other) = delete; \ + Type(Type&& other) = delete; \ Type& operator=(Type&&) = delete //========================================================================= diff --git a/include/verilatedos_c.h b/include/verilatedos_c.h index 16279d8c0..ce55994f1 100644 --- a/include/verilatedos_c.h +++ b/include/verilatedos_c.h @@ -35,13 +35,13 @@ # include // GetProcessMemoryInfo #endif -#if defined(__linux) +#ifdef __linux # include // For sched_getcpu() #endif #if defined(__APPLE__) && !defined(__arm64__) && !defined(__POWERPC__) # include // For __cpuid_count() #endif -#if defined(__FreeBSD__) +#ifdef __FreeBSD__ # include // For pthread_getaffinity_np() #endif @@ -93,7 +93,7 @@ double DeltaWallTime::gettime() VL_MT_SAFE { // Vlos::getcpu implementation uint16_t getcpu() VL_MT_SAFE { -#if defined(__linux) +#ifdef __linux return sched_getcpu(); // TODO: this is a system call. Not exactly cheap. #elif defined(__APPLE__) && !defined(__arm64__) && !defined(__POWERPC__) uint32_t info[4]; @@ -194,7 +194,7 @@ void memUsageBytes(uint64_t& peakr, uint64_t& currentr) VL_MT_SAFE { std::string getenvStr(const std::string& envvar, const std::string& defaultValue) VL_MT_SAFE { std::string ret; -#if defined(_MSC_VER) +#ifdef _MSC_VER // Note: MinGW does not offer _dupenv_s const char* envvalue = nullptr; _dupenv_s((char**)&envvalue, nullptr, envvar.c_str()); diff --git a/src/V3Assert.cpp b/src/V3Assert.cpp index 4922bd0e3..d95431fe1 100644 --- a/src/V3Assert.cpp +++ b/src/V3Assert.cpp @@ -198,11 +198,10 @@ class AssertVisitor final : public VNVisitor { return ("[%0t] "s + prefix + ": " + nodep->fileline()->filebasename() + ":" + cvtToStr(nodep->fileline()->lineno()) + ": Assertion failed in %m" + ((message != "") ? ": " : "") + message + "\n"); - } else { - return ("[%0t] "s + prefix + ": " + nodep->fileline()->filebasename() + ":" - + cvtToStr(nodep->fileline()->lineno()) + ": %m" - + ((message != "") ? ": " : "") + message + "\n"); } + return ("[%0t] "s + prefix + ": " + nodep->fileline()->filebasename() + ":" + + cvtToStr(nodep->fileline()->lineno()) + ": %m" + ((message != "") ? ": " : "") + + message + "\n"); } static bool resolveAssertType(AstAssertCtl* nodep) { if (!nodep->assertTypesp()) { @@ -413,9 +412,8 @@ class AssertVisitor final : public VNVisitor { nodep->immediate(false); static_cast(m_procedurep)->addNext(nodep->unlinkFrBack()); return; // Later iterate will pick up - } else { - sentreep->unlinkFrBack(); } + sentreep->unlinkFrBack(); } // const string& message = nodep->name(); diff --git a/src/V3AssertProp.cpp b/src/V3AssertProp.cpp index f4e561444..6888284c4 100644 --- a/src/V3AssertProp.cpp +++ b/src/V3AssertProp.cpp @@ -663,7 +663,8 @@ class RangeDelayExpander final : public VNVisitor { AstDelay* const dlyp = VN_CAST(curp->delayp(), Delay); UASSERT_OBJ(dlyp, curp, "Expected AstDelay"); bool isRange = false; - int minVal = 0, maxVal = 0; + int minVal = 0; + int maxVal = 0; if (!extractDelayBounds(dlyp, isRange, minVal, maxVal)) return false; if (isRange) hasRange = true; @@ -691,7 +692,7 @@ class RangeDelayExpander final : public VNVisitor { // State 3: WAIT_FIXED (count down 1 cycle for ##1) // State 4: CHECK_TAIL (check c, report pass/fail) AstNode* buildFsmBody(FileLine* flp, AstVar* stateVarp, AstVar* cntVarp, AstVar* failVarp, - const std::vector& steps, AstSenItem* sensesp, + const std::vector& steps, AstSenItem* /*sensesp*/, AstNodeExpr* antExprp) { AstNode* fsmChainp = nullptr; diff --git a/src/V3Ast.cpp b/src/V3Ast.cpp index a55da1b05..1dbd951ce 100644 --- a/src/V3Ast.cpp +++ b/src/V3Ast.cpp @@ -63,7 +63,7 @@ VCMethod VCMethod::arrayMethod(const string& name) { void VCMethod::selfTest() { int i = 0; for (const auto& it : s_itemData) { - VCMethod exp{i}; + const VCMethod exp{i}; UASSERT_STATIC(it.m_e == exp, "VCMethod::s_itemData table rows are out-of-order, starting at row "s + cvtToStr(i) + " '" + +it.m_name + '\''); @@ -181,11 +181,8 @@ string AstNode::encodeName(const string& namein) { } string AstNode::encodeNumber(int64_t num) { - if (num < 0) { - return "__02D" + cvtToStr(-num); // 2D=- - } else { - return cvtToStr(num); - } + if (num < 0) return "__02D" + cvtToStr(-num); // 2D=- + return cvtToStr(num); } string AstNode::nameProtect() const { return VIdProtect::protectIf(name(), protect()); } @@ -394,36 +391,36 @@ AstNode* AstNode::addNext(AstNode* nodep, AstNode* newp) { UDEBUGONLY(UASSERT_OBJ(newp, nodep, "Null item passed to addNext");); debugTreeChange(nodep, "-addNextThs: ", __LINE__, false); debugTreeChange(newp, "-addNextNew: ", __LINE__, true); - if (!nodep) { // verilog.y and lots of other places assume this + if (!nodep) // verilog.y and lots of other places assume this return newp; - } else { - // Find end of old list - AstNode* oldtailp = nodep; - if (oldtailp->m_nextp) { - if (oldtailp->m_headtailp) { - oldtailp = oldtailp->m_headtailp; // This=beginning of list, jump to end - UDEBUGONLY(UASSERT_OBJ(!oldtailp->m_nextp, nodep, - "Node had next, but headtail says it shouldn't");); - } else { - // Though inefficient, we are occasionally passed an - // addNext in the middle of a list. - while (oldtailp->m_nextp) oldtailp = oldtailp->m_nextp; - } + + // Find end of old list + AstNode* oldtailp = nodep; + if (oldtailp->m_nextp) { + if (oldtailp->m_headtailp) { + oldtailp = oldtailp->m_headtailp; // This=beginning of list, jump to end + UDEBUGONLY(UASSERT_OBJ(!oldtailp->m_nextp, nodep, + "Node had next, but headtail says it shouldn't");); + } else { + // Though inefficient, we are occasionally passed an + // addNext in the middle of a list. + while (oldtailp->m_nextp) oldtailp = oldtailp->m_nextp; } - // Link it in - oldtailp->m_nextp = newp; - newp->m_backp = oldtailp; - // New tail needs the head - AstNode* const newtailp = newp->m_headtailp; - AstNode* const headp = oldtailp->m_headtailp; - oldtailp->m_headtailp = nullptr; // May be written again as new head - newp->m_headtailp = nullptr; // May be written again as new tail - newtailp->m_headtailp = headp; - headp->m_headtailp = newtailp; - newp->editCountInc(); - // No change of m_iterpp, as only changing m_nextp of current node; - // the current node is still the one at the iteration point } + // Link it in + oldtailp->m_nextp = newp; + newp->m_backp = oldtailp; + // New tail needs the head + AstNode* const newtailp = newp->m_headtailp; + AstNode* const headp = oldtailp->m_headtailp; + oldtailp->m_headtailp = nullptr; // May be written again as new head + newp->m_headtailp = nullptr; // May be written again as new tail + newtailp->m_headtailp = headp; + headp->m_headtailp = newtailp; + newp->editCountInc(); + // No change of m_iterpp, as only changing m_nextp of current node; + // the current node is still the one at the iteration point + debugTreeChange(nodep, "-addNextOut:", __LINE__, true); return nodep; } @@ -1651,7 +1648,8 @@ static const AstNodeDType* computeCastableBase(const AstNodeDType* nodep) { if (const AstPackArrayDType* const packp = VN_CAST(nodep, PackArrayDType)) { nodep = packp->subDTypep(); continue; - } else if (const AstNodeDType* const refp = nodep->skipRefToEnump()) { + } + if (const AstNodeDType* const refp = nodep->skipRefToEnump()) { if (refp != nodep) { nodep = refp; continue; @@ -1679,9 +1677,9 @@ static VCastable computeCastableImp(const AstNodeDType* toDtp, const AstNodeDTyp const bool toNumericable = VN_IS(toBaseDtp, BasicDType) || VN_IS(toBaseDtp, NodeUOrStructDType); - if (toBaseDtp == fromBaseDtp) { - return VCastable::COMPATIBLE; - } else if (toNumericable) { + if (toBaseDtp == fromBaseDtp) return VCastable::COMPATIBLE; + + if (toNumericable) { if (fromNumericable) return VCastable::COMPATIBLE; } else if (VN_IS(toBaseDtp, EnumDType)) { if (VN_IS(fromBaseDtp, EnumDType) && toDtp->sameTree(fromDtp)) @@ -1697,13 +1695,9 @@ static VCastable computeCastableImp(const AstNodeDType* toDtp, const AstNodeDTyp const AstClass* const fromClassp = VN_AS(fromDtp, ClassRefDType)->classp(); const bool downcast = AstClass::isClassExtendedFrom(toClassp, fromClassp); const bool upcast = AstClass::isClassExtendedFrom(fromClassp, toClassp); - if (upcast) { - return VCastable::COMPATIBLE; - } else if (downcast) { - return VCastable::DYNAMIC_CLASS; - } else { - return VCastable::INCOMPATIBLE; - } + if (upcast) return VCastable::COMPATIBLE; + if (downcast) return VCastable::DYNAMIC_CLASS; + return VCastable::INCOMPATIBLE; } return castable; } @@ -1727,11 +1721,9 @@ AstNodeDType* AstNode::getCommonClassTypep(AstNode* node1p, AstNode* node2p) { if (VN_IS(node1p, Const)) std::swap(node1p, node2p); { const VCastable castable = computeCastable(node1p->dtypep(), node2p->dtypep(), node2p); - if (castable == VCastable::SAMEISH || castable == VCastable::COMPATIBLE) { + if (castable == VCastable::SAMEISH || castable == VCastable::COMPATIBLE) return node1p->dtypep(); - } else if (castable == VCastable::DYNAMIC_CLASS) { - return node2p->dtypep(); - } + if (castable == VCastable::DYNAMIC_CLASS) return node2p->dtypep(); } AstClassRefDType* classDtypep1 = VN_CAST(node1p->dtypep(), ClassRefDType); diff --git a/src/V3Ast.h b/src/V3Ast.h index 125f2b357..0e8b1ea21 100644 --- a/src/V3Ast.h +++ b/src/V3Ast.h @@ -95,7 +95,7 @@ class ExecMTask; struct VNTypeInfo final { const char* m_namep; - enum uint8_t { + enum OpEn : uint8_t { OP_UNUSED, OP_USED, OP_LIST, @@ -147,7 +147,7 @@ public: // non-explicit: // cppcheck-suppress noExplicitConstructor VNUser(int i) { - m_u.up = 0; + m_u.up = nullptr; m_u.ui = i; } explicit VNUser(void* p) { m_u.up = p; } diff --git a/src/V3AstAttr.h b/src/V3AstAttr.h index eebe39a92..91a7c5257 100644 --- a/src/V3AstAttr.h +++ b/src/V3AstAttr.h @@ -716,13 +716,9 @@ public: 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; - } + if (m_e == BP_UNLIKELY) return BP_LIKELY; + if (m_e == BP_LIKELY) return BP_UNLIKELY; + return m_e; } const char* ascii() const { static const char* const names[] = {"", "VL_LIKELY", "VL_UNLIKELY"}; @@ -1438,7 +1434,7 @@ public: bool isAutomatic() const { return m_e == AUTOMATIC_EXPLICIT || m_e == AUTOMATIC_IMPLICIT; } bool isStatic() const { return m_e == STATIC_EXPLICIT || m_e == STATIC_IMPLICIT; } bool isStaticExplicit() const { return m_e == STATIC_EXPLICIT; } - VLifetime makeImplicit() { + VLifetime makeImplicit() const { switch (m_e) { case AUTOMATIC_EXPLICIT: return AUTOMATIC_IMPLICIT; case STATIC_EXPLICIT: return STATIC_IMPLICIT; @@ -1834,7 +1830,7 @@ public: explicit VUseType(int _e) : m_e(static_cast(_e)) {} // Need () or GCC 4.8 false warning constexpr operator en() const { return m_e; } - bool containsAny(VUseType other) { return m_e & other.m_e; } + bool containsAny(VUseType other) const { return m_e & other.m_e; } const char* ascii() const { static const char* const names[] = {"INT_FWD", "INT_INC", "INT_FWD_INC"}; return names[m_e - 1]; @@ -1844,10 +1840,10 @@ constexpr bool operator==(const VUseType& lhs, const VUseType& rhs) { return lhs constexpr bool operator==(const VUseType& lhs, VUseType::en rhs) { return lhs.m_e == rhs; } constexpr bool operator==(VUseType::en lhs, const VUseType& rhs) { return lhs == rhs.m_e; } constexpr VUseType::en operator|(VUseType::en lhs, VUseType::en rhs) { - return VUseType::en((uint8_t)lhs | (uint8_t)rhs); + return VUseType::en(static_cast(lhs) | static_cast(rhs)); } constexpr VUseType::en operator&(VUseType::en lhs, VUseType::en rhs) { - return VUseType::en((uint8_t)lhs & (uint8_t)rhs); + return VUseType::en(static_cast(lhs) & static_cast(rhs)); } inline std::ostream& operator<<(std::ostream& os, const VUseType& rhs) { return os << rhs.ascii(); diff --git a/src/V3AstInlines.h b/src/V3AstInlines.h index 86e6ee9cc..e31960429 100644 --- a/src/V3AstInlines.h +++ b/src/V3AstInlines.h @@ -183,23 +183,17 @@ AstVarRef::AstVarRef(FileLine* fl, AstVarScope* varscp, const VAccess& access) string AstVarRef::name() const { return varp() ? varp()->name() : nameThis(); } bool AstVarRef::sameNode(const AstVarRef* samep) const { - if (varScopep()) { - return (varScopep() == samep->varScopep() && access() == samep->access()); - } else { - return (selfPointer() == samep->selfPointer() - && classOrPackagep() == samep->classOrPackagep() && access() == samep->access() - && (varp() && samep->varp() && varp()->sameNode(samep->varp()))); - } + if (varScopep()) return (varScopep() == samep->varScopep() && access() == samep->access()); + return (selfPointer() == samep->selfPointer() && classOrPackagep() == samep->classOrPackagep() + && access() == samep->access() + && (varp() && samep->varp() && varp()->sameNode(samep->varp()))); } bool AstVarRef::sameNoLvalue(const AstVarRef* samep) const { - if (varScopep()) { - return (varScopep() == samep->varScopep()); - } else { - return (selfPointer() == samep->selfPointer() - && classOrPackagep() == samep->classOrPackagep() - && (!selfPointer().isEmpty() || !samep->selfPointer().isEmpty()) - && varp()->sameNode(samep->varp())); - } + if (varScopep()) return (varScopep() == samep->varScopep()); + + return (selfPointer() == samep->selfPointer() && classOrPackagep() == samep->classOrPackagep() + && (!selfPointer().isEmpty() || !samep->selfPointer().isEmpty()) + && varp()->sameNode(samep->varp())); } AstVarXRef::AstVarXRef(FileLine* fl, AstVar* varp, const string& dotted, const VAccess& access) diff --git a/src/V3AstNodeDType.h b/src/V3AstNodeDType.h index 608ab7e1b..b9e122715 100644 --- a/src/V3AstNodeDType.h +++ b/src/V3AstNodeDType.h @@ -251,8 +251,7 @@ protected: , m_name{other.m_name} , m_uniqueNum{uniqueNumInc()} , m_packed{other.m_packed} - , m_isFourstate{other.m_isFourstate} - , m_constrainedRand{false} {} + , m_isFourstate{other.m_isFourstate} {} public: ASTGEN_MEMBERS_AstNodeUOrStructDType; @@ -542,7 +541,6 @@ public: dtypep(this); } -public: ASTGEN_MEMBERS_AstCDType; bool sameNode(const AstNode* samep) const override { const AstCDType* const asamep = VN_DBG_AS(samep, CDType); @@ -557,16 +555,12 @@ public: int widthTotalBytes() const override { return 8; } // Assume bool isCompound() const override { return true; } static string typeToHold(int width) { - if (width <= 8) - return "CData"; - else if (width <= 16) - return "SData"; - else if (width <= VL_IDATASIZE) - return "IData"; - else if (width <= VL_QUADSIZE) - return "QData"; - else - return "VlWide<" + std::to_string(VL_WORDS_I(width)) + ">"; + if (width <= 8) return "CData"; + if (width <= 16) return "SData"; + if (width <= VL_IDATASIZE) return "IData"; + if (width <= VL_QUADSIZE) return "QData"; + + return "VlWide<" + std::to_string(VL_WORDS_I(width)) + ">"; } }; class AstClassRefDType final : public AstNodeDType { @@ -968,8 +962,7 @@ public: AstMemberDType(FileLine* fl, const string& name, VFlagChildDType, AstNodeDType* dtp, AstNode* valuep) : ASTGEN_SUPER_MemberDType(fl) - , m_name{name} - , m_constrainedRand{false} { + , m_name{name} { childDTypep(dtp); // Only for parser this->valuep(valuep); dtypep(nullptr); // V3Width will resolve @@ -977,8 +970,7 @@ public: } AstMemberDType(FileLine* fl, const string& name, AstNodeDType* dtp) : ASTGEN_SUPER_MemberDType(fl) - , m_name{name} - , m_constrainedRand{false} { + , m_name{name} { UASSERT(dtp, "AstMember created with no dtype"); refDTypep(dtp); dtypep(this); @@ -1253,10 +1245,9 @@ public: AstBasicDType* basicp() const override VL_MT_STABLE { return nullptr; } AstNodeDType* subDTypep() const override VL_MT_STABLE { // Used for recursive definition checking - if (AstNodeDType* const dtp = VN_CAST(lhsp(), NodeDType)) - return dtp; - else - return nullptr; + if (AstNodeDType* const dtp = VN_CAST(lhsp(), NodeDType)) return dtp; + + return nullptr; } int widthAlignBytes() const override { V3ERROR_NA_RETURN(1); } int widthTotalBytes() const override { V3ERROR_NA_RETURN(1); } diff --git a/src/V3AstNodeExpr.h b/src/V3AstNodeExpr.h index a7b7a124f..63b0ce757 100644 --- a/src/V3AstNodeExpr.h +++ b/src/V3AstNodeExpr.h @@ -562,7 +562,6 @@ public: dtypep(findCHandleDType()); } -public: ASTGEN_MEMBERS_AstAddrOfCFunc; void dump(std::ostream& str) const override; string emitVerilog() override { V3ERROR_NA_RETURN(""); } @@ -2048,17 +2047,11 @@ public: } string emitC() override { if (seedp()) { - if (urandom()) { - return "VL_URANDOM_SEEDED_%nq%lq(%li)"; - } else { - return "VL_RANDOM_SEEDED_%nq%lq(%li)"; - } - } - if (isWide()) { - return "VL_RANDOM_%nq(%nw, %P)"; - } else { - return "VL_RANDOM_%nq()"; + if (urandom()) return "VL_URANDOM_SEEDED_%nq%lq(%li)"; + return "VL_RANDOM_SEEDED_%nq%lq(%li)"; } + if (isWide()) return "VL_RANDOM_%nq(%nw, %P)"; + return "VL_RANDOM_%nq()"; } bool cleanOut() const override { return false; } bool isGateOptimizable() const override { return false; } diff --git a/src/V3AstNodeOther.h b/src/V3AstNodeOther.h index 210c55f7a..0b7760673 100644 --- a/src/V3AstNodeOther.h +++ b/src/V3AstNodeOther.h @@ -1496,7 +1496,7 @@ public: bool sameNode(const AstNode* samep) const override { return direction() == VN_DBG_AS(samep, Pull)->direction(); } - uint32_t direction() const { return (uint32_t)m_direction; } + uint32_t direction() const { return static_cast(m_direction); } }; class AstScope final : public AstNode { // A particular usage of a cell diff --git a/src/V3AstNodes.cpp b/src/V3AstNodes.cpp index 417ffa5b6..97cf8f2b2 100644 --- a/src/V3AstNodes.cpp +++ b/src/V3AstNodes.cpp @@ -1935,9 +1935,8 @@ AstClass* AstClassExtends::classOrNullp() const { if (refp && !refp->paramsp()) { // Class already resolved return refp->classp(); - } else { - return nullptr; } + return nullptr; } AstClass* AstClassExtends::classp() const { AstClass* const clsp = classOrNullp(); @@ -2019,7 +2018,7 @@ void AstEnumDType::dump(std::ostream& str) const { str << " enum"; } void AstEnumDType::dumpJson(std::ostream& str) const { - dumpJsonBoolIf(str, "enum", 1); + dumpJsonBoolIf(str, "enum", true); dumpJsonGen(str); } void AstEnumDType::dumpSmall(std::ostream& str) const { @@ -2152,11 +2151,8 @@ void AstInitArray::addIndexValuep(uint64_t index, AstNodeExpr* newp) { } AstNodeExpr* AstInitArray::getIndexValuep(uint64_t index) const { const auto it = m_map.find(index); - if (it == m_map.end()) { - return nullptr; - } else { - return it->second->valuep(); - } + if (it == m_map.end()) { return nullptr; } + return it->second->valuep(); } AstNodeExpr* AstInitArray::getIndexDefaultedValuep(uint64_t index) const { AstNodeExpr* valuep = getIndexValuep(index); @@ -2515,7 +2511,7 @@ void AstNodeDType::dump(std::ostream& str) const { } void AstNodeDType::dumpJson(std::ostream& str) const { dumpJsonBoolFuncIf(str, generic); - if (isSigned() && !isDouble()) dumpJsonBoolIf(str, "signed", 1); + if (isSigned() && !isDouble()) dumpJsonBoolIf(str, "signed", true); dumpJsonGen(str); } void AstNodeDType::dumpSmall(std::ostream& str) const VL_MT_STABLE { @@ -3430,18 +3426,12 @@ static AstDelay* getLhsNetDelayRecurse(const AstNodeExpr* const nodep) { AstDelay* AstAssignW::getLhsNetDelay() const { return getLhsNetDelayRecurse(lhsp()); } string AstCase::pragmaString() const { - if (fullPragma() && parallelPragma()) - return "synthesis full_case parallel_case"; - else if (fullPragma()) - return "synthesis full_case"; - else if (parallelPragma()) - return "synthesis parallel_case"; - else if (uniquePragma()) - return "unique case"; - else if (unique0Pragma()) - return "unique0 case"; - else if (priorityPragma()) - return "priority case"; + if (fullPragma() && parallelPragma()) return "synthesis full_case parallel_case"; + if (fullPragma()) return "synthesis full_case"; + if (parallelPragma()) return "synthesis parallel_case"; + if (uniquePragma()) return "unique case"; + if (unique0Pragma()) return "unique0 case"; + if (priorityPragma()) return "priority case"; return ""; } diff --git a/src/V3Begin.cpp b/src/V3Begin.cpp index b1b02ca0a..fdfe2abe7 100644 --- a/src/V3Begin.cpp +++ b/src/V3Begin.cpp @@ -499,7 +499,7 @@ void V3Begin::debeginAll(AstNetlist* nodep) { V3Global::dumpCheckGlobalTree("begin", 0, dumpTreeEitherLevel() >= 3); } -static AstNode* createForeachLoop(AstNodeForeach* nodep, AstNode* bodysp, AstVar* varp, +static AstNode* createForeachLoop(AstNodeForeach* /*nodep*/, AstNode* bodysp, AstVar* varp, AstNodeExpr* leftp, AstNodeExpr* rightp, VNType nodeType) { FileLine* const fl = varp->fileline(); AstNodeExpr* varRefp = new AstVarRef{fl, varp, VAccess::READ}; @@ -532,7 +532,8 @@ static AstNode* createForeachLoop(AstNodeForeach* nodep, AstNode* bodysp, AstVar static AstNode* createForeachLoopRanged(AstNodeForeach* nodep, AstNode* bodysp, AstVar* varp, const VNumRange& declRange) { FileLine* const fl = varp->fileline(); - V3Number left{nodep, 32}, right{nodep, 32}; + V3Number left{nodep, 32}; + V3Number right{nodep, 32}; left.isSigned(true); right.isSigned(true); left.setLongS(declRange.left()); diff --git a/src/V3Broken.cpp b/src/V3Broken.cpp index c1245d5fd..fab0077cc 100644 --- a/src/V3Broken.cpp +++ b/src/V3Broken.cpp @@ -71,7 +71,7 @@ public: void addNewed(const AstNode* nodep) VL_MT_SAFE_EXCLUDES(m_mutex) { // Called by operator new on any node - only if VL_LEAK_CHECKS // LCOV_EXCL_START - V3LockGuard lock{m_mutex}; + const V3LockGuard lock{m_mutex}; if (VL_UNCOVERABLE(!m_allocated.emplace(nodep).second)) { nodep->v3fatalSrc("Newing AstNode object that is already allocated"); } @@ -80,7 +80,7 @@ public: void deleted(const AstNode* nodep) VL_MT_SAFE_EXCLUDES(m_mutex) { // Called by operator delete on any node - only if VL_LEAK_CHECKS // LCOV_EXCL_START - V3LockGuard lock{m_mutex}; + const V3LockGuard lock{m_mutex}; if (VL_UNCOVERABLE(m_allocated.erase(nodep) == 0)) { nodep->v3fatalSrc("Deleting AstNode object that was not allocated or already freed"); } @@ -377,7 +377,7 @@ void V3Broken::brokenAll(AstNetlist* nodep) { } else { s_inBroken = true; - V3LockGuard lock{s_allocTable.m_mutex}; + const V3LockGuard lock{s_allocTable.m_mutex}; // Mark every node in the tree const uint8_t brokenCntCurrent = s_brokenCntGlobal.get(); diff --git a/src/V3CUse.cpp b/src/V3CUse.cpp index ce4158542..2fddf7f82 100644 --- a/src/V3CUse.cpp +++ b/src/V3CUse.cpp @@ -59,7 +59,7 @@ class CUseVisitor final : public VNVisitorConst { iterateAndNextConstNull(nodep->argsp()); iterateAndNextConstNull(nodep->stmtsp()); } - void visit(AstCCall* nodep) override { return; } + void visit(AstCCall* /*nodep*/) override {} void visit(AstCReturn* nodep) override { UASSERT_OBJ(!nodep->user1SetOnce(), nodep, "Visited same return twice"); iterateConst(nodep->lhsp()->dtypep()); diff --git a/src/V3Const.cpp b/src/V3Const.cpp index 2409ec165..8e2fde0aa 100644 --- a/src/V3Const.cpp +++ b/src/V3Const.cpp @@ -197,7 +197,7 @@ class ConstBitOpTreeVisitor final : public VNVisitorConst { const size_t m_frozenSize; const unsigned m_ops; const bool m_polarity; - bool m_restore; + bool m_restore = true; public: explicit Restorer(ConstBitOpTreeVisitor& visitor) @@ -205,8 +205,7 @@ class ConstBitOpTreeVisitor final : public VNVisitorConst { , m_polaritiesSize{visitor.m_bitPolarities.size()} , m_frozenSize{visitor.m_frozenNodes.size()} , m_ops{visitor.m_ops} - , m_polarity{visitor.m_polarity} - , m_restore{true} {} + , m_polarity{visitor.m_polarity} {} ~Restorer() { UASSERT(m_visitor.m_bitPolarities.size() >= m_polaritiesSize, "m_bitPolarities must grow monotonically"); @@ -1351,7 +1350,7 @@ class ConstVisitor final : public VNVisitor { if (newp) { newp->dumpTree(debugPrefix + "RESULT: "); } else { - cout << debugPrefix << "not replaced" << endl; + cout << debugPrefix << "not replaced\n"; } } // LCOV_EXCL_STOP @@ -1528,7 +1527,7 @@ class ConstVisitor final : public VNVisitor { nodep->rhsp(smallerp); constp->unlinkFrBack(); - V3Number num{constp, subsize, constp->num()}; + const V3Number num{constp, subsize, constp->num()}; nodep->lhsp(new AstConst{constp->fileline(), num}); VL_DO_DANGLING(pushDeletep(constp), constp); UINFOTREE(9, nodep, "", "BI(EXTEND)-ou"); @@ -1741,7 +1740,7 @@ class ConstVisitor final : public VNVisitor { VL_DO_DANGLING(pushDeletep(oldp), oldp); } void replaceNum(AstNode* nodep, uint32_t val) { - V3Number num{nodep, nodep->width(), val}; + const V3Number num{nodep, nodep->width(), val}; VL_DO_DANGLING(replaceNum(nodep, num), nodep); } void replaceNumSigned(AstNodeBiop* nodep, uint32_t val) { @@ -2235,7 +2234,7 @@ class ConstVisitor final : public VNVisitor { } } else if (m_doV && VN_IS(nodep->lhsp(), Concat)) { bool need_temp = false; - bool need_temp_pure = !nodep->rhsp()->isPure(); + const bool need_temp_pure = !nodep->rhsp()->isPure(); if (m_warn && !VN_IS(nodep, AssignDly) && !need_temp_pure) { // Is same var on LHS and RHS? // Note only do this (need user4) when m_warn, which is @@ -3817,7 +3816,7 @@ class ConstVisitor final : public VNVisitor { m_hasJumpDelay = false; m_hasLoopTest = false; iterateChildren(nodep); - bool thisLoopHasJumpDelay = m_hasJumpDelay; + const bool thisLoopHasJumpDelay = m_hasJumpDelay; m_hasJumpDelay = thisLoopHasJumpDelay || oldHasJumpDelay; // If the first statement always break, the loop is useless if (const AstLoopTest* const testp = VN_CAST(nodep->stmtsp(), LoopTest)) { diff --git a/src/V3Control.cpp b/src/V3Control.cpp index bb0eb6821..2d281e367 100644 --- a/src/V3Control.cpp +++ b/src/V3Control.cpp @@ -49,8 +49,8 @@ public: // Update this resolved file's item map by inserting other's (wildcarded filename's) items void update(const V3ControlWildcardResolver& other) VL_MT_SAFE_EXCLUDES(m_mutex) VL_EXCLUDES(other.m_mutex) { - V3LockGuard lock{m_mutex}; - V3LockGuard otherLock{other.m_mutex}; + const V3LockGuard lock{m_mutex}; + const V3LockGuard otherLock{other.m_mutex}; // Clear the resolved cache, as 'other' might add new patterns that need to be applied as // well. m_mapResolved.clear(); @@ -59,14 +59,14 @@ public: // Access and create a pattern entry T& at(const string& name) VL_MT_SAFE_EXCLUDES(m_mutex) { - V3LockGuard lock{m_mutex}; + const V3LockGuard lock{m_mutex}; // We might be adding a new entry under this, so clear the cache. m_mapResolved.clear(); return m_mapPatterns[name]; } // Access an entity and resolve patterns that match it T* resolve(const string& name) VL_MT_SAFE_EXCLUDES(m_mutex) { - V3LockGuard lock{m_mutex}; + const V3LockGuard lock{m_mutex}; // Lookup if it was resolved before, typically not const auto pair = m_mapResolved.emplace(name, nullptr); std::unique_ptr& entryr = pair.first->second; @@ -369,10 +369,11 @@ private: maxval = std::max(maxval, cign.m_lineMax); } - int center = minval + (maxval - minval) / 2; + const int center = minval + (maxval - minval) / 2; auto entp = std::unique_ptr(new Entry{center}); - IgnIndices leftPoints, rightPoints; + IgnIndices leftPoints; + IgnIndices rightPoints; for (const auto& it : points) { const V3ControlIgnoresLine& cign = controlIgnLines[it]; if (cign.everyLine()) continue; @@ -438,7 +439,7 @@ private: public: // CONSTRUCTORS - VIntervalTree() {} + VIntervalTree() = default; ~VIntervalTree() = default; // METHODS void clear() { m_rootp = nullptr; } @@ -477,41 +478,41 @@ public: IgnIndices results; int nextChange = 0; tree.find(0, results, nextChange); - UASSERT_SELFTEST(size_t, results.size(), 0); - UASSERT_SELFTEST(int, nextChange, 10); + UASSERT_SELFTEST(const size_t, results.size(), 0); + UASSERT_SELFTEST(const int, nextChange, 10); tree.find(10, results, nextChange); - UASSERT_SELFTEST(size_t, results.size(), 2); - UASSERT_SELFTEST(int, results[0], 0); - UASSERT_SELFTEST(int, results[1], 3); - UASSERT_SELFTEST(int, nextChange, 11); + UASSERT_SELFTEST(const size_t, results.size(), 2); + UASSERT_SELFTEST(const int, results[0], 0); + UASSERT_SELFTEST(const int, results[1], 3); + UASSERT_SELFTEST(const int, nextChange, 11); tree.find(11, results, nextChange); - UASSERT_SELFTEST(size_t, results.size(), 1); - UASSERT_SELFTEST(int, results[0], 3); - UASSERT_SELFTEST(int, nextChange, 15); // Center, or would be 20 + UASSERT_SELFTEST(const size_t, results.size(), 1); + UASSERT_SELFTEST(const int, results[0], 3); + UASSERT_SELFTEST(const int, nextChange, 15); // Center, or would be 20 tree.find(20, results, nextChange); - UASSERT_SELFTEST(size_t, results.size(), 3); - UASSERT_SELFTEST(int, results[0], 1); - UASSERT_SELFTEST(int, results[1], 3); - UASSERT_SELFTEST(int, results[2], 4); - UASSERT_SELFTEST(int, nextChange, 21); + UASSERT_SELFTEST(const size_t, results.size(), 3); + UASSERT_SELFTEST(const int, results[0], 1); + UASSERT_SELFTEST(const int, results[1], 3); + UASSERT_SELFTEST(const int, results[2], 4); + UASSERT_SELFTEST(const int, nextChange, 21); tree.find(21, results, nextChange); - UASSERT_SELFTEST(size_t, results.size(), 2); - UASSERT_SELFTEST(int, results[0], 3); - UASSERT_SELFTEST(int, results[1], 4); - UASSERT_SELFTEST(int, nextChange, 25); // Center, or would be 30 + UASSERT_SELFTEST(const size_t, results.size(), 2); + UASSERT_SELFTEST(const int, results[0], 3); + UASSERT_SELFTEST(const int, results[1], 4); + UASSERT_SELFTEST(const int, nextChange, 25); // Center, or would be 30 tree.find(30, results, nextChange); - UASSERT_SELFTEST(size_t, results.size(), 2); - UASSERT_SELFTEST(int, results[0], 3); - UASSERT_SELFTEST(int, results[1], 4); - UASSERT_SELFTEST(int, nextChange, 31); + UASSERT_SELFTEST(const size_t, results.size(), 2); + UASSERT_SELFTEST(const int, results[0], 3); + UASSERT_SELFTEST(const int, results[1], 4); + UASSERT_SELFTEST(const int, nextChange, 31); tree.find(40, results, nextChange); - UASSERT_SELFTEST(size_t, results.size(), 2); - UASSERT_SELFTEST(int, results[0], 2); - UASSERT_SELFTEST(int, results[1], 4); - UASSERT_SELFTEST(int, nextChange, 41); + UASSERT_SELFTEST(const size_t, results.size(), 2); + UASSERT_SELFTEST(const int, results[0], 2); + UASSERT_SELFTEST(const int, results[1], 4); + UASSERT_SELFTEST(const int, nextChange, 41); tree.find(41, results, nextChange); - UASSERT_SELFTEST(size_t, results.size(), 0); - UASSERT_SELFTEST(int, nextChange, std::numeric_limits::max()); + UASSERT_SELFTEST(const size_t, results.size(), 0); + UASSERT_SELFTEST(const int, nextChange, std::numeric_limits::max()); // points = {{0, 0}}; for (const auto& it : points) { @@ -522,8 +523,8 @@ public: tree.build(data); // tree.find(50, results, nextChange); - UASSERT_SELFTEST(size_t, results.size(), 1); - UASSERT_SELFTEST(int, results[0], 5); + UASSERT_SELFTEST(const size_t, results.size(), 1); + UASSERT_SELFTEST(const int, results[0], 5); } }; @@ -541,12 +542,7 @@ public: , m_contents{contents} , m_match{match} {} ~WaiverSetting() = default; - WaiverSetting& operator=(const WaiverSetting& rhs) { - m_code = rhs.m_code; - m_contents = rhs.m_contents; - m_match = rhs.m_match; - return *this; - } + WaiverSetting& operator=(const WaiverSetting& rhs) = default; }; // File entity @@ -573,7 +569,7 @@ class V3ControlFile final { } public: - V3ControlFile() {} + V3ControlFile() = default; void update(const V3ControlFile& file) { // Copy in all attributes and waivers for (const auto& itr : file.m_lineAttrs) m_lineAttrs[itr.first] |= itr.second; @@ -1083,7 +1079,7 @@ bool V3Control::getScopeTraceOn(const string& scope) { return V3ControlResolver::s().scopeTraces().getScopeTraceOn(scope); } -void V3Control::contentsPushText(const string& text) { return WildcardContents::pushText(text); } +void V3Control::contentsPushText(const string& text) { WildcardContents::pushText(text); } bool V3Control::containsMTaskProfileData() { return V3ControlResolver::s().containsMTaskProfileData(); diff --git a/src/V3Coverage.cpp b/src/V3Coverage.cpp index ccb3c9326..7f25d6b5b 100644 --- a/src/V3Coverage.cpp +++ b/src/V3Coverage.cpp @@ -78,7 +78,7 @@ public: explicit ExprCoverageEligibleVisitor(AstNode* nodep) { iterateConst(nodep); } ~ExprCoverageEligibleVisitor() override = default; - bool eligible() { return m_eligible; } + bool eligible() const { return m_eligible; } }; //###################################################################### @@ -252,7 +252,7 @@ class CoverageVisitor final : public VNVisitor { const LinenoSet& lines = m_handleLines[state.m_handle]; int first = 0; int last = 0; - for (int linen : lines) { + for (const int linen : lines) { if (!first) { first = last = linen; } else if (linen == last + 1) { @@ -898,8 +898,8 @@ class CoverageVisitor final : public VNVisitor { CoverExprs rhsExprs; m_exprs.swap(rhsExprs); - for (CoverExpr& l : lhsExprs) { - for (CoverExpr& r : rhsExprs) { + for (const CoverExpr& l : lhsExprs) { + for (const CoverExpr& r : rhsExprs) { // array size 2 -> (false, true) std::array, 2> varps; std::array, 2> strs; @@ -913,7 +913,7 @@ class CoverageVisitor final : public VNVisitor { // Equivalent terms which don't match on either of these criteria will // not be flagged as redundant or impossible, however the results will // still be valid, albeit messier - for (CoverTerm& term : l) { + for (const CoverTerm& term : l) { if (const AstVarRef* const refp = VN_CAST(term.m_exprp, VarRef)) { varps[term.m_objective].insert(refp->varp()); } else { @@ -922,7 +922,7 @@ class CoverageVisitor final : public VNVisitor { expr.push_back(term); } bool impossible = false; - for (CoverTerm& term : r) { + for (const CoverTerm& term : r) { bool redundant = false; if (const AstNodeVarRef* const refp = VN_CAST(term.m_exprp, NodeVarRef)) { if (varps[term.m_objective].find(refp->varp()) @@ -1087,8 +1087,8 @@ class CoverageVisitor final : public VNVisitor { void exprUnsupported(AstNode* nodep, const string& why) { UINFO(9, "unsupported: " << why << " " << nodep); - bool wasSeeking = m_seeking == SEEKING; - Objective oldSeeking = m_seeking; + const bool wasSeeking = m_seeking == SEEKING; + const Objective oldSeeking = m_seeking; if (wasSeeking) abortExprCoverage(); m_seeking = ABORTED; iterateChildren(nodep); diff --git a/src/V3Dead.cpp b/src/V3Dead.cpp index 94dfbface..f2453eec2 100644 --- a/src/V3Dead.cpp +++ b/src/V3Dead.cpp @@ -362,7 +362,7 @@ class DeadVisitor final : public VNVisitor { checkAll(typedefp); } } - bool shouldDeleteTypedef(const AstTypedef* typedefp) { + bool shouldDeleteTypedef(const AstTypedef* typedefp) const { if (const auto* const structp = VN_CAST(typedefp->subDTypep(), NodeUOrStructDType)) { if (structp->user1() && !structp->packed()) return false; } diff --git a/src/V3DebugBisect.h b/src/V3DebugBisect.h index 778b893df..70d9ddbc6 100644 --- a/src/V3DebugBisect.h +++ b/src/V3DebugBisect.h @@ -32,7 +32,7 @@ class V3DebugBisect final { size_t m_count = 0; public: - V3DebugBisect(const char* namep) + explicit V3DebugBisect(const char* namep) : m_namep{namep} {} // Returns 'false' up to m_limit invocations, then returns 'true'. diff --git a/src/V3Delayed.cpp b/src/V3Delayed.cpp index 49aeb4705..6feb4e4da 100644 --- a/src/V3Delayed.cpp +++ b/src/V3Delayed.cpp @@ -255,9 +255,9 @@ class DelayedVisitor final : public VNVisitor { // AstVarScope::user1p() -> VarScopeInfo via m_vscpInfo // AstVarScope::user2p() -> AstVarRef*: First write reference to the Variable // AstVarScope::user3p() -> std::vector via m_writeRefs; - const VNUser1InUse m_user1InUse{}; - const VNUser2InUse m_user2InUse{}; - const VNUser3InUse m_user3InUse{}; + const VNUser1InUse m_user1InUse; + const VNUser2InUse m_user2InUse; + const VNUser3InUse m_user3InUse; AstUser1Allocator> m_varMap; AstUser1Allocator m_vscpInfo; AstUser3Allocator> m_writeRefs; diff --git a/src/V3Descope.cpp b/src/V3Descope.cpp index 9511a44e1..8df6651bd 100644 --- a/src/V3Descope.cpp +++ b/src/V3Descope.cpp @@ -72,8 +72,8 @@ class DescopeVisitor final : public VNVisitor { auto& ret = m_scopeToSelf[scopep]; if (ret.thisPtr.isEmpty()) { string name = scopep->name(); - string::size_type pos; - if ((pos = name.rfind('.')) != string::npos) name.erase(0, pos + 1); + string::size_type pos = name.rfind('.'); + if (pos != string::npos) name.erase(0, pos + 1); ret.thisPtr = VSelfPointerText{VSelfPointerText::This{}, name}; } return ret.thisPtr; diff --git a/src/V3Dfg.h b/src/V3Dfg.h index 7133085ec..94e588c26 100644 --- a/src/V3Dfg.h +++ b/src/V3Dfg.h @@ -97,7 +97,6 @@ class DfgEdge final { DfgVertex* const m_dstp; // The vertex driven by this edge, which owns this edge, so immutable V3ListLinks m_links; // V3List links in the list of sinks of m_srcp - DfgEdge() = delete; VL_UNCOPYABLE(DfgEdge); VL_UNMOVABLE(DfgEdge); @@ -108,6 +107,7 @@ public: explicit DfgEdge(DfgVertex* dstp) : m_dstp{dstp} {} ~DfgEdge() { unlinkSrcp(); } + DfgEdge() = delete; // The source (driver) of this edge DfgVertex* srcp() const { return m_srcp; } @@ -403,7 +403,6 @@ public: VL_UNCOPYABLE(DfgGraph); // METHODS -public: // Number of vertices in this graph size_t size() const { return m_size; } // Parent module - or nullptr when run after V3Scope @@ -604,12 +603,12 @@ protected: , m_currentGeneration{that.m_currentGeneration} { that.m_dfgp = nullptr; } - DfgUserMapBase& operator=(DfgUserMapBase&&) = delete; public: ~DfgUserMapBase() { if (m_dfgp) m_dfgp->m_vertexUserInUse = false; } + DfgUserMapBase& operator=(DfgUserMapBase&&) = delete; }; // Specialization where T_Value fits in DfgVertex::m_userStorage directly @@ -623,11 +622,11 @@ class DfgUserMap final : public DfgUserMapBase { explicit DfgUserMap(const DfgGraph* dfgp) : DfgUserMapBase{dfgp} {} VL_UNCOPYABLE(DfgUserMap); - DfgUserMap& operator=(DfgUserMap&&) = delete; public: DfgUserMap(DfgUserMap&&) = default; ~DfgUserMap() = default; + DfgUserMap& operator=(DfgUserMap&&) = delete; // METHODS // Retrieve mapped value for 'vtx', value initializing it on first access @@ -672,11 +671,11 @@ class DfgUserMap final : public DfgUserMapBase { explicit DfgUserMap(const DfgGraph* dfgp) : DfgUserMapBase{dfgp} {} VL_UNCOPYABLE(DfgUserMap); - DfgUserMap& operator=(DfgUserMap&&) = delete; public: DfgUserMap(DfgUserMap&&) = default; ~DfgUserMap() = default; + DfgUserMap& operator=(DfgUserMap&&) = delete; // METHODS // Retrieve mapped value for 'vtx', value initializing it on first access diff --git a/src/V3DfgBreakCycles.cpp b/src/V3DfgBreakCycles.cpp index f44501606..eb8d719a2 100644 --- a/src/V3DfgBreakCycles.cpp +++ b/src/V3DfgBreakCycles.cpp @@ -300,7 +300,7 @@ class TraceDriver final : public DfgVisitor { m_lsb = driver.m_lsb; } // Driver covers searched range, pick the needed/available bits - uint32_t lim = std::min(m_msb, driver.m_msb); + const uint32_t lim = std::min(m_msb, driver.m_msb); termps.emplace_back(trace(driver.m_vtxp, lim - driver.m_lsb, m_lsb - driver.m_lsb)); m_lsb = lim + 1; } diff --git a/src/V3DfgCache.h b/src/V3DfgCache.h index 78fa2e4e5..aa9cb050a 100644 --- a/src/V3DfgCache.h +++ b/src/V3DfgCache.h @@ -62,7 +62,7 @@ class V3DfgCache final { : m_dtype{dtype} , m_fromp{fromp} , m_lsb{lsb} {} - KeySel(const DfgSel* vtxp) + explicit KeySel(const DfgSel* vtxp) : m_dtype{vtxp->dtype()} , m_fromp{vtxp->fromp()} , m_lsb{vtxp->lsb()} {} @@ -94,7 +94,7 @@ class V3DfgCache final { KeyUnary(const DfgDataType& dtype, DfgVertex* source0p) : m_dtype{dtype} , m_source0p{source0p} {} - KeyUnary(const DfgVertexUnary* vtxp) + explicit KeyUnary(const DfgVertexUnary* vtxp) : m_dtype{vtxp->dtype()} , m_source0p{vtxp->inputp(0)} {} @@ -123,7 +123,7 @@ class V3DfgCache final { : m_dtype{dtype} , m_source0p{source0p} , m_source1p{source1p} {} - KeyBinary(const DfgVertexBinary* vtxp) + explicit KeyBinary(const DfgVertexBinary* vtxp) : m_dtype{vtxp->dtype()} , m_source0p{vtxp->inputp(0)} , m_source1p{vtxp->inputp(1)} {} @@ -158,7 +158,7 @@ class V3DfgCache final { , m_source0p{source0p} , m_source1p{source1p} , m_source2p{source2p} {} - KeyTernary(const DfgVertexTernary* vtxp) + explicit KeyTernary(const DfgVertexTernary* vtxp) : m_dtype{vtxp->dtype()} , m_source0p{vtxp->inputp(0)} , m_source1p{vtxp->inputp(1)} @@ -210,7 +210,7 @@ class V3DfgCache final { public: // CacheBase does not cache anything virtual DfgVertex* cache(DfgVertex*) { return nullptr; } - virtual void invalidate(const DfgVertex*) { return; } + virtual void invalidate(const DfgVertex*) {} }; template diff --git a/src/V3DfgCse.cpp b/src/V3DfgCse.cpp index b72707494..0257c4117 100644 --- a/src/V3DfgCse.cpp +++ b/src/V3DfgCse.cpp @@ -336,7 +336,7 @@ class V3DfgCse final { public: static void apply(DfgGraph& dfg, V3DfgCseContext& ctx) { - V3DfgCse{dfg, ctx}; + { V3DfgCse{dfg, ctx}; } // Prune unused nodes V3DfgPasses::removeUnused(dfg); } diff --git a/src/V3DfgDecomposition.cpp b/src/V3DfgDecomposition.cpp index 51bcd0faf..c867adf1a 100644 --- a/src/V3DfgDecomposition.cpp +++ b/src/V3DfgDecomposition.cpp @@ -182,7 +182,7 @@ class ExtractCyclicComponents final { // cyclic variable, put both its 'srcp' and 'defaultp' into the same // component if they are not variables themselves. The assertions below // must hold because of the assumption above. - for (DfgVertexVar& vtx : m_dfg.varVertices()) { + for (const DfgVertexVar& vtx : m_dfg.varVertices()) { const uint64_t varComponent = m_component.at(vtx); if (!varComponent) continue; if (DfgVertex* const srcp = vtx.srcp()) { diff --git a/src/V3DfgPasses.cpp b/src/V3DfgPasses.cpp index dff67fc6d..6c411138c 100644 --- a/src/V3DfgPasses.cpp +++ b/src/V3DfgPasses.cpp @@ -38,7 +38,7 @@ void V3DfgPasses::removeUnobservable(DfgGraph& dfg, V3DfgContext& dfgCtx) { workList.foreach([&](DfgVertex& vtx) { DfgLogic* const logicp = vtx.as(); // Check all variables driven by this logic are removable - bool used = logicp->foreachSink([&](DfgVertex& snk) { + const bool used = logicp->foreachSink([&](DfgVertex& snk) { DfgUnresolved* const uVtxp = snk.as(); DfgVertexVar* const vVtxp = uVtxp->firtsSinkp()->as(); if (vVtxp->hasSinks()) return true; diff --git a/src/V3DfgPeephole.cpp b/src/V3DfgPeephole.cpp index 089655971..d40d61114 100644 --- a/src/V3DfgPeephole.cpp +++ b/src/V3DfgPeephole.cpp @@ -1858,7 +1858,7 @@ class V3DfgPeephole final : public DfgVisitor { // Need to insert via a partial splice to avoid infinite matching, // this splice will be eliminated on later visits to its sinks. - DfgVertex::ScopeCache scopeCache; + const DfgVertex::ScopeCache scopeCache; DfgSplicePacked* const sp = new DfgSplicePacked{m_dfg, flp, vtxp->dtype()}; sp->addDriver(catp, lsb, flp); m_vInfo[sp].m_id = ++m_lastId; diff --git a/src/V3DfgPushDownSels.cpp b/src/V3DfgPushDownSels.cpp index a6ce6c9e3..658be1b34 100644 --- a/src/V3DfgPushDownSels.cpp +++ b/src/V3DfgPushDownSels.cpp @@ -136,8 +136,8 @@ class V3DfgPushDownSels final { // if the edge was indeed added, so caller must add the actual edge. bool addEdge(DfgVertex& src, DfgVertex& dst) { UASSERT_OBJ(&src != &dst, &src, "Should be different"); - State& srcState = m_stateMap[src]; - State& dstState = m_stateMap[dst]; + const State& srcState = m_stateMap[src]; + const State& dstState = m_stateMap[dst]; // If 'dst' is after 'src' in the topological ordering, // then ok to add edge and no need to update the ordering. if (dstState.ord > srcState.ord) return true; @@ -169,7 +169,7 @@ class V3DfgPushDownSels final { // Enqueue unvisited sinks in affeced area const bool cyclic = vtx.foreachSink([&](DfgVertex& sink) { - State& sinkState = m_stateMap[sink]; + const State& sinkState = m_stateMap[sink]; if (sinkState.ord == srcOrd) return true; // Stop completely if cyclic if (sinkState.visited) return false; // Stop search if already visited if (sinkState.ord > srcOrd) return false; // Stop search if outside critical area diff --git a/src/V3DfgRegularize.cpp b/src/V3DfgRegularize.cpp index 11010f5bb..5f397f4ac 100644 --- a/src/V3DfgRegularize.cpp +++ b/src/V3DfgRegularize.cpp @@ -67,7 +67,7 @@ class DfgRegularize final { return circularVariables; } - bool isUnused(const DfgVertex& vtx) { + static bool isUnused(const DfgVertex& vtx) { if (vtx.hasSinks()) return false; if (const DfgVertexVar* const varp = vtx.cast()) { // There is only one Dfg when running this pass diff --git a/src/V3DfgSynthesize.cpp b/src/V3DfgSynthesize.cpp index 92e24d99a..9210dffa2 100644 --- a/src/V3DfgSynthesize.cpp +++ b/src/V3DfgSynthesize.cpp @@ -356,7 +356,7 @@ class AstToDfgConverter final : public VNVisitor { // VISITORS // Unhandled node - void visit(AstNode* nodep) override { + void visit(AstNode* /*nodep*/) override { if (!m_foundUnhandled && m_converting) ++m_ctx.m_conv.nonRepUnknown; m_foundUnhandled = true; } @@ -1231,7 +1231,7 @@ class AstToDfgSynthesize final { std::vector computePropagatedDrivers(const std::vector& newDrivers, DfgVertexVar* oldp) { // Gather drivers of 'oldp' - they are in incresing range order with no overlaps - std::vector oldDrivers = gatherDrivers(oldp->srcp()->as()); + const std::vector oldDrivers = gatherDrivers(oldp->srcp()->as()); UASSERT_OBJ(!oldDrivers.empty(), oldp, "Should have a proper driver"); // Additional drivers of 'newp' propagated from 'oldp' diff --git a/src/V3EmitCFunc.cpp b/src/V3EmitCFunc.cpp index c31f8bd29..f324623a0 100644 --- a/src/V3EmitCFunc.cpp +++ b/src/V3EmitCFunc.cpp @@ -174,7 +174,7 @@ void EmitCFunc::emitOpName(AstNode* nodep, const string& format, AstNode* lhsp, putOut(); } -bool EmitCFunc::displayEmitHeader(AstNode* nodep, bool isScan) { +bool EmitCFunc::displayEmitHeader(AstNode* nodep) { bool isStmt = false; if (const AstFScanF* const dispp = VN_CAST(nodep, FScanF)) { isStmt = false; @@ -258,7 +258,7 @@ void EmitCFunc::displayNode(AstNode* nodep, AstSFormatF* fmtp, // fmtp is nullp if (vformat.empty() && VN_IS(nodep, Display)) // not fscanf etc, as they need to return value return; // NOP - const bool isStmt = displayEmitHeader(nodep, isScan); + const bool isStmt = displayEmitHeader(nodep); if (exprFormat) { UASSERT_OBJ(exprsp, nodep, "Missing format expression"); @@ -366,7 +366,7 @@ void EmitCFunc::emitCCallArgs(const AstNodeCCall* nodep, const string& selfPoint puts(")"); } -std::string EmitCFunc::dereferenceString(const std::string& pointer) { +std::string EmitCFunc::dereferenceString(const std::string& pointer) const { if (pointer[0] == '(' && pointer[1] == '&') { // remove "address of" followed by immediate dereference // Note: this relies on only the form '(&OBJECT)' being used by Verilator diff --git a/src/V3EmitCFunc.h b/src/V3EmitCFunc.h index c212b47d7..d24f33765 100644 --- a/src/V3EmitCFunc.h +++ b/src/V3EmitCFunc.h @@ -150,7 +150,7 @@ protected: public: // METHODS - bool displayEmitHeader(AstNode* nodep, bool isScan); + bool displayEmitHeader(AstNode* nodep); void displayNode(AstNode* nodep, AstSFormatF* fmtp, const string& vformat, AstNode* exprsp, bool isScan); @@ -185,7 +185,7 @@ public: AstNode* thsp); void emitCCallArgs(const AstNodeCCall* nodep, const string& selfPointer, bool inProcess); void emitDereference(AstNode* nodep, const string& pointer); - std::string dereferenceString(const std::string& pointer); + std::string dereferenceString(const std::string& pointer) const; void emitCvtPackStr(AstNode* nodep); void emitCvtWideArray(AstNode* nodep, AstNode* fromp); void emitConstant(AstConst* nodep); diff --git a/src/V3EmitCHeaders.cpp b/src/V3EmitCHeaders.cpp index 77124ad91..de3727e6a 100644 --- a/src/V3EmitCHeaders.cpp +++ b/src/V3EmitCHeaders.cpp @@ -693,7 +693,7 @@ class EmitCHeader final : public EmitCConstInit { ~EmitCHeader() override = default; public: - static void main(const AstNodeModule* modp) { EmitCHeader emitCHeader{modp}; } + static void main(const AstNodeModule* modp) { const EmitCHeader emitCHeader{modp}; } }; //###################################################################### diff --git a/src/V3EmitCMain.cpp b/src/V3EmitCMain.cpp index 624ae5b72..d4df97d08 100644 --- a/src/V3EmitCMain.cpp +++ b/src/V3EmitCMain.cpp @@ -174,5 +174,5 @@ private: void V3EmitCMain::emit() { UINFO(2, __FUNCTION__ << ":"); - { EmitCMain visitor; } + { const EmitCMain visitor; } } diff --git a/src/V3EmitCPch.cpp b/src/V3EmitCPch.cpp index 9c26d22d9..16b6776c2 100644 --- a/src/V3EmitCPch.cpp +++ b/src/V3EmitCPch.cpp @@ -24,7 +24,6 @@ VL_DEFINE_DEBUG_FUNCTIONS; // Precompiled header emitter class EmitCPch final : public EmitCBaseVisitorConst { -public: // METHODS void emitPch() { diff --git a/src/V3EmitCSyms.cpp b/src/V3EmitCSyms.cpp index 58bc6c621..31a125414 100644 --- a/src/V3EmitCSyms.cpp +++ b/src/V3EmitCSyms.cpp @@ -1086,7 +1086,7 @@ void EmitCSyms::emitSplit(std::vector& stmts, const std::string& na // Reduce into a balanced tree of sub-function calls until we end up with a single statement while (stmts.size() > 1) { size_t nSplits = 0; - size_t nStmts = stmts.size(); + const size_t nStmts = stmts.size(); for (size_t splitStart = 0, splitEnd = 0; splitStart < nStmts; splitStart = splitEnd) { // Gather up at at most 'maxCost' worth of statements in this split, // but always at least 2 (if less than 2, the reduction makes no diff --git a/src/V3EmitMk.cpp b/src/V3EmitMk.cpp index fcc151acd..f76945279 100644 --- a/src/V3EmitMk.cpp +++ b/src/V3EmitMk.cpp @@ -127,7 +127,7 @@ private: for (const Interval& iv : intervals) { const int scaledSize = iv.m_size * (MAX_BAR_LENGTH + 1) / topIntervalSize; - std::string line = " |" + std::string(scaledSize, '#'); + const std::string line = " |" + std::string(scaledSize, '#'); os << std::setw(maxScoreWidth) << iv.m_lowerBound << line << " " << iv.m_size << '\n'; } @@ -225,7 +225,7 @@ private: // Add new list if the last list's concatenability does not match the inputFile's // concatenability if (m_workLists.empty() || m_workLists.back().m_isConcatenable != fileIsConcatenable) { - m_workLists.push_back(WorkList{nextWorkListId++}); + m_workLists.emplace_back(WorkList{nextWorkListId++}); m_workLists.back().m_isConcatenable = fileIsConcatenable; } // Add inputFile to the last list @@ -313,7 +313,7 @@ private: int concatenatedFileId = 0; for (WorkList& list : m_workLists) { if (!list.m_isConcatenable) { - for (FilenameWithScore& file : list.m_files) { + for (const FilenameWithScore& file : list.m_files) { m_outputFiles.push_back({std::move(file.m_filename), {}}); } continue; diff --git a/src/V3EmitV.cpp b/src/V3EmitV.cpp index f720cf776..0272c62db 100644 --- a/src/V3EmitV.cpp +++ b/src/V3EmitV.cpp @@ -267,7 +267,7 @@ class EmitVBaseVisitorConst VL_NOT_FINAL : public VNVisitorConst { if (nodep->sensp()) puts(" "); iterateChildrenConst(nodep); } - void visit(AstCReset* nodep) override { puts("/*CRESET*/"); } + void visit(AstCReset* /*nodep*/) override { puts("/*CRESET*/"); } void visit(AstCase* nodep) override { putfs(nodep, ""); if (nodep->priorityPragma()) puts("priority "); @@ -795,7 +795,7 @@ class EmitVBaseVisitorConst VL_NOT_FINAL : public VNVisitorConst { iterateAndNextConstNull(nodep->fromp()); puts(cvtToStr(nodep->declRange())); } - void visit(AstThisRef* nodep) override { puts("this"); } + void visit(AstThisRef* /*nodep*/) override { puts("this"); } void visit(AstTypedef* nodep) override { putfs(nodep, "typedef "); iterateConstNull(nodep->subDTypep()); diff --git a/src/V3Error.cpp b/src/V3Error.cpp index 6dc1f1faa..10d76ef09 100644 --- a/src/V3Error.cpp +++ b/src/V3Error.cpp @@ -51,11 +51,9 @@ V3ErrorCode::V3ErrorCode(const char* msgp) { } string V3ErrorCode::url() const { - if (!isNamed()) { + if (!isNamed()) return "https://verilator.org/verilator_doc.html"s + "?v=" + PACKAGE_VERSION_NUMBER_STRING; - } else { - return "https://verilator.org/warn/"s + ascii() + "?v=" + PACKAGE_VERSION_NUMBER_STRING; - } + return "https://verilator.org/warn/"s + ascii() + "?v=" + PACKAGE_VERSION_NUMBER_STRING; } //###################################################################### @@ -73,23 +71,14 @@ bool V3ErrorGuarded::isError(V3ErrorCode code, bool supp) VL_REQUIRES(m_mutex) { string V3ErrorGuarded::msgPrefix() VL_REQUIRES(m_mutex) { const V3ErrorCode code = m_message.code(); const bool supp = m_errorSuppressed; - if (supp) { - return "-arning-suppressed-" + std::string{code.ascii()} + ": "; - } else if (code.severityInfo()) { - return "-Info: "; - } else if (code == V3ErrorCode::EC_FATAL) { - return "%Error: "; - } else if (code == V3ErrorCode::EC_FATALMANY) { - return "%Error: "; - } else if (code == V3ErrorCode::EC_FATALSRC) { - return "%Error: Internal Error: "; - } else if (code == V3ErrorCode::EC_ERROR) { - return "%Error: "; - } else if (isError(code, supp)) { - return "%Error-" + std::string{code.ascii()} + ": "; - } else { - return "%Warning-" + std::string{code.ascii()} + ": "; - } + if (supp) return "-arning-suppressed-" + std::string{code.ascii()} + ": "; + if (code.severityInfo()) return "-Info: "; + if (code == V3ErrorCode::EC_FATAL) return "%Error: "; + if (code == V3ErrorCode::EC_FATALMANY) return "%Error: "; + if (code == V3ErrorCode::EC_FATALSRC) return "%Error: Internal Error: "; + if (code == V3ErrorCode::EC_ERROR) return "%Error: "; + if (isError(code, supp)) return "%Error-" + std::string{code.ascii()} + ": "; + return "%Warning-" + std::string{code.ascii()} + ": "; } void V3ErrorGuarded::vlAbortOrExit() VL_REQUIRES(m_mutex) { @@ -166,8 +155,7 @@ void V3ErrorGuarded::v3errorEndGuts(const std::ostringstream& sstr, const string if (m_errorSuppressed) { // On debug, show only non default-off warning to prevent pages of warnings if (m_message.code().defaultsOff()) return; - if (!debug() || debug() < 3 || (debug() < 9 && m_showedSuppressed.test(m_message.code()))) - return; + if (debug() < 3 || (debug() < 9 && m_showedSuppressed.test(m_message.code()))) return; m_showedSuppressed.set(m_message.code(), true); } string msg @@ -176,8 +164,8 @@ void V3ErrorGuarded::v3errorEndGuts(const std::ostringstream& sstr, const string // If suppressed print only first line to reduce verbosity string firstLine = msg; { - string::size_type pos; - if ((pos = firstLine.find('\n')) != string::npos) { + const string::size_type pos = firstLine.find('\n'); + if (pos != string::npos) { firstLine.erase(pos, firstLine.length() - pos); firstLine += "..."; } @@ -190,8 +178,8 @@ void V3ErrorGuarded::v3errorEndGuts(const std::ostringstream& sstr, const string string msg_additional; { - string::size_type pos; - if ((pos = msg.find(V3Error::warnAdditionalInfo())) != string::npos) { + const string::size_type pos = msg.find(V3Error::warnAdditionalInfo()); + if (pos != string::npos) { msg_additional = msg.substr(pos + V3Error::warnAdditionalInfo().size()); msg.erase(pos); } diff --git a/src/V3Error.h b/src/V3Error.h index 33083a9dc..c5f49dfd4 100644 --- a/src/V3Error.h +++ b/src/V3Error.h @@ -379,7 +379,7 @@ class VErrorBitSet final { public: class AllOnes {}; - VErrorBitSet() {} + VErrorBitSet() = default; explicit VErrorBitSet(AllOnes) { m_bitset.set(); } ~VErrorBitSet() = default; bool test(V3ErrorCode code) const { return m_bitset[code]; } @@ -497,8 +497,8 @@ public: void errorContexted(bool flag) VL_REQUIRES(m_mutex) { m_errorContexted = flag; } void incWarnings() VL_REQUIRES(m_mutex) { ++m_warnCount; } void incErrors() VL_REQUIRES(m_mutex) { ++m_errCount; } - int errorCount() VL_REQUIRES(m_mutex) { return m_errCount; } - bool isErrorOrWarn() VL_REQUIRES(m_mutex) { + int errorCount() const VL_REQUIRES(m_mutex) { return m_errCount; } + bool isErrorOrWarn() const VL_REQUIRES(m_mutex) { return errorCount() || (warnFatal() && warnCount()); } bool pretendError(V3ErrorCode code) VL_REQUIRES(m_mutex) { return m_pretendError.test(code); } @@ -506,16 +506,16 @@ public: code.forDelegateCodes([this, flag](V3ErrorCode subcode) VL_REQUIRES(m_mutex) { m_pretendError.set(subcode, flag); }); } - int debugDefault() VL_MT_SAFE { return m_debugDefault; } + int debugDefault() const VL_MT_SAFE { return m_debugDefault; } void debugDefault(int level) VL_MT_UNSAFE { m_debugDefault = level; } - int errorLimit() VL_REQUIRES(m_mutex) { return m_errorLimit; } + int errorLimit() const VL_REQUIRES(m_mutex) { return m_errorLimit; } void errorLimit(int level) VL_REQUIRES(m_mutex) { m_errorLimit = level; } - bool warnFatal() VL_REQUIRES(m_mutex) { return m_warnFatal; } + bool warnFatal() const VL_REQUIRES(m_mutex) { return m_warnFatal; } void warnFatal(bool flag) VL_REQUIRES(m_mutex) { m_warnFatal = flag; } - V3ErrorCode errorCode() VL_REQUIRES(m_mutex) { return m_message.code(); } + V3ErrorCode errorCode() const VL_REQUIRES(m_mutex) { return m_message.code(); } bool errorContexted() VL_REQUIRES(m_mutex) { return m_errorContexted; } - int warnCount() VL_REQUIRES(m_mutex) { return m_warnCount; } - bool errorSuppressed() VL_REQUIRES(m_mutex) { return m_errorSuppressed; } + int warnCount() const VL_REQUIRES(m_mutex) { return m_warnCount; } + bool errorSuppressed() const VL_REQUIRES(m_mutex) { return m_errorSuppressed; } void errorSuppressed(bool flag) VL_REQUIRES(m_mutex) { m_errorSuppressed = flag; } bool describedEachWarn(V3ErrorCode code) VL_REQUIRES(m_mutex) { return m_describedEachWarn.test(code); @@ -538,9 +538,9 @@ public: class V3Error final { // Static members only - V3Error() = delete; public: + V3Error() = delete; static V3ErrorGuarded& s() VL_MT_SAFE { // Singleton static V3ErrorGuarded s_s; return s_s; diff --git a/src/V3ExecGraph.cpp b/src/V3ExecGraph.cpp index f201cc6b5..6ac658602 100644 --- a/src/V3ExecGraph.cpp +++ b/src/V3ExecGraph.cpp @@ -517,7 +517,7 @@ class PackThreads final { // Update the ready list const size_t erased = readyMTasks.erase(bestMtaskp); UASSERT_OBJ(erased > 0, bestMtaskp, "Should have erased something?"); - for (V3GraphEdge& edgeOut : bestMtaskp->outEdges()) { + for (const V3GraphEdge& edgeOut : bestMtaskp->outEdges()) { ExecMTask* const nextp = edgeOut.top()->as(); // Dependent MTask should not yet be assigned to a thread UASSERT(schedule.threadId(nextp) == ThreadSchedule::UNASSIGNED, @@ -598,76 +598,76 @@ public: 10}; // Sandbag denom const std::vector scheduled = packer.pack(graph); - UASSERT_SELFTEST(size_t, scheduled.size(), 3); - UASSERT_SELFTEST(size_t, scheduled[0].m_threads.size(), threads); - UASSERT_SELFTEST(size_t, scheduled[0].m_threads[0].size(), 2); + UASSERT_SELFTEST(const size_t, scheduled.size(), 3); + UASSERT_SELFTEST(const size_t, scheduled[0].m_threads.size(), threads); + UASSERT_SELFTEST(const size_t, scheduled[0].m_threads[0].size(), 2); for (size_t i = 1; i < scheduled[0].m_threads.size(); ++i) - UASSERT_SELFTEST(size_t, scheduled[0].m_threads[i].size(), 0); + UASSERT_SELFTEST(const size_t, scheduled[0].m_threads[i].size(), 0); UASSERT_SELFTEST(const ExecMTask*, scheduled[0].m_threads[0][0], t0); UASSERT_SELFTEST(const ExecMTask*, scheduled[0].m_threads[0][1], t1); - UASSERT_SELFTEST(size_t, scheduled[1].m_threads.size(), hierThreads / 3); + UASSERT_SELFTEST(const size_t, scheduled[1].m_threads.size(), hierThreads / 3); UASSERT_SELFTEST(const ExecMTask*, scheduled[1].m_threads[0][0], t2); UASSERT_SELFTEST(const ExecMTask*, scheduled[1].m_threads[0][1], t3); UASSERT_SELFTEST(const ExecMTask*, scheduled[1].m_threads[1][0], t4); - UASSERT_SELFTEST(size_t, scheduled[2].m_threads.size(), threads); + UASSERT_SELFTEST(const size_t, scheduled[2].m_threads.size(), threads); UASSERT_SELFTEST(const ExecMTask*, scheduled[2].m_threads[0][0], t5); UASSERT_SELFTEST(const ExecMTask*, scheduled[2].m_threads[1][0], t6); - UASSERT_SELFTEST(size_t, ThreadSchedule::s_mtaskState.size(), 7); + UASSERT_SELFTEST(const size_t, ThreadSchedule::s_mtaskState.size(), 7); - UASSERT_SELFTEST(uint32_t, ThreadSchedule::threadId(t0), 0); - UASSERT_SELFTEST(uint32_t, ThreadSchedule::threadId(t1), 0); - UASSERT_SELFTEST(uint32_t, ThreadSchedule::threadId(t2), 0); - UASSERT_SELFTEST(uint32_t, ThreadSchedule::threadId(t3), 0); - UASSERT_SELFTEST(uint32_t, ThreadSchedule::threadId(t4), 1); - UASSERT_SELFTEST(uint32_t, ThreadSchedule::threadId(t5), 0); - UASSERT_SELFTEST(uint32_t, ThreadSchedule::threadId(t6), 1); + UASSERT_SELFTEST(const uint32_t, ThreadSchedule::threadId(t0), 0); + UASSERT_SELFTEST(const uint32_t, ThreadSchedule::threadId(t1), 0); + UASSERT_SELFTEST(const uint32_t, ThreadSchedule::threadId(t2), 0); + UASSERT_SELFTEST(const uint32_t, ThreadSchedule::threadId(t3), 0); + UASSERT_SELFTEST(const uint32_t, ThreadSchedule::threadId(t4), 1); + UASSERT_SELFTEST(const uint32_t, ThreadSchedule::threadId(t5), 0); + UASSERT_SELFTEST(const uint32_t, ThreadSchedule::threadId(t6), 1); // On its native thread, we see the actual end time for t0: - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[0], t0, 0), 1000); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[0], t0, 0), 1000); // On the other thread, we see a sandbagged end time which does not // exceed the t1 end time: - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[0], t0, 1), 1099); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[0], t0, 1), 1099); // Actual end time on native thread: - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[0], t1, 0), 1100); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[0], t1, 0), 1100); // Sandbagged end time seen on thread 1. Note it does not compound // with t0's sandbagged time; compounding caused trouble in // practice. - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[0], t1, 1), 1130); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[0], t1, 1), 1130); // Wide task scheduling // Task does not depend on previous or future schedules - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[0], t2, 0), 0); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[2], t2, 0), 0); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[0], t2, 0), 0); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[2], t2, 0), 0); // We allow sandbagging for hierarchical children tasks, this does not affect // wide task scheduling. When the next schedule is created it doesn't matter // anyway. - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t2, 0), 1200); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t2, 1), 1230); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t2, 2), 1230); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t2, 3), 1230); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t2, 4), 1230); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t2, 5), 1230); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t2, 0), 1200); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t2, 1), 1230); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t2, 2), 1230); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t2, 3), 1230); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t2, 4), 1230); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t2, 5), 1230); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t3, 0), 1300); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t3, 1), 1330); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t3, 2), 1330); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t3, 3), 1330); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t3, 4), 1330); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t3, 5), 1330); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t3, 0), 1300); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t3, 1), 1330); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t3, 2), 1330); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t3, 3), 1330); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t3, 4), 1330); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t3, 5), 1330); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t4, 0), 1360); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t4, 1), 1330); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t4, 2), 1360); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t4, 3), 1360); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t4, 4), 1360); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t4, 5), 1360); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t4, 0), 1360); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t4, 1), 1330); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t4, 2), 1360); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t4, 3), 1360); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t4, 4), 1360); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t4, 5), 1360); for (V3GraphVertex& vtx : graph.vertices()) vtx.as()->funcp()->deleteTree(); VL_DO_DANGLING(execGraphp->deleteTree(), execGraphp); @@ -700,29 +700,29 @@ public: 10}; // Sandbag denom const std::vector scheduled = packer.pack(graph); - UASSERT_SELFTEST(size_t, scheduled.size(), 2); - UASSERT_SELFTEST(size_t, scheduled[0].m_threads.size(), hierThreads / 2); - UASSERT_SELFTEST(size_t, scheduled[0].m_threads[0].size(), 1); + UASSERT_SELFTEST(const size_t, scheduled.size(), 2); + UASSERT_SELFTEST(const size_t, scheduled[0].m_threads.size(), hierThreads / 2); + UASSERT_SELFTEST(const size_t, scheduled[0].m_threads[0].size(), 1); for (size_t i = 1; i < scheduled[0].m_threads.size(); ++i) - UASSERT_SELFTEST(size_t, scheduled[0].m_threads[i].size(), 0); + UASSERT_SELFTEST(const size_t, scheduled[0].m_threads[i].size(), 0); UASSERT_SELFTEST(const ExecMTask*, scheduled[0].m_threads[0][0], t0); - UASSERT_SELFTEST(size_t, scheduled[1].m_threads.size(), threads); - UASSERT_SELFTEST(size_t, scheduled[1].m_threads[0].size(), 1); + UASSERT_SELFTEST(const size_t, scheduled[1].m_threads.size(), threads); + UASSERT_SELFTEST(const size_t, scheduled[1].m_threads[0].size(), 1); for (size_t i = 1; i < scheduled[1].m_threads.size(); ++i) - UASSERT_SELFTEST(size_t, scheduled[1].m_threads[i].size(), 0); + UASSERT_SELFTEST(const size_t, scheduled[1].m_threads[i].size(), 0); UASSERT_SELFTEST(const ExecMTask*, scheduled[1].m_threads[0][0], t1); - UASSERT_SELFTEST(size_t, ThreadSchedule::s_mtaskState.size(), 2); + UASSERT_SELFTEST(const size_t, ThreadSchedule::s_mtaskState.size(), 2); - UASSERT_SELFTEST(uint32_t, ThreadSchedule::threadId(t0), 0); - UASSERT_SELFTEST(uint32_t, ThreadSchedule::threadId(t1), 0); + UASSERT_SELFTEST(const uint32_t, ThreadSchedule::threadId(t0), 0); + UASSERT_SELFTEST(const uint32_t, ThreadSchedule::threadId(t1), 0); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[0], t0, 0), 1000); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[0], t0, 0), 1000); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t1, 0), 1100); - UASSERT_SELFTEST(uint32_t, packer.completionTime(scheduled[1], t1, 1), 1130); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t1, 0), 1100); + UASSERT_SELFTEST(const uint32_t, packer.completionTime(scheduled[1], t1, 1), 1130); for (V3GraphVertex& vtx : graph.vertices()) vtx.as()->funcp()->deleteTree(); VL_DO_DANGLING(execGraphp->deleteTree(), execGraphp); @@ -1201,12 +1201,12 @@ void selfTest() { {2, {20, 0}}, // Note no profile {3, {30, 3000}}}); normalizeCosts(costs); - UASSERT_SELFTEST(uint64_t, costs[1].first, 1000); - UASSERT_SELFTEST(uint64_t, costs[1].second, 1000); - UASSERT_SELFTEST(uint64_t, costs[2].first, 2000); - UASSERT_SELFTEST(uint64_t, costs[2].second, 0); - UASSERT_SELFTEST(uint64_t, costs[3].first, 3000); - UASSERT_SELFTEST(uint64_t, costs[3].second, 3000); + UASSERT_SELFTEST(const uint64_t, costs[1].first, 1000); + UASSERT_SELFTEST(const uint64_t, costs[1].second, 1000); + UASSERT_SELFTEST(const uint64_t, costs[2].first, 2000); + UASSERT_SELFTEST(const uint64_t, costs[2].second, 0); + UASSERT_SELFTEST(const uint64_t, costs[3].first, 3000); + UASSERT_SELFTEST(const uint64_t, costs[3].second, 3000); } { // Test that very large profile data properly scales Costs costs({// id est prof @@ -1214,12 +1214,12 @@ void selfTest() { {2, {20, 200000000000}}, {3, {30, 1}}}); // Make sure doesn't underflow normalizeCosts(costs); - UASSERT_SELFTEST(uint64_t, costs[1].first, 2500000); - UASSERT_SELFTEST(uint64_t, costs[1].second, 5000000); - UASSERT_SELFTEST(uint64_t, costs[2].first, 5000000); - UASSERT_SELFTEST(uint64_t, costs[2].second, 10000000); - UASSERT_SELFTEST(uint64_t, costs[3].first, 7500000); - UASSERT_SELFTEST(uint64_t, costs[3].second, 1); + UASSERT_SELFTEST(const uint64_t, costs[1].first, 2500000); + UASSERT_SELFTEST(const uint64_t, costs[1].second, 5000000); + UASSERT_SELFTEST(const uint64_t, costs[2].first, 5000000); + UASSERT_SELFTEST(const uint64_t, costs[2].second, 10000000); + UASSERT_SELFTEST(const uint64_t, costs[3].first, 7500000); + UASSERT_SELFTEST(const uint64_t, costs[3].second, 1); } PackThreads::selfTest(); diff --git a/src/V3Expand.cpp b/src/V3Expand.cpp index 0eb724ea5..83d9d35ea 100644 --- a/src/V3Expand.cpp +++ b/src/V3Expand.cpp @@ -90,7 +90,7 @@ class ExpandVisitor final : public VNVisitor { // METHODS // Use state that ExpandOkVisitor calculated - bool isImpure(AstNode* nodep) { + static bool isImpure(AstNode* nodep) { const bool impure = nodep->user2(); if (impure) UINFO(9, " impure " << nodep); return impure; @@ -1142,7 +1142,7 @@ public: void V3Expand::expandAll(AstNetlist* nodep) { UINFO(2, __FUNCTION__ << ":"); { - ExpandOkVisitor okVisitor{nodep}; + const ExpandOkVisitor okVisitor{nodep}; ExpandVisitor{nodep}; } // Destruct before checking V3Global::dumpCheckGlobalTree("expand", 0, dumpTreeEitherLevel() >= 3); diff --git a/src/V3File.cpp b/src/V3File.cpp index 34f1e8597..f6f063c47 100644 --- a/src/V3File.cpp +++ b/src/V3File.cpp @@ -304,8 +304,7 @@ bool V3FileDependImp::checkTimes(const string& filename, const string& cmdlineIn << chkFilename << "; " << curStat.st_size << "=?" << chkSize << " " << curStat.st_ctime << "." << VL_STAT_CTIME_NSEC(curStat) << "=?" << chkCstime << "." << chkCnstime << " " << curStat.st_mtime << "." - << VL_STAT_MTIME_NSEC(curStat) << "=?" << chkMstime << "." << chkMnstime - << endl); + << VL_STAT_MTIME_NSEC(curStat) << "=?" << chkMstime << "." << chkMnstime); if (skipHashing) return false; // We didn't hash target output files, nor large files, // as unlikely to find a match and can be large @@ -435,7 +434,7 @@ private: // UINFO(9, "RD GOT g " << got << " e " << errno << " " << strerror(errno)); // usleep(50*1000); if (got > 0) { - outl.push_back(string(buf, got)); + outl.emplace_back(string(buf, got)); sizegot += got; } else if (errno == EINTR || errno == EAGAIN #ifdef EWOULDBLOCK @@ -477,7 +476,7 @@ private: void writeFilter(const string& out) { if (debug() >= 6) { UINFO(6, "filter-out: " << out); - if (out[out.length() - 1] != '\n') cout << endl; + if (out[out.length() - 1] != '\n') cout << '\n'; } if (!m_pid) { v3error("--pipe-filter: write to closed file\n"); @@ -939,7 +938,7 @@ string V3OutFormatter::quoteNameControls(const string& namein, } else if (std::isprint(c)) { out += c; } else { - out += "&#"s + cvtToStr((unsigned int)(c & 0xff)) + ";"; + out += "&#"s + cvtToStr(static_cast(c & 0xff)) + ";"; } } } else { diff --git a/src/V3File.h b/src/V3File.h index 666736414..66b3d60f3 100644 --- a/src/V3File.h +++ b/src/V3File.h @@ -51,11 +51,8 @@ public: } static std::ofstream* new_ofstream_nodepend(const string& filename, bool append = false) { createMakeDirFor(filename); - if (append) { - return new std::ofstream{filename.c_str(), std::ios::app}; - } else { - return new std::ofstream{filename.c_str()}; - } + if (append) return new std::ofstream{filename.c_str(), std::ios::app}; + return new std::ofstream{filename.c_str()}; } static FILE* new_fopen_w(const string& filename) { createMakeDirFor(filename); @@ -130,7 +127,7 @@ private: void putcNoTracking(char chr); public: - V3OutFormatter(Language lang); + explicit V3OutFormatter(Language lang); virtual ~V3OutFormatter() = default; // ACCESSORS void blockIndent(int flag) { m_blockIndent = flag; } @@ -355,7 +352,7 @@ public: return *this; } - V3OutJsonFile& operator+=(V3OutJsonFile& cursor) { + V3OutJsonFile& operator+=(V3OutJsonFile& /*cursor*/) { // Meaningless syntax sugar, at least for now return *this; } diff --git a/src/V3FileLine.cpp b/src/V3FileLine.cpp index 4e82a497e..df0d580ad 100644 --- a/src/V3FileLine.cpp +++ b/src/V3FileLine.cpp @@ -98,7 +98,7 @@ void FileLineSingleton::fileNameNumMapDumpJson(std::ostream& os) { FileLineSingleton::msgEnSetIdx_t FileLineSingleton::addMsgEnBitSet(const MsgEnBitSet& bitSet) VL_MT_SAFE_EXCLUDES(m_mutex) { - V3LockGuard lock{m_mutex}; + const V3LockGuard lock{m_mutex}; const auto pair = m_internedMsgEnIdxs.emplace(bitSet, 0); msgEnSetIdx_t& idx = pair.first->second; if (pair.second) { diff --git a/src/V3FileLine.h b/src/V3FileLine.h index 40c28ec1d..5e66d6db8 100644 --- a/src/V3FileLine.h +++ b/src/V3FileLine.h @@ -470,7 +470,7 @@ public: const MsgEnBitSet& lhsMsgEn = msgEn(); const MsgEnBitSet& rhsMsgEn = rhs.msgEn(); for (size_t i = 0; i < V3ErrorCode::_ENUM_MAX; ++i) { - V3ErrorCode code = static_cast(i); + const V3ErrorCode code = static_cast(i); if (lhsMsgEn.enabled(code) != rhsMsgEn.enabled(code)) return rhsMsgEn.enabled(code) ? -1 : 1; } diff --git a/src/V3Force.cpp b/src/V3Force.cpp index 553fc46d0..727494130 100644 --- a/src/V3Force.cpp +++ b/src/V3Force.cpp @@ -117,7 +117,7 @@ public: lhsVarRefp->replaceWith(new AstVarRef{flp, m_enVscp, VAccess::WRITE}); lhsVarRefp->deleteTree(); assignp->rhsp()->unlinkFrBack()->deleteTree(); - V3Number zero{m_enVscp, assignp->lhsp()->dtypep()->width()}; + const V3Number zero{m_enVscp, assignp->lhsp()->dtypep()->width()}; assignp->rhsp(new AstConst{flp, zero}); } activeInitp->addStmtsp(new AstInitial{flp, enInitStmtsp}); diff --git a/src/V3Gate.cpp b/src/V3Gate.cpp index 182a451c7..298dc0b03 100644 --- a/src/V3Gate.cpp +++ b/src/V3Gate.cpp @@ -456,7 +456,7 @@ class GateOkVisitor final : public VNVisitorConst { clearSimple("Not a buffer (goes to a clock)"); } } - void visit(AstCReset* nodep) override { + void visit(AstCReset* /*nodep*/) override { if (!m_isSimple) return; // CReset is pure because we can optimize assignments, but if is // the only assignment to a variable we still need to initial @@ -721,7 +721,7 @@ class GateInline final { // If the consumer logic writes one of the variables that the substitution // is reading, then we would get a cycles, so we cannot do that. bool canInline = true; - for (V3GraphEdge& dedge : dstVtxp->outEdges()) { + for (const V3GraphEdge& dedge : dstVtxp->outEdges()) { const GateVarVertex* const consVVertexp = dedge.top()->as(); if (readVscps.count(consVVertexp->varScp())) { canInline = false; @@ -824,7 +824,7 @@ class GateDedupeHash final : public V3DupFinderUserSame { V3DupFinder m_dupFinder; // Duplicate finder for rhs of assigns - bool same(AstNode* node1p, AstNode* node2p) { + static bool same(AstNode* node1p, AstNode* node2p) { // Regarding the complexity of this function 'same': // Applying this comparison function to a a set of n trees pairwise is O(n^2) in the // number of comparisons (number of pairs). AstNode::sameTree itself, is O(sizeOfTree) in diff --git a/src/V3Global.h b/src/V3Global.h index 3f778285a..7b5c1aa18 100644 --- a/src/V3Global.h +++ b/src/V3Global.h @@ -148,7 +148,7 @@ public: V3Options opt; // All options; let user see them directly // CONSTRUCTORS - V3Global() {} + V3Global() = default; void boot(); void shutdown(); // Release allocated resources diff --git a/src/V3Graph.cpp b/src/V3Graph.cpp index 69a04e5a8..bdb72f6d5 100644 --- a/src/V3Graph.cpp +++ b/src/V3Graph.cpp @@ -68,8 +68,8 @@ void V3GraphVertex::unlinkDelete(V3Graph* graphp) { void V3GraphVertex::rerouteEdges(V3Graph* graphp) { // Make new edges for each from/to pair - for (V3GraphEdge& iedge : inEdges()) { - for (V3GraphEdge& oedge : outEdges()) { + for (const V3GraphEdge& iedge : inEdges()) { + for (const V3GraphEdge& oedge : outEdges()) { new V3GraphEdge{graphp, iedge.fromp(), oedge.top(), std::min(iedge.weight(), oedge.weight()), iedge.cutable() && oedge.cutable()}; diff --git a/src/V3Graph.h b/src/V3Graph.h index c93b4115d..7ecb09418 100644 --- a/src/V3Graph.h +++ b/src/V3Graph.h @@ -108,7 +108,6 @@ protected: bool cutable = false) VL_MT_DISABLED; void cut() { m_weight = 0; } // 0 weight is same as disconnected // CONSTRUCTORS -protected: V3GraphEdge(V3Graph* graphp, V3GraphVertex* fromp, V3GraphVertex* top, const V3GraphEdge& old) VL_MT_DISABLED { init(graphp, fromp, top, old.m_weight, old.m_cutable); diff --git a/src/V3GraphPathChecker.cpp b/src/V3GraphPathChecker.cpp index ceec04edc..a3d9c5c22 100644 --- a/src/V3GraphPathChecker.cpp +++ b/src/V3GraphPathChecker.cpp @@ -44,7 +44,7 @@ struct GraphPCNode final { uint64_t m_seenAtGeneration = 0; // CONSTRUCTORS - GraphPCNode() {} + GraphPCNode() = default; ~GraphPCNode() = default; }; diff --git a/src/V3GraphStream.h b/src/V3GraphStream.h index 62c9b8b21..99ace2691 100644 --- a/src/V3GraphStream.h +++ b/src/V3GraphStream.h @@ -256,11 +256,8 @@ public: m_readyVertices.clear(); } const V3GraphVertex* const resultp = m_nextVertices[m_nextIndex++]; - if (m_way == GraphWay::FORWARD) { - return unblock(resultp); - } else { - return unblock(resultp); - } + if (m_way == GraphWay::FORWARD) return unblock(resultp); + return unblock(resultp); } private: diff --git a/src/V3HierBlock.cpp b/src/V3HierBlock.cpp index 454c21797..79bd3667c 100644 --- a/src/V3HierBlock.cpp +++ b/src/V3HierBlock.cpp @@ -203,7 +203,7 @@ VStringList V3HierBlock::commandArgs(bool forMkJson) const { VStringList V3HierBlock::hierBlockArgs() const { VStringList opts; const StrGParams gparamsStr = stringifyParams(m_params, false); - opts.push_back("--hierarchical-block "); + opts.emplace_back("--hierarchical-block "); string s = modp()->origName(); // origName s += "," + modp()->name(); // mangledName for (const StrGParam& pair : gparamsStr) { diff --git a/src/V3InlineCFuncs.cpp b/src/V3InlineCFuncs.cpp index 922cc17f1..99efbc201 100644 --- a/src/V3InlineCFuncs.cpp +++ b/src/V3InlineCFuncs.cpp @@ -56,7 +56,7 @@ class CFuncInlineCheckVisitor final : public VNVisitorConst { m_whyNotNodep = nodep; UINFO(9, "CFunc not inlineable: " << why); if (nodep) UINFO(9, ": " << nodep); - UINFO(9, endl); + UINFO(9, ""); } } @@ -211,7 +211,7 @@ class InlineCFuncsVisitor final : public VNVisitor { AstCFunc* const cfuncp = std::get<1>(tuple); AstCFunc* const callerp = std::get<2>(tuple); - UINFO(6, "Inlining CFunc " << cfuncp->name() << " into " << callerp->name() << endl); + UINFO(6, "Inlining CFunc " << cfuncp->name() << " into " << callerp->name()); ++m_statInlined; // Clone local variables with unique names to avoid collisions diff --git a/src/V3Inst.cpp b/src/V3Inst.cpp index 5122eafbf..ad6a04860 100644 --- a/src/V3Inst.cpp +++ b/src/V3Inst.cpp @@ -158,7 +158,7 @@ public: } void dump() { for (const auto& itr : m_modVarNameMap) { - cout << "-namemap: " << itr.first << " -> " << itr.second << endl; + cout << "-namemap: " << itr.first << " -> " << itr.second << '\n'; } } @@ -220,7 +220,7 @@ private: if (prevp) nodep->addNextHere(prevp); if (prevp && debug() == 9) { prevp->dumpTree("- newintf: "); - cout << endl; + cout << '\n'; } } iterateChildren(nodep); @@ -283,14 +283,14 @@ private: newp->addNextHere(varNewp); if (debug() == 9) { varNewp->dumpTree("- newintf: "); - cout << endl; + cout << '\n'; } } // Fixup pins iterateAndNextNull(newp->pinsp()); if (debug() == 9) { newp->dumpTree("- newcell: "); - cout << endl; + cout << '\n'; } } diff --git a/src/V3InstrCount.cpp b/src/V3InstrCount.cpp index 6b4b2676e..5e0cb7b9f 100644 --- a/src/V3InstrCount.cpp +++ b/src/V3InstrCount.cpp @@ -307,7 +307,7 @@ private: string indent() const { return string(m_depth, ':') + " "; } void visit(AstNode* nodep) override { ++m_depth; - if (unsigned costPlus1 = nodep->user2()) { + if (const unsigned costPlus1 = nodep->user2()) { *m_osp << " " << indent() << "cost " << std::setw(6) << std::left << (costPlus1 - 1) << " " << nodep << '\n'; iterateChildrenConst(nodep); @@ -320,6 +320,6 @@ private: uint32_t V3InstrCount::count(AstNode* nodep, bool assertNoDups, std::ostream* osp) { const InstrCountVisitor visitor{nodep, assertNoDups, osp}; - if (osp) InstrCountDumpVisitor dumper{nodep, osp}; + if (osp) const InstrCountDumpVisitor dumper{nodep, osp}; return visitor.instrCount(); } diff --git a/src/V3LibMap.cpp b/src/V3LibMap.cpp index b7e3803fd..5a2e153b3 100644 --- a/src/V3LibMap.cpp +++ b/src/V3LibMap.cpp @@ -88,7 +88,7 @@ string V3LibMap::matchMapping(const string& filename) { void V3LibMap::addPattern(const string& pattern, const string& libname, const string& base) { UINFO(4, __FUNCTION__ << ": pattern '" << pattern << "' => library '" << libname << "'"); - bool isIncDir = pattern.back() == '/'; + const bool isIncDir = pattern.back() == '/'; const string& nondir = V3Os::filenameNonDir(pattern); const string& cleanPattern = V3Os::filenameCleanup(pattern); diff --git a/src/V3LiftExpr.cpp b/src/V3LiftExpr.cpp index 544ab93cd..d6bd9e7c2 100644 --- a/src/V3LiftExpr.cpp +++ b/src/V3LiftExpr.cpp @@ -487,6 +487,6 @@ public: void V3LiftExpr::liftExprAll(AstNetlist* nodep) { UINFO(2, __FUNCTION__ << ":"); - LiftExprVisitor{nodep}; + { LiftExprVisitor{nodep}; } V3Global::dumpCheckGlobalTree("lift_expr", 0, dumpTreeEitherLevel() >= 3); } diff --git a/src/V3LinkCells.cpp b/src/V3LinkCells.cpp index ccdbdc61a..3eb3cc60e 100644 --- a/src/V3LinkCells.cpp +++ b/src/V3LinkCells.cpp @@ -271,7 +271,7 @@ class LinkCellsVisitor final : public VNVisitor { AstNodeModule* findModuleSym(const string& modName, const string& libname) { // Given module and library to start search in, resolve using config library choices AstNodeModule* foundp; - string fullName = libname + "." + modName; + const std::string fullName = libname + "." + modName; // First search cell-specific use list const auto itCellUseList = m_state.m_uselistCell.find(fullName); if (itCellUseList != m_state.m_uselistCell.end()) { diff --git a/src/V3LinkDot.cpp b/src/V3LinkDot.cpp index 0c088ffee..5d368024d 100644 --- a/src/V3LinkDot.cpp +++ b/src/V3LinkDot.cpp @@ -265,7 +265,7 @@ public: // ACCESSORS VSymGraph* symsp() { return &m_syms; } - int stepNumber() const { return int(m_step); } + int stepNumber() const { return static_cast(m_step); } bool forPrimary() const { return m_step == LDS_PRIMARY; } bool forParamed() const { return m_step == LDS_PARAMED; } bool forPrearray() const { return m_step == LDS_PARAMED || m_step == LDS_PRIMARY; } @@ -587,7 +587,7 @@ public: if (newIfacep && newIfacep != ifacerefp->ifaceViaCellp()) { UINFO(4, " REPAIR-IFACE-REF var=" << varp->prettyNameQ() << " old=" << ifacerefp->ifacep()->prettyNameQ() - << " new=" << newIfacep->prettyNameQ() << endl); + << " new=" << newIfacep->prettyNameQ()); ifacerefp->ifacep(newIfacep); return true; } @@ -755,9 +755,9 @@ public: string leftname = dotname; okSymp = lookupSymp; // So can list bad scopes while (leftname != "") { // foreach dotted part of xref name - string::size_type pos; + string::size_type pos = leftname.find('.'); string ident; - if ((pos = leftname.find('.')) != string::npos) { + if (pos != string::npos) { ident = leftname.substr(0, pos); leftname = leftname.substr(pos + 1); } else { @@ -1110,7 +1110,7 @@ class LinkDotFindVisitor final : public VNVisitor { m_statep->insertBlock(m_curSymp, newp->name(), newp, m_classOrPackagep); } - bool isHierBlockWrapper(const string& name) const { + static bool isHierBlockWrapper(const string& name) { const V3HierBlockOptSet& hierBlocks = v3Global.opt.hierBlocks(); return hierBlocks.find(name) != hierBlocks.end(); } @@ -1377,8 +1377,8 @@ class LinkDotFindVisitor final : public VNVisitor { // Where do we add it? VSymEnt* aboveSymp = m_curSymp; const string origname = AstNode::dedotName(nodep->name()); - string::size_type pos; - if ((pos = origname.rfind('.')) != string::npos) { + string::size_type pos = origname.rfind('.'); + if (pos != string::npos) { // Flattened, find what CellInline it should live under const string scope = origname.substr(0, pos); string baddot; @@ -1402,8 +1402,8 @@ class LinkDotFindVisitor final : public VNVisitor { VSymEnt* aboveSymp = m_curSymp; // If baz__DOT__foo__DOT__bar, we need to find baz__DOT__foo and add bar to it. const string dottedname = nodep->name(); - string::size_type pos; - if ((pos = dottedname.rfind("__DOT__")) != string::npos) { + string::size_type pos = dottedname.rfind("__DOT__"); + if (pos != string::npos) { const string dotted = dottedname.substr(0, pos); const string ident = dottedname.substr(pos + std::strlen("__DOT__")); string baddot; @@ -1511,7 +1511,7 @@ class LinkDotFindVisitor final : public VNVisitor { // rewriting port-prefixed references in the body. void moveIfaceExportBody(AstNodeFTask* nodep) { const string& portName = nodep->ifacePortName(); - UINFO(5, " moveIfaceExportBody: port=" << portName << " task=" << nodep->name() << endl); + UINFO(5, " moveIfaceExportBody: port=" << portName << " task=" << nodep->name()); // Look up the interface port variable in the module's symbol table VSymEnt* const portSymp = m_modSymp->findIdFallback(portName); if (!portSymp) { @@ -1541,7 +1541,7 @@ class LinkDotFindVisitor final : public VNVisitor { return; } const string ifaceName = ifaceRefDtp->ifaceName(); - UINFO(5, " moveIfaceExportBody: iface=" << ifaceName << endl); + UINFO(5, " moveIfaceExportBody: iface=" << ifaceName); // Find the interface module by name AstNodeModule* const ifaceModp = m_statep->findModuleSym(ifaceName); if (!ifaceModp) { @@ -1599,8 +1599,7 @@ class LinkDotFindVisitor final : public VNVisitor { if (!dotp->colon()) { const AstParseRef* const lhsRefp = VN_CAST(dotp->lhsp(), ParseRef); if (lhsRefp && lhsRefp->name() == portName) { - UINFO(5, - " rewriteIfacePortRefs: stripping port prefix from " << dotp << endl); + UINFO(5, " rewriteIfacePortRefs: stripping port prefix from " << dotp); AstNode* const rhsp = dotp->rhsp()->unlinkFrBack(); dotp->replaceWith(rhsp); VL_DO_DANGLING(dotp->deleteTree(), dotp); @@ -2875,13 +2874,13 @@ class LinkDotIfaceVisitor final : public VNVisitor { curOkSymp = remainingOkSymp; } - UINFO(1, "Nested interface resolution depth limit exceeded at " << fl << endl); + UINFO(1, "Nested interface resolution depth limit exceeded at " << fl); return nullptr; } // Resolve a modport expression to find the referenced symbol VSymEnt* resolveModportExpression(FileLine* fl, AstNodeExpr* exprp) { - UINFO(5, " resolveModportExpression: " << exprp << endl); + UINFO(5, " resolveModportExpression: " << exprp); VSymEnt* symp = nullptr; if (AstParseRef* const refp = VN_CAST(exprp, ParseRef)) { // Simple variable reference: modport mp(input .a(sig_a)) @@ -3244,7 +3243,7 @@ class LinkDotResolveVisitor final : public VNVisitor { = m_ds.m_dotSymp ? VN_CAST(m_ds.m_dotSymp->nodep(), Cell) : nullptr; if (!cellForCapture) return; UINFO(9, indent() << "iface capture add paramtype " << nodep - << " iface=" << defOwnerModp->prettyNameQ() << endl); + << " iface=" << defOwnerModp->prettyNameQ()); V3LinkDotIfaceCapture::addParamType(nodep, cellForCapture->name(), m_modp, defp, defOwnerModp->name(), capEntryp ? capEntryp->ifacePortVarp : nullptr); @@ -3370,7 +3369,7 @@ class LinkDotResolveVisitor final : public VNVisitor { return dotSymp; } - bool isParamedClassRefDType(const AstNode* classp) { + static bool isParamedClassRefDType(const AstNode* classp) { while (const AstRefDType* const refp = VN_CAST(classp, RefDType)) classp = refp->subDTypep(); return (VN_IS(classp, ClassRefDType) && VN_AS(classp, ClassRefDType)->paramsp()) @@ -3405,7 +3404,7 @@ class LinkDotResolveVisitor final : public VNVisitor { const VSymEnt* const foundp = m_curSymp->findIdFlat(baseSubp->name()); const AstNodeFTask* const baseFuncp = VN_CAST(baseSubp, NodeFTask); if (!baseFuncp || !baseFuncp->pureVirtual()) continue; - bool existsInDerived = foundp && !foundp->imported(); + const bool existsInDerived = foundp && !foundp->imported(); if (m_statep->forPrimary() && !existsInDerived && !derivedClassp->isInterfaceClass()) { derivedClassp->v3error( @@ -3438,7 +3437,7 @@ class LinkDotResolveVisitor final : public VNVisitor { const VSymEnt* const foundp = m_curSymp->findIdFlat(baseSubp->name()); const AstConstraint* const baseFuncp = VN_CAST(baseSubp, Constraint); if (!baseFuncp || !baseFuncp->isKwdPure()) continue; - bool existsInDerived = foundp && !foundp->imported(); + const bool existsInDerived = foundp && !foundp->imported(); if (m_statep->forPrimary() && !existsInDerived && !derivedClassp->isInterfaceClass() && !derivedClassp->isVirtual()) { derivedClassp->v3error( @@ -3469,7 +3468,7 @@ class LinkDotResolveVisitor final : public VNVisitor { } void checkDeclOrder(AstNode* nodep, AstNode* declp) { - uint32_t declTokenNum = declp->declTokenNum(); + const uint32_t declTokenNum = declp->declTokenNum(); if (!declTokenNum) return; // Not implemented/valid on this object if (nodep->fileline()->tokenNum() < declTokenNum) { UINFO(1, "Related node " << nodep->fileline()->tokenNum() << " " << nodep); @@ -6114,7 +6113,8 @@ public: // refp pointers to deleted AST nodes, so iterating it is unsafe. iterate(rootp); - std::map modulesToRevisit = std::move(m_modulesToRevisit); + const std::map modulesToRevisit + = std::move(m_modulesToRevisit); m_lastDeferredp = nullptr; for (auto& p : modulesToRevisit) { AstNodeModule* const modp = p.second; @@ -6166,7 +6166,7 @@ void V3LinkDot::linkDotGuts(AstNetlist* rootp, VLinkDotStep step) { state.computeIfaceVarSyms(); state.computeScopeAliases(); state.dumpSelf("linkdot-preresolve"); - LinkDotResolveVisitor visitor{rootp, &state}; + const LinkDotResolveVisitor visitor{rootp, &state}; state.dumpSelf("linkdot-done"); } diff --git a/src/V3LinkDotIfaceCapture.cpp b/src/V3LinkDotIfaceCapture.cpp index dde304e2b..8cde2845b 100644 --- a/src/V3LinkDotIfaceCapture.cpp +++ b/src/V3LinkDotIfaceCapture.cpp @@ -557,7 +557,7 @@ void V3LinkDotIfaceCapture::forEachImpl(T_FilterFn&& filter, T_Fn&& fn) { for (const CaptureKey& key : keys) { const auto it = s_map.find(key); if (it == s_map.end()) continue; - CapturedEntry& entry = it->second; + const CapturedEntry& entry = it->second; if (!filter(entry)) continue; fn(entry); } @@ -835,7 +835,7 @@ public: int V3LinkDotIfaceCapture::fixDeadRefsInTypeTable() { if (!v3Global.rootp()->typeTablep()) return 0; - TypeTableDeadRefVisitor visitor{v3Global.rootp()->typeTablep()}; + const TypeTableDeadRefVisitor visitor{v3Global.rootp()->typeTablep()}; return visitor.fixed(); } diff --git a/src/V3LinkLevel.cpp b/src/V3LinkLevel.cpp index c6a5621d2..b3c7bf258 100644 --- a/src/V3LinkLevel.cpp +++ b/src/V3LinkLevel.cpp @@ -60,7 +60,7 @@ void V3LinkLevel::modSortByLevel() { VL_REQUIRES(V3Error::s().m_mutex) -> std::string { std::stringstream ss; for (AstNode* alsop : tops) { - ss << secp->warnMore() << "... Top module " << alsop->prettyNameQ() << endl + ss << secp->warnMore() << "... Top module " << alsop->prettyNameQ() << '\n' << alsop->warnContextSecondary(); } return ss.str(); diff --git a/src/V3Mutex.h b/src/V3Mutex.h index 7cab9caa3..2c17e6c59 100644 --- a/src/V3Mutex.h +++ b/src/V3Mutex.h @@ -70,7 +70,7 @@ public: std::abort(); // LCOV_EXCL_LINE } } - bool enable() VL_MT_SAFE { return m_enable; } + bool enable() const VL_MT_SAFE { return m_enable; } }; /// Mutex, wrapped to allow -fthread_safety checks diff --git a/src/V3Number.cpp b/src/V3Number.cpp index 6a5c415be..901ed2d39 100644 --- a/src/V3Number.cpp +++ b/src/V3Number.cpp @@ -719,7 +719,7 @@ string V3Number::displayed(FileLine* fl, const string& vformat, : formatAttr.isSigned() ? toSQuad() : toUQuad(); char tmp[MAX_SPRINTF_DOUBLE_SIZE]; - VL_SNPRINTF(tmp, MAX_SPRINTF_DOUBLE_SIZE, vformat.c_str(), n); + (void)VL_SNPRINTF(tmp, MAX_SPRINTF_DOUBLE_SIZE, vformat.c_str(), n); return tmp; } case 's': { @@ -751,7 +751,7 @@ string V3Number::displayed(FileLine* fl, const string& vformat, : formatAttr.isSigned() ? toSQuad() : toUQuad(); char tmp[MAX_SPRINTF_DOUBLE_SIZE]; - VL_SNPRINTF(tmp, MAX_SPRINTF_DOUBLE_SIZE, "%g", n); + (void)VL_SNPRINTF(tmp, MAX_SPRINTF_DOUBLE_SIZE, "%g", n); return tmp; } if (formatAttr.isString()) return '"' + toString() + '"'; @@ -853,7 +853,7 @@ string V3Number::displayed(FileLine* fl, const string& vformat, // which is (+1.0 is for rounding bias): double dchars = mantissabits / 3.321928094887362 + 1.0; if (issigned) ++dchars; // space for sign - fmtsize = cvtToStr(int(dchars)); + fmtsize = cvtToStr(static_cast(dchars)); } bool hasXZ = false; if (isAllX()) { @@ -953,7 +953,7 @@ string V3Number::emitC() const VL_MT_STABLE { const char* const fmt = (static_cast(dnum) == dnum && -1000 < dnum && dnum < 1000) ? "%3.1f" // Force decimal point : "%.17e"; // %e always yields a float literal - VL_SNPRINTF(sbuf, bufsize, fmt, dnum); + (void)VL_SNPRINTF(sbuf, bufsize, fmt, dnum); return sbuf; } } else if (isString()) { @@ -970,7 +970,7 @@ string V3Number::emitC() const VL_MT_STABLE { if (words() > 4) result += '\n'; for (int n = 0; n < words(); ++n) { if (n) result += ((n % 4) ? ", " : ",\n"); - VL_SNPRINTF(sbuf, bufsize, "0x%08" PRIx32, edataWord(n)); + (void)VL_SNPRINTF(sbuf, bufsize, "0x%08" PRIx32, edataWord(n)); result += sbuf; } if (words() > 4) result += '\n'; @@ -979,7 +979,7 @@ string V3Number::emitC() const VL_MT_STABLE { const uint64_t qnum = static_cast(toUQuad()); const char* const fmt = (qnum < 10) ? ("%" PRIx64 "ULL") : ("0x%016" PRIx64 "ULL"); // cppcheck-suppress wrongPrintfScanfArgNum - VL_SNPRINTF(sbuf, bufsize, fmt, qnum); + (void)VL_SNPRINTF(sbuf, bufsize, fmt, qnum); return sbuf; } else { // Always emit unsigned, if signed, will call correct signed functions @@ -990,7 +990,7 @@ string V3Number::emitC() const VL_MT_STABLE { : (width() > 8) ? ("0x%04" PRIx32 "U") : ("0x%02" PRIx32 "U"); // cppcheck-suppress wrongPrintfScanfArgNum - VL_SNPRINTF(sbuf, bufsize, fmt, unum); + (void)VL_SNPRINTF(sbuf, bufsize, fmt, unum); return sbuf; } return result; @@ -1587,7 +1587,8 @@ V3Number& V3Number::opRepl(const V3Number& lhs, // i op repl, L(i)*value(rhs) bit return NUM_ASSERT_OP_ARGS1(lhs); NUM_ASSERT_LOGIC_ARGS1(lhs); - if (v3Global.opt.replicationLimit() && rhsval > (uint32_t)v3Global.opt.replicationLimit()) { + if (v3Global.opt.replicationLimit() + && rhsval > static_cast(v3Global.opt.replicationLimit())) { v3warn(WIDTHCONCAT, "Replication of more that --replication-limit " << v3Global.opt.replicationLimit() << " is suspect: " << rhsval); } @@ -2661,13 +2662,13 @@ V3Number& V3Number::opReplN(const V3Number& lhs, uint32_t rhsval) { V3Number& V3Number::opToLowerN(const V3Number& lhs) { NUM_ASSERT_OP_ARGS1(lhs); NUM_ASSERT_STRING_ARGS1(lhs); - std::string out = VString::downcase(lhs.toString()); + const std::string out = VString::downcase(lhs.toString()); return setString(out); } V3Number& V3Number::opToUpperN(const V3Number& lhs) { NUM_ASSERT_OP_ARGS1(lhs); NUM_ASSERT_STRING_ARGS1(lhs); - std::string out = VString::upcase(lhs.toString()); + const std::string out = VString::upcase(lhs.toString()); return setString(out); } @@ -2714,24 +2715,24 @@ void V3Number::selfTest() { void V3Number::selfTestThis() { // The self test has a "this" so UASSERT_SELFTEST/errorEndFatal works correctly - UASSERT_SELFTEST(bool, V3Number::epsilonEqual(0, 0), true); - UASSERT_SELFTEST(bool, V3Number::epsilonEqual(1e19, 1e19), true); - UASSERT_SELFTEST(bool, V3Number::epsilonEqual(9, 0.0001), false); - UASSERT_SELFTEST(bool, V3Number::epsilonEqual(1, 1 + std::numeric_limits::epsilon()), - true); - UASSERT_SELFTEST(bool, V3Number::epsilonEqual(0.009, 0.00899999999999999931998839741709), + UASSERT_SELFTEST(const bool, V3Number::epsilonEqual(0, 0), true); + UASSERT_SELFTEST(const bool, V3Number::epsilonEqual(1e19, 1e19), true); + UASSERT_SELFTEST(const bool, V3Number::epsilonEqual(9, 0.0001), false); + UASSERT_SELFTEST(const bool, + V3Number::epsilonEqual(1, 1 + std::numeric_limits::epsilon()), true); + UASSERT_SELFTEST(const bool, V3Number::epsilonEqual(0.009, 0.00899999999999999931998839741709), true); - UASSERT_SELFTEST(bool, V3Number::epsilonIntegral(0), true); - UASSERT_SELFTEST(bool, V3Number::epsilonIntegral(1), true); - UASSERT_SELFTEST(bool, V3Number::epsilonIntegral(-1), true); - UASSERT_SELFTEST(bool, V3Number::epsilonIntegral(1.0001), false); - UASSERT_SELFTEST(bool, V3Number::epsilonIntegral(0.9999), false); - UASSERT_SELFTEST(bool, V3Number::epsilonIntegral(-1.0001), false); - UASSERT_SELFTEST(bool, V3Number::epsilonIntegral(-0.9999), false); + UASSERT_SELFTEST(const bool, V3Number::epsilonIntegral(0), true); + UASSERT_SELFTEST(const bool, V3Number::epsilonIntegral(1), true); + UASSERT_SELFTEST(const bool, V3Number::epsilonIntegral(-1), true); + UASSERT_SELFTEST(const bool, V3Number::epsilonIntegral(1.0001), false); + UASSERT_SELFTEST(const bool, V3Number::epsilonIntegral(0.9999), false); + UASSERT_SELFTEST(const bool, V3Number::epsilonIntegral(-1.0001), false); + UASSERT_SELFTEST(const bool, V3Number::epsilonIntegral(-0.9999), false); - UASSERT_SELFTEST(int, log2b(0), 0); - UASSERT_SELFTEST(int, log2b(1), 0); - UASSERT_SELFTEST(int, log2b(0x40000000UL), 30); - UASSERT_SELFTEST(int, log2bQuad(0x4000000000000000ULL), 62); + UASSERT_SELFTEST(const int, log2b(0), 0); + UASSERT_SELFTEST(const int, log2b(1), 0); + UASSERT_SELFTEST(const int, log2b(0x40000000UL), 30); + UASSERT_SELFTEST(const int, log2bQuad(0x4000000000000000ULL), 62); } diff --git a/src/V3Number.h b/src/V3Number.h index a088219ef..21a917bea 100644 --- a/src/V3Number.h +++ b/src/V3Number.h @@ -135,7 +135,6 @@ public: bool m_fromString : 1; // True if from string literal bool m_autoExtend : 1; // True if SystemVerilog extend-to-any-width -public: // CONSTRUCTORS V3NumberData() : m_type{V3NumberDataType::UNINITIALIZED} @@ -580,7 +579,7 @@ public: V3Number(V3Number&& other) = default; V3Number& operator=(V3Number&& other) = default; - ~V3Number() {} + ~V3Number() = default; private: void selfTestThis(); diff --git a/src/V3OptionParser.cpp b/src/V3OptionParser.cpp index eb9b73d5b..84a6c20ba 100644 --- a/src/V3OptionParser.cpp +++ b/src/V3OptionParser.cpp @@ -213,7 +213,8 @@ std::pair V3OptionParser::parse(int idx, int argc, char* argv[]) { if (!actp->isValueNeeded()) { actp->exec(optp, nullptr); return {1, !actp->isNotForRerun()}; - } else if (idx + 1 < argc) { + } + if (idx + 1 < argc) { actp->exec(optp, argv[idx + 1]); return {2, !actp->isNotForRerun()}; } diff --git a/src/V3Options.cpp b/src/V3Options.cpp index 73d3b8f0e..f0b9a77f6 100644 --- a/src/V3Options.cpp +++ b/src/V3Options.cpp @@ -385,7 +385,7 @@ void V3Options::addLibraryFile(const string& filename, const string& libname) { void V3Options::addVFile(const string& filename, const string& libname) { // We use a list for v files, because it's legal to have includes // in a specific order and multiple of them. - m_vFiles.push_back({filename, libname}); + m_vFiles.push_back({filename, libname}); // Not emplace } void V3Options::addVltFile(const string& filename, const string& libname) { m_vltFiles.insert({filename, libname}); @@ -677,7 +677,7 @@ string V3Options::filePath(FileLine* fl, const string& modname, const string& la return ""; } -string V3Options::filePathLookedMsg(FileLine* fl, const string& modname) { +string V3Options::filePathLookedMsg(FileLine* /*fl*/, const string& modname) { static bool s_shown_notfound_msg = false; std::ostringstream ss; if (modname.find("__Vhsh") != string::npos) { @@ -775,7 +775,7 @@ string V3Options::getenvSYSTEMC() { string var = V3Os::getenvStr("SYSTEMC", ""); // Treat compiled-in DEFENV string literals as C-strings to enable // binary patching for relocatable installs (e.g. conda) - string defenv = string{DEFENV_SYSTEMC}.c_str(); + const string defenv = string{DEFENV_SYSTEMC}; if (var == "" && defenv != "") { var = defenv; V3Os::setenvStr("SYSTEMC", var, "Hardcoded at build time"); @@ -787,7 +787,7 @@ string V3Options::getenvSYSTEMC_ARCH() { string var = V3Os::getenvStr("SYSTEMC_ARCH", ""); // Treat compiled-in DEFENV string literals as C-strings to enable // binary patching for relocatable installs (e.g. conda) - string defenv = string{DEFENV_SYSTEMC_ARCH}.c_str(); + const string defenv = string{DEFENV_SYSTEMC_ARCH}; if (var == "" && defenv != "") { var = defenv; V3Os::setenvStr("SYSTEMC_ARCH", var, "Hardcoded at build time"); @@ -822,7 +822,7 @@ string V3Options::getenvSYSTEMC_INCLUDE() { string var = V3Os::getenvStr("SYSTEMC_INCLUDE", ""); // Treat compiled-in DEFENV string literals as C-strings to enable // binary patching for relocatable installs (e.g. conda) - string defenv = string{DEFENV_SYSTEMC_INCLUDE}.c_str(); + const string defenv = string{DEFENV_SYSTEMC_INCLUDE}; if (var == "" && defenv != "") { var = defenv; V3Os::setenvStr("SYSTEMC_INCLUDE", var, "Hardcoded at build time"); @@ -838,7 +838,7 @@ string V3Options::getenvSYSTEMC_LIBDIR() { string var = V3Os::getenvStr("SYSTEMC_LIBDIR", ""); // Treat compiled-in DEFENV string literals as C-strings to enable // binary patching for relocatable installs (e.g. conda) - string defenv = string{DEFENV_SYSTEMC_LIBDIR}.c_str(); + const string defenv = string{DEFENV_SYSTEMC_LIBDIR}; if (var == "" && defenv != "") { var = defenv; V3Os::setenvStr("SYSTEMC_LIBDIR", var, "Hardcoded at build time"); @@ -855,7 +855,7 @@ string V3Options::getenvVERILATOR_ROOT() { string var = V3Os::getenvStr("VERILATOR_ROOT", ""); // Treat compiled-in DEFENV string literals as C-strings to enable // binary patching for relocatable installs (e.g. conda) - string defenv = string{DEFENV_VERILATOR_ROOT}.c_str(); + const string defenv = string{DEFENV_VERILATOR_ROOT}; if (var == "" && defenv != "") { var = defenv; V3Os::setenvStr("VERILATOR_ROOT", var, "Hardcoded at build time"); @@ -868,7 +868,7 @@ string V3Options::getenvVERILATOR_SOLVER() { string var = V3Os::getenvStr("VERILATOR_SOLVER", ""); // Treat compiled-in DEFENV string literals as C-strings to enable // binary patching for relocatable installs (e.g. conda) - string defenv = string{DEFENV_VERILATOR_SOLVER}.c_str(); + const string defenv = string{DEFENV_VERILATOR_SOLVER}; if (var == "" && defenv != "") { var = defenv; V3Os::setenvStr("VERILATOR_SOLVER", var, "Hardcoded at build time"); @@ -958,14 +958,14 @@ void V3Options::notify() VL_MT_DISABLED { std::vector backendFlags; if (m_build) { if (m_binary) - backendFlags.push_back("--binary"); + backendFlags.emplace_back("--binary"); else - backendFlags.push_back("--build"); + backendFlags.emplace_back("--build"); } - if (m_preprocOnly) backendFlags.push_back("-E"); - if (m_dpiHdrOnly) backendFlags.push_back("--dpi-hdr-only"); - if (m_lintOnly) backendFlags.push_back("--lint-only"); - if (m_jsonOnly) backendFlags.push_back("--json-only"); + if (m_preprocOnly) backendFlags.emplace_back("-E"); + if (m_dpiHdrOnly) backendFlags.emplace_back("--dpi-hdr-only"); + if (m_lintOnly) backendFlags.emplace_back("--lint-only"); + if (m_jsonOnly) backendFlags.emplace_back("--json-only"); if (backendFlags.size() > 1) { std::string backendFlagsString = backendFlags.front(); for (size_t i = 1; i < backendFlags.size(); i++) { @@ -1509,15 +1509,15 @@ void V3Options::parseOptsList(FileLine* fl, const string& optdir, int argc, DECL_OPTION("-gdb", CbCall, []() {}); // Processed only in bin/verilator shell DECL_OPTION("-gdbbt", CbCall, []() {}); // Processed only in bin/verilator shell DECL_OPTION("-generate-key", CbCall, [this]() { - cout << protectKeyDefaulted() << endl; + cout << protectKeyDefaulted() << '\n'; v3Global.vlExit(0); }); DECL_OPTION("-getenv", CbVal, [](const char* valp) { - cout << V3Options::getenvBuiltins(valp) << endl; + cout << V3Options::getenvBuiltins(valp) << '\n'; v3Global.vlExit(0); }); DECL_OPTION("-get-supported", CbVal, [](const char* valp) { - cout << V3Options::getSupported(valp) << endl; + cout << V3Options::getSupported(valp) << '\n'; v3Global.vlExit(0); }); diff --git a/src/V3Options.h b/src/V3Options.h index cde9bf40f..bfe27f491 100644 --- a/src/V3Options.h +++ b/src/V3Options.h @@ -70,9 +70,7 @@ public: VFileLibName(const string& filename, const string& libname) : m_filename{filename} , m_libname{libname} {} - VFileLibName(const VFileLibName& rhs) - : m_filename{rhs.m_filename} - , m_libname{rhs.m_libname} {} + VFileLibName(const VFileLibName& rhs) = default; string filename() const { return m_filename; } string libname() const { return m_libname; } bool operator==(const VFileLibName& rhs) const { @@ -436,7 +434,6 @@ private: bool m_available = false; // Set to true at the end of option parsing -private: // METHODS void addArg(char** argv, size_t count, bool isForRerun); void addArg(const std::string& arg, bool isForRerun); @@ -665,7 +662,7 @@ public: string jsonOnlyMetaOutput() const { return m_jsonOnlyMetaOutput; } string l2Name() const { return m_l2Name; } string libCreate() const { return m_libCreate; } - string libCreateName(bool shared) { + string libCreateName(bool shared) const { string libName = "lib" + libCreate(); if (shared) { libName += ".so"; diff --git a/src/V3OrderParallel.cpp b/src/V3OrderParallel.cpp index beefae02e..02ab788d0 100644 --- a/src/V3OrderParallel.cpp +++ b/src/V3OrderParallel.cpp @@ -1637,7 +1637,7 @@ private: chain_len * 2, nullptr, nullptr, /* slowAsserts: */ false); // All vertices should merge into one - UASSERT_SELFTEST(bool, mTaskGraph.vertices().hasSingleElement(), true); + UASSERT_SELFTEST(const bool, mTaskGraph.vertices().hasSingleElement(), true); const uint64_t endUsecs = V3Os::timeUsecs(); const uint64_t elapsedUsecs = endUsecs - startUsecs; @@ -1686,10 +1686,10 @@ private: // Checking exact values here is maybe overly precise. What we're // mostly looking for is a healthy reduction in the number of mTaskGraphp. - UASSERT_SELFTEST(uint64_t, report.criticalPathCost(), 19); - UASSERT_SELFTEST(uint64_t, report.totalGraphCost(), 101); - UASSERT_SELFTEST(uint64_t, report.vertexCount(), 14); - UASSERT_SELFTEST(uint64_t, report.edgeCount(), 13); + UASSERT_SELFTEST(const uint64_t, report.criticalPathCost(), 19); + UASSERT_SELFTEST(const uint64_t, report.totalGraphCost(), 101); + UASSERT_SELFTEST(const uint64_t, report.vertexCount(), 14); + UASSERT_SELFTEST(const uint64_t, report.edgeCount(), 13); } public: @@ -2244,7 +2244,7 @@ class Partitioner final { }; // Iterate downstream direct dependents - for (V3GraphEdge& dEdge : mVtxp->outEdges()) { + for (const V3GraphEdge& dEdge : mVtxp->outEdges()) { V3GraphVertex* const top = dEdge.top(); if (LogicMTask* const otherp = static_cast(top->userp())) { // The opposite end of the edge is not a bypassed vertex, add as direct @@ -2252,7 +2252,7 @@ class Partitioner final { addEdge(otherp); } else { // The opposite end of the edge is a bypassed vertex, add transitive dependents - for (V3GraphEdge& tEdge : top->outEdges()) { + for (const V3GraphEdge& tEdge : top->outEdges()) { LogicMTask* const transp = static_cast(tEdge.top()->userp()); // The Move graph is bipartite (logic <-> var), and logic is never // bypassed, hence 'transp' must be non-nullptr. @@ -2359,7 +2359,7 @@ class Partitioner final { OrderMoveVertex::List& vertexList = mtaskp->vertexList(); // Check if MTask is empty bool empty = true; - for (OrderMoveVertex& mVtx : vertexList) { + for (const OrderMoveVertex& mVtx : vertexList) { if (mVtx.logicp()) { empty = false; break; diff --git a/src/V3Os.cpp b/src/V3Os.cpp index f0b8a8764..7891dd102 100644 --- a/src/V3Os.cpp +++ b/src/V3Os.cpp @@ -20,7 +20,7 @@ # define PSAPI_VERSION 1 // Needed for compatibility with Windows 7 # endif #endif -#if defined(__MINGW32__) +#ifndef __MINGW32__ # define MINGW_HAS_SECURE_API 1 // Needed to expose a "secure" POSIX-like API #endif // clang-format on @@ -150,12 +150,9 @@ string V3Os::filenameCleanup(const string& filename) VL_PURE { string V3Os::filenameJoin(std::initializer_list paths) VL_PURE { string fullpath; for (const auto& item : paths) { - if (item.empty() || item == ".") { - continue; - } else { - if (!fullpath.empty()) fullpath += V3OS_SLASH; - fullpath += item; - } + if (item.empty() || item == ".") continue; + if (!fullpath.empty()) fullpath += V3OS_SLASH; + fullpath += item; } return fullpath; } @@ -166,22 +163,18 @@ string V3Os::filenameDir(const string& filename) VL_PURE { for (; it != filename.rend(); ++it) { if (isSlash(*it)) break; } - if (it.base() == filename.begin()) { - return "."; - } else { - return string{filename.begin(), (++it).base()}; - } + if (it.base() == filename.begin()) return "."; + return string{filename.begin(), (++it).base()}; } string V3Os::filenameExt(const string& filename) VL_PURE { string base = filenameNonDir(filename); - string::size_type pos; - if ((pos = base.find('.')) != string::npos) { + const string::size_type pos = base.find('.'); + if (pos != string::npos) { base.erase(0, pos); return base; - } else { - return ""; } + return ""; } string V3Os::filenameNonDir(const string& filename) VL_PURE { @@ -195,8 +188,8 @@ string V3Os::filenameNonDir(const string& filename) VL_PURE { string V3Os::filenameNonDirExt(const string& filename) VL_PURE { string base = filenameNonDir(filename); - string::size_type pos; - if ((pos = base.find('.')) != string::npos) base.erase(pos); + const string::size_type pos = base.find('.'); + if (pos != string::npos) base.erase(pos); return base; } @@ -256,9 +249,8 @@ string V3Os::filenameRealPath(const string& filename) VL_PURE { #endif ) { return std::string{retpath}; - } else { - return filename; } + return filename; } string V3Os::filenameRelativePath(const string& filename, const string& base) VL_PURE { @@ -318,13 +310,13 @@ bool V3Os::filenameIsRel(const string& filename) VL_PURE { #endif } -string V3Os::filenameSlashPath(const string& path) VL_PURE { +string V3Os::filenameSlashPath(const string& filename) VL_PURE { #if defined(_WIN32) || defined(__MINGW32__) - string slashedPath = path; + string slashedPath = filename; std::replace(slashedPath.begin(), slashedPath.end(), '\\', '/'); return slashedPath; #else - return path; + return filename; #endif } @@ -333,7 +325,7 @@ string V3Os::filenameSlashPath(const string& path) VL_PURE { string V3Os::getline(std::istream& is, char delim) { string line; -#if defined(__CYGWIN__) // Work around buggy implementation of getline +#ifdef __CYGWIN__ // Work around buggy implementation of getline char buf[65536]; is.getline(buf, 65535, delim); line = buf; @@ -365,7 +357,7 @@ void V3Os::filesystemFlush(const string& dirname) { // Faster to just try both rather than check if a file is a dir. if (DIR* const dirp = opendir(dirname.c_str())) { // LCOV_EXCL_BR_LINE closedir(dirp); // LCOV_EXCL_LINE - } else if (int fd = ::open(dirname.c_str(), O_RDONLY)) { // LCOV_EXCL_BR_LINE + } else if (const int fd = ::open(dirname.c_str(), O_RDONLY)) { // LCOV_EXCL_BR_LINE if (fd > 0) ::close(fd); } #endif @@ -425,7 +417,7 @@ void V3Os::releaseMemory() { } char buf[64]; // Index equal to narenas represents all arenas - VL_SNPRINTF(buf, sizeof(buf), "arena.%u.purge", narenas); + (void)VL_SNPRINTF(buf, sizeof(buf), "arena.%u.purge", narenas); mallctl(buf, nullptr, nullptr, nullptr, 0); #endif } @@ -506,53 +498,52 @@ int V3Os::system(const string& command) { v3fatal("Failed to execute command:" // LCOV_EXCL_LINE << command << " " << std::strerror(errno)); // LCOV_EXCL_LINE return -1; // LCOV_EXCL_LINE - } else { - UASSERT(WIFEXITED(ret), "system(" << command << ") returned unexpected value of " << ret); - const int exit_code = WEXITSTATUS(ret); - UINFO(1, command << " returned exit code of " << exit_code); - UASSERT(exit_code >= 0, "exit code must not be negative"); - return exit_code; } + UASSERT(WIFEXITED(ret), "system(" << command << ") returned unexpected value of " << ret); + const int exit_code = WEXITSTATUS(ret); + UINFO(1, command << " returned exit code of " << exit_code); + UASSERT(exit_code >= 0, "exit code must not be negative"); + return exit_code; } void V3Os::selfTest() { #ifdef VL_DEBUG - UASSERT_SELFTEST(string, filenameCleanup(""), ""); - UASSERT_SELFTEST(string, filenameCleanup("."), "."); - UASSERT_SELFTEST(string, filenameCleanup(".."), ".."); - UASSERT_SELFTEST(string, filenameCleanup("/"), "/"); - UASSERT_SELFTEST(string, filenameCleanup("../"), ".."); - UASSERT_SELFTEST(string, filenameCleanup("//"), "/"); - UASSERT_SELFTEST(string, filenameCleanup("//."), "/."); - UASSERT_SELFTEST(string, filenameCleanup("./"), "."); - UASSERT_SELFTEST(string, filenameCleanup("././"), "."); - UASSERT_SELFTEST(string, filenameCleanup(".///"), "."); - UASSERT_SELFTEST(string, filenameCleanup("a"), "a"); - UASSERT_SELFTEST(string, filenameCleanup("a/"), "a"); - UASSERT_SELFTEST(string, filenameCleanup("a/b"), "a/b"); - UASSERT_SELFTEST(string, filenameCleanup("././//./a/b"), "a/b"); - UASSERT_SELFTEST(string, filenameCleanup(".//./a///"), "a"); - UASSERT_SELFTEST(string, filenameCleanup("///a/./b///."), "/a/./b/."); - UASSERT_SELFTEST(string, filenameCleanup("aaa/bbb/ccc/"), "aaa/bbb/ccc"); - UASSERT_SELFTEST(string, filenameCleanup("./aaa/bbb/ccc/"), "aaa/bbb/ccc"); - UASSERT_SELFTEST(string, filenameCleanup("../aaa/bbb/ccc/"), "../aaa/bbb/ccc"); - UASSERT_SELFTEST(string, filenameDir("a.a/b.b/f.e"), "a.a/b.b"); - UASSERT_SELFTEST(string, filenameExt("a.a/b.b/f"), ""); - UASSERT_SELFTEST(string, filenameExt("a.a/b.b/f.e"), ".e"); - UASSERT_SELFTEST(string, filenameNonDirExt("a.a/b.b/f.e"), "f"); - UASSERT_SELFTEST(string, filenameRelativePath("/a/b", "/a/b"), "."); - UASSERT_SELFTEST(string, filenameRelativePath("/a/b", "/a/b/c"), ".."); - UASSERT_SELFTEST(string, filenameRelativePath("/a/b", "/a/b/c/d"), "../.."); - UASSERT_SELFTEST(string, filenameRelativePath("/a/b/x", "/a/b/c/d"), "../../x"); - UASSERT_SELFTEST(string, filenameRelativePath("/a/b/x/y", "/"), "a/b/x/y"); - UASSERT_SELFTEST(string, filenameRelativePath("/a/b/x/y", "/a/b"), "x/y"); - UASSERT_SELFTEST(string, filenameRelativePath("/a/b/x/y", "/a/q"), "../b/x/y"); - UASSERT_SELFTEST(string, filenameRelativePath("a/b", "a/b"), "."); - UASSERT_SELFTEST(string, filenameRelativePath("a/b", "a/b/c"), ".."); - UASSERT_SELFTEST(string, filenameRelativePath("a/b", "a/b/c/d"), "../.."); - UASSERT_SELFTEST(string, filenameRelativePath("a/b/x", "a/b/c/d"), "../../x"); - UASSERT_SELFTEST(string, filenameRelativePath("a/b/x/y", ""), "a/b/x/y"); - UASSERT_SELFTEST(string, filenameRelativePath("a/b/x/y", "a/b"), "x/y"); - UASSERT_SELFTEST(string, filenameRelativePath("a/b/x/y", "a/q"), "../b/x/y"); + UASSERT_SELFTEST(const string, filenameCleanup(""), ""); + UASSERT_SELFTEST(const string, filenameCleanup("."), "."); + UASSERT_SELFTEST(const string, filenameCleanup(".."), ".."); + UASSERT_SELFTEST(const string, filenameCleanup("/"), "/"); + UASSERT_SELFTEST(const string, filenameCleanup("../"), ".."); + UASSERT_SELFTEST(const string, filenameCleanup("//"), "/"); + UASSERT_SELFTEST(const string, filenameCleanup("//."), "/."); + UASSERT_SELFTEST(const string, filenameCleanup("./"), "."); + UASSERT_SELFTEST(const string, filenameCleanup("././"), "."); + UASSERT_SELFTEST(const string, filenameCleanup(".///"), "."); + UASSERT_SELFTEST(const string, filenameCleanup("a"), "a"); + UASSERT_SELFTEST(const string, filenameCleanup("a/"), "a"); + UASSERT_SELFTEST(const string, filenameCleanup("a/b"), "a/b"); + UASSERT_SELFTEST(const string, filenameCleanup("././//./a/b"), "a/b"); + UASSERT_SELFTEST(const string, filenameCleanup(".//./a///"), "a"); + UASSERT_SELFTEST(const string, filenameCleanup("///a/./b///."), "/a/./b/."); + UASSERT_SELFTEST(const string, filenameCleanup("aaa/bbb/ccc/"), "aaa/bbb/ccc"); + UASSERT_SELFTEST(const string, filenameCleanup("./aaa/bbb/ccc/"), "aaa/bbb/ccc"); + UASSERT_SELFTEST(const string, filenameCleanup("../aaa/bbb/ccc/"), "../aaa/bbb/ccc"); + UASSERT_SELFTEST(const string, filenameDir("a.a/b.b/f.e"), "a.a/b.b"); + UASSERT_SELFTEST(const string, filenameExt("a.a/b.b/f"), ""); + UASSERT_SELFTEST(const string, filenameExt("a.a/b.b/f.e"), ".e"); + UASSERT_SELFTEST(const string, filenameNonDirExt("a.a/b.b/f.e"), "f"); + UASSERT_SELFTEST(const string, filenameRelativePath("/a/b", "/a/b"), "."); + UASSERT_SELFTEST(const string, filenameRelativePath("/a/b", "/a/b/c"), ".."); + UASSERT_SELFTEST(const string, filenameRelativePath("/a/b", "/a/b/c/d"), "../.."); + UASSERT_SELFTEST(const string, filenameRelativePath("/a/b/x", "/a/b/c/d"), "../../x"); + UASSERT_SELFTEST(const string, filenameRelativePath("/a/b/x/y", "/"), "a/b/x/y"); + UASSERT_SELFTEST(const string, filenameRelativePath("/a/b/x/y", "/a/b"), "x/y"); + UASSERT_SELFTEST(const string, filenameRelativePath("/a/b/x/y", "/a/q"), "../b/x/y"); + UASSERT_SELFTEST(const string, filenameRelativePath("a/b", "a/b"), "."); + UASSERT_SELFTEST(const string, filenameRelativePath("a/b", "a/b/c"), ".."); + UASSERT_SELFTEST(const string, filenameRelativePath("a/b", "a/b/c/d"), "../.."); + UASSERT_SELFTEST(const string, filenameRelativePath("a/b/x", "a/b/c/d"), "../../x"); + UASSERT_SELFTEST(const string, filenameRelativePath("a/b/x/y", ""), "a/b/x/y"); + UASSERT_SELFTEST(const string, filenameRelativePath("a/b/x/y", "a/b"), "x/y"); + UASSERT_SELFTEST(const string, filenameRelativePath("a/b/x/y", "a/q"), "../b/x/y"); #endif } diff --git a/src/V3PairingHeap.h b/src/V3PairingHeap.h index 4e8daf7a4..f435ac75f 100644 --- a/src/V3PairingHeap.h +++ b/src/V3PairingHeap.h @@ -243,11 +243,10 @@ private: bp->m_next.link(ap->m_kids.unlink()); ap->m_kids.linkNonNull(bp); return ap; - } else { // ap goes under bp - ap->m_next.link(bp->m_kids.unlink()); - bp->m_kids.linkNonNull(ap); - return bp; - } + } // else ap goes under bp + ap->m_next.link(bp->m_kids.unlink()); + bp->m_kids.linkNonNull(ap); + return bp; } // Reduces the list of nodes starting at the given node into a single node that is returned diff --git a/src/V3Param.cpp b/src/V3Param.cpp index 36bd6d2d1..5ea555145 100644 --- a/src/V3Param.cpp +++ b/src/V3Param.cpp @@ -324,7 +324,7 @@ class ParamProcessor final { const char ch = varp->user3() & 255; string st = cvtToStr(ch); while (index) { - st += cvtToStr(char((index % 25) + 'A')); + st += cvtToStr(static_cast((index % 25) + 'A')); index /= 26; } return st; @@ -388,7 +388,7 @@ class ParamProcessor final { << className << " origName=" << origName << " isSpecialized=" << isSpecialized << " hasParams=" << (classRefp->paramsp() ? "Y" : "N") - << " classHasGParam=" << classRefp->classp()->hasGParam() << endl); + << " classHasGParam=" << classRefp->classp()->hasGParam()); if (classRefp->paramsp()) { // ClassRefDType should have been deparameterized (paramsp @@ -459,7 +459,7 @@ class ParamProcessor final { UINFO(4, "Name: " << srcModp->name() << "->" << longname << "->" << newname); return newname; } - AstNodeDType* arraySubDTypep(AstNodeDType* nodep) { + static AstNodeDType* arraySubDTypep(AstNodeDType* nodep) { // If an unpacked array, return the subDTypep under it if (const AstUnpackArrayDType* const adtypep = VN_CAST(nodep, UnpackArrayDType)) { return adtypep->subDTypep(); @@ -472,7 +472,7 @@ class ParamProcessor final { } return nullptr; } - bool isString(AstNodeDType* nodep) { + static bool isString(AstNodeDType* nodep) { if (AstBasicDType* const basicp = VN_CAST(nodep->skipRefToNonRefp(), BasicDType)) return basicp->isString(); return false; @@ -802,7 +802,7 @@ class ParamProcessor final { if (AstVar* const newVarp = VN_CAST(stmtp, Var)) { if (newVarp->name() == varp->name()) { UINFO(9, "VarXRef relink " << varp->name() << " in " << varModp->name() - << " -> " << newIfacep->name() << endl); + << " -> " << newIfacep->name()); nodep->varp(newVarp); break; } @@ -874,7 +874,7 @@ class ParamProcessor final { // Phase A: path-based fixup using ledger entries with cellPath. // Phase B: reachable-set fallback for remaining REFDTYPEs. void fixupCrossModuleRefDTypes(AstNodeModule* newModp, AstNodeModule* srcModp, - AstNode* ifErrorp, const IfaceRefRefs& ifaceRefRefs) { + AstNode* /*ifErrorp*/, const IfaceRefRefs& ifaceRefRefs) { if (!V3LinkDotIfaceCapture::enabled()) return; // Phase A: path-based fixup using ledger entries std::set ledgerFixed; @@ -882,8 +882,8 @@ class ParamProcessor final { // Must match the cloneCellPath used by propagateClone (newname). const string cloneCP = newModp->name(); const string srcName = srcModp->name(); - UINFO(9, "iface capture FIXUP-A: srcName=" << srcName << " cloneCP='" << cloneCP << "'" - << endl); + UINFO(9, + "iface capture FIXUP-A: srcName=" << srcName << " cloneCP='" << cloneCP << "'"); V3LinkDotIfaceCapture::forEach([&](const V3LinkDotIfaceCapture::CapturedEntry& entry) { if (!entry.refp) return; if (entry.cloneCellPath != cloneCP) return; @@ -894,8 +894,7 @@ class ParamProcessor final { AstNodeModule* const correctModp = V3LinkDotIfaceCapture::followCellPath(newModp, entry.cellPath); UINFO(9, " path fixup: " << refp << " cellPath='" << entry.cellPath << "' -> " - << (correctModp ? correctModp->name() : "") - << endl); + << (correctModp ? correctModp->name() : "")); if (!correctModp || correctModp->dead()) return; if (correctModp->parameterizedTemplate()) return; @@ -997,14 +996,14 @@ class ParamProcessor final { if (V3LinkDotIfaceCapture::enabled()) { AstCell* const cloneCellp = VN_CAST(ifErrorp, Cell); UINFO(9, "iface capture clone: " << srcModp->prettyNameQ() << " -> " - << newModp->prettyNameQ() << endl); + << newModp->prettyNameQ()); // First pass: register clone entries and direct-retarget // REFDTYPEs whose owner won't be cloned later. V3LinkDotIfaceCapture::forEachOwned( srcModp, [&](const V3LinkDotIfaceCapture::CapturedEntry& entry) { if (!entry.refp) return; UINFO(9, "iface capture entry: " << entry.refp << " cellPath='" - << entry.cellPath << "'" << endl); + << entry.cellPath << "'"); // Disambiguate via cellPath when cloning the interface // that owns the typedef (matched via typedefOwnerModName). if (cloneCellp && entry.ownerModp != srcModp @@ -1013,7 +1012,7 @@ class ParamProcessor final { "cellPath is empty in entry matched via typedefOwnerModName"); if (!cellPathMatchesClone(entry.cellPath, cloneCellp, entry.ownerModp, m_modp)) { - UINFO(9, "iface capture skipping (path mismatch)" << endl); + UINFO(9, "iface capture skipping (path mismatch)"); return; } } @@ -1033,8 +1032,7 @@ class ParamProcessor final { // Owner won't be cloned - directly retarget now. if (retargetRefToModule(entry, newModp)) { UINFO(9, "iface capture direct retarget: " << entry.refp << " -> " - << newModp->prettyNameQ() - << endl); + << newModp->prettyNameQ()); } } }); @@ -1053,8 +1051,8 @@ class ParamProcessor final { return; } if (retargetRefToModule(entry, newModp)) { - UINFO(9, "iface capture clone-entry retarget: " - << entry.refp << " -> " << newModp->prettyNameQ() << endl); + UINFO(9, "iface capture clone-entry retarget: " << entry.refp << " -> " + << newModp->prettyNameQ()); } }); } @@ -1219,7 +1217,7 @@ class ParamProcessor final { if (srcClassp && srcClassp->hasGParam()) { // Specialize if the reference still points to the generic class if (lhsClassp == srcClassp || !lhsClassp) { - UINFO(9, "resolveDotToTypedef: specializing " << srcClassp->name() << endl); + UINFO(9, "resolveDotToTypedef: specializing " << srcClassp->name()); classRefDeparam(classRefp, srcClassp); lhsClassp = VN_CAST(classRefp->classOrPackageSkipp(), Class); } @@ -1333,7 +1331,7 @@ class ParamProcessor final { << resolvedp->prettyTypeName() << " templateOwner=" << ownerModp->prettyNameQ() << " pin=" << pinp->prettyNameQ() << " of " << nodep->prettyNameQ() - << " srcMod=" << srcModp->prettyNameQ() << endl); + << " srcMod=" << srcModp->prettyNameQ()); } } if (rawTypep && !skipWidthForTemplateStruct) V3Width::widthParamsEdit(rawTypep); @@ -1415,7 +1413,7 @@ class ParamProcessor final { // array) The CellArrayRef is not yet fully linked to an interface type. Skip // interface cleanup for this pin - V3LinkDot will resolve this later. Just // continue to the next pin without error. - UINFO(9, "Skipping interface cleanup for CellArrayRef pin: " << pinp << endl); + UINFO(9, "Skipping interface cleanup for CellArrayRef pin: " << pinp); continue; } @@ -1640,8 +1638,8 @@ class ParamProcessor final { any_overrides = true; } - UINFO(9, "nodeDeparamCommon: " << srcModp->prettyNameQ() << " overrides=" << any_overrides - << endl); + UINFO(9, + "nodeDeparamCommon: " << srcModp->prettyNameQ() << " overrides=" << any_overrides); AstNodeModule* newModp = nullptr; if (m_hierBlocks.hierSubRun() && m_hierBlocks.isHierBlock(srcModp->origName())) { @@ -1681,8 +1679,7 @@ class ParamProcessor final { } const bool cloned = (newModp != srcModp); - UINFO(9, "nodeDeparamCommon result: " << newModp->prettyNameQ() << " cloned=" << cloned - << endl); + UINFO(9, "nodeDeparamCommon result: " << newModp->prettyNameQ() << " cloned=" << cloned); // Link source class to its specialized version for later relinking of method references if (defaultsResolved) srcModp->user4p(newModp); @@ -1762,8 +1759,7 @@ class ParamProcessor final { } if (allOwnParams) { UINFO(5, "ifaceRefDeparam: self-reference pattern detected in " - << ownerIfacep->prettyNameQ() << ", using owner interface" - << endl); + << ownerIfacep->prettyNameQ() << ", using owner interface"); V3Stats::addStatSum("Param, Self-reference iface typedefs", 1); nodep->ifacep(ownerIfacep); if (nodep->paramsp()) nodep->paramsp()->unlinkFrBackWithNext()->deleteTree(); @@ -1832,8 +1828,8 @@ public: return; } if (retargetRefToModule(entry, correctModp)) { - UINFO(9, "retargetIfaceRefs: " << entry.refp << " -> " - << correctModp->prettyNameQ() << endl); + UINFO(9, + "retargetIfaceRefs: " << entry.refp << " -> " << correctModp->prettyNameQ()); } }); } @@ -1854,7 +1850,7 @@ public: << " parentMod=" << (modp ? modp->prettyNameQ() : "''") << " parentSomeInstanceName='" << (modp ? modp->someInstanceName() : string("")) << "'" - << " inputSomeInstanceName='" << someInstanceName << "'" << endl); + << " inputSomeInstanceName='" << someInstanceName << "'"); string nodeName = nodep->name(); if (AstIfaceRefDType* const ifaceRefp = VN_CAST(nodep, IfaceRefDType)) { if (nodeName.empty()) nodeName = ifaceRefp->cellName(); @@ -1885,7 +1881,7 @@ public: UINFO(9, "nodeDeparam SET-SRC-INST srcMod=" << srcModp->prettyNameQ() << " someInstanceName='" << srcModp->someInstanceName() << "'" << " node=<" << AstNode::nodeAddr(nodep) - << ">" << " nodeType=" << nodep->typeName() << endl); + << ">" << " nodeType=" << nodep->typeName()); AstNodeModule* newModp = nullptr; if (AstCell* const cellp = VN_CAST(nodep, Cell)) { @@ -1912,7 +1908,7 @@ public: << (srcModp ? srcModp->someInstanceName() : string("")) << "'" << " newMod=" << (newModp ? newModp->prettyNameQ() : "''") << " newSomeInstanceName='" - << (newModp ? newModp->someInstanceName() : string("")) << "'" << endl); + << (newModp ? newModp->someInstanceName() : string("")) << "'"); UINFO(8, " Done with orig " << nodep); // if (debug() >= 10) @@ -2077,7 +2073,7 @@ class ParamVisitor final : public VNVisitor { << " someInstanceName='" << modp->someInstanceName() << "'" << " hasGParam=" << (modp->hasGParam() ? "yes" : "no") << " user3p=" << (modp->user3p() ? "set" : "null") - << " dead=" << (modp->dead() ? "yes" : "no") << endl); + << " dead=" << (modp->dead() ? "yes" : "no")); // TODO: this really should be an assert, but classes and hier_blocks are // special... @@ -2163,7 +2159,7 @@ class ParamVisitor final : public VNVisitor { } // Extract the base reference name from a dotted VarXRef (e.g., "iface.FOO" -> "iface") - string getRefBaseName(const AstVarXRef* refp) { + static string getRefBaseName(const AstVarXRef* refp) { const string dotted = refp->dotted(); if (dotted.empty()) return ""; return dotted.substr(0, dotted.find('.')); @@ -2205,9 +2201,8 @@ class ParamVisitor final : public VNVisitor { << " contextName=" << (contextp ? contextp->prettyNameQ() : "''") << " leak=REFDTYPE typedef owner" << " ref=<" - << AstNode::nodeAddr(refp) << ">" - << " refName=" << refp->prettyNameQ() - << " ancestry=" << ancestryOf(refp) << endl); + << AstNode::nodeAddr(refp) << ">" << " refName=" + << refp->prettyNameQ() << " ancestry=" << ancestryOf(refp)); } } if (refp->refDTypep()) { @@ -2222,9 +2217,8 @@ class ParamVisitor final : public VNVisitor { << " contextName=" << (contextp ? contextp->prettyNameQ() : "''") << " leak=REFDTYPE refDType owner" << " ref=<" - << AstNode::nodeAddr(refp) << ">" - << " refName=" << refp->prettyNameQ() - << " ancestry=" << ancestryOf(refp) << endl); + << AstNode::nodeAddr(refp) << ">" << " refName=" + << refp->prettyNameQ() << " ancestry=" << ancestryOf(refp)); } } }); @@ -2242,13 +2236,13 @@ class ParamVisitor final : public VNVisitor { << " contextName=" << (contextp ? contextp->prettyNameQ() : "''") << " leak=VARREF target owner" << " ref=<" << AstNode::nodeAddr(varrefp) << ">" << " var=" << varrefp->prettyNameQ() - << " ancestry=" << ancestryOf(varrefp) << endl); + << " ancestry=" << ancestryOf(varrefp)); }); if (leakCount > 0) { UINFO(9, "TEMPLATE-LEAK summary stage='" - << stage << "' parent=" << parentModp->prettyNameQ() << " template=" - << templateModp->prettyNameQ() << " count=" << leakCount << endl); + << stage << "' parent=" << parentModp->prettyNameQ() + << " template=" << templateModp->prettyNameQ() << " count=" << leakCount); } // LCOV_EXCL_STOP } @@ -2361,12 +2355,12 @@ class ParamVisitor final : public VNVisitor { void visit(AstNodeModule* nodep) override { if (nodep->recursiveClone()) nodep->dead(true); // Fake, made for recursive elimination if (nodep->dead()) return; // Marked by LinkDot (and above) - UINFO(9, "V3Param: visit module name=" - << nodep->prettyNameQ() << " orig='" << nodep->origName() - << "' someInstanceName='" << nodep->someInstanceName() - << "' hasGParam=" << (nodep->hasGParam() ? "yes" : "no") - << " user3p=" << (nodep->user3p() ? "set" : "null") - << " dead=" << (nodep->dead() ? "yes" : "no") << endl); + UINFO(9, "V3Param: visit module name=" << nodep->prettyNameQ() << " orig='" + << nodep->origName() << "' someInstanceName='" + << nodep->someInstanceName() << "' hasGParam=" + << (nodep->hasGParam() ? "yes" : "no") + << " user3p=" << (nodep->user3p() ? "set" : "null") + << " dead=" << (nodep->dead() ? "yes" : "no")); if (AstClass* const classp = VN_CAST(nodep, Class)) { if (classp->hasGParam()) { // Don't enter into a definition. @@ -2619,7 +2613,7 @@ class ParamVisitor final : public VNVisitor { // In such cases, m_unlinkedTxt won't contain the expected pattern. // Simply skip the replacement - the cell array ref will be resolved later. if (pos == string::npos) { - UINFO(9, "Skipping unlinked text replacement for " << nodep << endl); + UINFO(9, "Skipping unlinked text replacement for " << nodep); return; } m_unlinkedTxt.replace(pos, replacestr.length(), @@ -2842,15 +2836,15 @@ public: // CONSTRUCTORS explicit ParamTop(AstNetlist* netlistp) { // Relies on modules already being in top-down-order - ParamVisitor paramVisitor{m_state /*ref*/, netlistp}; + const ParamVisitor paramVisitor{m_state /*ref*/, netlistp}; // Mark classes which cannot be removed because they are still referenced - ClassRefUnlinkerVisitor classUnlinkerVisitor{netlistp}; + const ClassRefUnlinkerVisitor classUnlinkerVisitor{netlistp}; netlistp->foreach([](AstNodeFTaskRef* ftaskrefp) { AstNodeFTask* ftaskp = ftaskrefp->taskp(); if (!ftaskp || !ftaskp->classMethod()) return; - string funcName = ftaskp->name(); + const std::string funcName = ftaskp->name(); // Find the nearest containing (ancestor) class for a node. // Uses aboveLoopp() which correctly skips sibling links // (e.g. covergroup classes) to find the true parent. @@ -2890,7 +2884,7 @@ public: } }); - ParamClassRefDTypeRelinkVisitor paramClassDTypeRelinkVisitor{netlistp}; + const ParamClassRefDTypeRelinkVisitor paramClassDTypeRelinkVisitor{netlistp}; relinkDots(); diff --git a/src/V3ParseGrammar.h b/src/V3ParseGrammar.h index 276ed2ffb..c7b251f5a 100644 --- a/src/V3ParseGrammar.h +++ b/src/V3ParseGrammar.h @@ -59,7 +59,7 @@ public: static int s_typeImpNum; // Implicit type number, incremented each module // CONSTRUCTORS - V3ParseGrammar() {} + V3ParseGrammar() = default; static V3ParseGrammar* singletonp() { static V3ParseGrammar singleton; return &singleton; @@ -192,11 +192,8 @@ public: } AstNodeExpr* createGatePin(AstNodeExpr* exprp) { AstRange* const rangep = m_gateRangep; - if (!rangep) { - return exprp; - } else { - return new AstGatePin{rangep->fileline(), exprp, rangep->cloneTree(true)}; - } + if (!rangep) return exprp; + return new AstGatePin{rangep->fileline(), exprp, rangep->cloneTree(true)}; } AstSenTree* createSenTreeChanged(FileLine* fl, AstNodeExpr* exprp) { return new AstSenTree{fl, new AstSenItem{fl, VEdgeType::ET_CHANGED, exprp}}; @@ -229,10 +226,10 @@ public: V3ParseImp::parsep()->tagNodep(nodep); return nodep; } - void endLabel(FileLine* fl, const AstNode* nodep, const string* endnamep) { + static void endLabel(FileLine* fl, const AstNode* nodep, const string* endnamep) { endLabel(fl, nodep->prettyName(), endnamep); } - void endLabel(FileLine* fl, const string& name, const string* endnamep) { + static void endLabel(FileLine* fl, const string& name, const string* endnamep) { if (fl && endnamep && *endnamep != "" && name != *endnamep && name != AstNode::prettyName(*endnamep)) { fl->v3warn(ENDLABEL, "End label '" << *endnamep << "' does not match begin label '" @@ -265,36 +262,34 @@ public: } AstNodeDType* addRange(AstBasicDType* dtypep, AstNodeRange* rangesp, bool isPacked) { // If dtypep isn't basic, don't use this, call createArray() instead - if (!rangesp) { - return dtypep; + if (!rangesp) return dtypep; + + // If rangesp is "wire [3:3][2:2][1:1] foo [5:5][4:4]" + // then [1:1] becomes the basicdtype range; everything else is arraying + // the final [5:5][4:4] will be passed in another call to createArray + AstNodeRange* rangearraysp = nullptr; + if (dtypep->isRanged()) { + rangearraysp = rangesp; // Already a range; everything is an array } else { - // If rangesp is "wire [3:3][2:2][1:1] foo [5:5][4:4]" - // then [1:1] becomes the basicdtype range; everything else is arraying - // the final [5:5][4:4] will be passed in another call to createArray - AstNodeRange* rangearraysp = nullptr; - if (dtypep->isRanged()) { - rangearraysp = rangesp; // Already a range; everything is an array - } else { - AstNodeRange* finalp = rangesp; - while (finalp->nextp()) finalp = VN_CAST(finalp->nextp(), Range); - if (finalp != rangesp) { - finalp->unlinkFrBack(); - rangearraysp = rangesp; - } - if (AstRange* const finalRangep = VN_CAST(finalp, Range)) { // not an UnsizedRange - if (dtypep->implicit()) { - // It's no longer implicit but a wire logic type - AstBasicDType* const newp = new AstBasicDType{ - dtypep->fileline(), VBasicDTypeKwd::LOGIC, dtypep->numeric(), - dtypep->width(), dtypep->widthMin()}; - VL_DO_DANGLING(dtypep->deleteTree(), dtypep); - dtypep = newp; - } - dtypep->rangep(finalRangep); - } + AstNodeRange* finalp = rangesp; + while (finalp->nextp()) finalp = VN_CAST(finalp->nextp(), Range); + if (finalp != rangesp) { + finalp->unlinkFrBack(); + rangearraysp = rangesp; + } + if (AstRange* const finalRangep = VN_CAST(finalp, Range)) { // not an UnsizedRange + if (dtypep->implicit()) { + // It's no longer implicit but a wire logic type + AstBasicDType* const newp = new AstBasicDType{ + dtypep->fileline(), VBasicDTypeKwd::LOGIC, dtypep->numeric(), + dtypep->width(), dtypep->widthMin()}; + VL_DO_DANGLING(dtypep->deleteTree(), dtypep); + dtypep = newp; + } + dtypep->rangep(finalRangep); } - return createArray(dtypep, rangearraysp, isPacked); } + return createArray(dtypep, rangearraysp, isPacked); } string unquoteString(FileLine* fileline, const std::string& text) VL_MT_DISABLED; void checkDpiVer(FileLine* fileline, const string& str) { diff --git a/src/V3ParseImp.cpp b/src/V3ParseImp.cpp index 1bd7fea2d..2428e5aa5 100644 --- a/src/V3ParseImp.cpp +++ b/src/V3ParseImp.cpp @@ -168,8 +168,8 @@ void V3ParseImp::lexVerilatorCmtLint(FileLine* fl, const char* textp, bool turnO while (*sp && !std::isspace(*sp)) ++sp; while (*sp && std::isspace(*sp)) ++sp; string msg = sp; - string::size_type pos; - if ((pos = msg.find('*')) != string::npos) msg.erase(pos); + string::size_type pos = msg.find('*'); + if (pos != string::npos) msg.erase(pos); // Use parsep()->lexFileline() as want to affect later FileLine's warnings const string err = parsep()->lexFileline()->warnOffParse(msg, turnOff); if (!err.empty()) @@ -207,8 +207,8 @@ void V3ParseImp::lexErrorPreprocDirective(FileLine* fl, const char* textp) { string V3ParseImp::lexParseTag(const char* textp) { string tmp = textp + std::strlen("/*verilator tag "); - string::size_type pos; - if ((pos = tmp.rfind("*/")) != string::npos) tmp.erase(pos); + string::size_type pos = tmp.rfind("*/"); + if (pos != string::npos) tmp.erase(pos); return tmp; } @@ -267,15 +267,16 @@ size_t V3ParseImp::ppInputToLex(char* buf, size_t max_size) { } if (debug() >= 9) { const string out = std::string{buf, got}; - cout << " inputToLex got=" << got << " '" << out << "'" << endl; + cout << " inputToLex got=" << got << " '" << out << "'\n"; } // Note returns 0 at EOF return got; } void V3ParseImp::preprocDumps(std::ostream& os, bool forInputs) { - bool noblanks = forInputs || (v3Global.opt.preprocOnly() && v3Global.opt.preprocNoLine()); - bool nolines = forInputs; + const bool noblanks + = forInputs || (v3Global.opt.preprocOnly() && v3Global.opt.preprocNoLine()); + const bool nolines = forInputs; bool anyNonVerilog = false; for (auto& buf : m_ppBuffers) { if (noblanks) { @@ -529,7 +530,7 @@ size_t V3ParseImp::tokenPipeScanParam(size_t inDepth, bool forCell) { if (tokenPeekp(depth)->token != '(') { if (!forCell) return inDepth; // For module cells, we can have '#' and a number, or, annoyingly an idDotted - int ntoken = tokenPeekp(depth)->token; + const int ntoken = tokenPeekp(depth)->token; if (ntoken == yaINTNUM || ntoken == yaFLOATNUM || ntoken == yaTIMENUM || ntoken == yaID__LEX) { ++depth; diff --git a/src/V3ParseImp.h b/src/V3ParseImp.h index 636ea0ccf..e011b36f2 100644 --- a/src/V3ParseImp.h +++ b/src/V3ParseImp.h @@ -111,7 +111,7 @@ struct VMemberQualifiers final { struct V3ParseBisonYYSType final { FileLine* fl = nullptr; int token = 0; // Read token, aka tok - VBaseOverride baseOverride{}; + VBaseOverride baseOverride; bool flag = false; // Passed up some rules union { V3Number* nump; @@ -212,9 +212,8 @@ public: if (m_lexKwdDepth) { --m_lexKwdDepth; return true; - } else { - return false; } + return false; } int lexKwdLastState() const { return m_lexKwdLast; } static const char* tokenName(int tok) VL_MT_DISABLED; @@ -287,7 +286,6 @@ public: //==== Symbol tables AstPackage* unitPackage(FileLine* /*fl*/) { return parsep()->rootp()->dollarUnitPkgAddp(); } -public: // CONSTRUCTORS V3ParseImp(AstNetlist* rootp, VInFilter* filterp) : m_rootp{rootp} diff --git a/src/V3PreExpr.h b/src/V3PreExpr.h index c7bb334d7..e3321f673 100644 --- a/src/V3PreExpr.h +++ b/src/V3PreExpr.h @@ -25,8 +25,6 @@ #include -using namespace std; - class V3PreExprToken final { public: // TYPES @@ -161,7 +159,7 @@ class V3PreExpr final { } } const bool got = parser.result(); - UASSERT_SELFTEST(bool, got, expect); + UASSERT_SELFTEST(const bool, got, expect); } // METHODS @@ -185,7 +183,7 @@ class V3PreExpr final { } void reduce() { UASSERT(!m_ops.empty(), "lost op stack beginning END"); - V3PreExprToken tok = m_ops.back(); + const V3PreExprToken tok = m_ops.back(); // UINFO(9, "Reduce " << tok.ascii()); m_ops.pop_back(); switch (tok.token()) { @@ -239,7 +237,7 @@ class V3PreExpr final { } void parse() { while (!m_inputs.empty()) { - V3PreExprToken tok = m_inputs.front(); + const V3PreExprToken tok = m_inputs.front(); m_inputs.pop_front(); UINFO(9, "input read " << tok.ascii()); if (tok.isValue()) { @@ -248,7 +246,7 @@ class V3PreExpr final { } UASSERT(!m_ops.empty(), "lost op stack beginning END"); - V3PreExprToken topTok = m_ops.back(); + const V3PreExprToken topTok = m_ops.back(); auto action = parseTable[topTok.token()][tok.token()]; UINFO(9, "pop action " << actionAscii(action) << " from parseTable[" << topTok.ascii() << "][" << tok.ascii() << "]"); @@ -268,7 +266,7 @@ class V3PreExpr final { public: // METHODS - V3PreExpr() {} + V3PreExpr() = default; ~V3PreExpr() = default; void reset(FileLine* flp) { m_inputs.clear(); diff --git a/src/V3PreLex.l b/src/V3PreLex.l index db71ddb96..16b3a8dc8 100644 --- a/src/V3PreLex.l +++ b/src/V3PreLex.l @@ -249,7 +249,7 @@ bom [\357\273\277] return VP_STRING; } "`__LINE__" { FL_FWDC; static char s_buf[25]; - VL_SNPRINTF(s_buf, 25, "%d", LEXP->curFilelinep()->lastLineno()); + (void)VL_SNPRINTF(s_buf, 25, "%d", LEXP->curFilelinep()->lastLineno()); yytext = s_buf; yyleng = std::strlen(yytext); return VP_TEXT; } diff --git a/src/V3PreProc.cpp b/src/V3PreProc.cpp index 85a9d7b83..67e2cf3f9 100644 --- a/src/V3PreProc.cpp +++ b/src/V3PreProc.cpp @@ -1032,7 +1032,8 @@ int V3PreProcImp::getRawToken() { } void V3PreProcImp::debugToken(int tok, const char* cmtp) { - static int s_debugFileline = v3Global.opt.debugSrcLevel("fileline"); // --debugi-fileline 9 + const static int s_debugFileline + = v3Global.opt.debugSrcLevel("fileline"); // --debugi-fileline 9 if (debug() >= 5) { string buf{yyourtext(), yyourleng()}; string::size_type pos; @@ -1102,7 +1103,7 @@ int V3PreProcImp::getStateToken() { // `define Q1 `QA()``_b // -> a_b // This may be a side effect of how `UNDEFINED remains as `UNDEFINED, // but it screws up our method here. So hardcode it. - string name(yyourtext() + 1, yyourleng() - 1); + const std::string name(yyourtext() + 1, yyourleng() - 1); if (defExists(name)) { // JOIN(DEFREF) // Put back the `` and process the defref UINFO(5, "```: define " << name << " exists, expand first"); @@ -1123,7 +1124,7 @@ int V3PreProcImp::getStateToken() { if (tok == VP_SYMBOL_JOIN // not else if, can fallthru from above if() || tok == VP_DEFREF_JOIN || tok == VP_JOIN) { // a`` -> string doesn't include the ``, so can just grab next and continue - string out(yyourtext(), yyourleng()); + const std::string out(yyourtext(), yyourleng()); UINFO(5, "`` LHS:" << out); // a``b``c can have multiple joins, so we need a stack m_joinStack.push(out); @@ -1147,7 +1148,7 @@ int V3PreProcImp::getStateToken() { bool enable = defExists(m_lastSym); UINFO(4, "Ifdef " << m_lastSym << (enable ? " ON" : " OFF")); if (state() == ps_DEFNAME_IFNDEF) enable = !enable; - m_ifdefStack.push(VPreIfEntry{enable, false}); + m_ifdefStack.emplace(VPreIfEntry{enable, false}); if (!enable) parsingOff(); statePop(); goto next_tok; @@ -1162,7 +1163,7 @@ int V3PreProcImp::getStateToken() { // Handle `if portion const bool enable = !lastIf.everOn() && defExists(m_lastSym); UINFO(4, "Elsif " << m_lastSym << (enable ? " ON" : " OFF")); - m_ifdefStack.push(VPreIfEntry{enable, lastIf.everOn()}); + m_ifdefStack.emplace(VPreIfEntry{enable, lastIf.everOn()}); if (!enable) parsingOff(); } statePop(); @@ -1222,7 +1223,7 @@ int V3PreProcImp::getStateToken() { m_lastSym.assign(yyourtext(), yyourleng()); const bool exists = defExists(m_lastSym); if (exists) { - string value = defValue(m_lastSym); + const std::string value = defValue(m_lastSym); if (VString::removeWhitespace(value) == "0") { flp->v3warn( PREPROCZERO, @@ -1252,7 +1253,7 @@ int V3PreProcImp::getStateToken() { UINFO(4, "ifdef() result=" << enable); if (state() == ps_EXPR_IFDEF || state() == ps_EXPR_IFNDEF) { if (state() == ps_EXPR_IFNDEF) enable = !enable; - m_ifdefStack.push(VPreIfEntry{enable, false}); + m_ifdefStack.emplace(VPreIfEntry{enable, false}); if (!enable) parsingOff(); statePop(); goto next_tok; @@ -1267,7 +1268,7 @@ int V3PreProcImp::getStateToken() { // Handle `if portion enable = !lastIf.everOn() && enable; UINFO(4, "Elsif " << m_lastSym << (enable ? " ON" : " OFF")); - m_ifdefStack.push(VPreIfEntry{enable, lastIf.everOn()}); + m_ifdefStack.emplace(VPreIfEntry{enable, lastIf.everOn()}); if (!enable) parsingOff(); } statePop(); @@ -1310,11 +1311,8 @@ int V3PreProcImp::getStateToken() { goto next_tok; } else if (tok == VP_TEXT) { // IE, something like comment in formals - if (!m_off) { - return tok; - } else { - goto next_tok; - } + if (!m_off) return tok; + goto next_tok; } else { fileline()->v3error("Expecting define formal arguments. Found: "s + tokenName(tok) + "\n"); @@ -1495,7 +1493,7 @@ int V3PreProcImp::getStateToken() { const string lhs = m_joinStack.top(); m_joinStack.pop(); UINFO(5, "`` LHS:" << lhs); - string rhs(yyourtext(), yyourleng()); + const string rhs(yyourtext(), yyourleng()); UINFO(5, "`` RHS:" << rhs); const string out = lhs + rhs; UINFO(5, "`` Out:" << out); @@ -1571,7 +1569,7 @@ int V3PreProcImp::getStateToken() { m_ifdefStack.pop(); const bool enable = !lastIf.everOn(); UINFO(4, "Else " << (enable ? " ON" : " OFF")); - m_ifdefStack.push(VPreIfEntry{enable, lastIf.everOn()}); + m_ifdefStack.emplace(VPreIfEntry{enable, lastIf.everOn()}); if (!lastIf.on()) parsingOn(); if (!enable) parsingOff(); } @@ -1592,7 +1590,7 @@ int V3PreProcImp::getStateToken() { case VP_DEFREF: { // m_off not right here, but inside substitution, to make this work: // `ifdef NEVER `DEFUN(`endif) - string name(yyourtext() + 1, yyourleng() - 1); + const string name(yyourtext() + 1, yyourleng() - 1); UINFO(4, "DefRef " << name); if (m_defPutJoin) { m_defPutJoin = false; @@ -1656,7 +1654,7 @@ int V3PreProcImp::getStateToken() { // The CURRENT macro needs the paren saved, it's not a // property of the child macro if (!m_defRefs.empty()) m_defRefs.top().parenLevel(m_lexp->m_parenLevel); - m_defRefs.push(VDefineRef{name, params}); + m_defRefs.emplace(VDefineRef{name, params}); statePush(ps_DEFPAREN); m_lexp->pushStateDefArg(0); goto next_tok; @@ -1729,7 +1727,7 @@ int V3PreProcImp::getFinalToken(string& buf) { m_finFilelinep->lineDirective(bufp, enter /*ref*/); } else { if (m_finAtBol && !(tok == VP_TEXT && buf == "\n") && m_preprocp->lineDirectives()) { - if (int outBehind + if (const int outBehind = (m_lexp->m_tokFilelinep->lastLineno() - m_finFilelinep->lastLineno())) { if (debug() >= 5) { const string flcol = m_lexp->m_tokFilelinep->asciiLineCol(); @@ -1754,7 +1752,7 @@ int V3PreProcImp::getFinalToken(string& buf) { } } // Track newlines in prep for next token - for (char& c : buf) { + for (const char& c : buf) { if (c == '\n') { m_finAtBol = true; m_finFilelinep->linenoInc(); diff --git a/src/V3PreShell.cpp b/src/V3PreShell.cpp index b0698a21c..fca3a1684 100644 --- a/src/V3PreShell.cpp +++ b/src/V3PreShell.cpp @@ -45,7 +45,7 @@ protected: //--------------------------------------- // METHODS - void boot() { + static void boot() { // Create the implementation pointer if (!s_preprocp) { FileLine* const cmdfl = new FileLine{FileLine::commandLineFilename()}; diff --git a/src/V3Premit.cpp b/src/V3Premit.cpp index e58531403..26104ae08 100644 --- a/src/V3Premit.cpp +++ b/src/V3Premit.cpp @@ -167,11 +167,11 @@ class PremitVisitor final : public VNVisitor { // VISITORS - Statements #define START_STATEMENT_OR_RETURN(stmtp) \ if (!m_cfuncp) return; \ - if (stmtp->user1SetOnce()) return; \ + if ((stmtp)->user1SetOnce()) return; \ VL_RESTORER(m_assignLhs); \ VL_RESTORER(m_stmtp); \ m_assignLhs = false; \ - m_stmtp = stmtp; + m_stmtp = (stmtp); void visit(AstNodeAssign* nodep) override { START_STATEMENT_OR_RETURN(nodep); diff --git a/src/V3ProtectLib.cpp b/src/V3ProtectLib.cpp index e73b34bf2..c7be84580 100644 --- a/src/V3ProtectLib.cpp +++ b/src/V3ProtectLib.cpp @@ -98,7 +98,7 @@ class ProtectVisitor final : public VNVisitor { txtp->add(new AstComment{fl, comment}); } - void configSection(AstNodeModule* modp, AstTextBlock* txtp, FileLine* fl) { + void configSection(AstNodeModule* /*modp*/, AstTextBlock* txtp, FileLine* /*fl*/) { txtp->add("\n`ifdef VERILATOR\n"); txtp->add("`verilator_config\n"); @@ -313,7 +313,7 @@ class ProtectVisitor final : public VNVisitor { m_vfilep->tblockp(txtp); } - void castPtr(FileLine* fl, AstTextBlock* txtp) { + void castPtr(FileLine* /*fl*/, AstTextBlock* txtp) { txtp->add(m_topName + "_container* const handlep__V = " // LCOV_EXCL_LINE // lcov bug "static_cast<" diff --git a/src/V3RandSequence.cpp b/src/V3RandSequence.cpp index 8ee8a2861..efdb45b69 100644 --- a/src/V3RandSequence.cpp +++ b/src/V3RandSequence.cpp @@ -175,7 +175,7 @@ class RandSequenceVisitor final : public VNVisitor { UINFOTREE(9, newp, "newProd", ""); } - AstNode* newProdRandJoin(AstRSProd* prodp, AstRSProdList* prodlistp) { + AstNode* newProdRandJoin(AstRSProd* /*prodp*/, AstRSProdList* prodlistp) { // For weight == 1.0 longer sequence (favor stay in a) // For weight == 0.0 shorter squence (favor change a/b) UASSERT_OBJ(prodlistp->weightp(), prodlistp, "Weight should have default CONST(0.5)"); @@ -629,6 +629,6 @@ public: void V3RandSequence::randSequenceNetlist(AstNetlist* nodep) { UINFO(2, __FUNCTION__ << ":"); - { RandSequenceVisitor randSequenceVisitor{nodep}; } + { const RandSequenceVisitor randSequenceVisitor{nodep}; } V3Global::dumpCheckGlobalTree("randsequence", 0, dumpTreeEitherLevel() >= 3); } diff --git a/src/V3Randomize.cpp b/src/V3Randomize.cpp index 65825503c..ba0266a88 100644 --- a/src/V3Randomize.cpp +++ b/src/V3Randomize.cpp @@ -1418,7 +1418,7 @@ class ConstraintExprVisitor final : public VNVisitor { // argp is consumed; caller must clone if reusing. AstNodeExpr* buildCountOnesExpansion(FileLine* fl, AstNodeExpr* argp, AstNodeExpr* dtypeNodep) { - V3Number numOne{fl, argp->width(), 1}; + const V3Number numOne{fl, argp->width(), 1}; AstNodeExpr* sump = new AstAnd{fl, argp, new AstConst{fl, numOne}}; sump->user1(true); for (int i = 1; i < argp->width(); i++) { @@ -1427,8 +1427,10 @@ class ConstraintExprVisitor final : public VNVisitor { AstAnd* const andp = new AstAnd{fl, argp->cloneTreePure(false), new AstConst{fl, numBitMask}}; andp->user1(true); - AstShiftR* const shiftp = new AstShiftR{ - fl, andp, new AstConst{fl, AstConst::WidthedValue{}, argp->width(), (uint32_t)i}}; + AstShiftR* const shiftp + = new AstShiftR{fl, andp, + new AstConst{fl, AstConst::WidthedValue{}, argp->width(), + static_cast(i)}}; shiftp->user1(true); shiftp->dtypeFrom(dtypeNodep); sump = new AstAdd{fl, sump, shiftp}; @@ -1452,7 +1454,7 @@ class ConstraintExprVisitor final : public VNVisitor { // Convert to (x != 0) FileLine* const fl = nodep->fileline(); AstNodeExpr* const argp = nodep->lhsp()->unlinkFrBack(); - V3Number numZero{fl, argp->width(), 0}; + const V3Number numZero{fl, argp->width(), 0}; AstNodeExpr* const neqp = new AstNeq{fl, argp, new AstConst{fl, numZero}}; neqp->user1(true); nodep->replaceWith(neqp); @@ -1466,12 +1468,12 @@ class ConstraintExprVisitor final : public VNVisitor { AstNodeExpr* const argp = nodep->lhsp()->unlinkFrBack(); const int w = argp->width(); - V3Number numZero{fl, w, 0}; + const V3Number numZero{fl, w, 0}; AstNeq* const neZerop = new AstNeq{fl, argp->cloneTreePure(false), new AstConst{fl, numZero}}; neZerop->user1(true); - V3Number numOne{fl, w, 1}; + const V3Number numOne{fl, w, 1}; AstSub* const subp = new AstSub{fl, argp->cloneTreePure(false), new AstConst{fl, numOne}}; subp->dtypeFrom(argp); subp->user1(true); @@ -1480,7 +1482,7 @@ class ConstraintExprVisitor final : public VNVisitor { andp->dtypeFrom(argp); andp->user1(true); - V3Number numZero2{fl, w, 0}; + const V3Number numZero2{fl, w, 0}; AstEq* const eqZerop = new AstEq{fl, andp, new AstConst{fl, numZero2}}; eqZerop->user1(true); @@ -1498,7 +1500,7 @@ class ConstraintExprVisitor final : public VNVisitor { AstNodeExpr* const argp = nodep->lhsp()->unlinkFrBack(); const int w = argp->width(); - V3Number numOne{fl, w, 1}; + const V3Number numOne{fl, w, 1}; AstSub* const subp = new AstSub{fl, argp->cloneTreePure(false), new AstConst{fl, numOne}}; subp->dtypeFrom(argp); subp->user1(true); @@ -1507,7 +1509,7 @@ class ConstraintExprVisitor final : public VNVisitor { andp->dtypeFrom(argp); andp->user1(true); - V3Number numZero{fl, w, 0}; + const V3Number numZero{fl, w, 0}; AstEq* const eqp = new AstEq{fl, andp, new AstConst{fl, numZero}}; eqp->user1(true); @@ -1527,7 +1529,7 @@ class ConstraintExprVisitor final : public VNVisitor { nodep->v3warn(E_UNSUPPORTED, "Unsupported: non-constant control in $countbits inside constraint"); AstConst* const zerop - = new AstConst{fl, AstConst::WidthedValue{}, nodep->width(), 0u}; + = new AstConst{fl, AstConst::WidthedValue{}, nodep->width(), 0U}; nodep->replaceWith(zerop); VL_DO_DANGLING(nodep->deleteTree(), nodep); return; @@ -1550,12 +1552,12 @@ class ConstraintExprVisitor final : public VNVisitor { } else if (countZeros) { // width - countones(x) AstNodeExpr* const onesCountp = buildCountOnesExpansion(fl, argp, nodep); - V3Number widthVal{nodep, onesCountp->width(), (uint32_t)argWidth}; + const V3Number widthVal{nodep, onesCountp->width(), (uint32_t)argWidth}; sump = new AstSub{fl, new AstConst{fl, widthVal}, onesCountp}; sump->dtypeFrom(onesCountp); sump->user1(true); } else { - sump = new AstConst{fl, AstConst::WidthedValue{}, nodep->width(), 0u}; + sump = new AstConst{fl, AstConst::WidthedValue{}, nodep->width(), 0U}; VL_DO_DANGLING(argp->deleteTree(), argp); } @@ -1605,7 +1607,7 @@ class ConstraintExprVisitor final : public VNVisitor { if (AstConst* const exponentp = VN_CAST(nodep->rhsp(), Const)) { FileLine* const fl = nodep->fileline(); AstNodeExpr* const basep = nodep->lhsp(); - V3Number numOne{nodep, basep->width(), 1}; + const V3Number numOne{nodep, basep->width(), 1}; AstNodeExpr* powerp = new AstConst{fl, numOne}; const bool baseSigned = VN_IS(nodep, PowSS) || VN_IS(nodep, PowSU); const int32_t exponent = baseSigned ? exponentp->toSInt() : exponentp->toUInt(); @@ -2176,7 +2178,7 @@ class ConstraintExprVisitor final : public VNVisitor { AstNodeExpr* const exprp = nodep->exprp(); if (exprp->width() > 1) { FileLine* const fl = exprp->fileline(); - V3Number numZero{fl, exprp->width(), 0}; + const V3Number numZero{fl, exprp->width(), 0}; AstNodeExpr* const neqp = new AstNeq{fl, exprp->unlinkFrBack(), new AstConst{fl, numZero}}; neqp->user1(true); // Mark as rand-dependent for SMT path @@ -2241,7 +2243,7 @@ class ConstraintExprVisitor final : public VNVisitor { } if (nodep->method() == VCMethod::ARRAY_INSIDE) { - bool randArr = nodep->fromp()->user1(); + const bool randArr = nodep->fromp()->user1(); AstVar* const newVarp = new AstVar{fl, VVarType::BLOCKTEMP, "__Vinside", nodep->findSigned32DType()}; @@ -2345,9 +2347,9 @@ class ConstraintExprVisitor final : public VNVisitor { const int elemWidth = elemDtp->width(); const int hexDigits = (elemWidth + 3) / 4; - std::string zeroIdentity = "#x" + std::string(hexDigits, '0'); - std::string oneIdentity = "#x" + std::string(hexDigits - 1, '0') + "1"; - std::string allOnesIdentity = "#x" + std::string(hexDigits, 'f'); + const std::string zeroIdentity = "#x" + std::string(hexDigits, '0'); + const std::string oneIdentity = "#x" + std::string(hexDigits - 1, '0') + "1"; + const std::string allOnesIdentity = "#x" + std::string(hexDigits, 'f'); if (nodep->method() == VCMethod::ARRAY_R_SUM) { smtOp = "bvadd"; @@ -2592,7 +2594,7 @@ bool hasFlags(CaptureMode a, CaptureMode flags) { } class CaptureVisitor final : public VNVisitor { - AstArg* m_argsp; // Original references turned into arguments + AstArg* m_argsp = nullptr; // Original references turned into arguments AstNodeModule* m_callerp; // Module of the outer context (for capturing `this`) AstClass* m_targetp; // Module of inner context (for symbol lookup) std::map m_varCloneMap; // Map original var nodes to their clones @@ -2683,7 +2685,7 @@ class CaptureVisitor final : public VNVisitor { void captureRefByValue(AstNodeVarRef* nodep, CaptureMode capModeFlags) { AstVar* newVarp; - bool newCapture = captureVariable(nodep->fileline(), nodep, newVarp /*ref*/); + const bool newCapture = captureVariable(nodep->fileline(), nodep, newVarp /*ref*/); AstNodeVarRef* const newVarRefp = newCapture ? nodep->cloneTree(false) : nullptr; if (!hasFlags(capModeFlags, CaptureMode::CAP_F_SET_CLASSORPACKAGEP)) { // Keeping classOrPackagep will cause a broken link after inlining @@ -2703,7 +2705,7 @@ class CaptureVisitor final : public VNVisitor { m_argsp = AstNode::addNext(m_argsp, new AstArg{nodep->fileline(), "", newVarRefp}); } - void captureRefByThis(AstNodeVarRef* nodep, CaptureMode capModeFlags) { + void captureRefByThis(AstNodeVarRef* nodep, CaptureMode /*capModeFlags*/) { AstVar* const thisp = importThisp(nodep->fileline()); AstVarRef* const thisRefp = new AstVarRef{nodep->fileline(), thisp, nodep->access()}; thisRefp->user1(true); @@ -2724,7 +2726,7 @@ class CaptureVisitor final : public VNVisitor { m_ignore.emplace(nodep); UASSERT_OBJ(nodep->varp(), nodep, "Variable unlinked"); if (nodep->varp()->isStdRandomizeArg()) return; - CaptureMode capMode = getVarRefCaptureMode(nodep); + const CaptureMode capMode = getVarRefCaptureMode(nodep); if (mode(capMode) == CaptureMode::CAP_NO) return; if (mode(capMode) == CaptureMode::CAP_VALUE) captureRefByValue(nodep, capMode); if (mode(capMode) == CaptureMode::CAP_THIS) captureRefByThis(nodep, capMode); @@ -2798,8 +2800,7 @@ class CaptureVisitor final : public VNVisitor { public: explicit CaptureVisitor(AstNode* const nodep, AstNodeModule* callerp, AstClass* const targetp, bool staticContext = false) - : m_argsp{nullptr} - , m_callerp{callerp} + : m_callerp{callerp} , m_targetp{targetp} , m_staticContext{staticContext} { iterateAndNextNull(nodep); @@ -4605,8 +4606,8 @@ class RandomizeVisitor final : public VNVisitor { // each varref argument, then transform nodep to call that wrapper const bool inStaticContext = m_ftaskp && m_ftaskp->isStatic(); AstVar* const stdrand = createStdRandomGenerator(m_modp); - AstFunc* const randomizeFuncp = V3Randomize::newRandomizeStdFunc( - m_memberMap, m_modp, m_inlineUniqueStdName.get(nodep)); + AstFunc* const randomizeFuncp + = V3Randomize::newRandomizeStdFunc(m_modp, m_inlineUniqueStdName.get(nodep)); // When called from a static function, mark helper and stdrand as static // so V3Class moves them to __Vclpkg alongside the calling function if (inStaticContext) { @@ -4997,7 +4998,7 @@ void V3Randomize::randomizeNetlist(AstNetlist* nodep) { UINFO(2, __FUNCTION__ << ":"); { const RandomizeMarkVisitor markVisitor{nodep}; - RandomizeVisitor randomizeVisitor{nodep}; + const RandomizeVisitor randomizeVisitor{nodep}; } V3Global::dumpCheckGlobalTree("randomize", 0, dumpTreeEitherLevel() >= 3); } @@ -5032,8 +5033,7 @@ AstFunc* V3Randomize::newRandomizeFunc(VMemberMap& memberMap, AstClass* nodep, return funcp; } -AstFunc* V3Randomize::newRandomizeStdFunc(VMemberMap& memberMap, AstNodeModule* nodep, - const std::string& name) { +AstFunc* V3Randomize::newRandomizeStdFunc(AstNodeModule* nodep, const std::string& name) { AstFunc* funcp = nullptr; v3Global.useRandomizeMethods(true); AstNodeDType* const dtypep = nodep->findBitDType(32, 32, VSigning::SIGNED); diff --git a/src/V3Randomize.h b/src/V3Randomize.h index f7e2589d4..0b21a72bb 100644 --- a/src/V3Randomize.h +++ b/src/V3Randomize.h @@ -35,7 +35,7 @@ public: const std::string& name = "randomize", bool allowVirtual = true, bool childDType = false) VL_MT_DISABLED; - static AstFunc* newRandomizeStdFunc(VMemberMap& memberMap, AstNodeModule* nodep, + static AstFunc* newRandomizeStdFunc(AstNodeModule* nodep, const std::string& name) VL_MT_DISABLED; static AstFunc* newSRandomFunc(VMemberMap& memberMap, AstClass* nodep) VL_MT_DISABLED; }; diff --git a/src/V3Sched.h b/src/V3Sched.h index 98f399014..68945f7a7 100644 --- a/src/V3Sched.h +++ b/src/V3Sched.h @@ -247,12 +247,12 @@ private: uint32_t nPreWords, std::unordered_map, size_t> senItem2TrigIdx, bool useAcc); VL_UNCOPYABLE(TriggerKit); - TriggerKit& operator=(TriggerKit&&) = delete; public: // Move constructible TriggerKit(TriggerKit&&) = default; ~TriggerKit() = default; + TriggerKit& operator=(TriggerKit&&) = delete; // Utility for extra trigger allocation class ExtraTriggers final { diff --git a/src/V3SchedAcyclic.cpp b/src/V3SchedAcyclic.cpp index c91f97b83..313364d3e 100644 --- a/src/V3SchedAcyclic.cpp +++ b/src/V3SchedAcyclic.cpp @@ -293,7 +293,7 @@ void gatherSCCCandidates(V3GraphVertex* vtxp, std::vector& candidates } // Find all variables in a loop (SCC) that are candidates for splitting to break loops. -std::string reportLoopVars(FileLine* warnFl, Graph* graphp, SchedAcyclicVarVertex* vvtxp) { +std::string reportLoopVars(FileLine* /*warnFl*/, Graph* graphp, SchedAcyclicVarVertex* vvtxp) { std::ostringstream ss; // Vector of variables in UNOPTFLAT loop that are candidates for splitting. std::vector candidates; diff --git a/src/V3SchedPartition.cpp b/src/V3SchedPartition.cpp index 1de20a5da..194a030ac 100644 --- a/src/V3SchedPartition.cpp +++ b/src/V3SchedPartition.cpp @@ -287,7 +287,7 @@ public: static std::unique_ptr build(const LogicByScope& clockedLogic, const LogicByScope& combinationalLogic, const LogicByScope& hybridLogic) { - SchedGraphBuilder visitor{clockedLogic, combinationalLogic, hybridLogic}; + const SchedGraphBuilder visitor{clockedLogic, combinationalLogic, hybridLogic}; return std::unique_ptr{visitor.m_graphp}; } }; diff --git a/src/V3SchedTiming.cpp b/src/V3SchedTiming.cpp index e1c675579..5e9e427cd 100644 --- a/src/V3SchedTiming.cpp +++ b/src/V3SchedTiming.cpp @@ -113,7 +113,7 @@ AstCCall* TimingKit::createResume(AstNetlist* const netlistp) { return callp; } -AstVarScope* TimingKit::getDelayScheduler(AstNetlist* const netlistp) { +AstVarScope* TimingKit::getDelayScheduler(AstNetlist* const /*netlistp*/) { for (auto& p : m_lbs) { AstActive* const ap = p.second; // TODO: this triple VN_AS expression is ridiculous @@ -297,7 +297,7 @@ TimingKit prepareTiming(AstNetlist* const netlistp) { LogicByScope lbs; AstNodeStmt* postUpdates = nullptr; std::map> externalDomains; - AwaitVisitor{netlistp, lbs, postUpdates, externalDomains}; + { AwaitVisitor{netlistp, lbs, postUpdates, externalDomains}; } return {std::move(lbs), postUpdates, std::move(externalDomains)}; } @@ -466,7 +466,7 @@ public: void transformForks(AstNetlist* const netlistp) { if (!v3Global.usesTiming()) return; - TransformForksVisitor{netlistp}; + { TransformForksVisitor{netlistp}; } V3Global::dumpCheckGlobalTree("transform_forks", 0, dumpTreeEitherLevel() >= 3); } diff --git a/src/V3SchedTrigger.cpp b/src/V3SchedTrigger.cpp index 428f77457..6bd10a407 100644 --- a/src/V3SchedTrigger.cpp +++ b/src/V3SchedTrigger.cpp @@ -816,7 +816,7 @@ class AwaitBeforeTrigVisitor final : public VNVisitor { } } } - for (VNRef it : toRemove) m_senExprToSenItem.erase(it); + for (const VNRef it : toRemove) m_senExprToSenItem.erase(it); } // For set of bits indexes (of sensitivity vector) return map from those indexes to set @@ -966,7 +966,8 @@ public: } // Fill the function with neccessary statements - SenExprBuilder::Results results = m_senExprBuilder.getResultsAndClearUpdates(); + const SenExprBuilder::Results results + = m_senExprBuilder.getResultsAndClearUpdates(); for (AstNodeStmt* const stmtsp : results.m_inits) funcp->addStmtsp(stmtsp); for (AstNodeStmt* const stmtsp : results.m_preUpdates) funcp->addStmtsp(stmtsp); funcp->addStmtsp(TriggerKit::createSenTrigVecAssignment(vscp, trigps)); @@ -974,8 +975,8 @@ public: for (AstNodeStmt* const stmtsp : results.m_postUpdates) funcp->addStmtsp(stmtsp); } - std::map>> usedTrigsToUsingTrees - = getUsedTriggersToTrees(usedTriggers); + const std::map>> + usedTrigsToUsingTrees = getUsedTriggersToTrees(usedTriggers); usedTriggers.clear(); // Helper returning expression getting array index `idx` from `scocep` with access diff --git a/src/V3Simulate.h b/src/V3Simulate.h index 7946e661c..8c7d8f3a8 100644 --- a/src/V3Simulate.h +++ b/src/V3Simulate.h @@ -217,7 +217,7 @@ public: if (debug() >= 5) { // LCOV_EXCL_START UINFO_PREFIX("Clear optimizable: " << why); if (nodep) std::cout << ": " << nodep; - std::cout << std::endl; + std::cout << '\n'; } // LCOV_EXCL_STOP m_whyNotOptimizable = why; std::ostringstream stack; @@ -294,9 +294,8 @@ private: AstConst* const constp = allocConst(nodep); m_varAux(nodep).valuep = constp; return constp; - } else { - return fetchConst(nodep); } + return fetchConst(nodep); } AstConst* newOutConst(AstNode* nodep) { // Set a var-output constant value for this node @@ -304,9 +303,8 @@ private: AstConst* const constp = allocConst(nodep); m_varAux(nodep).outValuep = constp; return constp; - } else { - return fetchOutConst(nodep); } + return fetchOutConst(nodep); } public: @@ -548,10 +546,9 @@ private: if (m_scoped) { badNodeType(nodep); return; - } else { - clearOptimizable(nodep, "Language violation: Dotted hierarchical references not " - "allowed in constant functions"); } + clearOptimizable(nodep, "Language violation: Dotted hierarchical references not " + "allowed in constant functions"); } void visit(AstNodeFTask* nodep) override { if (jumpingOver()) return; @@ -654,7 +651,7 @@ private: // but in reality it would yield '0's without V3Table, so force 'x' bits to '0', // to ensure the result is the same with and without V3Table. if (!m_params && VN_IS(nodep, Sel) && valuep->num().isAnyX()) { - V3Number num{valuep, valuep->width(), valuep->num()}; + const V3Number num{valuep, valuep->width(), valuep->num()}; valuep->num().opBitsOne(num); } } @@ -843,7 +840,8 @@ private: outVarrefpRef = varrefp; lsbRef = fetchConst(selp->lsbp())->num(); return; // And presumably still optimizable() - } else if (AstSel* const subselp = VN_CAST(selp->fromp(), Sel)) { + } + if (AstSel* const subselp = VN_CAST(selp->fromp(), Sel)) { V3Number sublsb{nodep}; handleAssignSelRecurse(nodep, subselp, outVarrefpRef, sublsb /*ref*/, depth + 1); if (optimizable()) { @@ -1212,7 +1210,7 @@ private: // Evaluate pin value iterateConst(pinp); // Clone in case are recursing - portValues.push_back(std::make_pair(portp, newTrackedClone(fetchValue(pinp)))); + portValues.emplace_back(std::make_pair(portp, newTrackedClone(fetchValue(pinp)))); } } // Apply value to the function @@ -1262,7 +1260,7 @@ private: } } - void visit(AstScopeName* nodep) override { + void visit(AstScopeName* /*nodep*/) override { if (jumpingOver()) return; // Ignore } @@ -1361,14 +1359,14 @@ private: iterateChildrenConst(nodep); if (!optimizable()) return; if (m_checkOnly) return; - std::string result = toStringRecurse(nodep->lhsp()); + const std::string result = toStringRecurse(nodep->lhsp()); if (!optimizable()) return; AstConst* const resultConstp = new AstConst{nodep->fileline(), AstConst::String{}, result}; setValue(nodep, resultConstp); m_reclaimValuesp.push_back(resultConstp); } - void visit(AstCoverInc* nodep) override { m_isCoverage = true; } + void visit(AstCoverInc* /*nodep*/) override { m_isCoverage = true; } // ==== // Known Bad @@ -1394,7 +1392,6 @@ private: badNodeType(nodep); } -private: // MEMBERS - called by constructor void setMode(bool scoped, bool checkOnly, bool params) { m_checkOnly = checkOnly; diff --git a/src/V3Split.cpp b/src/V3Split.cpp index c3c835501..404383d51 100644 --- a/src/V3Split.cpp +++ b/src/V3Split.cpp @@ -510,7 +510,7 @@ public: void go() { // Create a new always for each color const ColorSet& colors = m_ifColorp->colors(); - for (unsigned int color : colors) { + for (const unsigned int color : colors) { // We don't need to clone m_origAlwaysp->sensesp() here; // V3Activate already moved it to a parent node. AstAlways* const alwaysp @@ -560,7 +560,7 @@ protected: using CloneMap = std::unordered_map; CloneMap clones; - for (unsigned int color : colors) { + for (const unsigned int color : colors) { // Clone this if into its set of split blocks AstSplitPlaceholder* const if_placeholderp = makePlaceholderp(); AstSplitPlaceholder* const else_placeholderp = makePlaceholderp(); diff --git a/src/V3Stats.h b/src/V3Stats.h index b84a7d9aa..d035aeeeb 100644 --- a/src/V3Stats.h +++ b/src/V3Stats.h @@ -45,7 +45,7 @@ public: return *this; } VDouble0 operator++(int) { // postfix - VDouble0 old = *this; + const VDouble0 old = *this; ++m_d; return old; } @@ -131,7 +131,7 @@ public: // Avoid memory blow-up when called frequently with zero adds, // e.g. from V3Const invoked on individual expressions. if (count == 0.0) return; - V3LockGuard lock{s_mutex}; + const V3LockGuard lock{s_mutex}; addStat(V3Statistic{"*", name, count, 0, true, false}); } static void addStatSum(const std::string& name, double count) { diff --git a/src/V3StatsReport.cpp b/src/V3StatsReport.cpp index f5901c920..52d6ed95e 100644 --- a/src/V3StatsReport.cpp +++ b/src/V3StatsReport.cpp @@ -137,8 +137,8 @@ class StatsReport final { lastName = repp->name(); { string commaName = lastName; - string::size_type pos; - if ((pos = commaName.find(',')) != string::npos) commaName.erase(pos); + string::size_type pos = commaName.find(','); + if (pos != string::npos) commaName.erase(pos); if (lastCommaName != commaName) { lastCommaName = commaName; os << '\n'; @@ -215,7 +215,8 @@ void V3Stats::statsStage(const string& name) { V3Stats::addStatPerf("Stage, Elapsed time (sec), " + digitName, wallTimeDelta); V3Stats::addStatPerf("Stage, Elapsed time (sec), TOTAL", wallTimeDelta); - uint64_t memPeak, memCurrent; + uint64_t memPeak; + uint64_t memCurrent; VlOs::memUsageBytes(memPeak /*ref*/, memCurrent /*ref*/); V3Stats::addStatPerf("Stage, Memory current (MB), " + digitName, memCurrent / 1024.0 / 1024.0); V3Stats::addStatPerf("Stage, Memory peak (MB), " + digitName, memPeak / 1024.0 / 1024.0); @@ -268,7 +269,8 @@ void V3Stats::summaryReport() { << ", cvt=" << walltimeCvt << ", bld=" << walltimeBuild << "); cpu " << cputime << " s on " << std::max(v3Global.opt.verilateJobs(), v3Global.opt.buildJobs()) << " threads"; - uint64_t memPeak, memCurrent; + uint64_t memPeak; + uint64_t memCurrent; VlOs::memUsageBytes(memPeak /*ref*/, memCurrent /*ref*/); const double memory = memPeak / 1024.0 / 1024.0; if (VL_UNCOVERABLE(memory != 0.0)) std::cout << "; allocated " << memory << " MB"; diff --git a/src/V3String.cpp b/src/V3String.cpp index 8f425f8bf..5978b4376 100644 --- a/src/V3String.cpp +++ b/src/V3String.cpp @@ -378,13 +378,14 @@ uint64_t VString::hashMurmur(const string& str) VL_PURE { const unsigned char* data2 = reinterpret_cast(data); switch (len & 7) { - case 7: h ^= uint64_t(data2[6]) << 48; /* fallthrough */ - case 6: h ^= uint64_t(data2[5]) << 40; /* fallthrough */ - case 5: h ^= uint64_t(data2[4]) << 32; /* fallthrough */ - case 4: h ^= uint64_t(data2[3]) << 24; /* fallthrough */ - case 3: h ^= uint64_t(data2[2]) << 16; /* fallthrough */ - case 2: h ^= uint64_t(data2[1]) << 8; /* fallthrough */ - case 1: h ^= uint64_t(data2[0]); h *= m; /* fallthrough */ + case 7: h ^= static_cast(data2[6]) << 48; // FALLTHRU + case 6: h ^= static_cast(data2[5]) << 40; // FALLTHRU + case 5: h ^= static_cast(data2[4]) << 32; // FALLTHRU + case 4: h ^= static_cast(data2[3]) << 24; // FALLTHRU + case 3: h ^= static_cast(data2[2]) << 16; // FALLTHRU + case 2: h ^= static_cast(data2[1]) << 8; // FALLTHRU + case 1: h ^= static_cast(data2[0]); h *= m; // FALLTHRU + default:; }; h ^= h >> r; @@ -686,23 +687,22 @@ string VName::hashedName() { if (s_maxLength == 0 || m_name.length() < s_maxLength) { m_hashed = m_name; return m_hashed; - } else { - VHashSha256 hash{m_name}; - const string suffix = "__Vhsh" + hash.digestSymbol(); - if (s_minLength < s_maxLength) { - // Keep a prefix from the original name - // Backup over digits so adding __Vhash doesn't look like a encoded hex digit - // ("__0__Vhsh") - size_t prefLength = s_minLength; - while (prefLength >= 1 && m_name[prefLength - 1] != '_') --prefLength; - s_dehashMap[suffix] = m_name.substr(prefLength); - m_hashed = m_name.substr(0, prefLength) + suffix; - } else { - s_dehashMap[suffix] = m_name; - m_hashed = suffix; - } - return m_hashed; } + VHashSha256 hash{m_name}; + const string suffix = "__Vhsh" + hash.digestSymbol(); + if (s_minLength < s_maxLength) { + // Keep a prefix from the original name + // Backup over digits so adding __Vhash doesn't look like a encoded hex digit + // ("__0__Vhsh") + size_t prefLength = s_minLength; + while (prefLength >= 1 && m_name[prefLength - 1] != '_') --prefLength; + s_dehashMap[suffix] = m_name.substr(prefLength); + m_hashed = m_name.substr(0, prefLength) + suffix; + } else { + s_dehashMap[suffix] = m_name; + m_hashed = suffix; + } + return m_hashed; } //###################################################################### @@ -786,8 +786,8 @@ string VSpellCheck::bestCandidateInfo(const string& goal, EditDistance& distance } void VSpellCheck::selfTestDistanceOne(const string& a, const string& b, EditDistance expected) { - UASSERT_SELFTEST(EditDistance, editDistance(a, b), expected); - UASSERT_SELFTEST(EditDistance, editDistance(b, a), expected); + UASSERT_SELFTEST(const EditDistance, editDistance(a, b), expected); + UASSERT_SELFTEST(const EditDistance, editDistance(b, a), expected); } void VSpellCheck::selfTestSuggestOne(bool matches, const string& c, const string& goal, @@ -798,7 +798,7 @@ void VSpellCheck::selfTestSuggestOne(bool matches, const string& c, const string const string got = speller.bestCandidateInfo(goal, gdist /*ref*/); if (matches) { UASSERT_SELFTEST(const string&, got, c); - UASSERT_SELFTEST(EditDistance, gdist, dist); + UASSERT_SELFTEST(const EditDistance, gdist, dist); } else { UASSERT_SELFTEST(const string&, got, ""); } @@ -821,16 +821,16 @@ void VSpellCheck::selfTest() { } { const VSpellCheck speller; - UASSERT_SELFTEST(string, "", speller.bestCandidate("")); + UASSERT_SELFTEST(const string, "", speller.bestCandidate("")); } { VSpellCheck speller; speller.pushCandidate("fred"); speller.pushCandidate("wilma"); speller.pushCandidate("barney"); - UASSERT_SELFTEST(string, "fred", speller.bestCandidate("fre")); - UASSERT_SELFTEST(string, "wilma", speller.bestCandidate("whilma")); - UASSERT_SELFTEST(string, "barney", speller.bestCandidate("Barney")); - UASSERT_SELFTEST(string, "", speller.bestCandidate("nothing close")); + UASSERT_SELFTEST(const string, "fred", speller.bestCandidate("fre")); + UASSERT_SELFTEST(const string, "wilma", speller.bestCandidate("whilma")); + UASSERT_SELFTEST(const string, "barney", speller.bestCandidate("Barney")); + UASSERT_SELFTEST(const string, "", speller.bestCandidate("nothing close")); } } diff --git a/src/V3String.h b/src/V3String.h index b04fb2c83..07f078c61 100644 --- a/src/V3String.h +++ b/src/V3String.h @@ -255,11 +255,8 @@ public: // Return friendly message string bestCandidateMsg(const string& goal) const { const string candidate = bestCandidate(goal); - if (candidate.empty()) { - return ""; - } else { - return "... Suggested alternative: '"s + candidate + "'"; - } + if (candidate.empty()) return ""; + return "... Suggested alternative: '"s + candidate + "'"; } static void selfTest(); const std::vector candidates() const { return m_candidates; } diff --git a/src/V3Subst.cpp b/src/V3Subst.cpp index cf9e4b265..bdc62e5d5 100644 --- a/src/V3Subst.cpp +++ b/src/V3Subst.cpp @@ -59,7 +59,7 @@ class SubstVarEntry final { // Variable this SubstVarEntry tracks AstVar* const m_varp; // The recrod for whole variable tracking - Record m_wholeRecord{}; + Record m_wholeRecord; // A record for each word in the variable std::vector m_wordRecords{static_cast(m_varp->widthWords()), Record{}}; @@ -169,12 +169,12 @@ class SubstValidVisitor final : public VNVisitorConst { // If either the whole variable, or any of the words were written to // after the original assignment was recorded, the value is invalid. - SubstVarEntry& entry = getEntry(nodep); + const SubstVarEntry& entry = getEntry(nodep); if (m_step < entry.m_wholeRecord.m_step) { m_valid = false; return; } - for (SubstVarEntry::Record& wordRecord : entry.m_wordRecords) { + for (const SubstVarEntry::Record& wordRecord : entry.m_wordRecords) { if (m_step < wordRecord.m_step) { m_valid = false; return; @@ -192,7 +192,7 @@ class SubstValidVisitor final : public VNVisitorConst { void visit(AstNode* nodep) override { nodep->v3fatalSrc("Non AstNodeExpr under AstNodeExpr"); } // CONSTRUCTORS - SubstValidVisitor(SubstVarEntry::Record& record) + explicit SubstValidVisitor(SubstVarEntry::Record& record) : m_step{record.m_step} { iterateConst(record.m_assignp->rhsp()); } @@ -260,7 +260,9 @@ class SubstVisitor final : public VNVisitor { // for variables that are written in the same basic block (ignoring AstCond) as // where they are consumed. The temporaries introduced in V3Premit are such, so // only substitute those for now. - bool isSubstitutable(AstVar* nodep) { return nodep->isStatementTemp() && !nodep->noSubst(); } + static bool isSubstitutable(AstVar* nodep) { + return nodep->isStatementTemp() && !nodep->noSubst(); + } void substitute(AstNode* nodep, AstNodeExpr* substp) { AstNodeExpr* newp = substp->backp() ? substp->cloneTreePure(true) : substp; diff --git a/src/V3SymTable.h b/src/V3SymTable.h index 305d1652f..dbb5b383d 100644 --- a/src/V3SymTable.h +++ b/src/V3SymTable.h @@ -195,7 +195,7 @@ private: reinsert(name, symp); } } - void exportOneSymbol(VSymGraph* graphp, const string& name, const VSymEnt* srcp) const { + void exportOneSymbol(VSymGraph* /*graphp*/, const string& name, const VSymEnt* srcp) const { if (srcp->exported()) { if (VSymEnt* const symp = findIdFlat(name)) { // Should already exist in current table if (!symp->exported()) symp->exported(true); @@ -238,7 +238,7 @@ public: } } } - void exportStarStar(VSymGraph* graphp) { + void exportStarStar(VSymGraph* /*graphp*/) { // Export *:*: Export all tokens from imported packages for (IdNameMap::const_iterator it = m_idNameMap.begin(); it != m_idNameMap.end(); ++it) { VSymEnt* const symp = it->second; diff --git a/src/V3Task.h b/src/V3Task.h index 553af1f70..95739c7ca 100644 --- a/src/V3Task.h +++ b/src/V3Task.h @@ -38,7 +38,7 @@ class V3TaskConnectState final { using WrapMap = std::map, AstNodeFTask*>; WrapMap m_wrapMap; // Map of {old function, arguments} -> new function public: - V3TaskConnectState() {} + V3TaskConnectState() = default; ~V3TaskConnectState() = default; void pushDeletep(AstNode* nodep) { m_deleter.pushDeletep(nodep); } bool didWrap() const { return m_didWrap; } diff --git a/src/V3ThreadPool.cpp b/src/V3ThreadPool.cpp index a823dabe6..8b0739f0e 100644 --- a/src/V3ThreadPool.cpp +++ b/src/V3ThreadPool.cpp @@ -104,17 +104,17 @@ void V3ThreadPool::selfTest() { auto secondJob = [&](int sleep) -> void { commonMutex.lock(); commonMutex.unlock(); - V3LockGuard lock{commonMutex}; + const V3LockGuard lock{commonMutex}; std::this_thread::sleep_for(std::chrono::milliseconds{sleep}); commonValue = 1000; }; auto thirdJob = [&](int sleep) -> void { { - V3LockGuard lock{commonMutex}; + const V3LockGuard lock{commonMutex}; std::this_thread::sleep_for(std::chrono::milliseconds{sleep}); } firstJob(sleep); - V3LockGuard lock{commonMutex}; + const V3LockGuard lock{commonMutex}; commonValue = 100; }; { diff --git a/src/V3Timing.cpp b/src/V3Timing.cpp index 74bb1cfc6..b5c58af77 100644 --- a/src/V3Timing.cpp +++ b/src/V3Timing.cpp @@ -1443,7 +1443,7 @@ void V3Timing::timingAll(AstNetlist* nodep) { { const VNUser1InUse m_user1InUse; const VNUser2InUse m_user2InUse; - TimingSuspendableVisitor{nodep}; + { TimingSuspendableVisitor{nodep}; } if (v3Global.usesTiming()) TimingControlVisitor{nodep}; } V3Global::dumpCheckGlobalTree("timing", 0, dumpTreeEitherLevel() >= 3); diff --git a/src/V3TraceDecl.cpp b/src/V3TraceDecl.cpp index fbb37599f..d79ffc540 100644 --- a/src/V3TraceDecl.cpp +++ b/src/V3TraceDecl.cpp @@ -67,7 +67,7 @@ public: : VTracePrefixType::SCOPE_MODULE; const std::string extraPrefix = newPath.substr(m_stack.back().size()); size_t begin = 0; - size_t last = extraPrefix.rfind(SEPARATOR); + const size_t last = extraPrefix.rfind(SEPARATOR); // Move down, one path element at a time while (true) { const size_t end = extraPrefix.find(SEPARATOR, begin); @@ -287,8 +287,8 @@ class TraceDeclVisitor final : public VNVisitor { void addIgnore(const string& why) { ++m_statIgnSigs; - std::string cmt = "Tracing: "s + m_traName + " // Ignored: " + why; - if (debug() > 3 && m_traVscp) std::cout << "- " << m_traVscp->fileline() << cmt << endl; + const std::string cmt = "Tracing: "s + m_traName + " // Ignored: " + why; + if (debug() > 3 && m_traVscp) std::cout << "- " << m_traVscp->fileline() << cmt << '\n'; } void fixupPlaceholder(const std::string& path, AstNodeStmt* placeholderp) { @@ -334,7 +334,6 @@ class TraceDeclVisitor final : public VNVisitor { placeholderp->addNextHere(initp); // Delete the placeholder VL_DO_DANGLING(placeholderp->unlinkFrBack()->deleteTree(), placeholderp); - return; } void fixupPlaceholders() { @@ -552,7 +551,7 @@ class TraceDeclVisitor final : public VNVisitor { if (!m_traVscp) return; iterate(nodep->subDTypep()->skipRefToEnump()); } - void visit(AstIfaceRefDType* nodep) override { + void visit(AstIfaceRefDType* /*nodep*/) override { if (!m_traVscp) return; // Insert a placeholder to be fixed up later FileLine* const flp = m_traVscp->fileline(); diff --git a/src/V3Tristate.cpp b/src/V3Tristate.cpp index db6f0ccc7..3fed69021 100644 --- a/src/V3Tristate.cpp +++ b/src/V3Tristate.cpp @@ -710,7 +710,7 @@ class TristateVisitor final : public TristateBaseVisitor { if (isCrossModule && !isIfaceTri) { // Hierarchical writes to non-interface module tri wires are unsupported - for (RefStrength& rs : *refsp) { + for (const RefStrength& rs : *refsp) { if (VN_IS(rs.m_varrefp, VarXRef)) { rs.m_varrefp->v3warn( E_UNSUPPORTED, @@ -730,7 +730,7 @@ class TristateVisitor final : public TristateBaseVisitor { string inlinedDots; }; std::map partitions; - for (RefStrength& rs : *refsp) { + for (const RefStrength& rs : *refsp) { if (AstVarXRef* const xrefp = VN_CAST(rs.m_varrefp, VarXRef)) { PartitionInfo& pi = partitions[xrefp->dotted()]; pi.refs.push_back(rs); @@ -1094,8 +1094,8 @@ class TristateVisitor final : public TristateBaseVisitor { AstAssignW* getStrongestAssignmentOfValue(const Assigns& assigns, bool value) { auto maxIt = std::max_element( assigns.begin(), assigns.end(), [&](const AstAssignW* ap, const AstAssignW* bp) { - bool valuesOnRhsA = assignmentOfValueOnAllBits(ap, value); - bool valuesOnRhsB = assignmentOfValueOnAllBits(bp, value); + const bool valuesOnRhsA = assignmentOfValueOnAllBits(ap, value); + const bool valuesOnRhsB = assignmentOfValueOnAllBits(bp, value); if (!valuesOnRhsA) return valuesOnRhsB; if (!valuesOnRhsB) return false; return getStrength(ap, value) < getStrength(bp, value); @@ -1193,7 +1193,7 @@ class TristateVisitor final : public TristateBaseVisitor { const auto getIfStrongest = [&](const AstAssignW* const strongestCandidatep, bool value) { if (!strongestCandidatep) return; - uint8_t strength = getStrength(strongestCandidatep, value); + const uint8_t strength = getStrength(strongestCandidatep, value); if (strength >= greatestKnownStrength) { greatestKnownStrength = strength; strongestp = strongestCandidatep; @@ -1229,7 +1229,7 @@ class TristateVisitor final : public TristateBaseVisitor { // needed to check if it is non-tristate. const AstAssignW* const strongestp = m_tgraph.isTristate(*maxIt) ? nullptr : *maxIt; if (strongestp) { - uint8_t greatestKnownStrength + const uint8_t greatestKnownStrength = std::min(getStrength(strongestp, 0), getStrength(strongestp, 1)); removeNotStrongerAssignments(assigns, strongestp, greatestKnownStrength); } @@ -2117,10 +2117,10 @@ class TristateVisitor final : public TristateBaseVisitor { // After all modules have been processed, combine per-module contributions // for each interface tristate signal into final resolution logic. // Key is the canonical AstVar in the interface module (shared across instances). - for (std::pair>>& kv : + for (const std::pair>>& kv : m_ifaceContribs) { AstVar* const invarp = kv.first; - std::vector>& contribs = kv.second; + const std::vector>& contribs = kv.second; AstNodeModule* const ifaceModp = findParentModule(invarp); UASSERT_OBJ(ifaceModp, invarp, "Interface tristate var has no parent module"); FileLine* const fl = invarp->fileline(); @@ -2131,7 +2131,7 @@ class TristateVisitor final : public TristateBaseVisitor { AstNodeExpr* orp = nullptr; AstNodeExpr* enp = nullptr; - for (std::pair& contrib : contribs) { + for (const std::pair& contrib : contribs) { AstVar* const contribEnp = contrib.first; AstVar* const contribOutp = contrib.second; diff --git a/src/V3Udp.cpp b/src/V3Udp.cpp index 291cfb72e..7234061ed 100644 --- a/src/V3Udp.cpp +++ b/src/V3Udp.cpp @@ -203,7 +203,7 @@ class UdpVisitor final : public VNVisitor { void visit(AstLogAnd* nodep) override { iterateChildren(nodep); } void visit(AstLogNot* nodep) override { iterateChildren(nodep); } // For logic processing. - bool isEdgeTrig(std::string& valName) { + static bool isEdgeTrig(std::string& valName) { if (valName == "x" || valName == "X") return false; if (valName == "*") return true; if (valName == "01" || valName == "p" || valName == "P" || valName == "r" @@ -228,14 +228,14 @@ class UdpVisitor final : public VNVisitor { if (valName[0] != '0' && valName[0] != '1') { valName = "?"; } return false; } - bool isCombOutputSig(const std::string& valName) { + static bool isCombOutputSig(const std::string& valName) { return (valName == "0" || valName == "1" || valName == "x" || valName == "X"); } - bool isSequentOutputSig(const std::string& valName) { + static bool isSequentOutputSig(const std::string& valName) { return (valName == "0" || valName == "1" || valName == "x" || valName == "X" || valName == "-"); } - V3Number getOutputNum(AstNode* nodep, const std::string& fieldNames) { + static V3Number getOutputNum(AstNode* nodep, const std::string& fieldNames) { V3Number outputNum{nodep, 1}; if (fieldNames == "0") { outputNum.setBit(0, 0); diff --git a/src/V3Undriven.cpp b/src/V3Undriven.cpp index b108f40bb..870f98cfd 100644 --- a/src/V3Undriven.cpp +++ b/src/V3Undriven.cpp @@ -175,7 +175,7 @@ public: bool isUsedNotDrivenAny() const { return isUsedNotDrivenBit(0, m_bitFlags.size() / FLAGS_PER_BIT); } - bool unusedMatch(AstVar* nodep) { + static bool unusedMatch(AstVar* nodep) { const string regexp = v3Global.opt.unusedRegexp(); if (regexp == "") return false; const string prettyName = nodep->prettyName(); @@ -212,7 +212,7 @@ public: } } else { // Signal const string varType{nodep->isFuncLocal() ? "Function variable" : "Signal"}; - bool funcInout = nodep->isFuncLocal() && nodep->isInout(); + const bool funcInout = nodep->isFuncLocal() && nodep->isInout(); bool allU = true; bool allD = true; bool anyU = m_wholeFlags[FLAG_USED]; @@ -674,7 +674,7 @@ void V3Undriven::undrivenAll(AstNetlist* nodep) { UINFO(2, __FUNCTION__ << ":"); V3UndrivenCapture capture{nodep}; - UndrivenVisitor{nodep, &capture}; + { UndrivenVisitor{nodep, &capture}; } if (v3Global.opt.stats()) V3Stats::statsStage("undriven"); } diff --git a/src/V3UniqueNames.h b/src/V3UniqueNames.h index 70226e846..25f05410e 100644 --- a/src/V3UniqueNames.h +++ b/src/V3UniqueNames.h @@ -52,9 +52,8 @@ public: if (m_multiplicity.count(name) == 0) { m_multiplicity[name] = 0; return name; - } else { - return get(name + "__" + cvtToStr(m_multiplicity[name]++)); } + return get(name + "__" + cvtToStr(m_multiplicity[name]++)); } // NORMAL mode const unsigned num = m_multiplicity[name]++; diff --git a/src/V3Width.cpp b/src/V3Width.cpp index 75dfed27a..bff4aef37 100644 --- a/src/V3Width.cpp +++ b/src/V3Width.cpp @@ -8323,7 +8323,8 @@ class WidthVisitor final : public VNVisitor { && (std::is_same::value || std::is_same::value), "Unsupported types provided."); if (!lhsRefp || !rhsRefp) return; - string lhsName, rhsName; + std::string lhsName; + std::string rhsName; if (VN_IS(nodep, Pin)) { lhsName = std::string{"Pin"}; rhsName = std::string{"Expression"}; diff --git a/src/V3WidthCommit.cpp b/src/V3WidthCommit.cpp index c5013ea6b..3e1a94c37 100644 --- a/src/V3WidthCommit.cpp +++ b/src/V3WidthCommit.cpp @@ -90,7 +90,7 @@ private: nodep->dumpSmall(std::cout); std::cout << " ----> "; newp->dumpSmall(std::cout); - std::cout << std::endl; + std::cout << '\n'; } return newp; } diff --git a/src/V3WidthCommit.h b/src/V3WidthCommit.h index 7715b1db7..03b18d23d 100644 --- a/src/V3WidthCommit.h +++ b/src/V3WidthCommit.h @@ -36,9 +36,8 @@ public: newp->dtypeFrom(nodep); newp->user1(true); return newp; - } else { - return nullptr; } + return nullptr; } // Final step... Mark all widths as equal diff --git a/src/V3WidthSel.cpp b/src/V3WidthSel.cpp index aa632a8c1..fb0f6a53a 100644 --- a/src/V3WidthSel.cpp +++ b/src/V3WidthSel.cpp @@ -390,9 +390,9 @@ class WidthSelVisitor final : public VNVisitor { // queue size, this allows a single queue reference, to support // for equations in side effects that select the queue to // operate upon. - VCMethod method = (qleftBacknessp ? VCMethod::DYN_SLICE_BACK_BACK - : qrightBacknessp ? VCMethod::DYN_SLICE_FRONT_BACK - : VCMethod::DYN_SLICE); + const VCMethod method = (qleftBacknessp ? VCMethod::DYN_SLICE_BACK_BACK + : qrightBacknessp ? VCMethod::DYN_SLICE_FRONT_BACK + : VCMethod::DYN_SLICE); AstCMethodHard* const newp = new AstCMethodHard{nodep->fileline(), fromp, method}; if (qleftBacknessp) { VL_DO_DANGLING(pushDeletep(qleftp), qleftp); diff --git a/src/Verilator.cpp b/src/Verilator.cpp index 993d781b8..f0f21eaab 100644 --- a/src/Verilator.cpp +++ b/src/Verilator.cpp @@ -145,7 +145,7 @@ static void emitSerialized() VL_MT_DISABLED { static void process() { { - VlOs::DeltaWallTime elabWallTime{true}; + const VlOs::DeltaWallTime elabWallTime{true}; // Sort modules by level so later algorithms don't need to care V3LinkLevel::modSortByLevel(); @@ -218,7 +218,7 @@ static void process() { // End of elaboration V3Stats::addStatPerf(V3Stats::STAT_WALLTIME_ELAB, elabWallTime.deltaTime()); - VlOs::DeltaWallTime cvtWallTime{true}; + const VlOs::DeltaWallTime cvtWallTime{true}; if (v3Global.opt.debugExitElab()) { V3Error::abortIfErrors(); if (v3Global.opt.serializeOnly()) emitSerialized(); @@ -836,7 +836,7 @@ static void execBuildJob() { UASSERT(v3Global.opt.build(), "--build is not specified."); UASSERT(v3Global.opt.gmake(), "--build requires GNU Make."); UASSERT(!v3Global.opt.makeJson(), "--build cannot use json build."); - VlOs::DeltaWallTime buildWallTime{true}; + const VlOs::DeltaWallTime buildWallTime{true}; UINFO(1, "Start Build"); const string cmdStr = buildMakeCmd(v3Global.opt.prefix() + ".mk", ""); @@ -868,8 +868,8 @@ static void execHierVerilation() { int main(int argc, char** argv) { // General initialization std::ios::sync_with_stdio(); - VlOs::DeltaWallTime wallTimeTotal{true}; - VlOs::DeltaCpuTime cpuTimeTotal{true}; + const VlOs::DeltaWallTime wallTimeTotal{true}; + const VlOs::DeltaCpuTime cpuTimeTotal{true}; time_t randseed; time(&randseed); diff --git a/src/VlcBucket.h b/src/VlcBucket.h index ff6f956d5..1c5039cea 100644 --- a/src/VlcBucket.h +++ b/src/VlcBucket.h @@ -75,25 +75,16 @@ public: } } void clearHits(uint64_t point) const { - if (point >= m_dataSize) { - return; - } else { - m_datap[point / 64] &= ~covBit(point); - } + if (point >= m_dataSize) return; + m_datap[point / 64] &= ~covBit(point); } bool exists(uint64_t point) const { - if (point >= m_dataSize) { - return false; - } else { - return (m_datap[point / 64] & covBit(point)) ? 1 : 0; - } + if (point >= m_dataSize) return false; + return (m_datap[point / 64] & covBit(point)) ? true : false; } uint64_t hits(uint64_t point) const { - if (point >= m_dataSize) { - return 0; - } else { - return (m_datap[point / 64] & covBit(point)) ? 1 : 0; - } + if (point >= m_dataSize) return 0; + return (m_datap[point / 64] & covBit(point)) ? 1 : 0; } uint64_t popCount() const { uint64_t pop = 0; @@ -102,7 +93,7 @@ public: } return pop; } - uint64_t dataPopCount(const VlcBuckets& remaining) { + uint64_t dataPopCount(const VlcBuckets& remaining) const { uint64_t pop = 0; for (uint64_t i = 0; i < m_dataSize; ++i) { if (hits(i) && remaining.hits(i)) ++pop; diff --git a/src/VlcPoint.h b/src/VlcPoint.h index 7f667adce..372b9f2bf 100644 --- a/src/VlcPoint.h +++ b/src/VlcPoint.h @@ -57,7 +57,7 @@ public: void testsCoveringInc() { m_testsCovering++; } bool ok(unsigned annotateMin) const { const std::string threshStr = thresh(); - unsigned threshi = !threshStr.empty() ? std::atoi(threshStr.c_str()) : annotateMin; + const unsigned threshi = !threshStr.empty() ? std::atoi(threshStr.c_str()) : annotateMin; return m_count >= threshi; } // KEY ACCESSORS diff --git a/src/VlcSource.h b/src/VlcSource.h index 095e66cb5..5a3270501 100644 --- a/src/VlcSource.h +++ b/src/VlcSource.h @@ -121,12 +121,9 @@ public: // METHODS VlcSource& findNewSource(const string& name) { NameMap::iterator iter = m_sources.find(name); - if (iter != m_sources.end()) { - return iter->second; - } else { - iter = m_sources.emplace(name, VlcSource{name}).first; - return iter->second; - } + if (iter != m_sources.end()) return iter->second; + iter = m_sources.emplace(name, VlcSource{name}).first; + return iter->second; } }; diff --git a/src/VlcTop.cpp b/src/VlcTop.cpp index a4cc92ae7..aad1f7f0d 100644 --- a/src/VlcTop.cpp +++ b/src/VlcTop.cpp @@ -123,7 +123,7 @@ void VlcTop::writeInfo(const string& filename) { for (auto& li : lines) { VlcSourceCount& sc = li.second; os << "DA:" << sc.lineno() << "," << sc.maxCount() << "\n"; - int num_branches = sc.points().size(); + const int num_branches = sc.points().size(); if (num_branches == 1) continue; branchesFound += num_branches; int point_num = 0; @@ -188,7 +188,7 @@ void VlcTop::rank() { uint64_t bestRemain = 0; for (const auto& testp : bytime) { if (!testp->rank()) { - uint64_t remain = testp->buckets().dataPopCount(remaining); + const uint64_t remain = testp->buckets().dataPopCount(remaining); if (remain > bestRemain) { bestTestp = testp; bestRemain = remain; @@ -256,9 +256,9 @@ void VlcTop::annotateCalcNeeded() { VlcSource& source = si.second; // UINFO(1, "Source " << source.name()); if (opt.annotateAll()) source.needed(true); - VlcSource::LinenoMap& lines = source.lines(); + const VlcSource::LinenoMap& lines = source.lines(); for (auto& li : lines) { - VlcSourceCount& sc = li.second; + const VlcSourceCount& sc = li.second; // UINFO(0, "Source " << source.name() << ":" << sc.lineno() << ":" << sc.column()); ++totCases; if (opt.countOk(sc.minCount())) { @@ -302,7 +302,7 @@ void VlcTop::annotateOutputFiles(const string& dirname) { int lineno = 0; while (!is.eof()) { lineno++; - string line = V3Os::getline(is); + const std::string line = V3Os::getline(is); VlcSource::LinenoMap& lines = source.lines(); const auto lit = lines.find(lineno); @@ -324,7 +324,7 @@ void VlcTop::annotateOutputFiles(const string& dirname) { os << std::setfill('0') << std::setw(6) << sc.maxCount() << " " << line << '\n'; if (opt.annotatePoints()) { - for (auto& pit : sc.points()) pit->dumpAnnotate(os, opt.annotateMin()); + for (const auto& pit : sc.points()) pit->dumpAnnotate(os, opt.annotateMin()); } } }