readability-container-size-empty currently modifies source code based on
AST nodes in template instantiations, which means that it makes
transformations based on substituted types. This can lead to
transforming code to be broken.
Change the matcher implementation to ignore template instantiations
explicitly, and add a matcher to explicitly handle template declarations
instead of instantiations.
Differential Revision: https://reviews.llvm.org/D91302
Modify the cppcoreguidelines-pro-type-member-init checker to ignore warnings from the move and copy-constructors when they are compiler defined with `= default` outside of the type declaration.
Reported as [LLVM bug 36819](https://bugs.llvm.org/show_bug.cgi?id=36819)
Reviewed By: malcolm.parsons
Differential Revision: https://reviews.llvm.org/D93333
This lint check is a part of the FLOCL (FPGA Linters for OpenCL)
project out of the Synergy Lab at Virginia Tech.
FLOCL is a set of lint checks aimed at FPGA developers who write code
in OpenCL.
The altera single work item barrier check finds OpenCL kernel functions
that call a barrier function but do not call an ID function. These
kernel functions will be treated as single work-item kernels, which
could be inefficient or lead to errors.
Based on the "Altera SDK for OpenCL: Best Practices Guide."
Extend the check to not only look at the variable the unnecessarily copied
variable is initialized from, but also ensure that any variable the old variable
references is not modified.
Extend DeclRefExprUtils to also count references and pointers to const assigned
from the DeclRef we check for const usages.
Reviewed-by: aaron.ballman
Differential Revision: https://reviews.llvm.org/D91893
Add methods for emitting diagnostics with no location as well as a special diagnostic for configuration errors.
These show up in the errors as [clang-tidy-config].
The reason to use a custom name rather than the check name is to distinguish the error isn't the same category as the check that reported it.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D91885
While casting an (integral) pointer to an integer is obvious - you just get
the integral value of the pointer, casting an integer to an (integral) pointer
is deceivingly different. While you will get a pointer with that integral value,
if you got that integral value via a pointer-to-integer cast originally,
the new pointer will lack the provenance information from the original pointer.
So while (integral) pointer to integer casts are effectively no-ops,
and are transparent to the optimizer, integer to (integral) pointer casts
are *NOT* transparent, and may conceal information from optimizer.
While that may be the intention, it is not always so. For example,
let's take a look at a routine to align the pointer up to the multiple of 16:
The obvious, naive implementation for that is:
```
char* src(char* maybe_underbiased_ptr) {
uintptr_t maybe_underbiased_intptr = (uintptr_t)maybe_underbiased_ptr;
uintptr_t aligned_biased_intptr = maybe_underbiased_intptr + 15;
uintptr_t aligned_intptr = aligned_biased_intptr & (~15);
return (char*)aligned_intptr; // warning: avoid integer to pointer casts [misc-no-inttoptr]
}
```
The check will rightfully diagnose that cast.
But when provenance concealment is not the goal of the code, but an accident,
this example can be rewritten as follows, without using integer to pointer cast:
```
char*
tgt(char* maybe_underbiased_ptr) {
uintptr_t maybe_underbiased_intptr = (uintptr_t)maybe_underbiased_ptr;
uintptr_t aligned_biased_intptr = maybe_underbiased_intptr + 15;
uintptr_t aligned_intptr = aligned_biased_intptr & (~15);
uintptr_t bias = aligned_intptr - maybe_underbiased_intptr;
return maybe_underbiased_ptr + bias;
}
```
See also:
* D71499
* [[ https://www.cs.utah.edu/~regehr/oopsla18.pdf | Juneyoung Lee, Chung-Kil Hur, Ralf Jung, Zhengyang Liu, John Regehr, and Nuno P. Lopes. 2018. Reconciling High-Level Optimizations and Low-Level Code in LLVM. Proc. ACM Program. Lang. 2, OOPSLA, Article 125 (November 2018), 28 pages. ]]
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D91055
The check 'cppcoreguidelines-narrowing-conversions' does not detect conversions
involving typedef. This notably includes the standard fixed-width integer types
like int32_t, uint64_t, etc. Now look through the typedefs at the desugared type.
This extends the check for default initialization in arrays added in
547f89d607 to include scalar types and exclude them from the suggested fix for
make_unique/make_shared.
Rewriting std::unique_ptr<int>(new int) as std::make_unique<int>() (or for
other, similar trivial T) switches from default initialization to value
initialization, a performance regression for trivial T. For these use cases,
std::make_unique_for_overwrite is more suitable alternative.
Reviewed By: hokein
Differential Revision: https://reviews.llvm.org/D90392
Commit fbdff6f3ae0b in the Abseil tree adds an overload for
absl::StrContains to accept a single character needle for optimized
lookups.
Reviewed By: hokein
Differential Revision: https://reviews.llvm.org/D92810
Checks for some thread-unsafe functions against a black list
of known-to-be-unsafe functions. Usually they access static variables
without synchronization (e.g. gmtime(3)) or utilize signals
in a racy way (e.g. sleep(3)).
The patch adds a check instead of auto-fix as thread-safe alternatives
usually have API with an additional argument
(e.g. gmtime(3) v.s. gmtime_r(3)) or have a different semantics
(e.g. exit(3) v.s. __exit(3)), so it is a rather tricky
or non-expected fix.
An option specifies which functions in libc should be considered
thread-safe, possible values are `posix`, `glibc`,
or `any` (the most strict check). It defaults to 'any' as it is
unknown what target libc type is - clang-tidy may be run
on linux but check sources compiled for other *NIX.
The check is used in Yandex Taxi backend and has caught
many unpleasant bugs. A similar patch for coroutine-unsafe API
is coming next.
Reviewed By: lebedev.ri
Differential Revision: https://reviews.llvm.org/D90944
The idea of suppressing naming checks for variables is to support code bases that allow short variables named e.g 'x' and 'i' without prefix/suffixes or casing styles. This was originally proposed as a 'ShortSizeThreshold' however has been made more generic with a regex to suppress identifier naming checks for those that match.
Reviewed By: njames93, aaron.ballman
Differential Revision: https://reviews.llvm.org/D90282
std::string_view("") produces a string_view instance that compares
equal to std::string_view(), but requires more complex initialization
(storing the address of the string literal, rather than zeroing).
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D91009
Consider this code:
```
if (Cond) {
#ifdef X_SUPPORTED
X();
#else
return;
#endif
} else {
Y();
}
Z();```
In this example, if `X_SUPPORTED` is not defined, currently we'll get a warning from the else-after-return check. However If we apply that fix, and then the code is recompiled with `X_SUPPORTED` defined, we have inadvertently changed the behaviour of the if statement due to the else being removed. Code flow when `Cond` is `true` will be:
```
X();
Y();
Z();```
where as before the fix it was:
```
X();
Z();```
This patch adds checks that guard against `#endif` directives appearing between the control flow interrupter and the else and not applying the fix if they are detected.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D91485
Do not warn for "pointer to aggregate" in a `sizeof(A) / sizeof(A[0])`
expression if `A` is an array of pointers. This is the usual way of
calculating the array length even if the array is of pointers.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D91543
This allows for matching the constructors std::string has in common with
std::string_view.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D91015
LLVM style puts both gtest and gmock to the end of the include list.
But llvm-include-order-check was only moving gtest headers to the end, resulting
in a false tidy-warning.
Differential Revision: https://reviews.llvm.org/D91602
This fixes false positive cases where a non-const reference is passed to a
std::function but interpreted as a const reference.
Fix the definition of the fake std::function added in the test to match
std::function and make the bug reproducible.
Reviewed-by: aaron.ballman
Differential Revision: https://reviews.llvm.org/D90042
The altera kernel name restriction check finds kernel files and include
directives whose filename is "kernel.cl", "Verilog.cl", or "VHDL.cl".
Such kernel file names cause the Altera Offline Compiler to generate
intermediate design files that have the same names as certain internal
files, which leads to a compilation error.
As per the "Guidelines for Naming the Kernel" section in the "Intel FPGA
SDK for OpenCL Pro Edition: Programming Guide."
This reverts the reversion from 43a38a6523.
Add IgnoreMainLikeFunctions to the per file config. This can be extended for new options added to the check easily.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D90832
SIG30-C. Call only asynchronous-safe functions within signal handlers
First version of this check, only minimal list of functions is allowed
("strictly conforming" case), for C only.
Differential Revision: https://reviews.llvm.org/D87449
Let clang-tidy to read config from specified file.
Example:
$ clang-tidy --config-file=/some/path/myTidyConfig --list-checks --
...this will read config from '/some/path/myTidyConfig'.
ClangTidyMain.cpp reads ConfigFile into string and then assigned read data to 'Config' i.e. makes like '--config' code flow internally.
May speed-up tidy runtime since now it will just look-up <file-path>
instead of searching ".clang-tidy" in parent-dir(s).
Directly specifying config path helps setting build dependencies.
Thanks to @DmitryPolukhin for valuable suggestion. This patch now propose
change only in ClangTidyMain.cpp.
Reviewed By: DmitryPolukhin
Differential Revision: https://reviews.llvm.org/D89936
The altera kernel name restriction check finds kernel files and include
directives whose filename is "kernel.cl", "Verilog.cl", or "VHDL.cl".
Such kernel file names cause the Altera Offline Compiler to generate
intermediate design files that have the same names as certain internal
files, which leads to a compilation error.
As per the "Guidelines for Naming the Kernel" section in the "Intel FPGA
SDK for OpenCL Pro Edition: Programming Guide."
On Windows the --use-color option cannot be used for its originally
intended purpose of forcing color when piping stdout, since Windows
does not use ANSI escape codes by default. This change turns on ANSI
escape codes on Windows when forcing color to a non-displayed stdout
(e.g. piped).
After https://reviews.llvm.org/D80531 landed, a subtle bug was introduced where the test would fail if `LLVM_ENABLE_WERROR` was set. This just silences that error so the test case runs correctly, down the line it may be worth not enabling `-Werror` for clang-tidy tests even if the cmake flag is passed.
Make check_clang_tidy.py not just pass -format-style=none by default
but a full -config={}. Without this, with a build dir outside of
the llvm root dir and a .clang-tidy config further up that contains
CheckOptions:
- key: modernize-use-default-member-init.UseAssignment
value: 1
these tests would fail:
Clang Tools :: clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer-modernize-use-default-member-init.cpp
Clang Tools :: clang-tidy/checkers/modernize-use-default-member-init-bitfield.cpp
Clang Tools :: clang-tidy/checkers/modernize-use-default-member-init.cpp
After this change, they pass fine, despite the unrelated
.clang-tidy file further up.
Since its call operator is const but can modify the state of its underlying
functor we cannot tell whether the copy is necessary or not.
This avoids false positives.
Reviewed-by: aaron.ballman, gribozavr2
Differential Revision: https://reviews.llvm.org/D89332
Added option `ScopedEnumConstant(Prefix|Case|Suffix)` to readability-identitied-naming.
This controls the style for constants in scoped enums, declared as enum (class|struct).
If this option is unspecified the EnumConstant style will be used instead.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D89407
new test: parsing and using compile_commands
new test: export fixes to yaml file
old test extended with CHECK-MESSAGES in order to ensure that they "fail as intended"
Enables support for transforming loops of the form
```
for (auto I = Cont.rbegin(), E = Cont.rend(); I != E;++I)
```
This is done automatically in C++20 mode using `std::ranges::reverse_view` but there are options to specify a different function to reverse iterator over a container.
This is the first step, down the line I'd like to possibly extend this support for array based loops
```
for (unsigned I = Arr.size() - 1;I >=0;--I) Arr[I]...
```
Currently if you pass a reversing function with no header in the options it will just assume that the function exists, however as we have the ASTContext it may be as wise to check before applying, or at least lower the confidence level if we can't find it.
Reviewed By: alexfh
Differential Revision: https://reviews.llvm.org/D82089
Currently, there is basically just one clang-tidy check to impose
some sanity limits on functions - `clang-tidy-readability-function-size`.
It is nice, allows to limit line count, total number of statements,
number of branches, number of function parameters (not counting
implicit `this`), nesting level.
However, those are simple generic metrics. It is still trivially possible
to write a function, which does not violate any of these metrics,
yet is still rather unreadable.
Thus, some additional, slightly more complicated metric is needed.
There is a well-known [[ https://en.wikipedia.org/wiki/Cyclomatic_complexity | Cyclomatic complexity]], but certainly has its downsides.
And there is a [[ https://www.sonarsource.com/docs/CognitiveComplexity.pdf | COGNITIVE COMPLEXITY by SonarSource ]], which is available for opensource on https://sonarcloud.io/.
This check checks function Cognitive Complexity metric, and flags
the functions with Cognitive Complexity exceeding the configured limit.
The default limit is `25`, same as in 'upstream'.
The metric is implemented as per [[ https://www.sonarsource.com/docs/CognitiveComplexity.pdf | COGNITIVE COMPLEXITY by SonarSource ]] specification version 1.2 (19 April 2017), with two notable exceptions:
* `preprocessor conditionals` (`#ifdef`, `#if`, `#elif`, `#else`,
`#endif`) are not accounted for.
Could be done. Currently, upstream does not account for them either.
* `each method in a recursion cycle` is not accounted for.
It can't be fully implemented, because cross-translational-unit
analysis would be needed, which is not possible in clang-tidy.
Thus, at least right now, i completely avoided implementing it.
There are some further possible improvements:
* Are GNU statement expressions (`BinaryConditionalOperator`) really free?
They should probably cause nesting level increase,
and complexity level increase when they are nested within eachother.
* Microsoft SEH support
* ???
Reviewed By: aaron.ballman, JonasToth, lattner
Differential Revision: https://reviews.llvm.org/D36836
Some projects do not use the TEMP_FAILURE_RETRY macro but define their
own one, as not to depend on glibc / Bionic details. By allowing the
user to override the list of macros, these projects can also benefit
from this check.
Differential Revision: https://reviews.llvm.org/D83144
Create targets `check-clang-extra-clang-tidy`, `check-clang-extra-clang-query`
similar to how `check-clang-sema`, `check-clang-parser`, etc. are
auto-generated from the directory structure.
This allows running only a particular sub-tool's tests, not having to wait
through the entire `check-clang-tools` execution.
Differential Revision: http://reviews.llvm.org/D84176
Finds member initializations in the constructor body which can be placed
into the initialization list instead. This does not only improves the
readability of the code but also affects positively its performance.
Class-member assignments inside a control statement or following the
first control statement are ignored.
Differential Revision: https://reviews.llvm.org/D71199
Placement new operators on non-object types cause crash in
`bugprone-misplaced-pointer-arithmetic-in-alloc`. This patch fixes this
issue.
Differential Revision: https://reviews.llvm.org/D87683
Instead of using CLANG_ENABLE_STATIC_ANALYZER for use of the
static analyzer in both clang and clang-tidy, add a second
toggle CLANG_TIDY_ENABLE_STATIC_ANALYZER.
This allows enabling the static analyzer in clang-tidy while
disabling it in clang.
Differential Revison: https://reviews.llvm.org/D87118
The altera struct pack align lint check finds structs that are inefficiently
packed or aligned and recommends packing/aligning of the structs using the
packed and aligned attributes as needed in a warning.
Commit `rGf5fd7486d6c0` caused a buildbot failure because exceptions are
disabled by default on one of the buildbots. This patch forcibly enables
exceptions for the affected test.
Checking the same condition again in a nested `if` usually make no sense,
except if the value of the expression could have been changed between
the two checks. Although compilers may optimize this out, such code is
suspicious: the programmer may have meant to check something else.
Therefore it is worth to find such places in the code and notify the
user about the problem.
This patch implements a basic check for this problem. Currently it
only detects redundant conditions where the condition is a variable of
integral type. It also detects the possible bug if the variable is in an
//or// or //and// logical expression in the inner if and/or the variable
is in an //and// logical expression in the outer if statement. Negated
cases are not handled yet.
Differential Revision: https://reviews.llvm.org/D81272
Finds member initializations in the constructor body which can
be placed to the member initializers of the constructor instead.
This does not only improves the readability of the code but also
affects positively its performance. Class-member assignments
inside a control statement or following the first control
statement are ignored.
Differential Revision: https://reviews.llvm.org/D71199
This checker appears to be intentionally not diagnosing cases where an
operator appearing in a duplicated expression might have side-effects;
Clang is now modeling fold-expressions as having an unresolved operator
name within them, so they now trip up this check.
When checking for the style of a decl that isn't in the main file, the check will now search for the configuration that the included files uses to gather the style for its decls.
This can be useful to silence warnings in header files that follow a different naming convention without using header-filter to silence all warnings(even from other checks) in the header file.
Reviewed By: aaron.ballman, gribozavr2
Differential Revision: https://reviews.llvm.org/D84814
Ordering of options isn't important so an `llvm::StringMap` is a much better container for this purpose.
Reviewed By: gribozavr2
Differential Revision: https://reviews.llvm.org/D84868
Handle insertion fix-its when removing incompatible errors by introducting a new EventType `ET_Insert`
This has lower prioirty than End events, but higher than begin.
Idea being If an insert is at the same place as a begin event, the insert should be processed first to reduce unnecessary conflicts.
Likewise if its at the same place as an end event, process the end event first for the same reason.
This also fixes https://bugs.llvm.org/show_bug.cgi?id=46511.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D82898
The previous fix for this, https://reviews.llvm.org/D76761, Passed test cases but failed in the real world as std::string has a non trivial destructor so creates a CXXBindTemporaryExpr.
This handles that shortfall and updates the test case std::basic_string implementation to use a non trivial destructor to reflect real world behaviour.
Reviewed By: gribozavr2
Differential Revision: https://reviews.llvm.org/D84831
Following on fcf7cc268f and 672207c319 which granted checks the ability to read boolean configuration arguments as `true` or `false`.
This enables storing the options back to the configuration file using `true` and `false`.
This is in line with how clang-format dumps boolean options in its style config.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D83053
This implements the default(firstprivate) clause as defined in OpenMP
Technical Report 8 (2.22.4).
Reviewed By: jdoerfert, ABataev
Differential Revision: https://reviews.llvm.org/D75591
The check assumed the matched function call has 3 arguments, but the
matcher didn't guaranteed that.
Differential Revision: https://reviews.llvm.org/D83301
The block arguments in dispatch_async() and dispatch_after() are
guaranteed to escape. If those blocks capture any pointers with the
noescape attribute then it is an error.
Added a 'RefactorConditionVariables' option to control how the check handles condition variables
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D82824
Extend the default string like classes to include `std::basic_string_view`.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D82720
In the process of running this check on a large codebase I found a
number of limitations, and thought I would pass on my fixes for
possible integration upstream:
* Templated function call operators are not supported
* Function object constructors are always used directly in the lambda
body, even if their arguments are not captured
* Placeholders with namespace qualifiers (std::placeholders::_1) are
not detected
* Lambda arguments should be forwarded to the stored function
* Data members from other classes still get captured with this
* Expressions (as opposed to variables) inside std::ref are not captured
properly
* Function object templates sometimes have their template arguments
replaced with concrete types
This patch resolves all those issues and adds suitable unit tests.
Prevent fixes being displayed if usages are found in the scratch buffer.
See [[ https://bugs.llvm.org/show_bug.cgi?id=46219 | Fix-It hints are being generated in the ScratchBuffer ]].
It may be wise down the line to put in a general fix in clang-tidy to prevent ScratchBuffer replacements being applied, but for now this will help.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D82162
Ignore paramater declarations of type `::llvm::Twine`, These don't suffer the same use after free risks as local twines.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D82281
Summary:
Currently, `cat` validates range selections before extracting the corresponding
source text. However, this means that any range inside a macro is rejected as an
error. This patch changes the implementation to first try to map the range to
something reasonable. This makes the behavior consistent with handling of ranges
used for selecting portions of the source to edit.
Also updates a clang-tidy lit-test for one of the checks which was affected by
this change.
Reviewers: gribozavr2, tdl-g
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D82126
Extend the `InheritParentConfig` support introduced in D75184 for the command line option `--config`.
The current behaviour of `--config` is to when set, disable looking for `.clang-tidy` configuration files.
This new behaviour lets you set `InheritParentConfig` to true in the command line to then look for `.clang-tidy` configuration files to be merged with what's been specified on the command line.
Reviewed By: DmitryPolukhin
Differential Revision: https://reviews.llvm.org/D81949
This patch adds `--use-color` command line option and `UseColor` option to clang-tidy to control colors in diagnostics. With these options, users can force colorful output. This is useful when using clang-tidy with parallelization command line tools (like ninja and GNU parallel), as they often pipe clang-tidy's standard output and make the colors disappear.
Reviewed By: njames93
Differential Revision: https://reviews.llvm.org/D79477
This changes the behavious of `RenamerClangTidyCheck` based checks by grouping declarations of the same thing into 1 warning where it is first declared.
This cleans up clang-tidy output and prevents issues where 1 fix-it couldn't be applied, yet all other warnings(and fix-its) for the same declaration would be applied.
The old behaviour of forward declaring a class without defining it isn't affected, i.e. no warnings will be emitted for that case.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D82059
Summary:
This check finds macro expansions of `DISALLOW_COPY_AND_ASSIGN(Type)` and
replaces them with a deleted copy constructor and a deleted assignment operator.
Before the `delete` keyword was introduced in C++11 it was common practice to
declare a copy constructor and an assignment operator as a private members. This
effectively makes them unusable to the public API of a class.
With the advent of the `delete` keyword in C++11 we can abandon the
`private` access of the copy constructor and the assignment operator and
delete the methods entirely.
Migration example:
```
lang=dif
class Foo {
private:
- DISALLOW_COPY_AND_ASSIGN(Foo);
+ Foo(const Foo &) = delete;
+ const Foo &operator=(const Foo &) = delete;
};
```
Reviewers: alexfh, hokein, aaron.ballman, njames93
Reviewed By: njames93
Subscribers: Eugene.Zelenko, mgorny, xazax.hun, cfe-commits
Tags: #clang, #clang-tools-extra
Differential Revision: https://reviews.llvm.org/D80531