Suggests switching the initialization pattern of `absl::Cleanup` instances from the factory function to class template argument deduction (CTAD) in C++17 and higher.
Reviewed By: ymandel
Differential Revision: https://reviews.llvm.org/D113195
Now in libcxx and clang, all the coroutine components are defined in
std::experimental namespace.
And now the coroutine TS is merged into C++20. So in the working draft
like N4892, we could find the coroutine components is defined in std
namespace instead of std::experimental namespace.
And the coroutine support in clang seems to be relatively stable. So I
think it may be suitable to move the coroutine component into the
experiment namespace now.
This patch would make clang lookup coroutine_traits in std namespace
first. For the compatibility consideration, clang would lookup in
std::experimental namespace if it can't find definitions in std
namespace. So the existing codes wouldn't be break after update
compiler.
And in case the compiler found std::coroutine_traits and
std::experimental::coroutine_traits at the same time, it would emit an
error for it.
The support for looking up std::experimental::coroutine_traits would be
removed in Clang16.
Reviewed By: lxfind, Quuxplusone
Differential Revision: https://reviews.llvm.org/D108696
Back in the mists of time, the CXXRecordDecl for the injected-class-name was
a redecl of the outer class itself.
This got changed in 470c454a61, but only for plain
classes: class template instantation was still detecting the injected-class-name
in the template body and marking its instantiation as a redecl.
This causes some subtle inconsistent behavior between the two, e.g.
hasDefinition() returns true for Foo<int>::Foo but false for Bar::Bar.
This is the root cause of PR51912.
Differential Revision: https://reviews.llvm.org/D112765
The CERT rule ERR33-C can be modeled partially by the existing check
'bugprone-unused-return-value'. The existing check is reused with
a fixed set of checked functions.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D112409
We're missing all cases where the return value is a type alias.
Unfortunately, this includes things we care about, such as
`std::vector<T>::operator[]` (return value is `const_reference`,
not `const T&`).
Match the canonical type instead.
Differential Revision: https://reviews.llvm.org/D112722
The string table `DefaultIgnoredParameterTypeSuffixes` has a typo:
`ForwardIt` is mistyped as `FowardIt`.
Correct typo and add test coverage.
Differential Revision: https://reviews.llvm.org/D112596
clang-tidy can be used to statically analyze CUDA code,
thanks to clang being able to compile CUDA code natively.
This makes clang-tidy the one and only open-source
static analyzer for CUDA.
However it currently warns for native CUDA built-in
variables, like threadIdx, due to the way they
are implemented in clang.
Users don't need to know the details of the clang
implementation, and they should continue to write
idiomatic code. Therefore, suppress the warning
if a CUDA built-in variable is encountered.
Fixes https://bugs.llvm.org/show_bug.cgi?id=48758
To simplify suppressing warnings (for example, for
when multiple check aliases are enabled).
The globbing format reuses the same code as for
globbing when enabling checks, so the semantics
and behavior is identical.
Differential Revision: https://reviews.llvm.org/D111208
Incorrectly triggers for template classes that inherit
from a base class that has virtual destructor.
Any class inheriting from a base that has a virtual destructor
will have their destructor also virtual, as per the Standard:
https://timsong-cpp.github.io/cppwp/n4140/class.dtor#9
> If a class has a base class with a virtual destructor,
> its destructor (whether user- or implicitly-declared) is virtual.
Added unit tests to prevent regression.
Fixes bug https://bugs.llvm.org/show_bug.cgi?id=51912
Differential Revision: https://reviews.llvm.org/D110614
If the Node has an invalid location, it will trigger assert in
isInSystemHeader(...).
void test() {
__builtin_va_list __args;
// __builtin_va_list has no defination in any source file and its
// CXXConstructorDecl has invalid sourcelocation
}
coredump with "Assertion `Loc.isValid() && "Can't get file
characteristic of invalid loc!"' failed." in
getFileCharacteristic(SourceLocation).
This requirement was introduced in the C++ Core guidelines in 2016:
1894380d0a
Then clang-tidy got updated to comply with the rule.
However in 2019 this decision was reverted:
5fdfb20b76
Therefore we need to apply the correct configuration to
clang-tidy again.
This also makes this cppcoreguidelines check consistent
with the other 2 alias checks: hicpp-use-override and
modernize-use-override.
Additionally, add another RUN line to the unit test,
to make sure cppcoreguidelines-explicit-virtual-functions
is tested.
Add support for NOLINTBEGIN ... NOLINTEND comments to suppress
clang-tidy warnings over multiple lines. All lines between the "begin"
and "end" markers are suppressed.
Example:
// NOLINTBEGIN(some-check)
<Code with warnings to be suppressed, line 1>
<Code with warnings to be suppressed, line 2>
<Code with warnings to be suppressed, line 3>
// NOLINTEND(some-check)
Follows similar syntax as the NOLINT and NOLINTNEXTLINE comments
that are already implemented, i.e. allows multiple checks to be provided
in parentheses; suppresses all checks if the parentheses are omitted,
etc.
If the comments are misused, e.g. using a NOLINTBEGIN but not
terminating it with a NOLINTEND, a clang-tidy-nolint diagnostic
message pointing to the misuse is generated.
As part of implementing this feature, the following bugs were fixed in
existing code:
IsNOLINTFound(): IsNOLINTFound("NOLINT", Str) returns true when Str is
"NOLINTNEXTLINE". This is because the textual search finds NOLINT as
the stem of NOLINTNEXTLINE.
LineIsMarkedWithNOLINT(): NOLINTNEXTLINEs on the very first line of a
file are ignored. This is due to rsplit('\n\').second returning a blank
string when there are no more newline chars to split on.
Fixes https://bugs.llvm.org/show_bug.cgi?id=51790. The check triggers
incorrectly with non-type template parameters.
A bisect determined that the bug was introduced here:
ea2225a10b
Unfortunately that patch can no longer be reverted on top of the main
branch, so add a fix instead. Add a unit test to avoid regression in
the future.
At most one variant member of a union may have a default member
initializer. The case of anonymous records with multiple levels of
nesting like the following also needs to meet this rule. The original
logic is to horizontally obtain all the member variables in a record
that need to be initialized and then filter to the variables that need
to be fixed. Obviously, it is impossible to correctly initialize the
desired variables according to the nesting relationship.
See Example 3 in class.union
union U {
U() {}
int x; // int x{};
union {
int k; // int k{}; <== wrong fix
};
union {
int z; // int z{}; <== wrong fix
int y;
};
};
This reverts commit 626586fc25.
Tweak the test for Windows. Windows defaults to delayed template
parsing, which resulted in the main template definition not registering
the test on Windows. Process the file with the additional
`-fno-delayed-template-parsing` flag to change the default beahviour.
Additionally, add an extra check for the fix it and use a more robust
test to ensure that the value is always evaluated.
Differential Revision: https://reviews.llvm.org/D108893
This reverts commit 76dc8ac36d.
Restore the change. The test had an incorrect negative from testing.
The test is expected to trigger a failure as mentioned in the review
comments. This corrects the test and should resolve the failure.
This introduces a new check, readability-containter-data-pointer. This
check is meant to catch the cases where the user may be trying to
materialize the data pointer by taking the address of the 0-th member of
a container. With C++11 or newer, the `data` member should be used for
this. This provides the following benefits:
- `.data()` is easier to read than `&[0]`
- it avoids an unnecessary re-materialization of the pointer
* this doesn't matter in the case of optimized code, but in the case
of unoptimized code, this will be visible
- it avoids a potential invalid memory de-reference caused by the
indexing when the container is empty (in debug mode, clang will
normally optimize away the re-materialization in optimized builds).
The small potential behavioural change raises the question of where the
check should belong. A reasoning of defense in depth applies here, and
this does an unchecked conversion, with the assumption that users can
use the static analyzer to catch cases where we can statically identify
an invalid memory de-reference. For the cases where the static analysis
is unable to prove the size of the container, UBSan can be used to track
the invalid access.
Special thanks to Aaron Ballmann for the discussion on whether this
check would be useful and where to place it.
This also partially resolves PR26817!
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D108893
Finds base classes and structs whose destructor is neither public and
virtual nor protected and non-virtual.
A base class's destructor should be specified in one of these ways to
prevent undefined behaviour.
Fixes are available for user-declared and implicit destructors that are
either public and non-virtual or protected and virtual.
This check implements C.35 [1] from the CppCoreGuidelines.
Reviewed By: aaron.ballman, njames93
Differential Revision: http://reviews.llvm.org/D102325
[1]: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-dtor-virtual
Low-level code may occasionally deal with direct access by concrete addresses
such as 0x1234. Values at these addresses act like globals: they can change
at any time. They typically wear volatile qualifiers.
Suppress all warnings on loops with conditions that involve casting anything to
a pointer-to-...-pointer-to-volatile type.
The closely related bugprone-redundant-branch-condition check
doesn't seem to be affected. Add a test just in case.
Differential Revision: https://reviews.llvm.org/D108808
This reverts commit 2fbd254aa4, which broke the libc++ CI. I'm reverting
to get things stable again until we've figured out a way forward.
Differential Revision: https://reviews.llvm.org/D108696
Summary: Now in libcxx and clang, all the coroutine components are
defined in std::experimental namespace.
And now the coroutine TS is merged into C++20. So in the working draft
like N4892, we could find the coroutine components is defined in std
namespace instead of std::experimental namespace.
And the coroutine support in clang seems to be relatively stable. So I
think it may be suitable to move the coroutine component into the
experiment namespace now.
But move the coroutine component into the std namespace may be an break
change. So I planned to split this change into two patch. One in clang
and other in libcxx.
This patch would make clang lookup coroutine_traits in std namespace
first. For the compatibility consideration, clang would lookup in
std::experimental namespace if it can't find definitions in std
namespace and emit a warning in this case. So the existing codes
wouldn't be break after update compiler.
Test Plan: check-clang, check-libcxx
Reviewed By: lxfind
Differential Revision: https://reviews.llvm.org/D108696
https://bugs.llvm.org/show_bug.cgi?id=50069
When clang-tidy sees:
```
if (true) [[unlikely]] {
...
}
```
It thinks the braces are missing and add them again.
```
if (true) { [[unlikely]] {
...
}
}
```
This revision aims to prevent that incorrect code generation
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D105479
The overload of the constructor will repeatedly fix the member variables that need to be initialized.
Removed the duplicate '{}'.
```
struct A {
A() {}
A(int) {}
int _var; // int _var{}{}; <-- wrong fix
};
```
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D107641
Add a check for enforcing minimum length for variable names. A default
minimum length of three characters is applied to regular variables
(including function parameters). Loop counters and exception variables
have a minimum of two characters. Additionally, the 'i', 'j' and 'k'
are accepted as legacy values.
All three sizes, as well as the list of accepted legacy loop counter
names are configurable.
std::string, std::string_view, and absl::string_view all have a three-parameter version of find()
which has a "count" (or "n") paremeter limiting the size of the substring to search. We don't want
to propose changing to absl::StrContains in those cases. This change fixes that and adds unit tests
to confirm.
Reviewed By: ymandel
Differential Revision: https://reviews.llvm.org/D107837
This patch tries to fix command line too long problem on Windows for
https://reviews.llvm.org/D86671.
The command line is too long with check_clang_tidy.py program on Windows,
because the configuration is long for regression test. Fix this issue by
passing the settings in file instead.
Differential Revision: https://reviews.llvm.org/D107325
FixIt, and add support for initialization check of scoped enum
In C++, the enumeration is never Integer, and the enumeration condition judgment is added to avoid compiling errors when it is initialized to an integer.
Add support for initialization check of scope enum.
As the following case show, clang-tidy will give a wrong automatic fix:
enum Color {Red, Green, Blue};
enum class Gender {Male, Female};
void func() {
Color color; // Color color = 0; <--- fix bug
Gender gender; // <--- no warning
}
Reviewd By: aaron.ballman, whisperity
Differential Revision: http://reviews.llvm.org/D106431
Many concepts emulation libraries, such as the one found in Range v3, tend to
use non-type template parameters for the enable_if type expression, due to
their versatility in template functions and constructors containing variadic
template parameter packs.
Unfortunately the bugprone-forwarding-reference-overload check does not
handle non-type template parameters, as was first noted in this bug report:
https://bugs.llvm.org/show_bug.cgi?id=38081
This patch fixes this long standing issue and allows for the check to be suppressed
with the use of a non-type template parameter containing enable_if or enable_if_t in
the type expression, so long as it has a default literal value.
An otherwise unexercised code path related to trying to model
"array-to-pointer decay" resulted in a null pointer dereference crash
when parameters of type "reference to array" were encountered.
Fixes crash report http://bugs.llvm.org/show_bug.cgi?id=50995.
Reviewed By: aaron.ballman
Differential Revision: http://reviews.llvm.org/D106946
Make the check handle cases of the "common type" involved in the mix
being non-trivial, e.g. pointers, references, attributes, these things
coming from typedefs, etc.
This results in clearer diagnostics that have more coverage in their
explanation, such as saying `const int &` as common type instead of
`int`.
Reviewed By: aaron.ballman
Differential Revision: http://reviews.llvm.org/D106442
Add string list option of type names analagous to `AllowedTypes` which lets
users specify a list of ExcludedContainerTypes.
Types matching this list will not trigger the check when an expensive variable
is copy initialized from a const accessor method they provide, i.e.:
```
ExcludedContainerTypes = 'ExcludedType'
void foo() {
ExcludedType<ExpensiveToCopy> Container;
const ExpensiveToCopy NecessaryCopy = Container.get();
}
```
Even though an expensive to copy variable is copy initialized the check does not
trigger because the container type is excluded.
This is useful for container types that don't own their data, such as view types
where modification of the returned references in other places cannot be reliably
tracked, or const incorrect types.
Differential Revision: https://reviews.llvm.org/D106173
Reviewed-by: ymandel
This can happen when a template with two parameter types is instantiated with a
single type. The fix would only be valid for this instantiation but fail for
others that rely on an implicit type conversion.
The test cases illustrate when the check should trigger and when not.
Differential Revision: https://reviews.llvm.org/D106011
@vabridgers identified a way to crash the check by running on code that
involve `AttributedType`s. This patch fixes the check to first and
foremost not crash, but also improves the logic handling qualifiers.
If the types contain any additional (not just CVR) qualifiers that are
not the same, they will not be deemed mixable. The logic for CVR-Mixing
and the `QualifiersMix` check option remain unchanged.
Reviewed By: aaron.ballman, vabridgers
Differential Revision: http://reviews.llvm.org/D106361
Finds function calls where the call arguments might be provided in an
incorrect order, based on the comparison (via string metrics) of the
parameter names and the argument names against each other.
A diagnostic is emitted if an argument name is similar to a *different*
parameter than the one currently passed to, and it is sufficiently
dissimilar to the one it **is** passed to currently.
False-positive warnings from this check are useful to indicate bad
naming convention issues, even if a swap isn't necessary.
This check does not generate FixIts.
Originally implemented by @varjujan as his Master's Thesis work.
The check was subsequently taken over by @barancsuk who added type
conformity checks to silence false positive matches.
The work by @whisperity involved driving the check's review and fixing
some more bugs in the process.
Reviewed By: aaron.ballman, alexfh
Differential Revision: http://reviews.llvm.org/D20689
Co-authored-by: János Varjú <varjujanos2@gmail.com>
Co-authored-by: Lilla Barancsuk <barancsuklilla@gmail.com>
When deleting the copy assignment statement because copied variable is not used
only remove trailing comments on the same line.
Differential Revision: https://reviews.llvm.org/D105734
Reviewed-by: ymandel
Structured bindings can currently trigger the check and lead to a wrong
fix. Because the DecompositionDecl itself is not used and the check does not
iterate through its the decl's bindings to verify whether the bindings' holding
vars are used this leads to the whole statement to be deleted.
To support structured bindings properly 3 cases would need to be considered.
1. All holding vars are not used -> The statement can be deleted.
2. All holding vars are used as const or not used -> auto can be converted to const auto&.
3. Neither case is true -> leave unchanged.
In the check we'll have to separate the logic that determines this from the code
that produces the diagnostic and fixes and first determine which of the cases
we're dealing with before creating fixes.
Since this is a bigger refactoring we'll disable structured bindings for now to
prevent incorrect fixes.
Differential Revision: https://reviews.llvm.org/D105727
Reviewed-by: ymandel
While the original check's purpose is to identify potentially dangerous
functions based on the parameter types (as identifier names do not mean
anything when it comes to the language rules), unfortunately, such a plain
interface check rule can be incredibly noisy. While the previous
"filtering heuristic" is able to find many similar usages, there is an entire
class of parameters that should not be warned about very easily mixed by that
check: parameters that have a name and their name follows a pattern,
e.g. `text1, text2, text3, ...`.`
This patch implements a simple, but powerful rule, that allows us to detect
such cases and ensure that no warnings are emitted for parameter sequences that
follow a pattern, even if their types allow for them to be potentially mixed at a call site.
Given a threshold `k`, warnings about two parameters are filtered from the
result set if the names of the parameters are either prefixes or suffixes of
each other, with at most k letters difference on the non-common end.
(Assuming that the names themselves are at least `k` long.)
- The above `text1, text2` is an example of this. (Live finding from Xerces.)
- `LHS` and `RHS` are also fitting the bill here. (Live finding from... virtually any project.)
- So does `Qmat, Tmat, Rmat`. (Live finding from I think OpenCV.)
Reviewed By: aaron.ballman
Differential Revision: http://reviews.llvm.org/D97297
There are several types of functions and various reasons why some
"swappable parameters" cannot be fixed with changing the parameters' types, etc.
The most common example might be int `min(int a, int b)`... no matter what you
do, the two parameters must remain the same type.
The **filtering heuristic** implemented in this patch deals with trying to find
such functions during the modelling and building of the swappable parameter
range.
If the parameter currently scrutinised matches either of the predicates below,
it will be regarded as **not swappable** even if the type of the parameter
matches.
Reviewed By: aaron.ballman
Differential Revision: http://reviews.llvm.org/D78652
Adds a relaxation option ModelImplicitConversions which will make the check
report for cases where parameters refer to types that are implicitly
convertible to one another.
Example:
struct IntBox { IntBox(int); operator int(); };
void foo(int i, double d, IntBox ib) {}
Implicit conversions are the last to model in the set of things that are
reasons for the possibility of a function being called the wrong way which is
not always immediately apparent when looking at the function (signature or
call).
Reviewed By: aaron.ballman, martong
Differential Revision: http://reviews.llvm.org/D75041
Adds a relaxation option QualifiersMix which will make the check report for
cases where parameters refer to the same type if they only differ in qualifiers.
This makes cases, such as the following, not warned about by default, produce
a warning.
void* memcpy(void* dst, const void* src, unsigned size) {}
However, unless people meticulously const their local variables, unfortunately,
even such a function carry a potential swap:
T* obj = new T; // Not const!!!
void* buf = malloc(sizeof(T));
memcpy(obj, buf, sizeof(T));
// ^~~ ^~~ accidental swap here, even though the interface "specified" a const.
Reviewed By: aaron.ballman
Differential Revision: http://reviews.llvm.org/D96355