3434 Commits

Author SHA1 Message Date
Matheus Izvekov
13b55ad3bb
[clang] implement printing of canonical expressions (#135133)
This patch extends the canonicalization printing policy to cover
expressions
and template names, and wires that up to the template argument printer,
covering expressions, and to the expression within a dependent decltype.

This is helpful for debugging, or if these expressions somehow end up
in diagnostics, as without this patch they can print as completely
unrelated
expressions, which can be quite confusing.

This is because expressions are not uniqued, unlike types, and
when a template specialization containing an expression is the first to
be
canonicalized, the expression ends up appearing in the canonical type of
subsequent equivalent specializations.

Fixes https://github.com/llvm/llvm-project/issues/92292
2025-04-14 12:59:36 -03:00
Congcong Cai
06814834a6
[clang-tidy] treat unsigned char and signed char as char type by default in bugprone-unintended-char-ostream-output (#134870)
Add `AllowedTypes` options to support custom defined char like type.
treat `unsigned char` and `signed char` as char like type by default.
The allowed types only effect when the var decl or explicit cast to this
non-canonical type names.

Fixed: #133425
2025-04-13 12:09:50 +08:00
Congcong Cai
302bc41410
[clang-tidy] matchesAnyListedTypeName support non canonical types (#134869) 2025-04-13 12:06:48 +08:00
Björn Svensson
0276915a6c
[clang-tidy] Fix cert-err33-c to ignore functions with same prefixes as target (#135160)
PR #82952 introduced regex matching for `CheckedFunctions` in
`UnusedReturnValueCheck` which is used by the checker `cert-err33-c`.

Add a testcase and fix false positives by adding end-of-string to target
regex's.

---------

Signed-off-by: Björn Svensson <bjorn.a.svensson@est.tech>
2025-04-11 10:08:29 +02:00
Congcong Cai
5aae0ee660
[clang-tidy] give dummy path when create ClangTidyContext (#134670)
#121323 changed the way the absolute path is computed. Empty file name
will cause absolute path ignore current folder.
This patch add "dummy" file name to avoid this issue
Fixed: #134502
2025-04-08 10:47:39 +08:00
Matheus Izvekov
d057811655
[clang] fix diagnostic printing of expressions ignoring LangOpts (#134693)
Currently when printing a template argument of expression type, the
expression is converted immediately into a string to be sent to the
diagnostic engine, unsing a fake LangOpts.

This makes the expression printing look incorrect for the current
language, besides being inneficient, as we don't actually need to print
the expression if the diagnostic would be ignored.

This fixes a nastiness with the TemplateArgument constructor for
expressions being implicit, and all current users just passing an
expression to a diagnostic were implicitly going through the template
argument path.

The expressions are also being printed unquoted. This will be fixed in a
subsequent patch, as the test churn is much larger.
2025-04-07 23:19:32 -03:00
Baranov Victor
da6e2454ff
[clang-tidy] Improve bugprone-capturing-this-in-member-variable check: add support of bind functions. (#132635)
Improve `bugprone-capturing-this-in-member-variable` check:
Added support of `bind`-like functions that capture and store `this`
pointer in class member.

Closes https://github.com/llvm/llvm-project/issues/131220.
2025-04-07 09:57:55 +08:00
Zahira Ammarguellat
ebb0e6cb25
[NFC] Remove dead code detected by code sanitizer. (#134385)
The code sanitizer is failing with this error: `Execution cannot reach
this statement.`
The execution code path would early exit at line 928 if `(Lil && Ril) =
true`.
2025-04-04 15:21:47 -04:00
Jan Svoboda
1688c3062a
[clang] Do not share ownership of PreprocessorOptions (#133467)
This PR makes it so that `CompilerInvocation` is the sole owner of the
`PreprocessorOptions` instance.
2025-04-04 10:11:14 -07:00
Carlos Galvez
6333fa5160
[clang-tidy] Fix broken HeaderFilterRegex when read from config file (#133582)
PR https://github.com/llvm/llvm-project/pull/91400 broke the usage of
HeaderFilterRegex via config file, because it is now created at a
different point in the execution and leads to a different value.

The result of that is that using HeaderFilterRegex only in the config
file does NOT work, in other words clang-tidy stops triggering warnings
on header files, thereby losing a lot of coverage.

This patch reverts the logic so that the header filter is created upon
calling the getHeaderFilter() function.

Additionally, this patch adds 2 unit tests to prevent regressions in the
future:

- One of them, "simple", tests the most basic use case with a single
top-level .clang-tidy file.

- The second one, "inheritance", demonstrates that the subfolder only
gets warnings from headers within it, and not from parent headers.

Fixes #118009
Fixes #121969
Fixes #133453

Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
2025-04-03 09:28:34 +02:00
Matheus Izvekov
ad1ca5f4a2
[clang] Concepts: support pack expansions for type constraints (#132626)
This reverts an earlier attempt
(adb0d8ddceb143749c519d14b8b31b481071da77 and
50e5411e4247421fd606f0a206682fcdf0303ae3) to support these expansions,
which was limited to type arguments and which subverted the purpose
of SubstTemplateTypeParmType.

This propagates the ArgumentPackSubstitutionIndex along with the
AssociatedConstraint, so that the pack expansion works, without
needing any new transforms or otherwise any changes to the template
instantiation process.

This keeps the tests from the reverted commits, and adds a few more
showing the new solution also works for NTTPs.

Fixes https://github.com/llvm/llvm-project/issues/131798
2025-04-01 21:11:56 -03:00
Kazu Hirata
ee3c892b35
[clang-tidy] Use DenseMap::insert_range (NFC) (#133844)
We can safely switch to insert_range here because
SyntheticStmtSourceMap starts out empty in the constructor.  Also
TheCFG->synthetic_stmts() comes from DenseMap, so we know that the
keys are unique.  That is, operator[] and insert are equivalent in
this particular case.
2025-03-31 22:11:06 -07:00
Kazu Hirata
884b19ab40
[clang-tools-extra] Use *Set::insert_range (NFC) (#133589) 2025-03-29 12:22:13 -07:00
Baranov Victor
d6dcd985c0
[clang-tidy] Fix thread_local false positives in misc-use-internal-linkage check (#132573)
Based on C++ standard (see issue
https://github.com/llvm/llvm-project/issues/131679) and
[StackOverflow](https://stackoverflow.com/questions/22794382/are-c11-thread-local-variables-automatically-static)
`thread_local` variables are implicitly `static` so we should not
suggest adding `static` on a `thread_local` variables. I'd appreciate if
someone else will confirm this too because reading standard is tricky.

However, many people still use `static` and `thread_local` together:
[github
code-search](https://github.com/search?type=code&q=%22static+thread_local%22+language%3AC%2B%2B).
Maybe disabling warnings on `thread_local` should be made as a flag?
WDYT?

Closes https://github.com/llvm/llvm-project/issues/131679.
2025-03-28 21:33:58 +08:00
Congcong Cai
01e505b992
[clang-tidy][misc-const-correctness] fix fp when using const array type. (#133018)
Fixed: #132931
const array is immutable in C/C++ language design, we don't need to
check constness for it.
2025-03-28 06:21:15 +08:00
Jan Svoboda
7a370748c0
[clang][lex] Store non-owning options ref in HeaderSearch (#132780)
This makes it so that `CompilerInvocation` can be the only entity that
manages ownership of `HeaderSearchOptions`, making it possible to
implement copy-on-write semantics.
2025-03-25 12:14:06 -07:00
Carlos Galvez
0fb4ef40b1
Revert "[clang-tidy] Avoid processing declarations in system headers … (#132743)
…(#128150)"

This was too aggressive, and leads to problems for downstream users:
https://github.com/llvm/llvm-project/pull/128150#issuecomment-2739803409

Let's revert and reland it once we have addressed the problems.

This reverts commit e4a8969e56572371201863594b3a549de2e23f32.

Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
2025-03-24 20:47:57 +01:00
Kazu Hirata
76b999d70f
[clang-tidy] Avoid repeated map lookups (NFC) (#132656) 2025-03-24 00:13:21 -07:00
Kazu Hirata
4a7643400c
[clang-tools-extra] Use *Set::insert_range (NFC) (#132589)
DenseSet, SmallPtrSet, SmallSet, SetVector, and StringSet recently
gained C++23-style insert_range.  This patch replaces:

  Dest.insert(Src.begin(), Src.end());

with:

  Dest.insert_range(Src);
2025-03-23 00:23:19 -07:00
Baranov Victor
2909c420f6
[clang-tidy] modernize-use-starts-ends-with: fix false positives on find and rfind (#129564)
Also document cases with two or three arguments (matching default arguments)
this check matches.

Closes https://github.com/llvm/llvm-project/issues/129498.
2025-03-22 08:07:58 -04:00
Matheus Izvekov
14f7bd63b9
Reland: [clang] preserve class type sugar when taking pointer to member (#132401)
Original PR: #130537
Originally reverted due to revert of dependent commit. Relanding with no
changes.

This changes the MemberPointerType representation to use a
NestedNameSpecifier instead of a Type to represent the base class.

Since the qualifiers are always parsed as nested names, there was an
impedance mismatch when converting these back and forth into types, and
this led to issues in preserving sugar.

The nested names are indeed a better match for these, as the differences
which a QualType can represent cannot be expressed syntatically, and
they represent the use case more exactly, being either dependent or
referring to a CXXRecord, unqualified.

This patch also makes the MemberPointerType able to represent sugar for
a {up/downcast}cast conversion of the base class, although for now the
underlying type is canonical, as preserving the sugar up to that point
requires further work.

As usual, includes a few drive-by fixes in order to make use of the
improvements.
2025-03-21 13:20:52 -03:00
Matheus Izvekov
1416566449
Reland: [clang] NFC: Clear some uses of MemberPointerType::getClass (#132317)
Relands Original PR: https://github.com/llvm/llvm-project/pull/131965
Addresses
https://github.com/llvm/llvm-project/pull/131965#issuecomment-2741619498
* Fixes isIncompleteType for injected classes

This clears up some uses of getClass on MemberPointerType when
equivalent uses of getMostRecentCXXRecordDecl would be just as simple or
simpler.
    
This is split-off from a larger patch which removes getClass, in order
to facilitate review.
2025-03-21 10:54:24 -03:00
Matheus Izvekov
335a4614de
Revert "[clang] NFC: Clear some uses of MemberPointerType::getClass" (#132281)
Reverts llvm/llvm-project#131965

Reverted due to issue reported here:
https://github.com/llvm/llvm-project/pull/131965#issuecomment-2741619498
2025-03-20 17:54:21 -03:00
Matheus Izvekov
5151e6d7fe
Revert "Reland: [clang] preserve class type sugar when taking pointer to member" (#132280)
Reverts llvm/llvm-project#132234

Needs to be reverted due to dependency.

This blocks reverting another PR, see here:
https://github.com/llvm/llvm-project/pull/131965#issuecomment-2741619498
2025-03-20 17:52:48 -03:00
Matheus Izvekov
578f38cd08
Reland: [clang] preserve class type sugar when taking pointer to member (#132234)
Original PR: #130537
Reland after updating lldb too.

This changes the MemberPointerType representation to use a
NestedNameSpecifier instead of a Type to represent the base class.

Since the qualifiers are always parsed as nested names, there was an
impedance mismatch when converting these back and forth into types, and
this led to issues in preserving sugar.

The nested names are indeed a better match for these, as the differences
which a QualType can represent cannot be expressed syntatically, and
they represent the use case more exactly, being either dependent or
referring to a CXXRecord, unqualified.

This patch also makes the MemberPointerType able to represent sugar for
a {up/downcast}cast conversion of the base class, although for now the
underlying type is canonical, as preserving the sugar up to that point
requires further work.

As usual, includes a few drive-by fixes in order to make use of the
improvements.
2025-03-20 15:33:54 -03:00
Matheus Izvekov
6cd62ad08c
Revert "[clang] improve class type sugar preservation in pointers to members" (#132215)
Reverts llvm/llvm-project#130537

This missed updating lldb, which we didn't notice due to lack of
pre-commit CI.
2025-03-20 11:09:25 -03:00
Matheus Izvekov
9b1f905b48
[clang] improve class type sugar preservation in pointers to members (#130537)
This changes the MemberPointerType representation to use a
NestedNameSpecifier instead of a Type to represent the class.

Since the qualifiers are always parsed as nested names, there was an
impedance mismatch when converting these back and forth into types, and
this led to issues in preserving sugar.

The nested names are indeed a better match for these, as the differences
which a QualType can represent cannot be expressed syntactically, and it
also represents the use case more exactly, being either dependent or
referring to a CXXRecord, unqualified.

This patch also makes the MemberPointerType able to represent sugar for
a {up/downcast}cast conversion of the base class, although for now the
underlying type is canonical, as preserving the sugar up to that point
requires further work.

As usual, includes a few drive-by fixes in order to make use of the
improvements, and removing some duplications, for example
CheckBaseClassAccess is deduplicated from across SemaAccess and
SemaCast.
2025-03-20 10:30:24 -03:00
Matheus Izvekov
fd7be0d2e9
[clang] NFC: Clear some uses of MemberPointerType::getClass (#131965) 2025-03-19 21:36:10 -03:00
Alexander Shaposhnikov
297f0b3f4c
[CudaSPIRV] Allow using integral non-type template parameters as attribute args (#131546)
Allow using integral non-type template parameters as attribute arguments
of
reqd_work_group_size and work_group_size_hint.

Test plan:
ninja check-all
2025-03-19 10:11:18 -07:00
Jan Voung
6f659b0060
[clang][dataflow] For bugprone-unchecked-optional-access report range (#131055)
Report the range in diagnostics, in addition to the location
in case the range helps disambiguate a little in chained `->`
expressions.
```
b->a->f->x = 1;
^~~~~~~
```
instead of just:
```
b->a->f->x = 1;
^
```
As a followup we should probably also report the location/range
of an `->` if that operator is used. Like:
```
b->a->f->x = 1;
       ^~
```
2025-03-17 16:04:15 -04:00
Julian Ruess
ccfabe8380
[clang-tidy-diff] Add an option to treat warnings as errors (#128221)
This patch allows to treat warnings as erros using clang-tidy-diff.

Co-authored-by: Piotr Zegar <me@piotrzegar.pl>
2025-03-17 15:55:40 +08:00
Congcong Cai
3b1e18c2db
[clang-tidy] Add new check bugprone-capture-this-by-field (#130297)
Finds lambda captures that capture the ``this`` pointer and store it as
class
members without handle the copy and move constructors and the
assignments.

Capture this in a lambda and store it as a class member is dangerous
because the
lambda can outlive the object it captures. Especially when the object is
copied
or moved, the captured ``this`` pointer will be implicitly propagated to
the
new object. Most of the time, people will believe that the captured
``this``
pointer points to the new object, which will lead to bugs.

Fixes: #120863

---------

Co-authored-by: Baranov Victor <70346889+vbvictor@users.noreply.github.com>
Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
2025-03-17 15:11:43 +08:00
David Rivera
5e65b40f9c
[clang-tidy] detect explicit casting within modernize-use-default-member-init (#129408)
This aims to fix a portion of #122480. Added some matchers to detect
explicit casting which utilize builtin types as its source expression.
these are the various forms of casting supported I thought would useful
for this check:

- C Style explicit casting
- Static explicit casting
- Functional explicit casting
2025-03-15 23:15:12 +01:00
Congcong Cai
1a68269e28
[clang-tidy] support pointee mutation check in misc-const-correctness (#130494)
Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
2025-03-14 21:18:43 +08:00
Carlos Galvez
e4a8969e56
[clang-tidy] Avoid processing declarations in system headers (#128150)
[clang-tidy] Avoid processing declarations in system headers

Currently, clang-tidy processes the entire TranslationUnit, including
declarations in system headers. However, the work done in system
headers is discarded at the very end when presenting results, unless
the SystemHeaders option is active.

This is a lot of wasted work, and makes clang-tidy very slow.
In comparison, clangd only processes declarations in the main file,
and it's claimed to be 10x faster than clang-tidy:

https://github.com/lljbash/clangd-tidy

To solve this problem, we can apply a similar solution done in clangd
into clang-tidy. We do this by changing the traversal scope from the
default TranslationUnitDecl, to only contain the top-level declarations
that are _not_ part of system headers. We do this in the
MatchASTConsumer class, so the logic can be reused by other tools.
This behavior is currently off by default, and only clang-tidy
enables skipping system headers. If wanted, this behavior can be
activated by other tools in follow-up patches.

I had to move MatchFinderOptions out of the MatchFinder class,
because otherwise I could not set a default value for the
"bool SkipSystemHeaders" member otherwise. The compiler error message
was "default member initializer required before the end of its
enclosing class".

Note: this behavior is not active if the user requests warnings from
system headers via the SystemHeaders option.

Note2: out of all the unit tests, only one of them fails:

readability/identifier-naming-anon-record-fields.cpp

This is because the limited traversal scope no longer includes the
"CXXRecordDecl" of the global anonymous union, see:
https://github.com/llvm/llvm-project/issues/130618

I have not found a way to make this work. For now, document the
technical debt introduced.

Note3: I have purposely decided to make this new feature enabled by
default, instead of adding a new "opt-in/opt-out" flag. Having a new
flag would mean duplicating all our tests to ensure they work in both
modes, which would be infeasible. Having it enabled by default allow
people to get the benefits immediately. Given that all unit tests pass,
the risk for regressions is low. Even if that's the case, the only
issue would be false negatives (fewer things are detected), which
are much more tolerable than false positives.

Credits: original implementation by @njames93, here:
https://reviews.llvm.org/D150126

This implementation is simpler in the sense that it does not consider
HeaderFilterRegex to filter even further. A follow-up patch could
include the functionality if wanted.

Fixes #52959

Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
2025-03-14 13:16:17 +01:00
Congcong Cai
0e4ba47ca8
[clang-tidy] support to detect conversion in make_optional for bugprone-optional-value-conversion (#130417)
Add support for std::make_optional.

Fixes #119554
2025-03-12 06:12:09 +08:00
Tommy Chen
d22d14375d
[clang-tidy] support different precisions (#130540)
Support float and long double versions of the math functions for
UseStdNumbersCheck.
For example, after this commit the check is able to catch `sqrtf(2)` and
`expl(1)`.

Fixes: #130325
2025-03-11 18:05:01 +01:00
David Rivera
517c6778ea
[clang-tidy] Add check on constexpr & static values in modernize-use-default-member-init (#129425)
This aims to fix a portion of #122480. Simply added a check to look for
either compile time initialized variables or static stored variables.
2025-03-11 18:00:43 +01:00
Congcong Cai
5cfc37b345
[clang-tidy][NFC]clean ConstCorrectnessCheck (#130493) 2025-03-11 14:53:06 +08:00
Congcong Cai
318bef91ea
[clang-tidy][NFC]refactor matcher for bugprone-optional-value-conversion (#130415)
The old `constructFrom` has hidden requirement which TypeMatcher must be used before ArgumentMatcher because there are bind inside.
Inlining this function to make it more intuitive.
2025-03-11 14:52:18 +08:00
Baranov Victor
75f76d482c
[clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (#121291)
Add new clang-tidy check that finds potentially erroneous calls to
``reset()`` method on smart pointers when
the pointee type also has a ``reset()`` method.

It's easy to make typo and delete object because the difference between
``.`` and ``->`` is really small.

Sometimes IDE's autocomplete will change ``->`` to ``.`` automatically.
For example, developer wrote ``ptr->res`` but after pressing _Tab_ it
became ``ptr.reset()``.

Fixes #120908
2025-03-11 07:22:15 +01:00
Andrewyuan34
2a3e782f40
[clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (#127162)
This PR fixes issue #124815 by correcting the handling of `nullptr` with
`std::unique_ptr` in the `modernize-use-ranges` check.

Updated the logic to suppress warnings for `nullptr` in `std::find`.
2025-03-09 20:09:59 +08:00
Congcong Cai
6f7570c200
[clang-tidy][misc-use-internal-linkage] fix false positives for function or variable in header file which contains macro expansion (#129594)
When check whether in main file, spelling loc will lead to `<scratch
space>`. instead, expansion loc is close to loc after preprocess. It is
suitable to analyze linkage.
2025-03-08 13:41:24 +08:00
Baranov Victor
e9c8d42b89
[clang-tidy] misc-unused-using-decls: add correct handling of operator"" with template parametes (#129392)
Fixes false-positives when operator"" has template paremetes, e.g.
```cpp
template <char... Ts>
int operator""_r() {
    return {};
}
```
Closes https://github.com/llvm/llvm-project/issues/53444.

---------

Co-authored-by: Congcong Cai <congcongcai0907@163.com>
2025-03-03 13:14:27 +08:00
Congcong Cai
56762b7ace
[clang-tidy] Add new check bugprone-unintended-char-ostream-output (#127720)
It wants to find unintended character output from `uint8_t` and `int8_t`
to an ostream.
e.g.
```c++
uint8_t v = 9;
std::cout << v;
```

---------

Co-authored-by: whisperity <whisperity@gmail.com>
2025-02-27 19:36:24 +08:00
David Rivera
556e4dbdcd
[clang-tidy] Fix performance-move-const-arg false negative in ternary… (#128402)
This PR aims to fix `performance-move-const-arg` #126515

## Changes
Enhanced the `performance-move-arg` check in Clang-Tidy to detect cases
where `std::move` is used
in **ternary operator expressions which was not being matched therefore
being tagged as a false negative**

## Testing
- A new mock class has been where the changes have been tested & all
tests pass

I'd appreciate any feedback since this is my first time contributing to
LLVM.
2025-02-27 19:35:10 +08:00
Congcong Cai
a00586171c
[clang-tidy]improve performance-unnecessary-value-param performance (#128383)
Tolerate fix-it breaking compilation when functions is used as pointers.
`isReferencedOutsideOfCallExpr` will visit the whole translate unit for
each matched function decls. It will waste lots of cpu time in some big
cpp files.
But the benefits of this validation are limited. Lots of function usage
are out of current translation unit.

After removing this validation step, the check profiling changes from
5.7 to 1.1 in SemaExprCXX.cpp, which is similar to version 18.
2025-02-26 20:39:41 +08:00
Nathan Ridge
7a4cb9bac5
[clang-tidy][NFC] Expose HeuristicResolver::lookupDependentName() and use it in StandaloneEmptyCheck (#128391)
The use replaces CXXRecordDecl::lookupDependentName() which
HeuristicResolver aims to supersede.
2025-02-24 11:31:46 -05:00
Benjamin Kramer
e1cc5e9f9a [clang-tidy] Fix build after 3dc159431be7a8c5f1a26a8bd57794f1c7008969 2025-02-24 12:40:02 +01:00
Baranov Victor
8363b0a6ba
[clang-tidy] add AllowedTypes option to misc-const-correctness (#122951)
Add option `AllowedTypes` which allow users to specify types they want
to exclude from const-correctness check.

Small real-world example:
```cpp
#include <mutex>

int main() {
  std::mutex m;
  std::lock_guard<std::mutex> l(m); // we want to ignore it since std::lock_guard is already immutable.
}
```

Closes issue https://github.com/llvm/llvm-project/issues/122592
2025-02-20 05:47:17 +08:00