This commit ensures that if the loop condition is opaque (the analyzer
cannot determine whether it's true or false) and there were at least two
iterations, then the analyzer doesn't make the unjustified assumption
that it can enter yet another iteration.
Note that the presence of a loop suggests that the developer thought
that two iterations can happen (otherwise an `if` would've been
sufficient), but it does not imply that the developer expected three or
four iterations -- and in fact there are many false positives where a
loop iterates over a two-element (or three-element) data structure, but
the analyzer cannot understand the loop condition and blindly assumes
that there may be three or more iterations. (In particular, analyzing
the FFMPEG project produces 100+ such false positives.)
Moreover, this provides some performance improvements in the sense that
the analyzer won't waste time on traversing the execution paths with 3
or 4 iterations in a loop (which are very similar to the paths with 2
iterations) and therefore will be able to traverse more branches
elsewhere on the `ExplodedGraph`.
This logic is disabled if the user enables the widen-loops analyzer
option (which is disabled by default), because the "simulate one final
iteration after the invalidation" execution path would be suppressed by
the "exit the loop if the loop condition is opaque and there were at
least two iterations" logic. If we want to support loop widening, we
would need to create a follow-up commit which ensures that it "plays
nicely" with this logic.
This fixes#101363 which is a resurrection of a previously opened but
never completed review: https://reviews.llvm.org/D11851
The feature is to allow code like the following not to be broken across
multiple lines:
```
namespace foo { class bar; }
namespace foo { namespace bar { class baz; } }
```
Code like this is commonly used for forward declarations, which are
ideally kept compact. This is also apparently the format that
include-what-you-use will insert for forward declarations.
Also, fix an off-by-one error in `CompactNamespaces` code. For nested
namespaces with 3 or more namespaces, it was incorrectly compacting
lines which were 1 or two spaces over the `ColumnLimit`, leading to
incorrect formatting results.
For structured bindings, a call to getCapturedDeclRefType(...) was
missing. This PR fixes that behavior and adds the related diagnostics
too.
This fixes https://github.com/llvm/llvm-project/issues/95081.
Summary:
We previously built this for every single architecture to deal with
incompatibility. This patch updates it to use the 'generic' IR that
`libc` and other projects use. Who knows if this will have any
side-effects, probably worth testing more but it passes the tests I
expect to pass on my side.
This is helpful when multiple functions operate on the same
capabilities, but we still want to use scoped lockable types for
readability and exception safety.
- Introduce support for thread safety annotations on function parameters
marked with the 'scoped_lockable' attribute.
- Add semantic checks for annotated function parameters, ensuring
correct usage.
- Enhance the analysis to recognize and handle parameters annotated for
thread safety, extending the scope of analysis to track these across
function boundries.
- Verify that the underlying mutexes of function arguments match the
expectations set by the annotations.
Limitation: This does not work when the attribute arguments are class
members, because attributes on function parameters are parsed
differently from attributes on functions.
Exposing `-fdiagnostic-color=` to clang-cl and clang-dxc.
`-fcolor-diagnostics` and `-fno-color-diagnostics` are already allowed
in both of these and `-fdiagnostics-color=` allows one additional value,
`auto`.
I've added the tests for clang-cl to `cl-options.c` as per the comments
in the issue linked below. I couldn't finding a suitable existing file
to add the clang-dxc tests to so I've created a new one.
Resolves#119184
#120613 removed -ubsan-unique-traps and replaced it with
-fno-sanitize-merge (introduced in #120511), which allows fine-grained
control of which UBSan checks to prevent merging. This analogous patch
removes -bound-checking-unique-traps, and allows it to be controlled via
-fno-sanitize-merge=local-bounds.
Most of this patch is simply plumbing through the compiler flags into
the bounds checking pass.
Note: this patch subtly changes -fsanitize-merge (the default) to also
include -fsanitize-merge=local-bounds. This is different from the
previous behavior, where -fsanitize-merge (or the old
-ubsan-unique-traps) did not affect local-bounds (requiring the separate
-bounds-checking-unique-traps). However, we argue that the new behavior
is more intuitive.
Removing -bounds-checking-unique-traps and merging its functionality
into -fsanitize-merge breaks backwards compatibility; we hope that this
is acceptable since '-mllvm -bounds-checking-unique-traps' was an
experimental flag.
The parser hangs when processing types/variables prefixed by `::` as an
optional scope specifier. For example,
```
- (instancetype)init:(::A *) foo;
```
The parser should not hang, and it should emit an error. This PR
implements the error check.
rdar://140885078
When analyzing a dangling gsl pointer, we currently filter out all field
access `MemberExpr` to avoid common false positives (`string_view sv =
Temp().sv`), However, this filter only applies to direct MemberExpr
instances, leaving the conditional operator as an escaping example
(`GSLPointer pointer(Cond ? Owner().ptr : GSLPointer());`).
This patch extends the MemberExpr logic to handle the conditional
operator. The heuristic is intentionally simple, which may result in
some false negatives. However, it effectively covers common cases like
`std::string_view sv = cond ? "123" : std::string();`, which is a
reasonable trade-off.
Fixes https://github.com/llvm/llvm-project/issues/120206
-fno-sanitize-merge (introduced in
https://github.com/llvm/llvm-project/pull/120511) duplicates the
functionality of -ubsan-unique-traps but also allows individual checks
to be specified e.g.,
* "-fno-sanitize-merge" without arguments is equivalent to
-ubsan-unique-traps
* "-fno-sanitize-merge=bool,enum" will apply it only to those two checks
Additionally, the naming is more consistent with the rest of the
-fsanitize- family.
This patch therefore removes -ubsan-unique-traps. This breaks backwards
compatibility; we hope that this is acceptable since '-mllvm
-ubsan-unique-traps' was an experimental flag.
This patch also adds negative test examples to bounds-checking.c, and
strengthens the NOOPTARRAY assertion to prevent spurious matches.
"-bounds-checking-unique-traps" is unaffected by this patch.
CheckParameterPacksForExpansion() previously assumed that template
arguments don't include PackExpansion types when attempting another pack
expansion (i.e. when NumExpansions is present). However, this assumption
doesn't hold for type aliases, whose substitution might involve
unexpanded packs. This can lead to incorrect diagnostics during
substitution because the pack size is not yet determined.
To address this, this patch calculates the minimum pack size (ignoring
unexpanded PackExpansionTypes) and compares it to the previously
expanded size. If the minimum pack size is smaller, then there's still a
chance for future substitution to expand it to a correct size, so we
don't diagnose it too eagerly.
Fixes#61415Fixes#32252Fixes#17042
This fixes a crash when instantiating default arguments for templated
friend function declarations which lack a definition.
There are implementation limits which prevents us from finding the
pattern for such functions, and this causes difficulties
setting up the instantiation scope for the function parameters.
This patch skips instantiating the default argument in these cases,
which causes a minor regression in error recovery, but otherwise avoids
the crash.
The previous attempt #113777 accidentally skipped all default argument
constructions, causing some regressions. This patch resolves that by
moving the guard to InstantiateDefaultArgument() where the handling of
templates takes place.
Fixes https://github.com/llvm/llvm-project/issues/113324
This is a rebase of #95112 with my own feedback apply as @MitalAshok has
been inactive for a while.
It's fairly important this makes clang 20 as it is a blocker for #107451
---
[CWG2813](https://cplusplus.github.io/CWG/issues/2813.html)
prvalue.member_fn(expression-list) now will not materialize a temporary
for prvalue if member_fn is an explicit object member function, and
prvalue will bind directly to the object parameter.
The E1 in E1.static_member is now a discarded-value expression, so if E1
was a call to a [[nodiscard]] function, there will now be a warning.
This also affects C++98 with [[gnu::warn_unused_result]] functions.
This should not affect C where TemporaryMaterializationConversion is a
no-op.
Closes#100314Fixes#100341
---------
Co-authored-by: Mital Ashok <mital@mitalashok.co.uk>
This diagnoses comparisons like `ptr + unsigned_index < ptr` and `ptr +
unsigned_index >= ptr`, which are always false/true because addition of
a pointer and an unsigned index cannot wrap (or the behavior is
undefined).
This warning is intended to help find broken bounds checks (which must
be implemented in terms of uintptr_t instead).
Fixes https://github.com/llvm/llvm-project/issues/120214.
We already support vector types, and since matrix element types have to
be scalar types, there should be no problem w/ just enabling this.
This now also allows matrix types to be stored in STL containers.
Essentially, this makes this ill-formed:
```c++
using mat4 = _BitInt(12) [[clang::matrix_type(3, 3)]];
```
This matches preexisting behaviour for vector types (e.g.
`ext_vector_type`), and given that LLVM IR intrinsics for matrices also
take vector types, it seems like a sensible thing to do.
This is currently especially problematic since we sometimes lower matrix
types to LLVM array types instead, and while e.g. `[4 x i32]` and `<4 x
i32>` *probably* have the same similar memory layout (though I don’t
think it’s sound to rely on that either, see #117486), `[4 x i12]` and
`<4 x i12>` definitely don’t.
PR for issue #78657
Updated clang/docs/LanguageExtensions.rst to detail the return value of
__builtin_COLUMN for this implementation.
--
Fyi, this is my first contribution, so please bear with me.
There already appears to be a unit test for __builtin_COLUMN in
clang/test/SemaCXX/source_location.cpp.
The lifetime analyzer processes GSL pointers:
- when encountering a constructor for a `gsl::pointer`, the analyzer
continues traversing the constructor argument, regardless of whether the
parameter has a `lifetimebound` annotation. This aims to catch cases
where a GSL pointer is constructed from a GSL owner, either directly
(e.g., `FooPointer(FooOwner)`) or through a chain of GSL pointers (e.g.,
`FooPointer(FooPointer(FooOwner))`);
- When a temporary object is reported in the callback, the analyzer has
heuristics to exclude non-owner types, aiming to avoid false positives
(like `FooPointer(FooPointer())`).
In the problematic case (discovered in
https://github.com/llvm/llvm-project/pull/112751#issuecomment-2441055471)
of `return foo.get();`:
- When the analyzer reports the local object `foo`, the `Path` is
`[GslPointerInit, Lifetimebound]`.
- The `Path` goes through
[`pathOnlyHandlesGslPointer`](https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/CheckExprLifetime.cpp#L1136)
and isn’t filtered out by the [[heuristics]](because `foo` is an owner
type), the analyzer treats it as the `FooPointer(FooOwner())` scenario,
thus triggering a diagnostic.
Filtering out base on the object 'foo' is wrong, because the GSLPointer
is constructed from the return result of the `foo.get()`. The patch
fixes this by teaching the heuristic to use the return result (only
`const GSLOwner&` is considered) of the lifetimebound annotated
function.
If the std::initializer_list is exported out of module, its
`DeclContext` is not a namespace as `Sema::isStdInitializerList`
expects, but an `Decl::Kind::Export` and only its parent is a namespace.
So this commit makes `Sema::isStdInitializerList` account for that.
I'm really new to clang so I'm not 100% sure that was the issue, it
seems so and it fixes compilation. Also I probably need to add tests but
I'd like someone to approve the idea first.
Fixes https://github.com/llvm/llvm-project/issues/118218
For a FunctionParmPackExpr that is used as the argument of a
sizeof...(pack) expression, we might exercise the logic that checks the
CXXRecordDecl's members regardless of the type being incomplete, when
rebuilding the DeclRefExpr into non-ODR-used forms.
Fixes https://github.com/llvm/llvm-project/issues/81436
Pack indexing type that introduces a scope, e.g. `T...[0]::value` would
be annotated as `annot_cxxscope`. This is something we didn't handle in
`ParseCastExpression`, causing it to mistakely fall through to the logic
for `raw_identifier`.
We should recurse into parsing the following specifiers for such cases.
Closes#119072
Currently, if a -l (or -Wl,) flag is added into a config file
(e.g. clang.cfg), it is situated before any object file in the
effective command line. If the library requested by given -l flag is
static, its symbols will not be made visible to any of the object
files provided by the user. Also, the presence of any of the linker
flags in a config file confuses the driver whenever the user invokes
clang without any parameters (see issue #67209).
This patch attempts to solve both of the problems, by allowing a split
of the arguments list into two parts. The head part of the list will
be used as before, but the tail part will be appended after the
command line flags provided by the user and only when it is known
that the linking should occur. The $-prefixed arguments will be added
to the tail part.