Commit graph

124988 commits

Author SHA1 Message Date
Daniel Paoliello
bd7bb26108
[clang] Match MSVC ABI for over-aligned base tail padding on Arm64 (#210461)
When targeting aarch64-pc-windows-msvc, clang laid out a base following
an over-aligned, non-standard-layout base at the wrong offset. MSVC on
Arm64 reuses the over-aligned base's tail padding for the subsequent
base, but clang rounded the base up to a full slot, so the two disagreed
on member offsets, breaking interop between clang- and MSVC-built
binaries.

Fix: store each record's natural non-virtual alignment (excluding
`alignas`/`__declspec(align)` over-alignment) as
`getNonRequiredNVAlignment()`, and on Arm64 fold in a base's natural
alignment rather than its full alignment. This is gated to Arm64 only;
Arm64EC and x64 follow the x64 rule (no reuse) and are unchanged.

Validated against MSVC (Hostx64\arm64\cl.exe
/d1reportSingleClassLayout): clang now matches MSVC Arm64 exactly for
the reduced repro, the original polymorphic case (vftable + empty base +
template), and a range of probe cases covering natural vs.
over-alignment padding and field vs. base reuse. Arm64EC and x64 output
is byte-identical to before.

Fixes #210174
2026-07-27 19:15:35 +00:00
Benedek Kaibas
68e94c9040
[analyzer] Improve dangling value tracking in DanglingPtrDeref (#211818)
Improve dangling value tracking in the `DanglingPtrDeref` checker by
adding `trackExpressionValue`. The report with this change now tracks
the dangling value and shows where the value originated from. Currently
the checker only points at the destruction and use sites which isn't
always useful for the user.
2026-07-27 20:20:19 +02:00
rdevshp
7336a38e5c
[clang] Add missing VisitAtomicTypeLoc to TypeLoc.cpp GetContainedAutoTypeLocVisitor (#211752)
Adds the missing `VisitAtomicTypeLoc` method to TypeLoc.cpp `GetContainedAutoTypeLocVisitor`.

Fixes: https://github.com/llvm/llvm-project/issues/211556 ICE.

Assisted-by: Codex
2026-07-27 11:18:02 -07:00
AZero13
41a5357e38
[clang][Sema] Allow abstract declarators to specify cv-qualified function types as per CWG1417 (#209836)
Abstract declarator contexts (specifically `DeclaratorContext::TypeName`) now properly bypass this restricted rule, allowing cv-qualified function types in `__typeof__` while maintaining restrictions in other contexts like `typeid`, `sizeof`, C-style casts, and `new` expressions per CWG1417.
2026-07-27 10:26:24 -07:00
dmaclach
3d2d8a9905
[clang][Tooling] Fix main header matching for headers with special characters. (#211934)
In Clang Tooling, escape HeaderStem before constructing MainIncludeRegex
to prevent special characters (such as '+') from being interpreted as
regex operators. Useful for Objective-C where "Foo+Bar.h" headers are
very common for categories.
2026-07-27 11:58:01 -04:00
Gang Chen
92cdb9dc83
[AMDGPU] Add amdgcn builtin for s_prefetch_inst (#211642) 2026-07-27 08:16:59 -07:00
Michael Klemm
750ed0a823
[Flang][OpenMP] Add support for -fopenmp-target-fast (#212181)
The `-fopenmp-target-fast` is a meta flag that enables several
optimizations for device code.
2026-07-27 16:59:21 +02:00
Serafean
0a75f1f77f
[libclang]Visit lambda init-capture as VarDeclaration (#174116)
```
int foo(){
    int i = 42;
    int j = 43;

    auto l1 = [x = i, &j ](){};
}
```

in the lambda capture:
- `x` is visited as VariableRef (referencing an unvisited VarDecl at the
same location)
- `i` is visited as DelcRefExpr (fair enough, same as in an assignment)
- `j` is visited as VariableRef

Visit `x` as a `VarDecl`, and stop visiting it as a `VariableRef`, as it
makes no sense (referencing itself at an unvisited cursor).

---------

Co-authored-by: Serafean <Serafean@users.noreply.github.com>
2026-07-27 09:38:01 -04:00
Hardik Kumar
187d096d44
[clang] Fix the StringRef assertion failure for non-narrow strings. (#212108)
StringRef assertion fires up when passing wide literals to
`__builtin_nanf()`.

The patch updates the `TryEvaluateBuiltinNan` method to reject
non-narrow string literals preventing the downstream assertion failure
caused by `getString()` in cases where the user might pass a non-narrow
/ non 1 byte literal."

Fix #205306
2026-07-27 19:28:17 +08:00
Marc Auberer
bd3551611e
[IR][NFC] Rename insertDbgValueIntrinsic -> insertDbgValue (#212151)
Rename `insertDbgValueIntrinsic` to `insertDbgValue`, which is
consistent with the other insert helpers like `insertDbgAssign`,
`insertDeclare`, etc.
Also use debug record instead of intrinsic terminology in doc comments.
2026-07-27 12:42:46 +02:00
Donát Nagy
8e374dbdf2
[NFC][analyzer] Eliminate NodeBuilder in VisitBlockExpr (#211865)
This is part of the commit series that gradually eliminates the class
`NodeBuilder` from the analyzer engine.

This is a straightforward case where `makeNodeWithBinding` can be
clearly applied.

The node set `Tmp` was superfluous because we can directly pass the node
to `runCheckersForPostStmt` where it will be implicitly converted to a
one-element set. (There are many precedents for this.)

Also notice that we explicitly pass the `State` to `makeNodeWithBinding`
because it can be different from `Pred->getState()` (which would have
been used implicitly by the 4-argument form of `makeNodeWithBinding`.)
2026-07-27 12:41:38 +02:00
Vlad Serebrennikov
a744ab39c4
[clang] Update C++ DR status page (#212210)
On top of updating the status page, this PR updates the `latest_release`
constant to 22 and fixes a small `cwg_index.html` parsing issue that
arose during the update.
2026-07-27 10:04:09 +00:00
Lucas Chollet
8dfdcfb116
[RISCV] Add support for vector registers with -fzero-call-used-regs (#206206)
The implementation is quite straightforward. Compared to the FP or GP
register implementations, the main difference is that we need to
configure the vector registers before clearing them.

Now that the backend supports clearing all standard registers, this
patch makes the clang driver accept all -fzero-call-used-regs options.
2026-07-27 09:37:37 +00:00
Utkarsh Saxena
ed326421d2
[LifetimeSafety][NFC] Update Checker to use prefix comparison interfaces (#207519)
This patch switches the Checker's expiry and invalidation checks to use
`AccessPath::isPrefixOf` instead of equality (`==`).

Since all generated access paths are currently empty, `isPrefixOf` is
behaviourally identical to `==` (NFC). This prepares the checker to
handle nested paths (fields and container interiors) in subsequent
commits.
2026-07-27 10:55:01 +02:00
Matt Arsenault
2d289b24a9
clang/AMDGPU: Migrate clang-linker-wrapper tests to amdgpu triples (15) (#212054)
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-27 10:45:46 +02:00
Matt Arsenault
3b6e754c0a
clang/AMDGPU: Rename amdgcn triples to amdgpu in cc1 tests (14) (#212053)
Replace the legacy amdgcn architecture name with amdgpu in various
test triples. This set of updates covers cases that did not have
a set -target-cpu.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-27 10:45:30 +02:00
Utkarsh Saxena
bb75638cb7
[LifetimeSafety][NFC] Refactor AccessPath and Loan representations
(#180369)

This patch refactors the internal representations of `AccessPath` and
`Loan` to support path elements, preparing for field-sensitive and
interior-sensitive lifetime tracking.
* Introduces `PathElement` representing a field or interior dereference.
* Refactors `AccessPath` to contain a base and a list of `PathElement`s.
* Updates `Loan` and `LoanManager` to use the new `AccessPath`
structure.

---
Old PR description:

Refactor loan representation to use structured access paths, enabling
more precise borrow tracking and detection of use-after-invalidation.

Previously, loans were associated only with top-level storage (e.g., a
variable `x`, temporary `t`). This was insufficient for reasoning about
borrows of sub-objects (interior memory regions), such as fields (`x.f`)
or container elements (`vec[0]`), or for modelling views like
`string_view` which borrow the interior of an object.

We modify `AccessPath`, which now consists of a `base` (a _variable_,
_temporary_, or _placeholder_ for _parameters/'this'_) and a sequence of
`PathElements`. A `PathElement` can be a field access (`.field`) or an
interior access (denoted as `.*`), representing an unnamed interior
memory region of an object, like the character buffer of a
`std::string`.

High-level changes:
* `PathLoan` and `PlaceholderLoan` are merged into a single Loan class,
containing an `AccessPath`.
* **Path-Based Expiry**: `ExpireFact` is changed from expiring a single
loan to expiring an `AccessPath`. If `x` goes out of scope, any loan
whose path starts with `x` (e.g., loans to `x`, `x.field`, `x.field.*`)
is now considered expired. The checker uses `isPrefixOf` to detect this.
* **Path Extension in Flows**: `OriginFlowFact` now supports extending
loan paths:
* Field access like for expression `obj.field` extends loans to `obj`
into loans to `obj.field`.
* Owner-to-view conversions like `std::string_view s(str)` extend loans
to `str` into loans to `str.*`.
* **Invalidation**: Container invalidation methods (e.g.,
`vec.push_back()`) invalidate loans whose path is a strict extension of
the container's path (e.g., loans to `vec.*` but not loans to `vec`).
The checker uses `isStrictPrefixOf`.
* **Move-Tracking**: Moves are now tracked based on path prefixes via
`isPrefixOf`.

This refactoring enables detection of use-after-invalidation bugs for
STL containers specially when the container appears as fields.
2026-07-27 08:23:32 +00:00
Nathan Ridge
e9240abc52
[clangd] Respect ArgumentLists for struct templates (#212094)
Also fix a bug in index::getSymbolKind where the returned symbol kind
would be Class for a struct template.

Fixes https://github.com/clangd/clangd/issues/2684
2026-07-27 03:07:00 +02:00
wanglei
a54947f406
[Clang][LoongArch] Implement getConstraintRegister for LoongArch (#210898)
Implement `getConstraintRegister` so Clang can diagnose inline asm
register clobber conflicts for LoongArch, matching GCC.
2026-07-27 09:00:56 +08:00
Andres-Salamanca
39eb2a11a2
[CIR][NFC] Reorganize coroutine tests (#211152)
Move the coroutine tests into a dedicated CodeGenCoroutines directory.
This is a test only reorganization in preparation for upcoming
coroutine-related changes.
2026-07-26 14:21:13 -05:00
Balázs Benics
5104dad7a1
[clang][CFG] Fix compound assignment evaluation order (#212115)
CompoundAssignOperator (e.g. `+=`, `-=`, `<<=`) is a distinct StmtClass
deriving from BinaryOperator, but it was not handled in the CFGBuilder
dispatch switches. As a result it fell through to the generic default
path (VisitChildren over reverse_children), which emits the LHS before
the RHS in the CFG.

Per C++17 [expr.ass]/1, all assignment operators - simple and compound -
sequence the right operand before the left operand. Route
CompoundAssignOperator through VisitBinaryOperator (and
VisitBinaryOperatorForTemporaries), whose existing isAssignmentOp()
branch already emits the RHS before the LHS, matching simple assignment.

This mirrors the class of evaluation-order defect fixed for lambda
captures in f3b31871e9.

rdar://183253943

Assisted-By: claude
2026-07-26 16:21:01 +01:00
rdevshp
c94c90b2ef
[analyzer] Fix _Atomic crashes for Z3 symbolic execution (#212050)
This PR fixes _Atomic crashes for Z3 symbolic execution by passing the
types through getAtomicUnqualifiedType and getCanonicalType and skip
casting in fromCast if `FromTy == ToTy && FromBitWidth == ToBitWidth`.

Assisted-by: Codex
2026-07-26 15:08:15 +01:00
Balázs Benics
f3b31871e9
[clang][CFG] Fix lambda capture evaluation order (#211877)
Previously, the captures were emitted in their spelling order - but in
the CFG that gets translared in a reversed order.
Because of this, we need to emit them in reversed order to get them
appear in their natural order.

Fixes rdar://183140177
2026-07-26 11:34:29 +01:00
Martin Storsjö
40daec88f9
[docs] Remove release notes for backported changes (#212069)
Commit 68f703f3e5 added these release
notes, but this commit was backported to the 23.x release branch in
47e2df730a (included in the 23.1.0 RC 1
tag).

Therefore, remove these release notes from the main branch (where they
would have been included in the 24.x release notes).
2026-07-26 12:28:48 +03:00
Martin Storsjö
2b660e0f1b
[clang] [test] Fix a new test on mingw (#212064)
This fixes running a new test that was added in
4b66bacd1f, in mingw environments.

The quirks that warranted adding the `!defined(_WIN32)` condition in the
test aren't actually specific to Windows in general, but specific to
MSVC environments - mingw environments behave just like other platforms.

Ideally we'd use `!defined(_MSC_VER)`, however in -cc1 mode, Clang
doesn't automatically define `_MSC_VER`; defining it requires setting a
command line option that the driver normally passes in MSVC mode.
Therefore, qualify the condition as `!defined(_MSC_VER) ||
defined(__MINGW32__)`.
2026-07-26 12:28:28 +03:00
Timm Baeder
545f9fab9e
[clang][bytecode] Don't check global variable init size (#212092)
The current interpreter doesn't do this either. If we do, the clang
build fails because AMDGPUGenGlobalISel.inc: contains a global constexpr
array called MatchTable0 with 1'926'005 elements.
2026-07-26 08:53:58 +02:00
Timm Baeder
3fd07e3235
[clang][bytecode] Only override constant-context state if we have an EvalEmitter (#211475)
This does not make sense when emitting bytecode, as the bytecode would
just contain a `PushCC`/`PopCC` pair with nothing in between.
2026-07-26 08:14:28 +02:00
Matt Arsenault
2f3f97fb72
clang/AMDGPU: Migrate -aux-triple amdgcn in cc1 tests to amdgpu (13) (#212052)
Update to the new architecture name.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-25 22:54:14 +02:00
Matt Arsenault
f704f39607
clang/AMDGPU: Migrate OpenMP cc1 tests to amdgpu triples (12) (#212051)
Migrate the OpenMP offload cc1 tests to the new amdgpu triple scheme:

* -fopenmp-targets=amdgcn-amd-amdhsa ->
-fopenmp-targets=amdgpu-amd-amdhsa
    (the offload toolchain triple, the generic amdgpu arch).
  * The device -triple amdgcn-amd-amdhsa -> amdgpu-amd-amdhsa, or to the
specific subarch triple (dropping -target-cpu) where a -target-cpu was
    present.

Autogenerated CHECK lines are regenerated, and the few -Wopenmp-target-
exception diagnostics that embed the triple string are updated. Tests
that
intentionally assert the "target-cpu" function attribute are left
unchanged.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-25 22:52:04 +02:00
Matt Arsenault
56f4b9c4e8
clang/AMDGPU: Migrate cc1 tests to subarch triples (11) (#211956)
Rewrite the second half of CodeGenOpenCL cc1 test RUN lines to the new
subarch triple form, dropping the redundant -target-cpu.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-25 21:50:11 +02:00
Alexis Engelke
890d1331a3
[Clang] Don't build static analyzer if disabled (#212024)
Even if the static analyzer is disabled, it still gets built into the
dylib. Unit tests and tools already get disables, so also stop building
the library. This reduces the time needed to build a dylib clang by
8-9%.
2026-07-25 21:07:27 +02:00
Matt Arsenault
197cf54ac8
clang/AMDGPU: Migrate cc1 tests to subarch triples (10) (#211955)
Rewrite the first half of CodeGenOpenCL cc1 test RUN lines to the new
subarch triple form, dropping the redundant -target-cpu.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-25 18:24:21 +00:00
Benjamin Kramer
191c60fe7c
[ThreadSafety] Fix C++20 build (#212042)
In C++20 (P1008R1 https://wg21.link/p1008r1), aggregates are prohibited
from having any user-declared constructors, even if they are = delete or
= default.
2026-07-25 18:03:00 +00:00
Hui
068ec1a282
[clang] fix __builtin_clear_padding not working with virtual base pointers on Windows (#211355)
Fixes https://github.com/llvm/llvm-project/issues/209787
It was an oversight that the builtin only takes care of the virtual
function table pointer but not the virtual base pointer. On Itanium
there is one pointer so it wasn't a problem but on windows msvc , this
is a problem. And the runtime test in libcxx CI was disabled in llvm 23
because we don't use trunk clang in our libcxx CI in general. and after
we flipped to llvm 24, the test started to fail on downstream (chromium)
where they use trunk clang with trunk libc++ on Windows.

We do have FileCheck test in clang test which covers this virtual case.
However, the target triple in the FileCheck under test were
`x86_64-linux-gnu` and `x86_64-windows-gnu` , which does not cover the
Windows msvc ABI. I updated the test to test `x86_64-pc-windows-msvc` in
this PR to cover that ABI.
2026-07-25 09:35:45 +01:00
Matt Arsenault
3055342ef9
clang/AMDGPU: Migrate cc1 tests to subarch triples (9) (#211954) 2026-07-25 09:30:57 +02:00
Matt Arsenault
943d6498fa
clang/AMDGPU: Migrate cc1 tests to subarch triples (8) (#211870)
Rewrite SemaHIP cc1 test RUN lines to the new subarch triple form,
dropping the redundant -target-cpu.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-25 08:20:47 +02:00
Hardik Kumar
bcd5798f6d
[clang][NFC]Remove unused variable (#211983)
The patch resolves the following warning.
```bash
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp:504:16: warning: variable ‘i’ set but not used [-Wunused-but-set-variable=]
  504 |       unsigned i = 0;
      |                ^
```

A count variable was set and incremented inside of a for loop but never
actually used inside of the loop or anywhere else in its scope.
2026-07-25 10:51:07 +05:30
Sirui Mu
bf7b5a0fed
[CIR] Add support for atomic fmaximum/fminimum/fmaximumnum/fminimumnum (#211845)
This patch adds CIR support for the following atomic builtin functions:

- `__atomic_fetch_fmaximum`
- `__atomic_fetch_fminimum`
- `__atomic_fetch_fmaximumnum`
- `__atomic_fetch_fminimumnum`

The scoped versions of these atomic builtin functions are supported as
well.

Specifically, this patch contains the following changes:

- It updates the `cir.atomic.fetch` operation and adds new fetch
operators including `maximum`, `minimum`, `maximumnum`, and
`minimumnum`. These operators accept floating-point inputs only.
- It updates the LLVM lowering of the `cir.atomic.fetch` operation. The
LLVM lowering now will lower `maximum`, `minimum`, `maximumnum`, and
`minimumnum` atomic fetch operators to the corresponding LLVM
`atomicrmw` operations, which are `fmaximum`, `fminimum`, `fmaximumnum`,
and `fminimumnum`, respectively, aligning with the OGCG behavior.
- It updates the CIRGen path for atomic operations and add supports for
these atomic builtin functions.

Assisted-by: GitHub Copilot / gpt-5.4 xhigh
2026-07-25 12:22:52 +08:00
Jannick Kremer
c64a5b0c4c
[libclang/python] Remove CompletionString.AvailabilityKindCompat (#210682)
This completes the fourth step of
https://github.com/llvm/llvm-project/pull/156680
This change is a follow-up to
https://github.com/llvm/llvm-project/pull/160296, following the release
branching, to ensure a one release-cycle deprecation period.

---------

Co-authored-by: Vlad Serebrennikov <serebrennikov.vladislav@gmail.com>
2026-07-25 12:38:13 +09:00
Rashmi Mudduluru
6d300116c0
[Webkit Checkers][SaferCpp] Fix MemoryUnsafeCastChecker to precisely exclude *this casts (#210180)
Exclude casts precisely matching `this` and `*this` (through
parens/implicit casts), without matching member accesses like
`this->m_field`.

rdar://173770064
2026-07-24 16:29:21 -07:00
Benedek Kaibas
002deaabe6
[analyzer] Match dangling subobjects by their base region in DanglingPtrDeref (#211552)
Currently the `DanglingPtrDeref` checker only records the whole object's
region as deallocated. However, dangling pointers often refer to
subobjects (e.g., a struct field or an element of an array). With the
change in this PR, `isDeallocated` now checks whether a region's base
region is in the `DeallocatedSourceSet`.
2026-07-25 01:15:59 +02:00
Sirraide
a891a5c40c
[Clang] [Sema] Use getCurFunctionDecl() to get the current function (#211938)
In `BuildReturnStmt()`, use `getCurFunctionDecl()` to get the current
function rather than attempting to cast `CurContext` to a
`FunctionDecl`, which breaks inside an expansion statement because the
current `DeclContext` will be that of the expansion statement, not the
function. `getCurFunctionDecl()` knows how to handle this case and we
already call it earlier in that function, so just reuse the result of
that call.

Fixes #211917.
2026-07-24 23:12:55 +00:00
Matt Arsenault
3f69551f6b
clang/AMDGPU: Migrate cc1 tests to subarch triples (7) (#211869)
Rewrite the remaining small test directories (CodeGenCXX, Misc, Sema,
SemaCUDA, SemaCXX) cc1 RUN lines to the new subarch triple form,
dropping the redundant -target-cpu.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-25 00:52:10 +02:00
Matt Arsenault
b6f5847d62
clang/AMDGPU: Migrate cc1 tests to subarch triples (6) (#211868)
Rewrite CIR/CodeGenHIP cc1 test RUN lines to the new subarch triple
form, dropping the redundant -target-cpu, and regenerate autogenerated 
CHECK lines.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-25 00:51:52 +02:00
Ziqing Luo
bd47223f20
[ThreadSafety] Add two-state semantics for handleCall in beta mode (#210219)
Previous contributions added alias analysis and strengthened soundness
by invalidating out-parameters in beta mode. The latter feature
introduced a distinction between the contexts before and after a
function call, because the invalidation assumes that an argument passed
by pointer or reference may be changed by the function.

This requires two-state semantics for handling function attributes.
Specifically, AcquireCapability and AssertCapability, which both ensure
that some locks are held after the call, should be associated with the
post-state. Other function attributes, like RequireCapability or
ReleaseCapability, are associated with the pre-state.

This commit implements these semantics. This change only affects beta
mode.

A previous discussion about these semantics:
https://github.com/llvm/llvm-project/pull/190154

rdar://171209196
2026-07-24 15:40:31 -07:00
Oliver Hunt
da798c26ae
[Sema] Skip expansion statements when determing local extern context (#210512) (#211745)
This bug showed up as a failed assertion that was asserting that if
not in a function or method context we should be in the global/file
context.

The root cause is that when determining the linkage context for a
decl we were failing to account for the existence of expansion
contexts. Ignoring the assertion failure, the functional effect of
this is that we would fail to detect incorrect local extern
declarations inside expansion contexts. The fix here is to make
sure that we use `getEnclosingNonExpansionStatementContext()` to
find the true DeclContext for the current scope.

The initial report only identified local extern function declarations
but the same bug occurred with extern var decls, but the path did
not lead to an assertion firing, just incorrect behaviour.

Thanks to Sirraide for explaining why this was going wrong, and
confirming this was the correct fix.

Also fixes #211912
2026-07-24 21:45:35 +00:00
Roland McGrath
0f7854f4a3
[clang][Fuchsia] Add __Fuchsia_Compiler_ABI__ predefine (#211744)
This establishes a new canonical predefine for *-fuchsia targets:
`__Fuchsia_Compiler_ABI__` is set to an integer for the version
number of the Fuchsia Compiler ABI the compiler supports.  The
value will change as appropriate with changes to *-fuchsia target
ABI expectations.  It is not anticipated that the compiler will
support selecting target ABI versions, only the latest as the
canonical target-specific behavior.  Fuchsia Compiler ABI
versions are unrelated to the Fuchsia API levels supported by
Fuchsia systems; newly-built programs may target older API levels
with `-ffuchsia-api-level`, but everything relying on the Fuchsia
Compiler ABI is built and deployed together as an isolated unit.
2026-07-24 12:04:35 -07:00
Matt Arsenault
982688d57f
clang/AMDGPU: Migrate cc1 tests to subarch triples (5) (#211840)
Rewrite OpenMP cc1 test RUN lines to the new subarch triple form,
dropping the redundant -target-cpu, and regenerate autogenerated CHECK
lines. Tests that intentionally assert the "target-cpu" attribute are
left unchanged.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-24 20:53:07 +02:00
Osama Abdelkader
de4b1f5572
[Clang] Avoid querying tag definitions for invalid DeclSpecs (#210085)
Guard hasTagDefinition() against invalid type-specifier state so
recovery from invalid auto/tag combinations does not assert.
Fixes #210014

---------

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
2026-07-24 20:23:08 +02:00
Ramkumar Ramachandra
15bb4a97a7
[IR] Make semantics of strictfp consistent v2 (#211769)
Changes: The patch was originally landed as af0c933e (#209465), but
there was an issue with strictfp functions being inlined into
non-strictfp functions. The issue has since been resolved by a2b42b10a
([IR] Reject inlining strictfp alwaysinline callee into non-strictfp
caller, #210701) and the re-land is identical.

Although the section on constrainedfp in the LangRef clearly states "All
function definitions that use constrained floating point intrinsics must
have the strictfp attribute", indicating that a function with strictfp
calls must be marked with strictfp, the general description of strictfp
does not specify this. Refine its semantics and make it so, eliminating
the inconsistency.
2026-07-24 18:02:54 +00:00
Ayokunle Amodu
b71410f770
[CIR][CUDA] Add support for NVVM ldu builtins (#211843)
Adds CIR codegen support for the NVVM global uniform load builtins
`nvvm_ldu_*` ,including the integer, floating-point, and vector
variants.

These are lowered to the corresponding `llvm.nvvm.ldu.global.*`
intrinsics based on the pointee type.
2026-07-24 13:38:33 -04:00
Matt Arsenault
c50d1635fe
clang/AMDGPU: Migrate cc1 tests to subarch triples (4) (#211839)
Rewrite Headers cc1 test RUN lines to the new subarch triple form,
dropping the redundant -target-cpu, and regenerate autogenerated CHECK
lines.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-24 19:13:12 +02:00
Nick Sarnie
0e0e0c388e
[clang][Driver][SYCL] Fix SYCLInstallationDetector for compiler installs outside sysroot (#211351)
Currently if the compiler install is not under SYSROOT, we don't try to
compute the relative path to `libLLVMSYCL.so` based on the compiler
binary installation directory, resulting us never setting
`SYCLRTLibPath` so when we try to geenerate a linker call we get a raw
`libLLVMSYCL.so` which fails unless the user happens to be running the
compiler from a directory with `libLLVMSYCL.so` inside it.

It seems we never use the result from SYCLInstallationDetector on
Windows, so I can't add a test, however change the code to be consistent
in case we start to use it in the future.

---------

Signed-off-by: Nick Sarnie <nick.sarnie@intel.com>
2026-07-24 17:11:24 +00:00
Balázs Benics
ca78391cea
Revert "[analyzer] Fix false positive in strchr/strrchr with constant args" (#211857)
Reverts llvm/llvm-project#210154

Broke some build bots.
https://github.com/llvm/llvm-project/pull/210154#issuecomment-5071830822
https://lab.llvm.org/buildbot/#/builders/144/builds/60200

```
# | error: 'expected-error' diagnostics seen but not expected: 
# |   File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 515: use of undeclared identifier 'u'
# |   File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 527: use of undeclared identifier 'u'
# |   File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 538: use of undeclared identifier 'U'
# |   File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 550: use of undeclared identifier 'u'
# |   File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 578: use of undeclared identifier 'u'
```
2026-07-24 17:59:41 +01:00
Matt Arsenault
57af943dfe
clang/AMDGPU: Migrate cc1 tests to subarch triples (3) (#211825)
Rewrite CodeGenHIP cc1 test RUN lines to the new subarch triple form,
dropping the redundant -target-cpu, and regenerate autogenerated CHECK
lines. Tests whose behavior depends on the implicit wave32 default
(which is not enabled by a bare subarch triple) are left for a later change.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-24 18:24:16 +02:00
Matt Arsenault
22116c946a
clang/AMDGPU: Migrate cc1 tests to subarch triples (2) (#211823)
Rewrite CodeGenCUDA cc1 test RUN lines from `-triple amdgcn...
-target-cpu gfxNNN` to the new subarch triple form, dropping the redundant
-target-cpu.
Autogenerated CHECK lines are regenerated. Tests that intentionally
assert the "target-cpu" function attribute are left unchanged.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-24 17:53:24 +02:00
Matt Arsenault
227ef987a7
clang/AMDGPU: Migrate cc1 tests to subarch triples (1) (#211822)
Mechanically rewrite cc1 test RUN lines from the old
`-triple amdgcn... -target-cpu gfxNNN` form to the new subarch triple
form (e.g. `-triple amdgpu9.00-amd-amdhsa`), dropping the now-redundant
-target-cpu. The subarch encodes the exact target, so the emitted IR no
longer carries a "target-cpu" function attribute; autogenerated CHECK
lines are regenerated accordingly.

This batch covers the small CodeGen, Frontend, Layout, and Preprocessor
test directories.

Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
2026-07-24 15:41:17 +00:00
earnol
570a19d1a9
[analyzer] Fix false positive in strchr/strrchr with constant args (#210154)
When both the source string and the search target are compile-time
constants, determine the outcome precisely and only emit the feasible
branch (found or not-found).
Handles strchr, strrchr, strchrnul, memchr, strstr, and strpbrk.

Fixes #209905

Assisted by: Kiro-cli

---------

Co-authored-by: Vladislav Aranov <vladislav.aranov@ericsson.com>
2026-07-24 16:29:49 +01:00
Abhina Sree
26f5da1392
[SystemZ][z/OS] Add text flag when parsing json (#211805)
This patch adds the text flag when we are opening json files to parse. 
This fixes two lit failures on z/OS
2026-07-24 11:27:10 -04:00
Jianjian Guan
a1341c9cf7
[CIR][RISCV] Add new builtins (#211555)
Leave them NYI now.
2026-07-24 17:30:16 +08:00
Jin Huang
4f8de7694a
[profcheck][coro] Adding Branch weights PGO in Coroutines Passes (#184466)
The CoroSplit and CoroFrame generate several control flow instructions
(`br`, `select`, `switch`) that previously lacked `!prof` branch weight
metadata.

When a coroutine is split, most basic blocks are simply cloned into the
generated functions (`.resume`, `.destroy`, and `.cleanup`) and don't
actually change their internal structure or layout. This PR changes:

1. Dispatch Branch Weights:
Since the original coroutine already ran through PGO, we already have
the `SuspendFreqs` records telling us exactly how many times each
suspension point was executed in the real world.

In the new clone `.resume` functions, the compiler generates new routing
`switch` instruction to direct the traffic. Instead of guessing the
probabilities for these new routes, we simply look back at the
`SuspendFreqs` records, calculate the exact execution frequency and
directly onto the new routing `switch` instructions as `!prof` data.

2. Function Entry Count:
We compute the entry count for the generated `.resume` function by
summing up the frequencies of all suspension target blocks, ensuring the
`.resume` function's entry metadata accurately reflects its true
invocation frequency rather than inheriting original counts. Two new
test cases is added see:
    ```

llvm/test/Transforms/Coroutines/coro-split-resume-entry-count-no-suspend.ll
    llvm/test/Transforms/Coroutines/coro-split-resume-entry-count.ll 
    ```

3. Others updates add branch weight metadata in several locations within
these passes:

* **CoroSplit.cpp**: 
* `handleFinalSuspend`: Added an equal (50/50) weight to conditional
branches handling final-suspend conditions via
`setExplicitlyUnknownBranchWeightsIfProfiled`.

* `updateCoroFrame`: Adds an equal (50/50) weight to the select
instruction that chooses either the `destroy` or `cleanup` function by
using `setExplicitlyUnknownBranchWeightsIfProfiled`.

* **CoroFrame.cpp**: 
* `rewritePHIsForCleanupPad`: Adds a branch weight of {0, 1, 1} to
two-way switch instructions driven by PHI nodes generated in the EH
dispatch block (.corodispatch). This provides accurate probabilistic
information for `SimplifyCFG`, which typically translates such `switch`
  ```
cleanup2.corodispatch: ; preds = %catch.dispatch.2, %handler2
    %1 = phi i8 [ 0, %handler2 ], [ 1, %catch.dispatch.2 ]
    %2 = cleanuppad within %h1 []
    switch i8 %1, label %unreachable [
      i8 0, label %cleanup2.from.handler2
      i8 1, label %cleanup2.from.catch.dispatch.2
    ]
  ```
    into `icmp` + `br`.
  
  ```
cleanup2.corodispatch: ; preds = %catch.dispatch.2, %handler2
    %1 = phi i8 [ 0, %handler2 ], [ 1, %catch.dispatch.2 ]
    %2 = cleanuppad within %h1 []
    %3 = icmp eq i8 %1, 0
br i1 %3, label %cleanup2.from.handler2, label
%cleanup2.from.catch.dispatch.2
  ```
* **CoroCleanup.cc**
* Setting the `unknown` profile to `NoopFn`/`__NoopCoro_ResumeDestroy`
to avoid the false warnings. because this function is generated by this
the pass, PGO has no profile count for it.

Co-authored-by: Jin Huang <jingold@google.com>
2026-07-23 21:04:20 -07:00
hev
cad3c95a89
[LoongArch] Support i128 operands for LSX inline assembly (#211464)
Allow `i128` values to be used with the `f` inline assembly constraint
when targeting LSX.

Although `i128` is not a legal LSX value type, it naturally maps to a
single 128-bit LSX vector register for inline assembly. This enables
instructions such as `vadd.q` to operate directly on `__int128` operands
without requiring explicit vector types.
2026-07-24 10:23:38 +08:00
arrowten
1ec7a13fb2
[Sema] Fix assertion in TreeTransform when rebuilding CXXParenListInitExpr (#203715) 2026-07-23 20:50:58 -03:00
Jiahao Guo
bee0671fa8
[CIR][AArch64] Lower Vector saturating shift and narrow intrinsics (#209389)
### summary

part of : https://github.com/llvm/llvm-project/issues/185382

lower all intrinsics in :
https://arm-software.github.io/acle/neon_intrinsics/advsimd.html#vector-saturating-shift-right-and-narrow
2026-07-24 07:37:22 +08:00
Jannick Kremer
89b84291ff
[libclang/python] Remove global SPELLING_CACHE alias (#210677)
This completes the second step of
https://github.com/llvm/llvm-project/issues/156680
This change is a follow-up to
https://github.com/llvm/llvm-project/pull/177586, following the release
branching, to ensure a one release-cycle deprecation period.

---------

Co-authored-by: Vlad Serebrennikov <serebrennikov.vladislav@gmail.com>
2026-07-24 08:28:03 +09:00
Joshua Batista
1ca413a270
Add InterlockedOr resource methods (#211639)
This PR builds upon the work merged in
https://github.com/llvm/llvm-project/pull/180804, and completes the
implementation of the InterlockedOr functions in HLSL, by adding these
methods to the existing resource types.
This PR also reflects the same implementation strategy used in
https://github.com/llvm/llvm-project/pull/208128
Fixes: https://github.com/llvm/llvm-project/issues/99126
Assisted by: Github Copilot
2026-07-23 15:09:23 -07:00
Yaxun (Sam) Liu
cdfa687cd2
[Driver] Print C++ standard library info (#207798)
Users and tools sometimes need to know which C++ standard library Clang
selected, and which include directories the driver added for it. Today
they have to inspect verbose or `-###` output.

Add options to print this information directly:

`--print-cxx-stdlib`
`--print-cxx-stdlib-include-dirs`

For MSVC targets, the default printed library is `msvcstl`. Explicit
`-stdlib=` values are still reported as requested. The include-dir query
reuses toolchain logic, including the MSVC STL include path for the
default MSVC case.
2026-07-23 17:59:38 -04:00
Ziqing Luo
c2a3cbedb5
[SSAF] Fix a stage2 test failure with ASan-instrumented clang (#211432)
ASan emits a symbol for a static global in `TestTransformation.cpp` that
causes link issues in green dragon.
Added `__attribute__((no_sanitize("address")))` to that static global to
fix the test.

rdar://182623740
2026-07-23 13:50:48 -07:00
Nikita Kornev
8b0eab1560
[SSAF] Fix Expected return type in TypeConstrainedPointers deserialization (gcc 7.5.0) (#211331)
GCC 7.5.0 fails to compile this code. Use explicit upcasts from
std::unique_ptr<Derived> to std::unique_ptr<Base> in deserializeSummary
and deserializeAnalysisResult. This resolves a compilation error where
llvm::Expected<std::unique_ptr<Base>> could not be constructed from
unique_ptr of derived summary/result types.
2026-07-23 19:28:26 +00:00
Hardik Kumar
b630323802
[clang][Driver]Fix opencl -cl-fast-relaxed-math flag to have similar behaviour as ffast-math (#208709)
Previously when using `-cl-fast-relaxed-math` flag along with
`fhonor-nans` or `fhonor-infinities` the honor flags did not override
the relaxed math flag. This behaviour is something that is not seen in
case of ffast-math for general targets.

This patch makes adjustments to how the driver and cc1 handles the
relaxed math flag for opencl. The flag was in the path of `fast-math` so
when someone used the `-cl-fast-relaxed-math` flag they were ultimately
overriding everything with fast-math. This was the main reason why honor
flags were not overriding relaxed math (atleast that's what I have
understood from my time working on this).

I have added tests for this as well and modified CodeGen cc1 tests
according to the changes in the patch.

I have personally not tested this on any AMD targets myself yet. So I am
unsure about this breaking anything (hopefully it should rather fix).

closes #178514
2026-07-23 21:01:50 +02:00
Soham Karandikar
1f93f282d4
[Clang] [Sema] Added a check for NameInfo not being empty after template instantiation (#210610)
Fixes #210234 

As per my investigation (mostly following stack traces and dumping
variable values), a default empty `DeclarationNameInfo` was being
returned after template substitution [over
here](c45b4e4d00/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (L3270)).

```cpp
// D-.>getNameInfo() has actual data here
 
 DeclarationNameInfo NameInfo
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);

// NameInfo has default values
```

This was being passed on directly to `CXXDestructorDecl::Create` leading
to the assertion being hit. This PR adds a check that ensures `NameInfo`
actually contains a valid destructor name before constructing a
`CXXDestructorDecl`. This fixes the assertion being hit in the
reproducer from the linked issue.
2026-07-23 20:45:41 +02:00
Mohammed Ashraf
52bc4102ac
[BoundsSafety] Introduce LateParsedAttrType AST placeholder type (#204125)
Split out from #179612 to make review easier. No functional change.

This introduces `LateParsedAttrType`, a new AST placeholder type used
during late parsing of type attributes. The actual late parsing
mechanism that uses this type is in #179612 and will be split into a
follow-up PR.
2026-07-23 11:44:49 -07:00
syhhyl
d8f7777f40
[clang][test] Add Darwin pragma weak alias IR coverage (#211499)
Add Clang IR coverage for `#pragma weak alias = target` on Darwin.

The test verifies that Clang:

- emits the alias with weak linkage;
- keeps calls referencing the alias instead of replacing them with the
aliasee.

This is a test-only follow-up to #198148 and covers the Clang lowering
path used by #111321.
2026-07-23 20:21:45 +02:00
Amr Hesham
ac61623826
[CIR] Implement convert to atomic intptr through temp alloca (#210794)
Implement the conversion to atomic int pointer through temp alloca
2026-07-23 18:11:14 +00:00
Joshua Batista
8d933f7478
Add InterlockedAdd resource methods (#208128)
This PR builds upon the work merged in
https://github.com/llvm/llvm-project/pull/195742, and completes the
implementation of the InterlockedAdd functions in HLSL, by adding these
methods to the existing resource types.
Fixes: https://github.com/llvm/llvm-project/issues/99122
Assisted by: Github Copilot
2026-07-23 10:13:21 -07:00
Ian Li
6425cf4ce7
[NFC][Clang][Lex] Add assert to prevent null pointer dereference in Preprocessor::HandleModuleContextualKeyword (#211117)
Coverity static analysis scans on clang are unhappy with
[this](e55d3bca36/clang/lib/Lex/Preprocessor.cpp (L920))
invocation of `HandleModuleContextualKeyword` due to the fact that
_technically_ nothing is stopping `CurPPLexer` reference in
`Preprocessor` from being `nullptr`, although AFAICT the current code
ensures this doesn't happen when `Preprocessor` is in file-lexing mode.

However, an assertion could be added to `HandleModuleContextualKeyword`
for future debugging's sake.

---------

Co-authored-by: Yihan Wang <yronglin777@gmail.com>
2026-07-23 17:12:31 +00:00
Benedek Kaibas
1e7817c938
[NFC][analyzer] Apply any_of to detect destructors stack frame (#211582)
Since #210938 is merged I have also applied the same parent-chain helper
to detect if a destructor's stack frame is on the current stack.
2026-07-23 17:00:51 +00:00
Ryosuke Niwa
10e0a2ee03
[WebKit Checkers] Share the safety model of WebKit smart pointers (#210195)
This PR introduces PtrRefSafetyModel to abstract away type checks for
various smart pointer types in WebKit to share more code between
different checkers.
2026-07-23 09:55:09 -07:00
Ian Li
3bf4e73825
[analyzer] Add some speculative hardening (#210823)
Coverity uncovered some potential hardening opportunities -
mainly to prevent nullptr derefs.
2026-07-23 17:23:53 +01:00
Rithik Sharma
557e5c12f8
[CIR] Recognize strlen in the IdiomRecognizer pass (#210400)
This patch adds the operation cir.std.strlen and teaches the recognizer
to raise strlen calls, following the ClangIR incubator. A C library
function carries no identity tag, so strlen is matched by its callee
symbol, which works since C names have no mangling.

The symbol alone is not enough when builtins are disabled, so the
recognizer honors the no builtin state CIRGen records, the mark on the
call and the list on the calling function. A call is raised only when it
is a direct call named strlen with one pointer to an 8 bit character of
either signedness, since the signedness of plain char follows the
target, and a fundamental unsigned integer result. A _BitInt is excluded
even at width 8.

The raised operation lowers back through the same generic function as
the other raised operations, and every call attribute is carried across,
so a no builtin mark or list survives the round trip. Tests cover the
raise, the symbol match, the no builtin cases, and the type guard.

Aided by Claude Opus 4.8
2026-07-23 09:15:00 -07:00
Lucas Ly Ba
10600d0f48
[analyzer] Make pointer/null comparison commutative for addresses of fields of symbolic regions (#209875)
Fixes #206798

A reversed ("Yoda") null check `nullptr == p` produced a false
`core.NullDereference` when `p` is the address of a field of a symbolic
region (e.g. `&r->s`). The natural form (`p == nullptr`) worked fine.
2026-07-23 16:09:40 +00:00
Dmitry Sidorov
6690cd6f9f
[DOC] Update SPIR-V Support on HIPAMD ToolChain (#211542)
SPIR-V backend now is the default path.
2026-07-23 17:12:41 +02:00
Akash Agrawal
97a5889383
[Clang][Sema] Don't delay the access check when computing implicit deletion (#210254)
Sema::isMemberAccessibleForDeletion treats AR_delayed as unreachable,
but CheckAccess returns AR_delayed whenever it runs inside an enclosing
delayed-diagnostics scope. That happens when deletion checking runs
synchronously while parsing a later declaration -- e.g. while explaining
why a defaulted operator<=> is deleted for an expression in that
declaration's initializer. The caller cannot consume a delayed
diagnostic, so letting CheckAccess delay always hits
llvm_unreachable("cannot delay =delete computation") and crashes.

Force an immediate answer by wrapping the CheckAccess call in
DelayedDiagnostics.pushUndelayed()/popUndelayed() via llvm::scope_exit,
mirroring the existing Sema::CheckEnableIf pattern in SemaOverload.cpp.

Fixes https://github.com/llvm/llvm-project/issues/210692

Co-authored-by: Claude-Sonnet
2026-07-23 15:06:49 +00:00
Yusuke MINATO
94404723f0
Revert "[NFC][clang][Driver] Add tests for --driver-mode=flang"
Reverts llvm/llvm-project#207658 due to buildbot failure
2026-07-23 12:55:32 +00:00
Evgenii Kudriashov
cb383a3744
[Clang][X86] Introduce Clang ABI Gate for MSVC alignment (#210305)
On x86_64-windows-msvc after 8ecec45518, clang applies the MSVC
size-based global-alignment scheme (Microsoft64BitMinGlobalAlign) and
does not apply the Sys V "large array" alignment increase. Users may
want to preserve the earlier ABI for compatibility with objects produced
by older clang releases.

Gate this behavior on the Clang ABI compatibility level. When
`-fclang-abi-compat=22` (or lower) is in effect,
MicrosoftX86_64TargetInfo restores LargeArrayMinWidth/LargeArrayAlign to
128 and getMinGlobalAlign skips the Microsoft64BitMinGlobalAlign step,
matching the older alignment choices.

Assisted by Claude (Anthropic).
2026-07-23 14:33:57 +02:00
Ariel-Burton
b0b0a53e67
Write original source language when writing and reading AST (#209353)
FAIL: Clang :: Frontend/ast-main.c
FAIL: Clang :: Frontend/ast-main.cpp

were failing on z/OS; this change fixes these lit failures.

The issue here is that on z/OS the original source code language needs
to be passed through to the IR so that the backend can encode this
information in the PPA2 in the object file. That means that it needs to
be exported to the AST so that going from saved AST -> IR will carry the
language through.
2026-07-23 08:13:14 -04:00
Matt Arsenault
fd67f99275
clang/AMDGPU: Fix handling of subarch triples with no -mcpu (#211467) 2026-07-23 13:39:16 +02:00
Balázs Benics
48d5c3edb0
[analyzer][NFC] Remove unused ProgramStateRef local variables (#211517)
Several checkers and ExprEngine declare a ProgramStateRef local that is
never read (typically `State = C.getState();` immediately followed by
code that re-fetches the state directly). These are not flagged by
-Wunused-variable because ProgramStateRef has a non-trivial destructor.

Found with a clang-query matcher over clang/lib/StaticAnalyzer.
Assisted-by: claude
2026-07-23 11:26:17 +00:00
Balázs Benics
ecf4c970dd
[analyzer][NFC] Remove leftover PreElideState stash in copy elision (#211518)
computeObjectUnderConstruction stashed the program state into
PreElideState "before trying to elide, as it'll get overwritten", but
never used it. That comment and stash are fossils of the old
prepareForObjectConstruction, which returned and threaded the state
(`std::tie(State, V) = ...`); the failure path then reverted it with
`State = PreElideState;`.

The refactor to the SVal-returning computeObjectUnderConstruction (State
is now passed by value and the state updates moved to
updateObjectsUnderConstruction) dropped that revert but left the stash
and comment behind. State is never overwritten here anymore, so remove
the dead PreElideState and reword the comment to describe only the
CallOpts stash, which is still needed (CallOpts is passed by reference
and genuinely overwritten by the elision attempt).

Found with a clang-query matcher over clang/lib/StaticAnalyzer.
Assisted-by: claude
2026-07-23 11:21:18 +00:00
Balázs Benics
de7cd6542a
[analyzer][Z3] Fix z3-bitint-arithmetic.c test RUN line (#211515)
I used to get these errors on M4 with `LLVM_ENABLE_Z3_SOLVER`:

```
error: 'expected-error' diagnostics seen but not expected:
  File clang/test/Analysis/z3/z3-bitint-arithmetic.c Line 26: unsigned _BitInt of bit sizes greater than 128 not supported
  File clang/test/Analysis/z3/z3-bitint-arithmetic.c Line 29: unsigned _BitInt of bit sizes greater than 128 not supported
```

Fixes up #210525
Another nail in the coffin of #184695
2026-07-23 11:15:17 +00:00
Yusuke MINATO
d814be1bb7
[NFC][clang][Driver] Add tests for --driver-mode=flang (#207658)
This patch intends to clarify the current behaviors, not to state the
expected/desirable behaviors.

---------

Co-authored-by: Tarun Prabhu <tarunprabhu@gmail.com>
2026-07-23 11:03:15 +00:00
Donát Nagy
0037f09f09
[NFC][analyzer] Eliminate the NodeBuilder in VisitUnaryOperator (#211304)
This is part of the commit series to gradually remove the class
`NodeBuilder` from the analyzer codebase.

This was a relatively complex situation because there were many
different `generateNode` calls and two situations where the the node
from `CheckedSet` was left in `EvalSet` without changes (which is
implicit with the `NodeBuilder` but now requires explicit
`EvalSet.insert(N)` calls).
2026-07-23 12:52:24 +02:00
guillem-bartrina-sonarsource
f953ed4ec6
[analyzer][z3] Fix crash in Z3 SMTConv when casting atomic int (#211489)
CPP-7675
2026-07-23 10:40:44 +00:00
Phoebe Wang
492d726bcc
[X86][AVX10.2] Add missing _mm_cvtts_ss/sd* intrinsics (#211185)
Fixes part of #210947

Assisted-by: Claude Opus 4.8
2026-07-23 18:37:55 +08:00
TelGome
58cebee609
[RISCV][P-ext] Support Packed "Q-format" Multiplication (#211236) 2026-07-23 17:15:50 +08:00
Balázs Benics
64b593c237
[clang][SSAF] Allow no Data for summary analysis (#211342)
Extractors might not always add summaries for all the TUs. If they don't
add any summaries to the TU result, then loading this summary for a
summary analysis would cause a failure.

This patch handles the situation gracefully by accepting such cases.

Split from: #209354

---------

Co-authored-by: Ziqing Luo <ziqing_luo@apple.com>
2026-07-23 09:13:59 +01:00
Marco Elver
bc3d3c9e3a
[AllocToken] Fix typeContainsPointer for references, PMFs, blocks, ObjC pointers (#211349)
When evaluating whether an allocated type contains a pointer to generate
the alloc_token metadata, typeContainsPointer() previously only checked
for PointerType.

Expand typeContainsPointer() to check isAnyPointerType(),
isReferenceType(), isMemberFunctionPointerType(), and
isBlockPointerType().
2026-07-23 08:52:35 +02:00
Mariusz Sikora
e407c4b677
[AMDGPU] Add gfx13 support for global_load_async_to_lds (#211248) 2026-07-23 08:49:39 +02:00
Damian Höster
f7ae0ec1b5
[clang-format][clang-tools-extra] Fix leaking of host-level config into test environment (#206358)
These leaks were causing false test failures due to my global
.clang-format being in an ancestor directory of the build directory.
These changes prevent those issues when running the tests on my system.
I used MiMo v2.5 Pro agentically in Zed to find and fix the issue. But I
understand the changes and judge them to be safe and a clear improvement
over the status quo.
2026-07-23 13:59:53 +08:00
Mariusz Sikora
6aa4d5ef9b
[AMDGPU] Add FeatureSubtarget for global async load/store lds (#211247) 2026-07-23 07:37:05 +02:00
Andres-Salamanca
b66aac64ed
[CIR][NFC] Remove unused LLVM lowering for cir.await (#211143)
`cir.await` is always eliminated by the FlattenCFG pass before the
DirectToLLVM conversion. Since the operation never reaches LLVM
lowering, remove the unused lowering implementation.
2026-07-22 18:31:28 -05:00
Jannick Kremer
9521d0c033
[libclang/python] Unify CompletionChunkKind.__str__ representation (#210676)
This completes the first step of
https://github.com/llvm/llvm-project/issues/156680
This change is a follow-up to
https://github.com/llvm/llvm-project/pull/176631, following the release
branching, to ensure a one release-cycle deprecation period.
2026-07-23 08:29:41 +09:00
Reid Kleckner
d7544537bc
[clang][docs] Fix markdown migration defects in the user manual (#210785)
First, replace all the `{eval-rst}` blocks for option documentation with
`:::{option}` fences. This means authors won't have to bounce between
markup languages within one file, and removes more semantic indentation,
which has been a recurring problem.

Second, remove blockquotes that seem unintentional. None of these are
real quotes, and they seem like artifacts of unintended indentation
before the Markdown migration (#208310).

---------

Co-authored-by: Andy Kaylor <akaylor@nvidia.com>
2026-07-22 21:39:35 +00:00
adams381
b4a12eb394
[CIR] Add opt-in flag to run x86_64 call-conv lowering (#211335)
The x86_64 System V classifier and the CallConvLowering pass that drives
it are already in the tree, but nothing runs them: the -fclangir
pipeline never adds the pass, so CIR still emits uncoerced aggregate
signatures on x86_64 and its LLVM output diverges from classic CodeGen
for anything passed or returned in registers.

This adds the cc1 flag -clangir-enable-call-conv-lowering, off by
default like -clangir-enable-idiom-recognizer, and runs the pass in
runCIRToCIRPasses right after CXXABILowering, which has already reduced
C++ ABI types to plain records the classifier can handle. The flag is
gated on x86_64. On other targets it is a silent no-op, so a driver can
set it unconditionally without breaking non-x86_64 builds. The AVX level
is fixed at None because the classifier's current supported subset has
no >128-bit vector aggregate where the level would change the result.

With the flag on, supported scalars and small aggregates are coerced to
match classic CodeGen: sign/zero-extended narrow integers, SSE scalars,
one- and two-eightbyte INTEGER/SSE struct coercion, ignored empty
structs, sret returns, and byval arguments. Types the classifier does
not yet handle — unions, long double, and float aggregates that classify
to an SSE vector — still errorNYI when the flag is on. CIR does emit
noalias on byval parameters where classic CodeGen does not, which the
test documents with split prefixes.
2026-07-22 16:06:36 -05:00
Benedek Kaibas
252f31a689
[analyzer] Detect dangling pointers passed to function calls (#211045)
In order to detect if a dangling pointer is passed to a function the
analyzer has to inspect each call argument. For that reason I have
implemented the `checkPostCall` for the `DanglingPtrDeref` checker to
check if an argument passed to a function is dangling. Since
`checkLocation` only catches dereferences and cannot reason about
whether an argument passed to a function is dangling it cannot detect
these type of bugs alone.
2026-07-22 22:48:32 +02:00
Paulius Velesko
3093d8c577
[HIPSPV] Preserve device debug info requested via -g
HIPSPVToolChain::adjustDebugInfoKind() unconditionally forced NoDebugInfo,
so compiling HIP device code with -g produced SPIR-V with no debug metadata.
Debuggers such as Intel's gdb-oneapi could therefore not resolve source
lines or local variables in offloaded kernels. The stated reason for
disabling it (the SPIRV-LLVM-Translator aborting on DW_OP_LLVM_convert) no
longer applies, as the translator now lowers that operation.

Stop clobbering the requested debug level, and when -g is given emit debug
info in the NonSemantic.Shader.DebugInfo form
(--spirv-debug-info-version=nonsemantic-shader-200), enabling the required
SPV_KHR_non_semantic_info extension. The default (no -g) output is
unchanged.

Also enable SPV_INTEL_optnone when -g is requested. At -O0 Clang marks
functions optnone; preserving that attribute lets gdb-oneapi inspect kernel
arguments and locals instead of reporting them as <optimized out>. The
extension is a no-op at -O1 and above.

Reported downstream: CHIP-SPV/chipStar#1004
2026-07-22 16:44:46 -04:00
Deric C.
7e9782bad1
[HLSL] Move sema tests out of ParserHLSL into SemaHLSL/Attributes (#211353)
This PR moves sema tests that were misplaced in `clang/test/ParserHLSL`
into a more appropriate location: `clang/test/SemaHLSL/Attributes`

These tests exercise `[[hlsl::...]]` attribute (resource_class,
contained_type, is_array, is_ms, is_rov, raw_buffer, dimension)
diagnostics from `DiagnosticSemaKinds.td`, relating to:
 - 'hlsl::X' attribute cannot be applied to a declaration
 - attribute takes one argument / takes no arguments
 - can be used only on HLSL intangible type '__hlsl_resource_t'
 - attribute is already applied / applied with different arguments
 - ResourceClass attribute argument not supported
 
 Which are appropriately related to semantics rather than parsing.
2026-07-22 19:46:03 +00:00
Tshaka Lekholoane
3e6d593738
[Clang] Add C++11/C23-style spellings for Swift import attributes (#183484)
Swift interop attributes such as `swift_name`, `swift_attr`, and
`swift_private` previously only supported GNU-style spelling. Add the
missing `[[]]` attribute spellings for C++11 and C23 compatibility,
bringing them in line with other Clang attributes.
2026-07-22 19:38:52 +00:00
Deric C.
0e9b8c3dfa
[HLSL] Add IsMultiSampled HLSL resource attribute (#211125)
This PR completes the frontend work for adding the IsMultiSampled HLSL
resource attribute (addressing
https://github.com/llvm/llvm-project/issues/194933)

The DirectX and SPIR-V backend work will be completed alongside the
implementation Texture2DMS
(https://github.com/llvm/llvm-project/issues/194955) so that the
functionality can be exercised.

Assisted by: Claude Opus 4.8
2026-07-22 11:34:05 -07:00
Andy Kaylor
e00944c8d8
[CIR] Generate cleanup region for loops when needed (#211158)
This adds support for generating a cleanup region in loops that declare
destructed variables in the loop condition. These variables need to be
destructed on a per-iteration basis, so it's not possible to have a
cleanup scope that properly encloses the variable without losing the
loop structure elements in the initial CIR representation.

The CFG flatteneing of these loops was added in a previous PR, and the
lowering to LLVM IR follows directly from the flattened form.

Assisted-by: Cursor / various models
2026-07-22 11:27:44 -07:00
adams381
9b0e63af7c
[CIR] Rewire byref args to the incoming pointer (#210836)
The CallConvLowering body rewrite for Indirect arguments treats byval
and
byref the same way: it inserts a cir.load at function entry and reroutes
body
uses to the loaded value. For byref — a non-trivially-copyable type
passed by
pointer — that entry load is a byte-copy, so the callee works on a local
copy
instead of the caller's storage. That breaks types whose representation
embeds
self-referential pointers: libstdc++'s SSO std::string keeps _M_p
pointing at
its own _M_local_buf, and a byte-copy leaves the copy's _M_p aliasing
the
source's buffer.

This mirrors the sret return fix in insertSRetStores. For byref only,
rewire
the CIRGen param-slot alloca to the incoming pointer and drop the spill
store,
so the body operates on the caller's storage in place. byval keeps the
load-at-entry copy, which is correct there.

The rewrite is exercised through the classification-injection driver in
clang/test/CIR/Transforms/abi-lowering/indirect-byval.cir, covering a
byref
field access on the incoming pointer and a byval control case that
retains the
copy. The call site still copies a value operand into a fresh alloca
before
passing it by reference; forwarding existing storage in place is left
for a
follow-up.
2026-07-22 12:47:47 -05:00
Amr Hesham
badd93d5df
[CIR][NFC] Remove unreachable code and add missing NYIs (#211084)
Remove unreachable code and add missing NYIs for Matrix row and elt
2026-07-22 18:41:29 +02:00
adams381
0590a36b31
[CIR] Convert byval/sret/byref arg-attr types when lowering to LLVM (#210764)
The CallConvLowering pass lowers an indirectly-passed aggregate to a pointer argument and records the pointee record type on the `llvm.byval`, `llvm.sret`, or `llvm.byref` argument attribute.  That type payload is still a CIR record after the pass runs, so once the module reaches the LLVM dialect and is translated to LLVM IR, the translation hits a CIR type inside the attribute and fails.

LowerToLLVM already routes every operand and result type through the type converter.  It now does the same for the type carried by those three argument attributes, in the attribute lowering shared by the function definition and by the call and invoke sites.  With the conversion in place, a byval or sret parameter translates to `byval(%struct.X)` / `sret(%struct.X)` carrying the lowered LLVM struct type, and byref does the same.  CallConvLowering does not classify `cir.try_call` yet, so no invoke carries these attributes today, but the shared path already covers the invoke once it is classified.

The test injects the three attributes directly, lowers to the LLVM dialect, and translates to LLVM IR, checking the emitted attributes carry the LLVM struct type.  It uses no aggregate classifier, so it stands alone from the x86_64 classifier stack.
2026-07-22 10:52:33 -05:00
Scott Todd
0769e6d05a
[offload-arch] Fix amdgpu HIP DLL search path on Windows (#209898)
## Motivation

This follows up on https://github.com/llvm/llvm-project/pull/194063 to
fix https://github.com/ROCm/TheRock/issues/6571, where `offload-arch`
distributed as part of ROCm has been failing with:
```diff
 D:\projects\TheRock (main -> upstream)
 λ .\build\dist\rocm\lib\llvm\bin\offload-arch.exe --verbose
 Found HIP runtime: D:/projects/TheRock/build/dist/rocm/bin/amdhip64_7.dll
-note: priming LoadLibraryExW failed for D:/projects/TheRock/build/dist/rocm/bin/amdhip64_7.dll (error 126)
 Failed to load D:/projects/TheRock/build/dist/rocm/bin/amdhip64_7.dll: D:/projects/TheRock/build/dist/rocm/bin/amdhip64_7.dll:  Can't open: The specified module could not be found.  (0x7E)
 Failed to 'dlopen' libcuda.so.1
 Unable to load library 'libze_loader.so': libze_loader.so: Can't open: The specified module could not be found.  (0x7E)
```

## Fix details

The relevant code path in offload-arch is this:
```c++
int printGPUsByHIP() {
  auto [DynamicHIPPath, IsFallback] = findNewestHIPDLL();
  // Prime DLL load so transitive deps resolve from its directory.
  primeLibraryLoad(DynamicHIPPath);
  // ... then load the library and use it
```

Here's where the relevant files are located on disk in both build and
package directories:
```
rocm/
    bin/
        amdhip64_7.dll
        rocm_kpack.dll    (amdhip64_7.dll newly depends on this!)
    lib/
        llvm/
            bin/
                offload-arch.exe
```

The documentation for the
[`LoadLibraryExW`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexw)
API that this code was calling says:
> If the string specifies a fully qualified path, the function searches
only that path for the module. When specifying a path, be sure to use
backslashes (`\`), not forward slashes (`/`). For more information about
paths, see [Naming Files, Paths, and
Namespaces](https://learn.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file).

the `primeLibraryLoad()` function has been receiving a path with forward
slashes in it though, leading to the `error 126`.

## Testing performed

* Built `offload-arch` with and without this fix and ran it locally on
Windows
* Added new unit tests asserting that `LoadLibraryExW` is called with
backslashes and not forward slashes (we could add more "real" tests that
actually exercise library loading but I'm not sure if LLVM unit tests
are the right spot for that)
* Ran a "real" test that uses `offload-arch` to list GPUs, compile some
code, and run a printf function over in TheRock:
a20ab791d7/tests/test_rocm_sanity.py (L85-L154)
(this test was disabled back in
https://github.com/ROCm/TheRock/pull/5346 due to suspected machine
issues, now we'll be able to re-enable it)
2026-07-22 08:31:14 -07:00
Rahul
34436db53d
[clang] Emit diagnostic for typedef+auto missed case in C++98/C23 (#210141)
CheckTypeSpec() converted 'auto' to a storage-class specifier without
checking whether 'typedef' was already set. [dcl.stc]p1 unconditionally
forbids typedef alongside any storage-class specifier regardless of C++
version.

This change add the check for tydef in the code handling auto.
2026-07-22 10:40:58 -04:00
Yuxuan Chen
b9e3e6546d
[Clang][coro] Fix coro.free in .resume clones with [[clang::coro_await_elidable]] (#207799)
Fixes https://github.com/llvm/llvm-project/issues/188230

CoroAnnotationElide rewrites annotated safe calls to the `.noalloc`
variant. The noalloc frame is caller-owned, but its `.resume` clone is
shared with ordinary heap-allocated instances.

With a `suspend_never` final suspend, normal resumption falls through to
the `coro.free` deallocation path. Regular frontend cleanup has already
run before this point. `coro.free` must therefore produce the frame
pointer for a heap instance and null for a `.noalloc` instance.

Use the frame destroy slot as a per-instance allocation tag. Cache its
value at resume entry, before user code can resume and release the
enclosing caller frame, then compare it with the cleanup clone. Replace
each `coro.free` result with the frame pointer for a heap instance and
null for an elided instance.

Update the CoroSplit and Clang CodeGen checks to cover the conditional
deallocation and the original suspend_never final-suspend shape.

Assisted-By: Codex GPT 5.5
2026-07-22 07:39:30 -07:00
Thibault Monnier
84301dd17f
[Clang][Lexer] Reland "Detect SSE4.2 availability at runtime in fastParseASCIIIdentifier" (#180631)
This PR reopens #175452 after it was merged then reverted by #177322
because of compilation failures and compatibility issues.

This change attempts to maximize usage of the SSE fast path in
`fastParseASCIIIdentifier`.

If the binary is compiled with SSE4.2 enabled, or if we are not
compiling for x86, then the behavior is the exact same, ensuring we have
no regressions.
Otherwise, we compile both the SSE fast path and the scalar loop. At
runtime, we check if SSE4.2 is available and dispatch to the right
function by using `__builtin_cpu_supports`. If it _is_ available, this
allows a net performance improvement. Otherwise, there's a very slight
but negligible regression... I believe that's perfectly reasonable for a
non-SSE4.2-supporting processor.

The benchmark results are available here:
https://llvm-compile-time-tracker.com/compare.php?from=3192fe2c7b08912cc72c86471a593165b615dc28&to=8960c57a2e5880616d2dd549f8422ca91c864e86&stat=instructions%3Au.
2026-07-22 15:57:56 +02:00
Alexander Kornienko
150aa53d48
Revert "[Clang] Rebuild lambda captures in default member initializers while skipping body (#196597)" (#211001)
This reverts commit 50f30bedaa. The commit
causes a crash in clang:
https://github.com/llvm/llvm-project/pull/196597#issuecomment-4997866573
2026-07-22 15:29:37 +02:00
Shilei Tian
d9cf5980b7
[Clang][LTO] Assign GUIDs after post-opt bitcode linking (#211155)
Run AssignGUIDPass after LinkInModulesPass so newly linked globals have
GUIDs before LTO summary emission.

Fixes LCOMPILER-2475.
2026-07-22 09:12:48 -04:00
Jannick Kremer
3ac7573589
[libclang/python] Remove CompletionChunk.isKind methods (#210678)
This completes the third step of
https://github.com/llvm/llvm-project/issues/156680
This change is a follow-up to
https://github.com/llvm/llvm-project/pull/177854, following the release
branching, to ensure a one release-cycle deprecation period.
2026-07-22 21:04:59 +09:00
Ayokunle Amodu
88840f264d
[CIR][CUDA] Add support for scoped NVVM atomic builtins (#210863)
Adds codegen support for the block and system-scoped NVVM atomic
builtins: add, and, or, xor, min, max, inc and dec.

These are lowered to the corresponding CIR `cir.atomic.fetch` operations
and subsequently lowered to LLVM `atomicrmw` instructions.
2026-07-22 07:30:44 -04:00
Timothy Day
f07e2f1aab
Thread Safety Analysis: Don't warn at joins that re-branch on a try-lock result (#209796)
Previously, when the result of a try-lock call is branched on more than
once, the paths between the branches would disagree on whether the
capability is held while remaining consistent at each branch. The analysis
then gave a false positive warning at the intermediate join:

    mutex 'lock' is not held on every path through here

Create getTerminatorTrylockCall() helper from getEdgeLockset(); if the terminator
of a block branches on the result of a call to a try_acquire_capability-function
(perhaps negated or stored in a local variable), this helper returns that call and
its callee.

Use this new helper in getTerminatorTrylockCaps(), which will return the
capabilities acquired by a trylock; feed these capabilites to intersectAndWarn()
during a branch join, in order to avoid false positives.

Soundness is preserved because intersectAndWarn() still removes the
capabilities from the join block's entry lockset, ensuring any guarded access
inside the join block before the terminator is diagnosed. getEdgeLockset()
then re-adds the capability on the success edge.

This change resolves the false positive warning reported in [1].

Reported-by: https://lore.kernel.org/linux-fsdevel/20260714181057.667977-1-timday@thelustrecollective.com/ [1]
Assisted-by: AI was used a bit to understand the code and to help with testing and validation
2026-07-22 11:22:52 +02:00
Mariusz Sikora
c75267c8ef
[AMDGPU] Builtins and intrinsics for v_cvt_scalef32_pk32_(fp|bf)6_f32 (#210713)
- builtins with documentation
- instructions
- new subtarget feature only for gfx13
- GlobalISel RegBankLegalize rules
- tests
2026-07-22 09:47:13 +02:00
aokblast
e6190fab2e
[clang] Switch to Default PIE on FreeBSD (#206139)
We have started to compile the binary in our base as PIE by defualt. It
makes sense to compile the binary to PIE by default in toolchain as
Linux now. Also, extended testcases to support default PIE and no-pie
parameter in freebsd.c and hip-fpie-option.hip.
2026-07-22 11:26:36 +08:00
David Brittain
564b027db1
[clang][Modules] Keep current-TU global-module-fragment internal-linkage functions viable in overload resolution (#210825)
Fixes #210822

A `static` (or anonymous-namespace) function declared in the global
module fragment of the current TU is usable within the module unit
([module.global.frag]/p1), but `Sema::AddOverloadCandidate` dropped it
from the overload set when `Function->isInAnotherModuleUnit()` misfired
— which it does when the enclosing template is instantiated after the
GMF closes (pending instantiations run in
`ActOnEndOfTranslationUnitFragment`, before the named module is in
scope). The candidate was removed with the hidden
`ovl_fail_module_mismatched` kind, so the error had no candidate notes.

The existing carve-out (#104701) only exempted inline /
implicitly-instantiated GMF functions. This also exempts
internal-linkage functions from the current TU's GMF
(`isFromGlobalModule() && !isFromASTFile()`); genuinely imported
internal-linkage functions stay subject to the rule.

`clang/test/Modules` and `clang/test/CXX/module` show no new failures;
the `expose-static-inline-from-gmf-*` tests still pass. Adds a
regression test.

This change was developed with substantial assistance from an AI tool
(Claude Code). The AI carried out the investigation and root-cause
analysis, wrote the code change and the regression test, and drafted
this description.
2026-07-22 01:57:32 +00:00
Jan Leyonberg
afb68446b4
[CIR][OpenMP] Add host op filtering pass to CIR pipeline (#209592)
This patch adds the host op filtering pass which prevents host code
being lowered when compiling for the target device.
2026-07-21 20:41:03 -04:00
Alex MacLean
aef1e4f249
[NVPTX] Support short entry param pointers (#206512) 2026-07-21 23:10:13 +00:00
Alexey Bader
3782c00acd
[clang-sycl-linker] Forward all --ocloc-options occurrences to ocloc (#211075)
getLastArgValue() only returned the final --ocloc-options= occurrence,
silently dropping earlier ones when the option is passed multiple
times (one token per occurrence). Use getAllArgValues() so every
occurrence is forwarded to ocloc.
2026-07-21 22:59:12 +00:00
adams381
4fff13bfb9
[CIR] Classify empty records as Ignore in x86_64 callconv (#211078)
The x86_64 aggregate calling-convention bridge rejects a zero-field
record as NYI, even though the SysV classifier already treats an empty
record as NoClass/NoClass (so it returns Ignore) and the rewriter
already drops arguments and returns classified Ignore.

Dropping the zero-field reject in `isSupportedType` lets a C empty
struct classify as Ignore: the argument slot is removed, the remaining
arguments shift down, and an empty-record return lowers to void.

The C++ empty class stays NYI. CIRGen lays it out as a single padded
byte, which the padded reject still catches. Unions, packed, and
all-float aggregates remain NYI as before.

---------

Co-authored-by: Andy Kaylor <akaylor@nvidia.com>
2026-07-21 17:58:48 -05:00
adams381
fcbf28ffc8
[CIR] Report NYI for defaulted union copy/move assignment
A defaulted union copy or move assignment operator has an empty synthesized
body because Sema skips union fields, leaving no AST expression for the
implied whole-object copy.  CIRGen emitted that empty body and silently
dropped the assignment.

Report NYI for defaulted union assignment instead.  Struct and array
assignments are unaffected because their synthesized bodies contain the
memberwise copies needed by the existing body-emission path.
2026-07-21 17:38:20 -05:00
Daniil Kovalev
8775feb5da
[clang] Drop stale *-buildattr module flag emission (#211021)
Module flags `sign-return-address-buildattr` and
`tag-stack-memory-buildattr` are never exercised elsewhere by existing
tests or code across the whole LLVM source tree, and there are no known
cases of them being used.

Moreover, the `sign-return-address-buildattr` flag emission was gated by
`ptrauth` target feature which does not actually exist: see
`AArch64TargetInfo::computeFeatureLookup()` and
`ARMTargetInfo::hasFeature(StringRef Feature)`. So, it was never
emitted.

This patch removes code responsible for these stale module flags
emission.

Note: the flags was previously introduced in
https://reviews.llvm.org/D112421
2026-07-21 22:06:06 +00:00
Andy Kaylor
5503126b61
[CIR] Flatten loop ops with a cleanup region (#210472)
This change adds support for CFG flattening of loop operations with
cleanup regions.

Rather than re-invent the entire branch through cleanup mechanism, I am
first rewriting the loop by sinking the condition into the body (as a
test + break-if-false) and hoisting the step into the body, and
surrounding the entire body with a cir.cleanup.scope op. Then the greedy
flattening algorithm runs the newly formed loop through the existing
flattening mechanisms so that the loop cleanup handling ends up being
done by the same code that flattens other cleanup scopes.

Assisted-by: Cursor / various models
2026-07-21 14:40:33 -07:00
Prabhu Rajasekaran
96b100337b
Reland "[Fuchsia] Stack analysis flags for runtimes" (#211072)
Reverts llvm/llvm-project#192515
We have addressed the CFI related workflow by introducing a new
MD_callgraph and by disambiguating it from MD_type used for CFI.
2026-07-21 14:38:48 -07:00
Vladislav Dzhidzhoev
db816fe2ed
[DirectX][Driver] Add /Qpdb_in_private flag support (#204903)
In DXC, when `/Qpdb_in_private` flag is specified, debug info PDB is
emitted into PRIV part of the output DXContainer (as well as into
separate PDB file, if its name is specified with `/Fd`).

This patch reimplements similar behavior in llc and Clang.

MC is modified to be able to emit PRIV part.

Depends on https://github.com/llvm/llvm-project/pull/204166.
2026-07-21 22:41:48 +02:00
Andy Kaylor
8dc94a5d51
[CIR] Fix avx512vlbw builtin test run lines (#211063)
The avx512vlbw-builtins.c test was using the now-nonexistant avx10.1-512
target feature in several of its run lines. Because the feature no
longer exists with that spelling it was being silently ignored.
Apparently it isn't needed for the test upstream because the test has
been passing, but I received reports from a downstream user that the
test was failing for them.

There was a recent change to more strictly enforce always-inlining if
target features didn't match. I suspect that this downstream project has
a different version of some intrinsic header files so that it requires
"avx10.1" (the correct spelling of the feature).

This change updates the test run lines to use the correct feature
spelling.
2026-07-21 13:37:59 -07:00
Farzon Lotfi
c7e1531885
[HLSL][SPIRV] Support Flat and Location decorators in the frontend (#210116)
fixes #194293
fixes #194432

In HLSL we need both Location and and Flat must be emitted as a single
`spirv.Decorations` node.
Also we need to apply Flat decoration to pixe/fragment shades with
inputs of integer or double because only 32 bit floats can be
interpolated.

Assisted with Claude Opus 4.8 via Copilot
2026-07-21 15:20:45 -04:00
Erich Keane
4bf0d282b9
[OpenACC/CIR] Remove std::transform_inclusive_scan use (#211076)
This seemingly is only added for GCC libstdcxx 11.1's C++17 support, but
our support matrix is 7.4. Replace it with a loop that implements the
same requirement.
2026-07-21 11:57:00 -07:00
Deric C.
b35c1aab48
Revert "[clang] Update diagnostics to include matrices as accepted types" (#211070)
Reverts llvm/llvm-project#201237. The PR did not update the test
assertions for `Sema/builtins-elementwise-math.c`

https://github.com/llvm/llvm-project/pull/201237#issuecomment-5037239584
2026-07-21 18:29:35 +00:00
adams381
0aa8e45b04
[CIR] Lower _BitInt to its in-memory storage integer (#206606)
ClangIR keeps a `_BitInt(N)` at its literal width, but in memory it has
to live in a wider padded integer, the same way `bool` is `i1` as a
value and `i8` in memory. Because CIRGen emitted the constant at its
exact width, the storage padding was left undefined: a `signed
_BitInt(6) = -1` wrote `0x3f` where classic CodeGen and GCC write
`0xff`. @andykaylor pointed this out on
[#205605](https://github.com/llvm/llvm-project/pull/205605).

The fix widens `_BitInt` to its storage integer `iM` and
sign/zero-extends by signedness during lowering to the LLVM dialect, the
same place `bool` becomes `i8` (`convertTypeForMemory` and the
to/from-memory helpers). CIRGen keeps the literal `!cir.int<N, bitint>`
unchanged.

The byte-array storage form for wide "split" widths, where the storage
integer's alloc size exceeds its store size (e.g. `_BitInt(129)` to
`i192`, 32 vs 24 bytes), is not implemented. The global, alloca, load,
and store lowerings report an NYI error and the aggregate type
converters fail the conversion, rather than emit a wrong-sized integer.
Atomic read-modify-write on a padded `_BitInt` and vector-of-`_BitInt`
are also unimplemented.

The storage width comes from `IntType::getABIAlignment`, which assumes a
fixed 64-bit maximum alignment (x86-64). It is verified byte-for-byte on
x86-64; on targets with a larger maximum (e.g. AArch64) any width that
would be mis-sized instead hits the split-storage NYI. On a target whose
`_BitInt` maximum alignment is below 64 bits (e.g. a 32-bit target) the
storage can be mis-sized. Making the computation target-aware needs the
target's `getBitIntAlign`, which is not in the data layout, and is left
as a follow-up.

The approach follows the RFC [Widen bool / _BitInt / ext-vector-bool to
their in-memory types in
lowering](https://discourse.llvm.org/t/rfc-clangir-widen-bool-bitint-ext-vector-bool-to-their-in-memory-types-in-lowering/91160).
It supersedes
[#205605](https://github.com/llvm/llvm-project/pull/205605), which
emitted the constant at its literal width.
2026-07-21 13:20:00 -05:00
Brad Smith
15de5a2c4c
[Driver] Remove SUSE SLES special casing for hash-style (#210223) 2026-07-21 14:17:33 -04:00
Arthur Eubanks
c2fac16a87
Revert "[IR] Make semantics of strictfp consistent" (#211057)
Reverts llvm/llvm-project#209465

Causes verifier issues:
https://github.com/llvm/llvm-project/pull/209465#issuecomment-5025559698
2026-07-21 18:12:17 +00:00
John Paul Jepko
accd1ed522
[analyzer] Fix StdVariantChecker crash on std::get with a non-ptr arg (#210167)
When `std::get` is called on a dereferenced integer-to-pointer cast, the
checker `alpha.core.StdVariant` crashes. Minimal reproducer:

```
std::get<int>(*(std::variant<int, char> *)11);
```

Godbolt reproducer - https://godbolt.org/z/4EKe1PrKb

The root cause is that `StdVariantChecker::handleStdGetCall()` calls
`SVal::getType()` on any non-unknown argument, then calls
`getPointeeType()` on the result while assuming it is a pointer type. In
the case of a concrete integer cast to a pointer and then dereferenced,
it is modeled as `loc::ConcreteInt`, whose recovered type is an integer.
`getPointeeType()` on such an input returns a null QualType, on which
`getTypePtr()` crashes.

Fix the crash by using the argument's static type rather than recovering
its SVal, eliminating the need to guard and call `getPointeeType()`.
2026-07-21 18:34:50 +01:00
Alex Sepkowski
ee1eab2a1d
[clang] Update diagnostics to include matrices as accepted types (#201237)
Several `err_builtin_invalid_arg_type` call sites still emit "scalar or
vector of ..." even though the underlying checkers already unwrap matrix
types. This extends the diagnostic with a new "scalar, vector, or matrix
of" option (index 6) and migrates the call sites whose checkers do
accept matrices:

Call sites whose checkers only unwrap VectorType are left at index 5 so
their diagnostic text continues to accurately describe what is accepted.

Tests using the old wording are updated to match.

Fixes #189147

Assisted by copilot

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-07-21 10:33:02 -07:00
Andy Ames
5b1fa37be6
[analyzer] Fix crash in RegionStoreManager::bindArray from constructor array-to-pointer decay (#210649)
ProcessInitializer() strips implicit casts from a CXXCtorInitializer's
init expression via IgnoreImplicit(), then decides whether to treat the
initializer as a direct array-to-array member copy by checking
Init->getType()->isArrayType(). For a pointer member initialized via
array-to-pointer decay of a reference-to-array constructor parameter
(e.g. `Foo(T (&arr)[N]) : ptr_(arr) {}`), IgnoreImplicit() strips the
ArrayToPointerDecay cast, exposing the underlying array-typed
expression, so this check misfires even though the field itself is a
pointer, not an array. That branch fetches the raw region address of the
whole array, bypassing the normal decay logic (which produces an
ElementRegion), so the pointer member ends up holding the address of the
whole array typed as the array itself, instead of an ElementRegion at
index 0.

Later, dereferencing and storing through that mistyped pointer routes
into RegionStoreManager::bindArray() (instead of bindScalar()), which
unconditionally casts its Init value to nonloc::CompoundVal, asserting
in a debug build and segfaulting in a release build when Init is
anything else, e.g. a nonloc::LocAsInteger produced by round-tripping a
pointer through an integer type.

Fix the actual bug by checking the field's type instead of the
initializer expression's type. Also generalize bindArray()'s existing
guard (added by #178923 for issue #178797) from an enumeration of
specific SVal kinds to the same exhaustive
`!isa<nonloc::CompoundVal>()` check already used by its siblings
bindStruct() and bindVector(), so it doesn't need to be extended again
every time a new SVal kind reaches this path -- this is what actually
catches our case (nonloc::LocAsInteger), which the prior enumeration
didn't cover.

This is the same underlying bug behind #147686 (fixed by #153177, which
its own author noted was "more of a workaround") and #178797 (fixed by
#178923); both those fixes patched symptoms at bindArray() without
addressing the ProcessInitializer() root cause. Fixing the root cause
also resolves two FIXME-annotated precision gaps in
clang/test/Analysis/initializer.cpp's gh147686 regression test.

Fixes #210183

AI tool use disclosure: Claude Code (Anthropic) assisted in reducing the
original crash to a minimal, dependency-free reproducer (via creduce
plus manual bisection, verifying each reduction step against the actual
crash), which informed root-causing this bug in
RegionStoreManager::bindArray and ExprEngine::ProcessInitializer. The
commits made here were drafted with Claude's assistance and reviewed by
me before being pushed. I've reviewed all AI-assisted contributions here
and take full responsibility for the correctness of this change.

---------

Co-authored-by: Andy Ames <andy.ames@joby.aero>
Co-authored-by: Balázs Benics <benicsbalazs@gmail.com>
2026-07-21 17:17:12 +01:00
Ian Li
ec8e379cac
[NFC][Clang] Remove dead code from LifetimeSafety/FactsGenerator.cpp (#210830)
This PR removes dead code in
`clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp`. This was
discovered by a Coverity scan on clang.
2026-07-21 17:11:23 +01:00
Benjamin Luke
315c8bba65
Reland "[clang][CodeGen][X86_64] Honor per-function AVX ABI in C/C++ call paths, maintain old psABI for PlayStation." (#210349)
https://github.com/llvm/llvm-project/pull/193298 was reverted because of
a compile time regression (see results
[here](https://llvm-compile-time-tracker.com/compare.php?from=b9869c8c920a7dfa983e215bc30729b13d8b353b&to=464b46a73b7592c95222cf2e64b34ffe6f2cf251&stat=instructions:u))

I added a conditional statement so that getFunctionFeatureMap and the
subsequent string lookup is only called if FD->hasAttr<TargetAttr>()
evaluates to true which should be very rare.

---------

Co-authored-by: Aaron Ballman <aaron@aaronballman.com>
2026-07-21 09:04:03 -07:00
Patrick Simmons
1301a69bc2
Fix Strong VTables Accidentally Emitted by #159856 (#200942)
Users have reported link errors due to duplicate vtables after the merge
of #159856. Root cause analysis revealed that these errors were due to
the VTables emitted in `CGOpenMPRuntime::emitAndRegisterVTable`, which
was added by PR #159856. This PR fixes the issue by changing that
function to emit its VTables as weak symbols.
2026-07-21 10:58:20 -05:00
adams381
d534912565
[CIR] Add x86_64 aggregate calling-convention lowering (#210528)
The x86_64 SysV calling-convention bridge in CallConvLowering so far handles only scalar arguments and returns.  A function with a struct or array parameter is reported NYI.  This teaches the bridge to classify struct and array aggregates.

A struct is mapped to an `llvm::abi` record built from the DataLayout field offsets and the CanPassInRegisters flag on the module's `cir.record_layouts` metadata, and an array maps to an `llvm::abi` array.  The library's classifier then produces the ArgInfo, either Direct with a coerced register type the existing rewriter flattens, or Indirect via sret, byval, or byref.  CIRABIRewriteContext already applies all of these, so this only feeds it the aggregate classifications and leaves the scalar path untouched.

Aggregate shapes the bridge does not yet classify stay errorNYI, so an unsupported signature fails cleanly instead of being misclassified.  Those are unions (whose register coercion needs a widen fixup), packed and over-aligned records, empty-for-ABI records, and `_BitInt`.  All-float aggregates such as a two-`float` struct or `float[2]` are included too.  Their SSE class coerces to a `<2 x float>` vector the bridge cannot yet represent, so instead of passing the aggregate through unchanged it reports the coercion as NYI.

The byval and sret argument attributes still carry the CIR record type.  Converting that to the LLVM type in LowerToLLVM is a separate change, so the byval and sret tests check the CIR output only, while the direct and flatten tests also check the lowered LLVM IR.
2026-07-21 10:51:01 -05:00
Erich Keane
15ec65a698
[OpenACC] Make sure our 'init' recipe handles nullptr_t (#211008)
The bug report shows that we missed one scalar type in our
initialization code, nullptr_t! This patch adds the initializer to make
sure it works correctly, and adds the test (plus a non-template
    version).

Fixes: #210877
2026-07-21 08:40:22 -07:00
Erich Keane
b4ef17b8c7
[OpenACC] Better handle error overloaded ops in ForStmtChecker (#211005)
The OpenACC 'loop' constructs do a bunch of checking on the contents of
a ForStmt. However, in cases of overloaded operators, some of the
checking we assumed happened (like operators having a certain number of
    args) doesn't hold in the case of errors.  This patch adds some
guards to make sure we error-out if the number of args doesn't match
what we're expecting everywhere I could find it.

Fixes: #210958
2026-07-21 08:40:10 -07:00
Abhina Sree
2542743b15
[SystemZ] Enable clang-target-64-bits for s390x (#210361)
Enable clang-target-64-bits for s390x so we can enable tests like
https://github.com/llvm/llvm-project/pull/210341
2026-07-21 11:22:42 -04:00
Corentin Jabot
4f58fc26ad
[Clang] Yet more consistent Unicode diagnostics (#211002)
This PR
- Use the recently introduced `EscapeSingleCodepointForDiagnostic` in
more places
- Fix a bug where U+FEFF was incorrectly treated as a BOM and therefore
did not render at all in diagnostics
2026-07-21 17:22:21 +02:00
Corentin Jabot
7b159b648b
[Clang] Defaults -Wunicode-whitespace to an error. (#210945)
Clang accepts some Unicode whitespaces in some context. There are a few
issues with this:
 - The support is incomplete and inconsistent, as illustrated in #38934
- We are not consistent with the Unicode specs (tr1, tr55) in that we
treat U+0028/0+0029 as horizontal separators while Unicode consider them
vertical.

Ultimately, Unicode whitespaces are more likely than not unintended.
Neither GCC nor MSVC support this extension.

Fixes #38934.
2026-07-21 14:33:14 +00:00
Erich Keane
42972f5e5d
[CIR] Introduce data_member_offset attribute (#208777)
Some fields, like no_unique_address marked ones, aren't present in the
CIR struct type. This attribute represents an offset into a struct
instead, since get_member isn't possible without a member.

I also considered representing these types in the struct, but it ends up
causing a lot of awful looking structs, and forces the LLVMIR to contain
empty fields for each of these, but not in lexical order, which is
particularly awful looking.

I considered making this part of data-member, but it seems like not a
particularly good idea, since this isn't really getting a 'member' in
the traditional sense.
2026-07-21 05:56:47 -07:00
Paulius Velesko
f90e121dde
[Darwin] Use macOS product version in ensureTargetInitialized (#206902)
`Darwin::ensureTargetInitialized()` recorded the raw triple OS version
from `getOSVersion()`, which on macOS is the Darwin *kernel* version
(e.g. `24.3.0`), not the macOS *product* version (`15.x`). The offload
host job later calls `setTarget()` again from `AddDeploymentTarget()`
with the product version; `setTarget()`'s reinit guard only
short-circuits when the versions match, so the mismatch trips
`assert(!TargetInitialized && "Target already initialized!")` and clang
aborts on every `-x hip --offload=spirv64* --target=arm64-apple-darwin`
compile.

Convert macOS kernel versions via `getMacOSXVersion()` so the lazy init
records the same version `AddDeploymentTarget()` uses later.
2026-07-21 07:39:12 -05:00
Matt Arsenault
27eeb73702
AMDGPU: Use module flags to control xnack and sramecc (#204595)
This ensures these ABI details are encoded in the IR module
rather than depending on external state from command-line flags.
Previously, these were encoded as function-level subtarget features.
The code object output was a single target ID directive implied
by the global subtarget. The backend would previously check if a
function's subtarget feature mismatched the global subtarget. This
is avoided by making xnack and sramecc module-level properties from
the start. This also provides proper linker compatibility
enforcement, moving the error point earlier.

The old encoding was also an abuse of the subtarget feature system.
Subtarget features are a bitvector, and later features in the string
can override earlier ones. The old handling added a special case
where explicit settings were preserved: ordinarily +feature,-feature
should result in the feature being disabled, but +xnack,-xnack would
preserve the explicit "-xnack" state, which differs from the absence
of any xnack setting.

The new flags are encoded as 0/1, with the "any" case represented
as the absence of the flag. I considered an explicit tri-state unknown
value, but decided against it.

This also removes warnings when using these module flags on targets
that do not support the corresponding feature. Previously, messages
were written directly to stderr instead of using proper diagnostics.
Avoiding the warning reduces burden on frontends to check which targets
require the flags.

For migration purposes, the subtarget features still exist. Currently,
they are still respected in the various binary tools, pending
disassembler changes to determine target ID modifiers from e_flags.
CodeGen requires using the module flags. An error will be raised when
attempting to use the old global subtarget features. These should be
removed after a migration period for frontends to update. Functionality
wise, bitcode autoupgrade should work. Old bitcode will not have the
flags, resulting in a different target ID in the output binary than
expected, but it should run correctly.

New cl::opts exist only because it was inconvenient to update all
tests using multiple xnack modes. Users should never use these.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-21 14:38:39 +02:00
eleviant
a83cc57559
Attempt to fix buildbot failure (#210956)
Value names are discarded by default on build without asserts.
2026-07-21 14:31:10 +02:00
Akshay K
3fc3ef399d
[Clang] Fix assertion failure when classifying a dependent call to a builtin (#210524)
## Summary
Fix an assertion failure when Clang classifies a built-in call with
type-dependent arguments before template instantiation, e.g., while
deducing an `auto` non-type template parameter:

  For example:
  ```cpp
  template <auto> struct S {};

  template <typename T>
  using Alias = S<__builtin_constant_p(T::x)>;
```
```
Assertion failed: (isa<T>(CanonicalType)), function castAs, file
TypeBase.h, line 9349.
 #9  clang::Type::castAs<clang::FunctionType>() const
 #10 clang::CallExpr::getCallReturnType(clang::ASTContext const&) const
 #11 ClassifyInternal(clang::ASTContext&, clang::Expr const*)
#12 clang::Expr::ClassifyImpl(clang::ASTContext&,
clang::SourceLocation*) const
 #13 clang::Sema::DeduceAutoType(...)
 #14 clang::Sema::CheckTemplateArgument(...)
```

## Cause
Built-in references initially have the BuiltinFn placeholder type. For a non-dependent call, `BuildResolvedCallExpr()` applies `CK_BuiltinFnToFnPtr`, converting the callee to its function-pointer type. 

When a call has type-dependent arguments, `BuildCallExpr()` postpones semantic analysis until instantiation. The callee, therefore, retains its BuiltinFn placeholder type. Deducing the auto non-type template parameter classifies the dependent call through `Expr::ClassifyImpl()`. This calls `CallExpr::getCallReturnType()`, which previously did not handle BuiltinFn and attempted to cast the placeholder to FunctionType, triggering an assertion.

The issue also affects ordinary builtins such as `__builtin_ffs` and is not specific to` __builtin_constant_p`.

 ## Fix
Handle `BuiltinFn` alongside the dependent and `Overload` callee cases in `CallExpr::getCallReturnType()` and return `DependentTy`. This matches the type `BuildCallExpr()` gives the `CallExpr` itself, so `getCallReturnType()` and `getType()` now agree on such calls.

Built-in resolution and built-in-specific type checking still occur as usual during template instantiation.

Added coverage for dependent calls and successful instantiation of `__builtin_constant_p` and `__builtin_ffs`,  a non-dependent control case, and getCallReturnType() for a BuiltinFn callee.
2026-07-21 13:47:38 +02:00
Balázs Benics
d7da964ee1
[analyzer][NFC] Add StackFrame parent-chain range helpers (#210938)
Walking a StackFrame's parent chain was open-coded across the Analysis
library and Static Analyzer as hand-rolled loops of the form `for (const
StackFrame *SF = X; SF; SF = SF->getParent())`.

Add range-based traversal helpers and convert the applicable loops:

* StackFrame::parents() - strict ancestors (excludes *this)
* StackFrame::parentsIncludingSelf() - *this then all ancestors

Both are built on a small forward `parent_iterator` that dereferences to
`const StackFrame &` and advances via getParent(), with a null
past-the-end sentinel.

For the common case of obtaining the current frame from an ExplodedNode
or CheckerContext, add a self-inclusive `stackframes()` convenience on
each that delegates to `getStackFrame()->parentsIncludingSelf()`.

Converted call-sites additionally adopt llvm::any_of / llvm::enumerate /
make_pointer_range where it makes the traversal more declarative. Loops
that stop at a target frame or advance conditionally (i.e. not "walk
until null") are intentionally left as-is.
2026-07-21 12:46:27 +01:00
Gábor Horváth
ad3f09c7de
[ADT] Add single-pass merge for ImmutableSet/ImmutableMap (#209807)
The immutable-set/map dataflow joins merged two containers by inserting
the
elements of one into the other one at a time, costing O(|B| * log|A|)
and
re-copying shared spine nodes on every insert.

Add a single-pass, structure-sharing tree merge on ImutAVLFactory
(mergeTrees), exposed as ImmutableSet::Factory::unionSets and
ImmutableMap::Factory::mergeWith. It recurses over the larger operand
and
splits the smaller at each key, returning non-overlapping subtrees
unchanged,
so each spine node is copied at most once: O(|B| * log(|A|/|B| + 1)).

Two flags tune it for the different joins:
* KeepUnmatched - keep keys unique to one side (set union / a lattice
join
with an identity) vs. pass them through the combiner (a symmetric join,
   e.g. liveness Must->Maybe).
* SkipShared - return a pointer-identical subtree unchanged in O(1).
Valid
for an idempotent merge (Combine(a, a) == a), which holds for set union
and
every lattice join. Since dataflow states are path-copied from one
another,
a join's operands usually share most subtrees by pointer, so a join that
   touches only a few keys becomes nearly O(diff).

Wire it into the Clang lifetime-safety analysis (set and map joins) and
the
LiveVariables merge, and add ImmutableMergeBM to track it.

Speedups on the lifetime-safety dataflow benchmark (LoanPropagation
phase):
      pointer cycle in a loop  ~2.6x   (1.59 s  -> 0.61 s)
      CFG merges               ~190x   (1.83 s  -> 9.5 ms)
switch fan-out ~1.9x (LiveOrigins; disjoint states, no skip)
LiveVariables is ~2-3x faster on liveness-heavy inputs and neutral on
typical
code (the join is a small fraction of real-code analysis time).

ImmutableMergeBM confirms the merge beats the add loop for small and
near-identical operands, except for independently-built sets differing
by
exactly one element; when one operand is derived from the other -- the
real
dataflow case -- the pointer-skip makes even that a large win. New
randomized
ADT stress tests check the merge against std::set/std::map oracles for
both
canonicalizing and non-canonicalizing factories.

Assisted by: Claude Opus 4.8

Co-authored-by: Gabor Horvath <gaborh@apple.com>
2026-07-21 12:33:28 +01:00
eleviant
6d8d3f8518
[clang] Add flag for making pointer subtraction defined (#196392)
The C and C++ standards require both operands of pointer subtraction to
refer to elements of the same array object. Clang/LLVM currently relies
on this rule in several optimizations:

- `inbounds` GEP introduces UB assumptions once the computed address
escapes the originating object bounds.

- `sdiv exact` assumes %op1 is divisable by %op2 otherwise it is a
poison value.

The first issue may be addressed with -fwrapv-pointer command line
option, however there is no option in clang to mitigate the second
issue. Patch adds a new -fdefined-pointer-subtraction to address this.
2026-07-21 12:44:23 +02:00
Younan Zhang
c6bb072d9e
[Clang] Don't print extra whitespace for comma expression in StmtPrinter (#210920)
For binary expression `1, 2`, StmtPrinter used to print it as `1 , 2`
which doesn't look very pretty.
2026-07-21 10:15:25 +00:00
Akash Agrawal
e2c012fa55
[Clang][Sema] Fix crash on lambda parameter pack with illegal default argument (#210718)
`Sema::ActOnParamDefaultArgument` checked a default-argument expression
for unexpanded parameter packs before checking whether the parameter
itself is a pack. For a lambda parameter pack given a default argument
that is a pack expansion referencing an enclosing function's parameter
pack (e.g. `[](Types... = args...) {}`), the first check runs while
still inside the lambda's scope and sets
`LambdaScopeInfo::ContainsUnexpandedParameterPack` (a mechanism meant
for legitimate outer-pack references). The subsequent
`isParameterPack()` check then correctly diagnoses the real error and
discards the default argument, but the stale flag survives into the
built `LambdaExpr`'s dependence bits. A later unexpanded-pack check on
that `LambdaExpr` finds nothing to report and hits
`assert(!Unexpanded.empty() || LambdaReferencingOuterPacks)`, aborting
instead of just diagnosing the error.

Fix: check `Param->isParameterPack()` first and return immediately after
discarding the default argument, before ever calling
`DiagnoseUnexpandedParameterPack` on an expression that is about to be
thrown away. [dcl.fct.default]p3 forbids a default argument on a pack
parameter unconditionally, so this ordering is also semantically
correct, not just a crash workaround.

Fixes #210714
2026-07-21 17:45:35 +08:00
Younan Zhang
dce3dc8049
[Clang] Add NormalizedConstraint::dump() (#210498)
This facilitates debugging with concepts, particularly when we need to
check complex parameter mappings.

Since this is mainly for debugging purpose, we don't promise any text
stability and hence no tests provided.
2026-07-21 17:18:37 +08:00
Benedek Kaibas
feabbb0f46
[analyzer] Fix false positive when a lifetimebound method is called during destruction (#210801)
When a `lifetimebound` method is called during destruction the checker
emits warnings which leads to false positives. To avoid this a dangling
stack source is not reported if any frame on the current stack belongs
to a destructor.
2026-07-21 11:15:57 +02:00
Yanzuo Liu
d13b8625ee
[clang][Parser] Warn when the body of expansion statement is not a compound statement (#209229)
<https://eel.is/c++draft/stmt.expand#nt:expansion-statement>:

_expansion-statement_:  
template for ( _init-statement<sub>opt</sub>_ _for-range-declaration_ :
_expansion-initializer_ ) _compound-statement_
2026-07-21 16:09:56 +08:00
Madhur Amilkanthwar
9b5c0571af
Enforce single-operand form for llvm.loop.distribute metadata (#201077)
This patch implements Phase 1 of the
[RFC](https://discourse.llvm.org/t/rfc-enforce-single-operand-format-for-all-enable-metadata-nodes/90571)
"Enforce Single-Operand Format for All .enable Metadata Nodes". The
two-operand boolean form !{!"llvm.loop.distribute.enable", i1 0/1} is
replaced by a single-operand enable/disable pair:

  !{!"llvm.loop.distribute.enable"}    ; force distribution
  !{!"llvm.loop.distribute.disable"}   ; suppress distribution
2026-07-21 12:55:09 +05:30
Henrik G. Olsson
e747c8b850
[clang] Remove stale TransformTypeTraits.def entry from module map (#210878)
Commit 2a33792a2e ("[clang][NFC] move traits to tablegen", #201491)
deleted clang/include/clang/Basic/TransformTypeTraits.def in favor of a
tablegen-generated clang/Basic/Traits.inc. The stale module map entry
broke module builds. Renaming it to "clang/Basic/Traits.inc" doesn't
seem to work, ('clang/Basic/Traits.inc' not found) but the build
succeeds with the entry dropped entirely.

Assisted-by: Claude Sonnet 5

rdar://182772346
2026-07-20 23:40:29 -07:00
Ken Matsui
ea52aa0375
[clang] Use key-value initialization for LangASMap (NFCI) (#210259)
The original implementation requires each target to list a value for
every LangAS in exact enum order. This forces targets to specify
mappings for unrelated address spaces and makes it easy to introduce
ordering bugs, such as the one fixed in
4479f3397f.

Address this by introducing a class that supports order-independent
key-value initialization and defaults unspecified entries to 0.
2026-07-21 01:34:47 -04:00
Ken Matsui
890b11e09e
[clang] Use 0 for wasm_funcref in non-Wasm address space maps (NFCI) (#210253)
The __funcref keyword is only supported by the WebAssembly target, so
the wasm_funcref entries in other targets' address space maps are
unused.

Use 0 for these entries, which is consistent with other unsupported
address spaces.
2026-07-20 22:45:46 -04:00
Erich Keane
e8f7d45fa9
[CIR] Refactor lowerUnion so unions get laid out consistently (#210709)
Perennial and a few other examples I came up with showed some situations
where we were bad at layout in CIR for unions. Sometimes we'd omit the
required fields, or miscalculate the storage type, or just not constant
init it correctly. This is mostly because we copy/pasted our
implementation from classic-codegen, but have different invariants.

This patch consistently adds ALL fields to the cir::UnionType, so we
always represent with all, which is an assumption we make elsewhere.

The lowerUnion function is significantly rewritten as the previous
version had a lot of interdepencies between loop runs. This patch
separates it out in a way that has less cyclic complexity which will
hopefully be more readable with minor/little compile-time impact.

This maintains the non-virtual-base functionality as well, though it
does it by collecting the fields like we do for the normal union case,
then just erases them. This greatly simplifies the calculation of
storageType, so it seems worth it.

Additionally, it fixes the constant layout of a null union, which got
the field count wrong in any non-trivial cases.
2026-07-20 22:31:13 +00:00
Erich Keane
13d822c935
[CIR] Fix how we lower bitfield constants (#210791)
My patch to change the type of a const missed that there is a difference
between how we were representing a bitfield (always as an int) in the
constant, and in the struct(as a byte array).

This patch makes sure we correctly match the storage type, and just
requires packing/unpacking arrays when we store it.
2026-07-20 22:20:22 +00:00
Lucas Ribeiro Lima
b4000b69fa
[CIR] X86 vperm2f128 builtin implementation (#208851)
This PR implements X86 VPerm2f128 intrinsics and its tests.

Addresses #167765
2026-07-20 15:18:32 -07:00
Ayokunle Amodu
95649d680b
[CIR][CUDA] Add support for NVVM binary atomic builtins (#210534)
Adds codegen support for the following NVVM binary atomic builtins: add,
sub, and, or, xor, min, umin, max and max.

These are lowered to the corresponding CIR `cir.atomic.fetch` operations
and subsequently lowered to LLVM `atomicrmw` instructions.
2026-07-20 18:07:26 -04:00
Ken Matsui
4479f3397f
[clang][TCE] Fix ordering of OpenCL address space mappings (#210244)
opencl_global_device and opencl_global_host are defined after
opencl_generic in LangAS, but commit
8d27be8dba inserted them before
opencl_generic in the TCE address space map.

Fix the order to restore the intended mappings.
2026-07-20 18:00:06 -04:00
Erich Keane
e92e1787bd
[CIR] Fixup conversion of const unions/structs of unions (#210146)
Now that we represent a union as all of the fields, it is possible for
the non-storage type to be initialized, so the fact that we were
lowering the types as storage in 1 way for the constant type, but
filling it with our actual value was wrong.

This patch makes sure we create a literal struct type for LLVM for union
types where they don't match, which generally matches the OGCG
implementation/output.

I've also generalized the work for the FAM to do this conversion, and
moved it to LoweringHelpers, so that our ConstantRecord lowering can use
it too.

This patch fixes up a couple uses of std::string initializers where they
fit in the SSO.

Note: I was assisted in this by Claude Opus. I did plenty of self-review
on this as it was being generated, and a post-review, but hopefully I
didn't miss anything.
2026-07-20 14:53:08 -07:00
Joseph Huber
33acb625bb
[Clang][AMDGPU] Search both amdgcn and amdgpu libraries again (#210767)
Summary:
Extension to https://github.com/llvm/llvm-project/pull/209770/, the
previous one did not cover all cases we search paths, it only did the
relative paths for a few cases. This adds it to the other case, should
be the same logic and motivation.
2026-07-20 14:44:13 -05:00
Vicky Nguyen
365a64ac93
[CIR][AArch64] Upstream store (vst1_*/vst1q_*) NEON builtins (#209347)
Related to https://github.com/llvm/llvm-project/issues/185382

CIR lowering for store intrinsics (`vst1_*`/`vst1q_*`)
(https://arm-software.github.io/acle/neon_intrinsics/advsimd.html#store)

Port tests:
- `clang/test/CodeGen/AArch64/neon-intrinsics.c`
-  `clang/test/CodeGen/AArch64/neon-ldst-one.c`
-  `clang/test/CodeGen/AArch64/poly64.c`
-  `clang/test/CodeGen/arm-neon-vst.c`

to `clang/test/CodeGen/AArch64/neon/store.c`
2026-07-20 11:31:45 -07:00
Haowei
a04f87fdd9
Reapply "Skipping host target exports during cross-compilation" (#210… (#210496)
This reverts commit 42eb7db188. This
reland 3fbb037d03 (#209922).

Under CMake 4+, calling add_library(... SHARED IMPORTED) on a target
platform that lacks dynamic linking support triggers a fatal error. This
becomes an issue when building LLVM and runtimes for baremetal targets
like armv6m-none-eabi. This patch adds the option
"LLVM_OMIT_EXPORTS_FROM_CONFIG" in LLVM. When used in sub builds like
LLVM runtimes, it makes CMake to skip including the LLVM and Clang
exports. This mitigates the CMake 4 errors on baremetal runtimes.

42eb7db188 originally
apply this flag on all runtimes build and causing issues on runtimes
like intel-sycl-gpu, amdgpu-offload-ubuntu-22-cmake-build-only.
This PR only set this flag when the target platform lacks shared library
support.
2026-07-20 10:47:59 -07:00
Matthias Wippich
bdfcef5276
[clang] improve diagnostics for enums (#204682)
This patch makes clang attempt printing enumerator names rather than
C-style cast expressions in more diagnostics (notably static_assert) iff
the value matches an enumerator exactly.

For example, consider a static assertion `static_assert(E ==
TestEnum::B);` where `E` is a constant template argument. Assuming
`(TestEnum)1 == TestEnum::A`, this changes emitted diagnostics as
follows:
```
// old
static assertion failed due to requirement '(TestEnum)1 == TestEnum::B'

// new
static assertion failed due to requirement 'TestEnum::A == TestEnum::B'
```
2026-07-20 18:34:37 +02:00
Matthias Wippich
272378ef3c
[clang][NFC] Extract LookupOverloadedUnaryOp (#210567)
This patch extracts `LookupOverloadedUnaryOp` from
`CreateOverloadedUnaryOp` for consistency with
`LookupOverloadedBinOp`/`CreateOverloadedBinOp`.
2026-07-20 18:30:19 +02:00
Matheus Izvekov
4158229224
[clang] fix a crash for uses of a pseudo-destructor of enum without definition (#210424)
Lookup for the destuctor name in the object type only applies to record
types.

Since this will be backported, there are no release notes.

Fixes #209808
2026-07-20 16:27:39 +00:00
Brian Cain
34aefe9744
[Hexagon] Fix compiler-rt install dir type, scope sanitizers (#209375)
COMPILER_RT_INSTALL_LIBRARY_DIR must be CACHE STRING, not CACHE PATH: a
relative PATH-typed cache entry resolves against the runtimes sub-build
directory instead of CMAKE_INSTALL_PREFIX, misplacing sanitizer libs.

Replace the explicit COMPILER_RT_BUILD_* ON list with
COMPILER_RT_SANITIZERS_TO_BUILD=all, since those options already default
ON upstream and infeasible sanitizers self-exclude via their own
ALL_<X>_SUPPORTED_ARCH lists.

Add FORCE to the dylib overrides so they take effect after
hexagon-unknown-linux-musl-clang-dist.cmake has already cached them OFF.
2026-07-20 10:42:33 -05:00
Erich Keane
35aa7b529e
Ensure that we properly propagate template decl attributes to redecls (#209873)
Variable and class templates weren't forwarding their declaration
attributes that were attached directly to them (at the moment, the only
one I could find that had this issue is the no_specialization attr). The
result was that intermediate redeclarations would prevent the
diagnostics from happening.

This patch ensures we propagate them properly for variable and class
templates. It seems our function templates already do the right thing.

Fixes: #209812
2026-07-20 07:32:26 -07:00
Matthias Wippich
2a33792a2e
[clang][NFC] move traits to tablegen (#201491)
This patch moves all traits to a tablegen file. 

The motivation for this change is a review comment in
https://github.com/llvm/llvm-project/pull/142341 - since then about a
year has passed and we've accumulated 9 standard names that are
maintained separately from their corresponding trait definitions. For
transform type traits we keep the standard names around as well. While
this is still a reasonably low number, it is definitely going to keep
increasing.
2026-07-20 06:50:22 -07:00
BohdanYehorov
ac41c58f7b
[clang][docs] Fix include path in InternalsManual (#209458)
The paths `include/Basic/StmtNodes.td` and `include/AST/Expr*.h` in the
Clang Internals Manual are incorrect.
2026-07-20 12:20:10 +00:00
rdevshp
d9c88062ec
[analyzer] Fix _BitInt support & casting behavior for Z3 symbolic execution (#210525)
Forces symbolic cast to be enabled for z3 symbolic execution, and
switches away from Ctx.getTypeSize for getting the bit width of integral
types.

The current patch might be a bit problematic for z3 cross-check, as this
relies on symbolic integer cast to be always on. I am not sure if
turning on ShouldSupportSymbolicIntegerCasts would cause issues for the
supported range-based solver, so I only kept it turned on when
AnalysisConstraintsOpt == Z3ConstraintsModel.

Assisted-by: Codex
2026-07-20 13:05:49 +01:00
Younan Zhang
a8ffce4247
[Clang] Fix evaluation of fold expanded constraints for NTTP (#210005)
This is a rework of #200185 and also reflects what we did for TTP in
C++26 fold expression constraints (adc64c6e17)

Fixes https://github.com/llvm/llvm-project/issues/199569
2026-07-20 19:32:18 +08:00
Benedek Kaibas
b21fb937f1
[analyzer][NFC] Correct the DanglingPtrDeref checker's filename (#209862)
The alpha `DanglingPtrDeref` checker got implemented in #209278. Since
it is under heavy development and subject to change significantly in the
near future it is in alpha stage. During the development of the
`DanglingPtrDeref` checker its name got changed from
`ReportDanglingPtrDeref` to `DanglingPtrDeref` based on the conversation
here:
https://github.com/llvm/llvm-project/pull/209278#discussion_r3578604913

While the checker's registration got updated in `Checkers.td` the same
change did not get applied to the `
clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt` and the checker's
filename. This PR addresses this issue.
2026-07-20 12:26:22 +01:00
Fangrui Song
1ad0e69895
[Driver,FreeBSD] Fix -pie for -r and -no-pie links (#210663)
Port Gnu.cpp changes ae623d16d5 and cac82e26c6 to FreeBSD and
Serenity: -r should suppress -pie. -nopie, OpenBSD specific, should not
be used by other OSes.

Group the options selecting the link mode and place them after -m, as
gnutools::Linker does, so that -r suppresses -export-dynamic and
--hash-style as well, and -no-pie overrides the -fsanitize PIE default.

Drop --enable-new-dtags: default in modern linkers.

Change -Bstatic to -static to follow Gnu.cpp (identical in lld and older
GNU ld).
2026-07-20 01:37:56 -07:00
Fangrui Song
751fca6c06
[Driver][test] Unwrap freebsd-mips-as.c RUN lines (#210658)
Collapse 3-line RUN blocks to 2 lines and move -### immediately after
%clang, matching the prevailing style for new tests.
2026-07-20 01:06:26 -07:00
Tony Varghese
8a119310da
[clang][NFC] Bump the maximum number of Frontend diagnostics (#210345)
The number of Frontend diagnostics in DiagnosticFrontendKinds.td is
close to the DIAG_SIZE_FRONTEND limit of 200 (195 in use), and in-flight
PRs adding frontend diagnostics (e.g. #187986) run into the static
assert in DiagnosticIDs.cpp. Increase the limit to 300, following the
precedent of #200948 which did the same for Sema diagnostics.

Co-authored-by: Tony Varghese <tony.varghese@ibm.com>
2026-07-20 09:04:19 +05:30
TelGome
5497f466e4
[RISCV][P-ext] Support Packed Narrowing Zip (#210040) 2026-07-20 10:35:49 +08:00
Brian Cain
c45b4e4d00
[Hexagon] Link static PIE executables against rcrt1.o (#210125)
We always selected crt1.o as the CRT start file, regardless of link
mode.

Select rcrt1.o - the self-relocating static-PIE start file when -static
and PIE are active
2026-07-19 10:48:48 -05:00
Mikołaj Piróg
1d55a816c6
[X86] Support apxf in attribute target (#184078)
As in title. This adds support for using apxf in attribute target.
Individual features are not supported for FMV but are supported for
enabling a feature for the function

Patch done with usage of Claude Code.
2026-07-19 13:38:48 +02:00
Kevin Sala Penades
ee62806354
[Clang][OpenMP] Add parsing/sema for dims modifier in num_teams and thread_limit (#206412)
Add parsing and sema support for `dims` modifier (OpenMP 6.1) in `num_teams` and
`thread_limit` clauses. Example:

```cpp
constexpr int N = 2;
#pragma omp teams num_teams(dims(3): x, y, z) thread_limit(dims(N): a, b)
{ ... }
```
2026-07-19 00:13:57 -07:00
aokblast
617e4f54e5
[Clang][Interpreter] Don't pass -fPIC on MSVC (#210507) 2026-07-19 08:32:37 +08:00
Ayokunle Amodu
4812a67a45
[CIR][AMDGPU] Add support for AMDGCN frexp_mant builtins (#198121)
Adds codegen for the following AMDGCN frexp mantissa builtins:

- __builtin_amdgcn_frexp_mant (double)
- __builtin_amdgcn_frexp_mantf (float)
- __builtin_amdgcn_frexp_manth (half)

These are lowered to the corresponding `llvm.amdgcn.frexp.mant`
intrinsic.
2026-07-18 12:57:05 -04:00
Prabhu Rajasekaran
acd3fcfdd6
[clang] Emit call graph type metadata for internal linkage symbols (#210194) 2026-07-18 08:59:20 -07:00
陈子昂
f6d9ec41d3
[RISCV] Add packed narrowing convert intrinsics (#210389)
Add RISC-V P-extension packed narrowing convert header APIs for `pncvt`
and `pncvth`.

The new APIs lower through generic IR: RV32 uses truncate / logical
shift plus truncate forms, while RV64 uses existing packed unzip shuffle
forms. This reuses the existing backend lowering and TableGen aliases
rather than adding intrinsic-specific lowering.

Tests cover Clang IR generation and cross-project header assembly checks
for RV32/RV64 spec-listed mnemonics.
2026-07-18 22:39:38 +08:00