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
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.
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.
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.
```
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>
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
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.
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`.)
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.
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.
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.
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>
(#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.
Move the coroutine tests into a dedicated CodeGenCoroutines directory.
This is a test only reorganization in preparation for upcoming
coroutine-related changes.
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
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
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
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).
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__)`.
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.
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>
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>
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%.
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>
In C++20 (P1008R1 https://wg21.link/p1008r1), aggregates are prohibited
from having any user-declared constructors, even if they are = delete or
= default.
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.
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>
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.
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
Exclude casts precisely matching `this` and `*this` (through
parens/implicit casts), without matching member accesses like
`this->m_field`.
rdar://173770064
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`.
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.
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>
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>
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
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
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.
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>
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>
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.
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.
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>
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>
Reverts llvm/llvm-project#210154
Broke some build bots.
https://github.com/llvm/llvm-project/pull/210154#issuecomment-5071830822https://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'
```
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>
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>
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>
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>
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>
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.
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.
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
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.
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
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.
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.
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.
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>
This PR introduces PtrRefSafetyModel to abstract away type checks for
various smart pointer types in WebKit to share more code between
different checkers.
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
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.
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
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).
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.
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
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
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
This patch intends to clarify the current behaviors, not to state the
expected/desirable behaviors.
---------
Co-authored-by: Tarun Prabhu <tarunprabhu@gmail.com>
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).
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>
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().
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.
`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.
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>
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.
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.
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
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.
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.
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
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.
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.
## 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)
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.
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
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.
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.
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
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.
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.
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.
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>
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.
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
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
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.
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.
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.
fixes#194293fixes#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
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.
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.
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()`.
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>
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>
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.
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.
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
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
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
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.
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.
`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.
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>
## 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.
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.
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>
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.
`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
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.
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.
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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'
```
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.
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
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.
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
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.
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).
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>
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
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.
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)
{ ... }
```
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.
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.