Repository navigation
Conversation
|
So I ran some numbers comparing the time with valueflow disabled:
It seems to be about ~20-30% slower, which is much better than what it was before at ~80% slower doing full rebuilds. Partial rebuilds seem to really help a lot with this. Obviously since we are doing more instantiations than before it is going to be slower even as there may be room to improve this further. I think this is an acceptable slowdown and in the end I think this will still be faster than the approach in #8688 as we will have to always compute the valuetypes twice since they are seperate components. So I think this approach is ultimately better. @danmar @chrchr-github What are you thoughts on this approach? I can work on cleaning up this PR and fixing the CI failures if you think this is the better way to go. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
The fix for C72 is incomplete. executableScopeDeclaresFunction() only treats name ( ... ) ; as a block-scope declaration. A local prototype with noexcept, throw() or a trailing return type therefore still fails to hide the function template, and the PR deduces the call and reports a zerodiv false positive that base does not report. The pattern is rare, but it is the case that the last commit set out to fix.
Apart from that, I found no new problems. At HEAD the earlier findings C36 (signed char), C44 (char16_t/char32_t), C52 (calls after binary operators) and C53 (the C :: inv<long> qualified call that is never instantiated) still reproduce. The other earlier findings that I rechecked are fixed.
Earlier comments
34 earlier comments, 4 open
@pfultz2, please fix, resolve or reply to the open comments: #15, #19, #23, #25.
For #23 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.
Testing
Builds: make -j8 cppcheck testrunner in pr/ and make -j6 cppcheck in base/ both built.
Unit tests: ./testrunner TestSimplifyTemplate TestSymbolDatabase TestOther TestUnusedVar TestIO TestCondition TestCmdlineParser TestToken TestGarbage TestNullPointer TestLeakAutoVar ran 2270 tests: 0 failed, 137 todos.
Python tests: pytest other_test.py -k "template or showtime" gave 20 passed, 4 skipped and 1 xfailed.
Incremental update vs. --template-full-rebuild vs. base: I ran --enable=all --inconclusive on lib/checkclass.cpp and lib/astutils.cpp. The warnings were identical in all three runs. test/cfg/std.cpp and boost.cpp did not finish in time.
Rechecks at HEAD:
- Fixed: C72 (
int f(long);), member calls (C70), theget(*this)removal (C47), theunsignedoverload signature (C50),accessMovedon function pointers (C62), the doubledN::C::N::Cqualification (C41), andconst T*(C35). - Still present:
signed chardeduces asf<char>andchar16_t/char32_tasf<unsignedshort>/f<unsignedint>(C36, C44). Intwice(k) + twice(l)only the first call is deduced (C52). Inp17.cpp,D::hstill gets thefunctionStaticFP (C53).
Other probes with no new FP, crash or hang: explicit specializations, local using N::f, using namespace, a static member template called through A::f, member templates of class templates, a declaration before the definition, arrays passed to T*, lambdas, recursion through W<T> and T*, this, enums and size_t.
New FP: a block-scope prototype with noexcept, throw() or a trailing return type does not hide the template
// d1.cpp
template<class T> int f(T x) { return 100 / x; }
int g() { int f(long) noexcept; int i = 0; return f(i); }
// d6.cpp
template<class T> int f(T x) { return 100 / x; }
int g() { int f(long) throw(); int i = 0; return f(i); }
// d7.cpp
template<class T> int f(T x) { return 100 / x; }
int g() { auto f(long) -> int; int i = 0; return f(i); }Command: cppcheck -q --enable=warning,style --template='{line}:{column}: {id} {message}' d1.cpp (the same for d6 and d7)
- base: no output for any of the three files.
- PR:
1:43: zerodiv Division by zero.for each of the three files.
--debug-normal on d1.cpp shows int f ( long ) noexcept ( true ) ; ... return f<int> ( i ) ;. With a plain int f(long); or int f(long y); the PR correctly gives no warning.
Automated review of 6aa7ff9 by Claude. The pull request was built and tested locally.
| tok = tok->link(); | ||
| continue; | ||
| } | ||
| if (tok->str() != name || !Token::Match(tok, "%name% (") || !Token::simpleMatch(tok->linkAt(1), ") ;")) |
There was a problem hiding this comment.
AI review
The check requires ) to be followed directly by ;. A block-scope prototype with anything after the parameter list is therefore not recognised, so it does not hide the template and the call is still deduced. After simplification, int f(long) noexcept; becomes int f ( long ) noexcept ( true ) ;. throw() and trailing return types (auto f(long) -> int;) fail the same way:
template<class T> int f(T x) { return 100 / x; }
int g() { int f(long) noexcept; int i = 0; return f(i); }The PR rewrites the call to f<int>(i) and reports zerodiv at 1:43. Base reports nothing. The same happens with throw() and with auto f(long) -> int;.
Since a false match only means a missed deduction, a looser test is enough here. For example, accept any declaration that reaches ; after the ) without a { or = in between.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
New false positive: a pointer to an array is deduced as a pointer to a pointer. For int (*p)[3], or for m + 1 with int m[2][3], the argument's ValueType has the array dimension as an extra pointer level. isUndecayedArray() only catches named arrays with two or more dimensions. So f(p) becomes f<int**> for a T parameter and f<int*> for a T* parameter. The body is then analysed with the wrong pointee type, and this gives a zerodiv that base does not report. I reproduced this.
Earlier findings at HEAD:
- C74 (prototypes with
noexcept/throw()/trailing return) is fixed. - C36 (
signed char→f<char>), C44 (char32_t→f<unsignedint>;char16_tis no longer deduced), C52 (calls after a binary operator) and the second finding of C53 (C :: inv<long>,functionStaticFP forD::h) still reproduce.
I found no other new problems.
Earlier comments
39 earlier comments, 5 open
@pfultz2, please fix, resolve or reply to the open comments: #18, #19, #23, #27, #28.
For #18 and #27 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.
Testing
Build: make cppcheck testrunner in pr/ and make cppcheck in base/ both built.
Unit tests: ./testrunner TestSimplifyTemplate TestSymbolDatabase TestOther TestUnusedVar TestIO TestCondition TestCmdlineParser TestToken TestGarbage TestNullPointer TestLeakAutoVar ran 2277 tests: 0 failed, 139 todos.
Python tests: pytest other_test.py -k "template or showtime" gave 20 passed, 4 skipped and 1 xfailed.
Incremental update vs. --template-full-rebuild: I ran --enable=all --inconclusive both ways on lib/token.cpp and on my probe files. The warnings were identical.
New FP: pointer to an array deduced as int**
// b1.cpp
template<class T> int count(T p) { return 100 / (int)(sizeof(*p) - sizeof(void*)); }
int g() { int a[3] = {0}; int (*p)[3] = &a; return count(p); }
// b4.cpp: the same template, called on a decayed 2D array
int g() { int m[2][3] = {}; return count(m + 1); }
// b5.cpp: the same body with a T* parameter
template<class T> int count(T* p) { return 100 / (int)(sizeof(*p) - sizeof(void*)); }
int g() { int a[3] = {0}; int (*p)[3] = &a; return count(p); }Command: cppcheck -q --enable=warning,style --template='{line}:{column}: {id} {message}' b1.cpp (the same for b4 and b5)
- base: no output.
- PR:
1:47: zerodiv Division by zero.(b5:1:48).
--debug-normal shows the wrong instantiations:
- b1:
int count<int**> ( int * * p ) - b4:
count<int**> ( m + 1 ) - b5:
int count<int*> ( int * * p )
sizeof(*p) should be 12, not 8.
Rechecks of earlier findings:
int f(long) noexcept;,throw()andauto f(long) -> int;in the caller's block are now recognised, so there is no warning (C74 fixed).- A prototype in a closed inner block does not hide the template. The warning is then correct.
signed charstill givesf<char>andchar32_tgivesf<unsignedint>.- In
twice(k) + twice(l),twice(l)stays undeduced. - With
struct D : C, the call still becomesC :: inv<long>, andD::hstill getsfunctionStatic. - A
T&¶meter is not deduced, so it is unchanged from base.
Automated review of 258a907 by Claude. The pull request was built and tested locally.
| if (vt->smartPointer || vt->smartPointerType || vt->smartPointerTypeToken || vt->container || vt->containerTypeToken) | ||
| return DeducedType(); | ||
| // "T" and "T *" decay an array argument, "T &" binds the array itself | ||
| if (isUndecayedArray(arg, !shape.isReference)) |
There was a problem hiding this comment.
AI review
A pointer to an array gets past this filter. For int (*p)[3] the variable has one dimension and is a pointer, so isUndecayedArray() returns false. Its ValueType is int with pointer == 2, so T is deduced as int**, and for a T* parameter int (*)[3] becomes int*. The same happens for expressions such as m + 1 with int m[2][3], because + is not inspected.
template<class T> int count(T p) { return 100 / (int)(sizeof(*p) - sizeof(void*)); }
int g() { int a[3] = {0}; int (*p)[3] = &a; return count(p); }The PR creates int count<int**> ( int * * p ) and reports zerodiv at 1:47. Base reports nothing. A fix could bail out when the argument variable is a pointer that also has array dimensions (var->isPointer() && !var->dimensions().empty()). A stricter option is to bail out when vt->pointer is larger than the pointer levels that the declaration and the expression account for.
|
This pull request has merge conflicts that must be resolved. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
New false positive: a non-template overload that a using namespace directive makes visible does not stop the deduction. For template<class T> int f(T), namespace N { int f(int); } and using namespace N;, C++ calls N::f(int): both candidates are exact matches, and in a tie the non-template wins. The PR still rewrites f(z) to f<int>(z) and reports a zerodiv that base does not report. The same happens when the directive is inside the function body. A using-declaration (using N::f;) is handled correctly.
The pointer-to-array FP from C76 also still reproduces, here through a struct member int (*arr)[2]. The earlier open items (C32 pos<unsigned>, C36, C44, C52, C53) are unchanged. I found no other new problems.
Earlier comments
40 earlier comments, 6 open
@pfultz2, please fix, resolve or reply to the open comments: #18, #20, #24, #28, #30, #40.
For #18 and #28 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built.
Unit tests: ./testrunner TestSimplifyTemplate TestSymbolDatabase TestOther TestUnusedVar TestIO TestCondition TestCmdlineParser TestToken TestTokenizer TestVarID ran 2372 tests: 0 failed, 123 todos.
Python tests: pytest other_test.py -k "template or showtime" gave 20 passed, 4 skipped, 1 xfailed.
New FP: overload visible through a using-directive
// c2.cpp
template<class T> int f(T t) { return 100 / t; }
namespace N { int f(int); }
using namespace N;
int g() { int z = 0; return f(z); }
// c8.cpp: the same, but with `using namespace N;` inside g()
template<class T> int f(T t) { return 100 / t; }
namespace N { int f(int); }
int g() { using namespace N; int z = 0; return f(z); }Command: cppcheck -q --template='{line}:{column}: {id} {message}' c2.cpp, and the same for c8.cpp.
- base: no output
- PR:
1:43: zerodiv Division by zero.for both files.--template-full-rebuildgives the same result.
--debug-normal shows return f<int> ( z ) ; in g. N::f(int) should be called here, because a non-template beats a template specialization with the same conversions. With using N::f; (c1.cpp), the PR correctly leaves the call alone.
Other probes. None of these gave a new wrong result compared with base:
- a template parameter that cannot be deduced (
conv<R,T>) - reference variables
int (&r)[2]- bool, char and promoted-expression arguments
int8_tchar* s[]- a 2D array passed to
T* - an array parameter
int a[3][4] using N::f- ADL non-template
- a non-template declared after the call
using B::fin a class
sz(s.arr) with a member int (*arr)[2] gives sz<int**> and a zerodiv FP. That is the C76 problem and is not reported again.
Automated review of fa536c6 by Claude. The pull request was built and tested locally.
| const Scope* declarationScope = nullptr; | ||
| for (const LookupLevel& level : lookup.levels) { | ||
| // a non template function with the same name might be a better overload match | ||
| if (level.scope && scopeHasNonTemplateFunction(level.scope, tok->str())) |
There was a problem hiding this comment.
AI review
This check only looks at the functions that are declared in level.scope itself. Functions that a using namespace directive brings in (Scope::usingList) are not considered. So a non-template overload that wins overload resolution does not stop the deduction:
template<class T> int f(T t) { return 100 / t; }
namespace N { int f(int); }
using namespace N; // also inside g() itself
int g() { int z = 0; return f(z); }The call should go to N::f(int): both are exact matches, and in a tie the non-template wins. The PR rewrites it to f<int>(z) and reports zerodiv at 1:43. Base reports nothing. A using N::f; declaration is handled correctly, apparently because the symbol database then links the call. A possible fix is to bail out when a level (or an executable scope on the way) has a using-directive whose namespace has a non-template function with that name.
|
Test results for commit fa536c6 (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-8720/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
|
I created a ticket for the last issue: https://trac.cppcheck.net/ticket/15243 |
|
@danmar Is there anymore feedback here? |
|
This pull request has merge conflicts that must be resolved. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems in this round. The head commit adds only a merge on top of the commit that was reviewed last (fa536c6). Unit tests and the template-related CLI tests pass.
These earlier findings still reproduce at HEAD and have no fix and no ticket:
- C76: a pointer to an array is deduced as a pointer to a pointer, which gives a
zerodivFP. - C53: a call through a base class is rewritten to
C :: inv<long>, but that instantiation is never created. This gives afunctionStaticFP forD::h. - C36 / C44:
signed charis deduced aschar, andchar32_tasunsigned int. - C32 and C52 are missed warnings (false negatives): the
pos<unsigned>bail-out also hides the warning for explicit calls, and calls after a binary operator are not deduced.
The using namespace FP from C79 also still reproduces, but it has a ticket.
Comments
41 comments, 6 open, 0 new
@pfultz2, please fix, resolve or reply to the open and new comments: #18, #20, #24, #28, #29, #40.
For #18 and #28 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.
Testing
Builds: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built.
Unit tests: ./testrunner TestSimplifyTemplate TestSymbolDatabase TestOther TestUnusedVar TestIO TestCondition TestCmdlineParser TestToken TestGarbage TestNullPointer TestLeakAutoVar TestTokenizer TestVarID ran 2901 tests: 0 failed, 144 todos.
Python tests: pytest other_test.py -k "template or showtime" gave 20 passed, 4 skipped, 1 xfailed.
Rechecks of earlier open findings at HEAD. Command: cppcheck -q --enable=style --template='{line}:{column}: {id} {message}', run with base and PR.
| File | Code | base | PR |
|---|---|---|---|
| e1 | explicit pos<unsigned>(u) |
unsignedPositive |
nothing (C32 still open) |
| e2 | signed char / char32_t |
— | --debug-normal: f<char>(s), f<unsignedint>(d) (C36, C44 still open) |
| e3 | return 1 + inv(z); |
— | not deduced (C52 still open) |
| e4 | C53 p17 example | functionStatic E::inv |
adds 3:10: functionStatic The member function 'D::h' can be static.; --debug-normal shows C :: inv<long> (still open) |
| e5 | int (*p)[3] passed to count(T p) |
nothing | 1:47: zerodiv (C76 still open) |
| e6 | using namespace N; with N::f(int) |
nothing | 1:43: zerodiv (C79, has a ticket) |
New probes: no wrong results compared with base. With --debug-normal I checked:
- Top-level const and pointer const:
const intpassed by value deducesT=int. AT¶meter withint* constdeducesint*const. AT*parameter withconst IP(a typedef'd pointer) deducesint. - Not deduced, which is correct: mismatched
T, Targuments, default parameters, and non-deducible non-type template parameters. Volatile arguments, bitfields and containers/iterators are also not deduced, which is conservative. - Correct deductions:
?:withint/longgiveslong.*ppgivesconst int*. Nestedsq(id(l))and static member templates throughM::st(z)are deduced. - Other cases: class template members that call a function template (
W<short>::get), and a record type that is declared after the template. The latter gives a truearrayIndexOutOfBounds, which the explicitf<S>form also reports in base.
I could not use the timing comparison because /usr/bin/time is missing in the container.
Automated review of dc69bb7 by Claude. The pull request was built and tested locally.
|
Test results for commit dc69bb7 (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-8720/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
|
I have tickets filed for each of the missing issues: #18 - https://trac.cppcheck.net/ticket/15161 |
|
This pull request has merge conflicts that must be resolved. |
|
@danmar Anymore feedback on this? |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems. The incremental update path gave the same results as --template-full-rebuild in every case I compared. A deduced instantiation produced the same tokens, AST and ValueFlow as an explicit f<int>(v) gives on base. Of the earlier findings, C76 (a pointer to an array is deduced as a pointer to a pointer, which gives a zerodiv false positive) is the only one that is still open and has no ticket. I did not re-run its reproducer. C84 reproduced it, and the only commit since then is a merge. The other open findings now have Trac tickets (C86). The PR also has merge conflicts again (C87).
Comments
41 comments, 1 open, 0 new
@pfultz2, please fix, resolve or reply to the open and new comments: #40.
Testing
Builds: make -j8 cppcheck testrunner built in pr/, and make -j8 cppcheck built in base/.
Unit tests: ./testrunner TestSimplifyTemplate TestSymbolDatabase TestOther TestUnusedVar TestIO TestCondition TestCmdlineParser TestToken TestGarbage TestNullPointer TestLeakAutoVar ran 2280 tests: 0 failed, 139 todos.
Python tests: pytest other_test.py -k template gave 5 passed, 1 xfailed.
Incremental update compared with full rebuild: I ran cppcheck --enable=all --inconclusive --std=c++20 with and without --template-full-rebuild on test/cfg/*.cpp, samples/*/*.cpp, lib/token.cpp, lib/library.cpp, lib/mathlib.cpp, lib/utils.cpp and lib/programmemory.cpp. The output was identical for every file.
Targeted probes (PR, PR with --template-full-rebuild, and base):
- Call sites that the incremental path handles specially: calls in a constructor initializer list, in a global initializer, in an array dimension and in a namespace-scope variable initializer. The
--debugoutput of incremental and full rebuild was identical, andzerodivin the initializer list is found. - Template body with many constructs:
T x(a), y = a, *p,T arr[] = {...}, aforwith two declarations, anifwith an init declaration,static const T, andT q{a}. The--debug-normaloutput of PRf(v)(deduced) is identical to basef<int>(v)(explicit), apart from var and expr ids. So the instantiations that are created late do not miss the tokenizer simplifications that run aftersimplifyTemplates(). - A local struct and a lambda inside a deduced instantiation: incremental and full rebuild agree. Base reports
uninitMemberVarNoCtoron the generic template and the PR does not. Base with explicitf<int>does not report it either, so this matches existing behaviour. - Recursive instantiation through a class template (
f(T){ W<T> w{x}; f(w); }): it stops after 5 rounds and does not hang. - Conservative bail-outs: overloads
f(T)andf(T*), a non-template overload, and conflictingT, Targuments (f(1, long)) are all not deduced. - A struct passed from inside a deduced body to another template (
h(s)insidef<int>): the true positivearrayIndexOutOfBoundsis found, the same as with full rebuild.
Not completed: my timing comparison of base and PR on lib/valueflow.cpp, lib/symboldatabase.cpp and lib/templatesimplifier.cpp ran past the tool timeout and was killed, so I have no performance numbers.
Automated review of c31f6ea by Claude. The pull request was built and tested locally.
|
I dont even know what #40 is, it isnt even a correct link. |
|
Test results for commit c31f6ea (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-8720/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
|
@danmar anymore feedback? |
hmm.. don't you see this comment? AI review A pointer to an array gets past this filter. For template<class T> int count(T p) { return 100 / (int)(sizeof(*p) - sizeof(void*)); }
int g() { int a[3] = {0}; int (*p)[3] = &a; return count(p); }The PR creates |
do you have any comments about the test results? Primarily the results classified as regressions. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found one new problem. Function pointers now have the value type function in the dump, and the misra addon reports rule 11.3 for casts it should leave alone. That includes a cast from one function pointer type to another. The tokenizer turns a function-pointer cast such as (fp_t)vf into ( int * ) vf, so the cast token's type is int * while the operand's type is function *. misra_11_3 takes this for a cast between two different object pointer types. Base reports 11.1 for these casts, and wrongly 11.5 for the void (*)(void) ones. The PR reports 11.1 plus 11.3.
The last open finding from earlier reviews, C76 (a pointer to an array deduced as a pointer to a pointer), is fixed now. I checked int (*p)[3], m + 1, p + 1 and a struct member int (*arr)[2], and none of them is deduced any more. I found no new problems in the deduction or the incremental symbol database code. danmar's question in C94 about the regressions in the test-server results has no reply yet.
Comments
44 comments, 1 open, 1 new
@pfultz2, please fix, resolve or reply to the open and new comments: #43, #44.
Testing
Builds: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built.
Unit tests: ./testrunner TestSimplifyTemplate TestSymbolDatabase TestToken TestUnusedVar TestOther TestTokenizer TestVarID TestCondition TestGarbage ran 2203 tests: 0 failed, 120 todos.
Python tests: pytest other_test.py -k "template or showtime" gave 20 passed, 4 skipped and 1 xfailed.
Recheck of C76: with count(T p), the calls count(p) (int (*p)[3]), count(m + 1) (int m[2][3]), count(s.arr) (int (*arr)[2]) and count(p + 1) are no longer deduced. There is no zerodiv and no count<...> in --debug-normal.
Other probes, no new wrong results:
chardeduced with--funsigned-char(thezerodivit gives is correct).- Variadic templates and default template arguments: not deduced, which is conservative.
const std::vector<T>&: not deduced.- A member function that calls a free template with a member.
New FP in the misra addon: rule 11.3 on function-pointer casts (m1.c)
typedef int (*fp_t)(int);
struct S { int a; };
void g(fp_t fp, int (*cb)(int), void (*vf)(void))
{
int *p1 = (int *)fp;
int *p2 = (int *)cb;
unsigned int *p3 = (unsigned int *)vf;
fp_t f2 = (fp_t)vf;
(void)p1; (void)p2; (void)p3; (void)f2;
}Commands: cppcheck -q --dump m1.c && python3 addons/misra.py m1.c.dump
- base: 8.4, 11.1 (9 times), and 11.5 on lines 7 and 8.
- PR: 8.4, 11.1 (9 times), and 11.3 on lines 5, 6, 7 and 8.
The dump for line 8 shows why. The cast token ( has valueType-type="int" valueType-pointer="1", because the cast was simplified to ( int * ). The operand vf has valueType-type="function" valueType-pointer="1". misra_11_3 (vt1.pointer == vt2.pointer and vt1.type != vt2.type) therefore reports a cast between two function pointer types. Rule 11.3 is only about pointers to object types, and rule 11.1 already covers conversions of function pointers.
Automated review of b845dd3 by Claude. The pull request was built and tested locally.
| CONTAINER, | ||
| ITERATOR, | ||
| VOID, | ||
| FUNCTION, ///< a function; a pointer to it ("int (*)(int)") is counted in pointer |
There was a problem hiding this comment.
AI review
The dump now gives function pointers valueType-type="function", but the tokenizer still turns a function-pointer cast into ( int * ), and the cast token gets the type int *. misra_11_3 in addons/misra.py compares the two types (vt1.pointer == vt2.pointer and vt1.type != vt2.type), so it now reports casts it should leave alone:
typedef int (*fp_t)(int);
void g(fp_t fp, void (*vf)(void)) {
int *p1 = (int *)fp; /* PR: 11.1 + new 11.3 */
fp_t f2 = (fp_t)vf; /* PR: 11.1 + new 11.3; this cast is function pointer to function pointer */
(void)p1; (void)f2;
}cppcheck --dump m1.c && python3 addons/misra.py m1.c.dump: base gives 11.1 for these casts (and 11.5 for the void (*)(void) operand). The PR adds 11.3 on every such line. Rule 11.3 is only about pointers to object types. A fix could skip function/member-pointer operands in misra_11_3, or give the simplified cast the FUNCTION type as well. A misra test case for this would be good too.
There was a problem hiding this comment.
This is already a trac issue in: https://trac.cppcheck.net/ticket/15141
Most of the regression already are issues on main, but show more because we are instantiating the template. There are two issues I saw that are caused by the templatesimplifier. One was a simple fix(moving |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems. The unit tests pass. My probes found no false positives, crashes, hangs or memory errors that are new and not already in comments.md. Incremental updates and --template-full-rebuild gave the same warnings on every probe.
Three earlier problems are still there, and the author has linked tickets for them: signed char and char32_t are still deduced as char and unsigned int. One earlier finding is still open with no reply: the misra 11.3 false positive on function-pointer casts (C97).
Comments
39 comments, 1 open, 0 new
@pfultz2, please fix, resolve or reply to the open and new comments: #39.
Testing
Builds: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built.
Unit tests: ./testrunner TestSimplifyTemplate TestSymbolDatabase TestToken TestUnusedVar TestOther TestCondition TestGarbage TestIO TestNullPointer TestLeakAutoVar TestCmdlineParser TestTokenizer TestVarID TestConstructors TestClass ran 3277 tests: 0 failed, 166 todos.
My probes (PR, PR with --template-full-rebuild, and base):
- Deduced types: I tried
wchar_t,long double,bool,float,unsigned long long,short, string and wide string literals, char literals, suffixed literals, comparison results,volatile/const volatile *andnullptr. I also triedT&with aconst intargument,const T&with records, casts, promotedunsigned charand a ternary that mixesintandlong. All the deduced types were correct. The uncertain cases were left undeduced. - A template-heavy file: an out-of-line member template in a namespaced class, a local struct and a lambda inside a deduced body, nested deduction, private and public member templates, and recursion. Under
valgrind, both the incremental and the full-rebuild runs were clean. The warnings were the same in both modes. Compared with base, the new warnings were the expected instantiation-level warnings (for examplezerodivreached throughp.h(s)withshort s = 0). - Function-pointer
ValueType: I compared base and PR with--enable=all --inconclusiveon null checks, conditions,printf,memset, assignments and calls through the pointer. The only difference was the intended CheckIO wording, "argument type is 'function *'". - Casts from a function pointer to an object pointer: base reported
invalidPointerCastwith the wrong type "signed int *", and the PR does not report it. I count that as an improvement, not a regression. - Ternary of two function pointers: the result is typed
function *and is not deduced.
Earlier findings, rechecked on HEAD:
- Still reproduce:
signed char→f<char>andchar32_t→f<unsignedint>(these have tickets).- The misra 11.3 problem from C97:
cppcheck --dump m1.c && python3 addons/misra.py m1.c.dumpstill reportsmisra-c2012-11.3three times for function-pointer casts.
- Fixed:
- A pointer to an array (
int (*p)[3]) is no longer deduced. - The
unsignedPositivefalse positive from C24 is gone.
- A pointer to an array (
Automated review of 8a1792f by Claude. The pull request was built and tested locally.
This creates a loop where we run the TemplateSimplifier -> varids/links/AST/SymbolDatabase/ValueTypes, so on the second round of
TemplateSimplifierwe can use type information from theSymbolDatabase. Not all the passes need to run withTemplateSimpliferso there is aSymbolDatabase::finalize().On a naive run, it would delete all the AST/SymbolDatabase information, but this can be kind of slow. So I added some incremental updates by tracking where new tokens are added(plus the function bodies around changed call sites), and then refactoring functions to work on token ranges, so there is now
TokenList::createAst(start, end)and in SymbolDatabase:addSymbolsForNewTokenRanges(),updateFunctionAndVariablePointers(), a range-limitedsetValueTypeInTokenList()andfindAllScopes(const Token* startToken, const Token* endToken, Scope* startScope). Also thecreateSymbolDatabaseFindAllScopesinternals were split into reusable per-scope/per-function helpers to support this.Now this only does incremental updates on function instantiation because its much simpler to do as it only adds a
Function, its scope and locals(and the only stale references in old code are the renamed call sites, whichupdateFunctionAndVariablePointers()re-resolves by name). Instantiating a class introduces new functions and types that could be resolved in other parts of the code. So for this case it does a full rebuild.Also the template alias simplifications requires a full build as well as it restructures existing tokens throughout the list, not just in new ranges. So the "unchanged tokens keep valid info" premise of the incremental update no longer holds.
We can probably address these in the future but will require a larger refactor. I also added a
--template-full-rebuildso we can debug any issue with the incremental updates.