Skip to content

[clang] Add check in SemaChecking for multiple unsequenced volatile accesses - #180955

Merged
AaronBallman merged 28 commits into
llvm:mainfrom
Seraphimt:VolatileCheckSema
Nov 13, 2026
Merged

AaronBallman merged 28 commits into
llvm:mainfrom
Seraphimt:VolatileCheckSema

Conversation

@Seraphimt

Copy link
Copy Markdown
Contributor

According to standards volatile accesses is sideeffects and multiple unsequenced volatile accesses same variable is UB.

@llvmbot llvmbot added clang Clang issues not falling into any other category clang:frontend Language frontend issues, e.g. anything involving "Sema" labels Feb 11, 2026
@llvmbot

llvmbot commented Feb 11, 2026 •

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-backend-powerpc
@llvm/pr-subscribers-backend-systemz

@llvm/pr-subscribers-clang

Author: None (Seraphimt)

Changes

According to standards volatile accesses is sideeffects and multiple unsequenced volatile accesses same variable is UB.


Full diff: https://github.com/llvm/llvm-project/pull/180955.diff

3 Files Affected:

  • (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2)
  • (modified) clang/lib/Sema/SemaChecking.cpp (+30-12)
  • (modified) clang/test/SemaCXX/warn-unsequenced.cpp (+26)
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index f12677ac11600..defd168b2c629 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2581,6 +2581,8 @@ def warn_unsequenced_mod_mod : Warning<
   "multiple unsequenced modifications to %0">, InGroup<Unsequenced>;
 def warn_unsequenced_mod_use : Warning<
   "unsequenced modification and access to %0">, InGroup<Unsequenced>;
+def warn_unsequenced_use_use_volatile : Warning<
+  "unsequenced volatile accesses to %0">, InGroup<Unsequenced>;
 
 def select_initialized_entity_kind : TextSubstitution<
   "%select{copying variable|copying parameter|initializing template parameter|"
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 89171246d0bcb..b9d1ae9240923 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14015,7 +14015,7 @@ class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
   };
 
   /// An object for which we can track unsequenced uses.
-  using Object = const NamedDecl *;
+  using Object = const ValueDecl *;
 
   /// Different flavors of object usage which we track. We only track the
   /// least-sequenced usage of each kind.
@@ -14034,6 +14034,12 @@ class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
     UK_Count = UK_ModAsSideEffect + 1
   };
 
+  enum WarningKind {
+    WK_UseAndMod,
+    WK_ModAndMod,
+    WK_Volatile_UseAndUse
+  };
+
   /// Bundle together a sequencing region and the expression corresponding
   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
   struct Usage {
@@ -14179,7 +14185,7 @@ class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
   /// usage and false we are checking for a mod-use unsequenced usage.
   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
-                  UsageKind OtherKind, bool IsModMod) {
+                  UsageKind OtherKind, WarningKind WarnKind) {
     if (UI.Diagnosed)
       return;
 
@@ -14192,11 +14198,22 @@ class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
     if (OtherKind == UK_Use)
       std::swap(Mod, ModOrUse);
 
+    unsigned DiagID = 0;
+    switch (WarnKind) {
+    case WK_UseAndMod:
+      DiagID = diag::warn_unsequenced_mod_use;
+      break;
+    case WK_ModAndMod: 
+      DiagID = diag::warn_unsequenced_mod_mod;
+      break;
+    case WK_Volatile_UseAndUse:
+      DiagID = diag::warn_unsequenced_use_use_volatile;
+      break;
+    }
+
     SemaRef.DiagRuntimeBehavior(
         Mod->getExprLoc(), {Mod, ModOrUse},
-        SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
-                               : diag::warn_unsequenced_mod_use)
-            << O << SourceRange(ModOrUse->getExprLoc()));
+        SemaRef.PDiag(DiagID)<< O << SourceRange(ModOrUse->getExprLoc()));
     UI.Diagnosed = true;
   }
 
@@ -14229,27 +14246,28 @@ class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
   void notePreUse(Object O, const Expr *UseExpr) {
     UsageInfo &UI = UsageMap[O];
     // Uses conflict with other modifications.
-    checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
+    checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, WK_UseAndMod);
+    // Volatile uses conflict with other uses.
+    if (O->getType().isVolatileQualified())
+      checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_Use, WK_Volatile_UseAndUse);
   }
 
   void notePostUse(Object O, const Expr *UseExpr) {
     UsageInfo &UI = UsageMap[O];
-    checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
-               /*IsModMod=*/false);
+    checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, WK_UseAndMod);
     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
   }
 
   void notePreMod(Object O, const Expr *ModExpr) {
     UsageInfo &UI = UsageMap[O];
     // Modifications conflict with other modifications and with uses.
-    checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
-    checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
+    checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, WK_ModAndMod);
+    checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, WK_UseAndMod);
   }
 
   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
     UsageInfo &UI = UsageMap[O];
-    checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
-               /*IsModMod=*/true);
+    checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, WK_ModAndMod);
     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
   }
 
diff --git a/clang/test/SemaCXX/warn-unsequenced.cpp b/clang/test/SemaCXX/warn-unsequenced.cpp
index 50dde8f3a5789..3b4a8ec9380d0 100644
--- a/clang/test/SemaCXX/warn-unsequenced.cpp
+++ b/clang/test/SemaCXX/warn-unsequenced.cpp
@@ -815,3 +815,29 @@ void test_var() {
 }
 
 } // namespace templates
+
+namespace muliple_read_volatile {
+  volatile int v1;
+  
+  void PositiveTest(){
+    int x = 0;
+    int y = 0;
+    x = v1 + v1;        // cxx11-warning {{unsequenced accesses to volatile qualified 'v1'}}
+                        // cxx17-warning@-1 {{unsequenced accesses to volatile qualified 'v1'}}
+    v1 = v1 * v1;       // cxx11-warning {{unsequenced accesses to volatile qualified 'v1'}}
+                        // cxx17-warning@-1 {{unsequenced accesses to volatile qualified 'v1'}}
+    x = v1 + (y++, v1); // cxx11-warning {{unsequenced accesses to volatile qualified 'v1'}}
+                        // cxx17-warning@-1 {{unsequenced accesses to volatile qualified 'v1'}}
+    x = v1 + v1 || y;   // cxx11-warning {{unsequenced accesses to volatile qualified 'v1'}}
+                        // cxx17-warning@-1 {{unsequenced accesses to volatile qualified 'v1'}}
+  }
+  
+  void NegativeTest(){
+    int x = 0;
+    int y = 0;
+    x = v1 + y;   // no-warning
+    v1 = v1 * y;  // no-warning
+    x = (v1, v1); // no-warning
+    x = v1 || v1; // no-warning
+  }
+} // namespace muliple_read_volatile
\ No newline at end of file

@github-actions

github-actions Bot commented Feb 11, 2026 •

Copy link
Copy Markdown

✅ With the latest revision this PR passed the C/C++ code formatter.

@cor3ntin

Copy link
Copy Markdown
Contributor

This looks pretty neat

This change needs a release note.
Please add an entry to clang/docs/ReleaseNotes.rst in the section the most adapted to the change, and referencing any Github issue this change fixes. Thanks!!

Comment thread clang/test/SemaCXX/warn-unsequenced.cpp Outdated
x = (v1, v1); // no-warning
x = v1 || v1; // no-warning
}
} // namespace muliple_read_volatile No newline at end of file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a newline at the end of file

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a newline at the end of file

@Fznamznon Done.
I'm quite a newbie сould please advise how fix build? As far I understand, in several tests appear new warning. Do they need to be marked?

Failed Tests (18):
Clang :: CodeGen/PowerPC/builtins-ppc-fma.c
Clang :: CodeGen/SystemZ/builtins-systemz-i128.c
Clang :: CodeGen/SystemZ/builtins-systemz-vector-constrained.c
Clang :: CodeGen/SystemZ/builtins-systemz-vector.c
Clang :: CodeGen/SystemZ/builtins-systemz-vector2-constrained.c
Clang :: CodeGen/SystemZ/builtins-systemz-vector2.c
Clang :: CodeGen/SystemZ/builtins-systemz-vector3.c
Clang :: CodeGen/SystemZ/builtins-systemz-vector4.c
Clang :: CodeGen/SystemZ/builtins-systemz-vector5.c
Clang :: CodeGen/SystemZ/builtins-systemz-zvector-constrained.c
Clang :: CodeGen/SystemZ/builtins-systemz-zvector-error.c
Clang :: CodeGen/SystemZ/builtins-systemz-zvector.c
Clang :: CodeGen/SystemZ/builtins-systemz-zvector2-constrained.c
Clang :: CodeGen/SystemZ/builtins-systemz-zvector2.c
Clang :: CodeGen/SystemZ/builtins-systemz-zvector3.c
Clang :: CodeGen/SystemZ/builtins-systemz-zvector4.c
Clang :: CodeGen/SystemZ/builtins-systemz-zvector5.c
Clang :: SemaCXX/warn-unsequenced.cpp

Also test warn-unsequenced.cpp failed too but it's pass on my pc =_=

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, are you using check-clang build target to verify that tests are ok?

In SemaCXX/warn-unsequenced.cpp seems a wrong diagnostic message is caught by expected-warning directives.

I think in most of CodeGen tests the new warning fires and they use Werror as I can see in the summary https://github.com/llvm/llvm-project/actions/runs/21958635491?pr=180955 . CodeGen tests usually don't mark diagnostic messages and check emitted code instead so an error will prevent such tests from passing. The tests need to be examined whether they are intentionally trigger the new warning and if they do and the warning is correct for these, we probably need to disable the warning for these via command line. Otherwise bugs in the warning or the tests need to be fixed.

@Seraphimt Seraphimt Feb 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Fznamznon Thank you! I messed two branch with different message and that's why SemaCXX/warn-unsequenced.cpp check fails =_= I fix it.
Rest failed tests related to builtin. As far I understand, builtin use shouldn't trigger warning because is't funcall.
But unseq checker does not take into account now, example: https://godbolt.org/z/Y7nsGPnPr
So I suppose in failed builtin tests turn off unsequenced check.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should fix the unseq checker first to avoid disrupting users? cc @AaronBallman

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Fznamznon I do some research on builtin. And if I understood correct, in some cases violation sequence exists.
It seems like ok for PowerPC\builtins-ppc-fma.c test, there arguments order - left to right:
https://github.com/llvm/llvm-project/blob/main/clang/lib/CodeGen/TargetBuiltins/PPC.cpp#L844

But, for tests of SystemZ, as far as I understood , violation sequence exists. Example, in
https://github.com/llvm/llvm-project/blob/main/clang/test/CodeGen/SystemZ/builtins-systemz-zvector2.c#L146

volatile vector float vf;
vf = vec_sel(vf, vf, vui);

Judging by vecintrin.h it emits into binary expr:

#define __ATTRS_o_ai __attribute__((__overloadable__, __always_inline__))

static inline __ATTRS_o_ai __vector signed char
vec_sel(__vector signed char __a, __vector signed char __b,
        __vector __bool char __c) {
  return (((__vector signed char)__c & __b) |
          (~(__vector signed char)__c & __a));
}

i.e. something like

volatile vector float vf;
vf = (vui & vf) | (~vui & vf)

@uweigand please, advise as creator of that test case.

@uweigand uweigand Feb 20, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess I don't quite understand how this reflects multiple volatile accesses? This is not a macro, but rather an (inline) function, and does not operate on memory at all but on simply on a parameter value. Even if some caller would use vec_sel with an argument for __c that derives from a volatile memory access, that would still be just one access, at that point.

In other words, I do not see how any invocation of the vec_sel routine can actually be "something like" the third code block you show.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@uweigand thank you for reply!
I guess I don't understand something, but shouldn't an 'inline function' inline the body at the call site?
And as far as I understand, arguments are evaluated once but in unspecified order.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, wait. I misread the example. I thought the duplicated use was caused by using __c twice in the implementation of vec_sel. But in fact, the issue is caused by using vf twice at the call site of vec_sel, once for the __a and once for the __b argument.

That is indeed a test case bug, it should probably just use distinct variables vf1 and vf2 instead.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@uweigand I tried to add new variables in couple tests and it is work, but I ran into problems:
I know nothing about what there tests is check so I'm not sure if I'm fix it correctly. And most important - places need to fixing over 1500 =_= Probably script required here? Or is there another way?

@shafik shafik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This need a release note as well as addressing the rest of the comments.

Comment thread clang/lib/Sema/SemaChecking.cpp Resolved
Comment thread clang/lib/Sema/SemaChecking.cpp Outdated
UK_Count = UK_ModAsSideEffect + 1
};

enum WarningKind { WK_UseAndMod, WK_ModAndMod, WK_Volatile_UseAndUse };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be documented with the same care as UsageKind above.

@AaronBallman AaronBallman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for working on this! You should also add a release note to clang/docs/ReleaseNotes.rst so users know about the improvement.

Comment thread clang/test/SemaCXX/warn-unsequenced.cpp Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd also like to see some additional tests like:

volatile int v1, v2;

x = v1 + v2; // Okay, accessing different values

volatile int *pv1 = v1, *pv2 = v1; // Pointing to same volatile object
x = *pv1 + *pv2; // unsequenced, but might be a FIXME if we're not tracking pointer ownership

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you planning to add the second test case?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SequenceChecker don't tracking pointer ownership and it is unlikely to happen, as far as I understood

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a test documenting the current behavior with a FIXME comment is reasonable. This seems like the exact kind of thing we'll someday replace with a CIR check and that likely will do better value tracking.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added.

Comment thread clang/test/SemaCXX/warn-unsequenced.cpp Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be diagnosed?

C2y 6.5.17.1p3: ... The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

This might be outside the scope of the PR, but it also applies to things like v = v; regardless of whether v is volatile or not.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still wondering about this as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand, why v=v needed warning, to be honest. "Computing the left operand value" is an address computation, dont read memory for this address, roughly speaking.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thinking is because "The evaluations of the operands are unsequenced." means there's an unsequenced access there, regardless of address computation or not.

Volatile accesses can do anything, including writing new values to that location. Consider a situation where reading the volatile value causes the system to change the value to zero after the read.

On such a system, the value computations being unsequenced could be an observable issue. A code example of this might be:

extern volatile int v;
extern int *func(int *ip, volatile int value);

int main() {
  int i;
  *func(&i, v) = v;
}

Let's say v starts out with value 12 and func() returns its first argument. If the value computation of the LHS happens before RHS, then the read of v will pass the value 12 to func() before resetting the value of v to zero, and then i will be 0 because of that reset. But if the value computation of the RHS happens before LHS, then func will be passed 0 and i will be 12.

That said, I think this might be more off in the weeds. I don't insist on a change here as part of this PR; this is probably better debated in a separate PR because it's pretty esoteric compared to the other changes in the PR which are more clearly helpful.

@Seraphimt Seraphimt Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code *func(&i, v) = v; must cause warning for C and C++ before C++17:
lhs unsequenced rhs => 2 unsequenced read of v.
But non warning for C++17:
rhs sequenced before lhs.
I check and it work correct.

v = v don't unsequenced because "updating the stored value of the left operand is sequenced after the value computations of the left and right" => read v sequenced before write v.

Comment thread clang/test/SemaCXX/warn-unsequenced.cpp Resolved
hubert-reinterpretcast pushed a commit that referenced this pull request Jul 16, 2026
… codegen tests (#199338)

When trying to add new Sema check in PR
#180955 some tests failed.
The following pattern is observed in these tests:
```
volatile x;
x = __builtinXXX(x, x, x);

```
For C and C++ standards order of evaluate funcall argument is
unsequence(or indeterminate sequence) and unsequence access for same
volatile variable is UB(because read volatile qualified variable is
side-effects).

As far as I undestand, unsequenced accesses is unwanted and new warning
is correct.
This PR try to fix it for tests:
```
\clang\test\CodeGen\PowerPC\builtins-ppc-fma.c
\clang\test\CodeGen\PowerPC\builtins-ppc-fpconstrained.c
```
Topics on discourse:
https://discourse.llvm.org/t/suspicious-use-volatile-qualified-variable-in-clang-codegen-tests/90837
Closed similar issue for SystemZ :
#186584
llvm-upstreamsync Bot pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Jul 16, 2026
…accesses in codegen tests (#199338)

When trying to add new Sema check in PR
llvm/llvm-project#180955 some tests failed.
The following pattern is observed in these tests:
```
volatile x;
x = __builtinXXX(x, x, x);

```
For C and C++ standards order of evaluate funcall argument is
unsequence(or indeterminate sequence) and unsequence access for same
volatile variable is UB(because read volatile qualified variable is
side-effects).

As far as I undestand, unsequenced accesses is unwanted and new warning
is correct.
This PR try to fix it for tests:
```
\clang\test\CodeGen\PowerPC\builtins-ppc-fma.c
\clang\test\CodeGen\PowerPC\builtins-ppc-fpconstrained.c
```
Topics on discourse:
https://discourse.llvm.org/t/suspicious-use-volatile-qualified-variable-in-clang-codegen-tests/90837
Closed similar issue for SystemZ :
llvm/llvm-project#186584
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Jul 17, 2026
…accesses in codegen tests (#199338)

When trying to add new Sema check in PR
llvm/llvm-project#180955 some tests failed.
The following pattern is observed in these tests:
```
volatile x;
x = __builtinXXX(x, x, x);

```
For C and C++ standards order of evaluate funcall argument is
unsequence(or indeterminate sequence) and unsequence access for same
volatile variable is UB(because read volatile qualified variable is
side-effects).

As far as I undestand, unsequenced accesses is unwanted and new warning
is correct.
This PR try to fix it for tests:
```
\clang\test\CodeGen\PowerPC\builtins-ppc-fma.c
\clang\test\CodeGen\PowerPC\builtins-ppc-fpconstrained.c
```
Topics on discourse:
https://discourse.llvm.org/t/suspicious-use-volatile-qualified-variable-in-clang-codegen-tests/90837
Closed similar issue for SystemZ :
llvm/llvm-project#186584
@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

🐧 Linux x64 Test Results

  • 95466 tests passed
  • 4353 tests skipped

✅ The build succeeded and all tests passed.

@zwuis zwuis changed the title Add check in SemaChecking for multiple unsequenced volatile accesses [clang] Add check in SemaChecking for multiple unsequenced volatile accesses Oct 30, 2026
@Seraphimt
Seraphimt requested a review from lntue as a code owner October 31, 2026 10:56
Comment thread clang/lib/Sema/SemaChecking.cpp Resolved

@AaronBallman AaronBallman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@Seraphimt
Seraphimt requested review from Fznamznon and zwuis November 13, 2026 05:24

@Fznamznon Fznamznon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for continuing working on this!

@AaronBallman
AaronBallman merged commit 9557154 into llvm:main Nov 13, 2026
47 checks passed
hebasto pushed a commit to hebasto/bitcoin-core-nightly that referenced this pull request Nov 14, 2026
In the 2026-11-14 nightly run both Clang-SNAPSHOT jobs failed in the
build step. The snapshot had moved from LLVM commit 382aa9e364b7 to
ab5a8378416f, which brought two changes that diagnose code in Bitcoin
Core's master branch:

 - llvm/llvm-project#180955 makes `-Wunsequenced` report two
   unsequenced reads of a volatile object, which occur 14 times in
   src/secp256k1/src/modinv32_impl.h and modinv64_impl.h;

 - llvm/llvm-project#237374 makes `-Wunused-private-field` check
   instantiated class templates, which flags the STL node helper
   structs in src/memusage.h.

With `CMAKE_COMPILE_WARNING_AS_ERROR=ON` both are errors, so the build
stopped at about 20% and no tests ran.

Downgrade the two diagnostics back to warnings with `APPEND_CFLAGS` and
`APPEND_CXXFLAGS`, so that the jobs build and test again while the
warnings stay visible on CDash. Every other warning remains an error.

The fixes are pending in bitcoin-core/secp256k1#1998 and
bitcoin/bitcoin#36869; each flag is to be dropped once its fix has
reached Bitcoin Core's master branch.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VSoBw5FaujuSeyXxkmHWRf
theStack added a commit to bitcoin-core/secp256k1 that referenced this pull request Nov 16, 2026
e7a34ba Avoid unsequenced accesses to volatile variables (Hennadii Stepanov)
709e39c refactor: Prefix volatile variable names with "v" (Hennadii Stepanov)

Pull request description:

  Since C11, if a side effect on a scalar object is unsequenced relative to another side effect on the same scalar object, the behavior is undefined (see https://en.cppreference.com/c/language/eval_order). Although this code targets C89, where the order of volatile reads is merely unspecified, this is exactly what happens with the volatile `cond_negate` in the master branch, because a read of such a variable is a side effect. Clang 24 [warns](llvm/llvm-project#180955) about it with `-Wunsequenced` regardless of the language standard:
  ```console
  $ cmake -B build -DCMAKE_C_COMPILER=clang-24
  $ cmake --build build
  [5/19] Building C object src/CMakeFiles/exhaustive_tests.dir/tests_exhaustive.c.o
  In file included from /home/hebasto/dev/secp256k1/secp256k1/src/tests_exhaustive.c:23:
  In file included from /home/hebasto/dev/secp256k1/secp256k1/src/secp256k1.c:27:
  In file included from /home/hebasto/dev/secp256k1/secp256k1/src/field_impl.h:14:
  In file included from /home/hebasto/dev/secp256k1/secp256k1/src/field_5x52_impl.h:13:
  /home/hebasto/dev/secp256k1/secp256k1/src/modinv64_impl.h:116:31: warning: unsequenced accesses to volatile qualified 'cond_negate' [-Wunsequenced]
    116 |     r0 = (r0 ^ cond_negate) - cond_negate;
        |                ~~~~~~~~~~~    ^
  /home/hebasto/dev/secp256k1/secp256k1/src/modinv64_impl.h:117:31: warning: unsequenced accesses to volatile qualified 'cond_negate' [-Wunsequenced]
    117 |     r1 = (r1 ^ cond_negate) - cond_negate;
        |                ~~~~~~~~~~~    ^
  /home/hebasto/dev/secp256k1/secp256k1/src/modinv64_impl.h:118:31: warning: unsequenced accesses to volatile qualified 'cond_negate' [-Wunsequenced]
    118 |     r2 = (r2 ^ cond_negate) - cond_negate;
        |                ~~~~~~~~~~~    ^
  /home/hebasto/dev/secp256k1/secp256k1/src/modinv64_impl.h:119:31: warning: unsequenced accesses to volatile qualified 'cond_negate' [-Wunsequenced]
    119 |     r3 = (r3 ^ cond_negate) - cond_negate;
        |                ~~~~~~~~~~~    ^
  /home/hebasto/dev/secp256k1/secp256k1/src/modinv64_impl.h:120:31: warning: unsequenced accesses to volatile qualified 'cond_negate' [-Wunsequenced]
    120 |     r4 = (r4 ^ cond_negate) - cond_negate;
        |                ~~~~~~~~~~~    ^
  5 warnings generated.
  <snip>
  ```

  Avoid such behavior by separating the access to a volatile variable, which still prevents compilers from generating branching, non-constant-time machine code, from the actual use of its value in expressions where the evaluation order is unspecified.

ACKs for top commit:
  real-or-random:
    utACK e7a34ba
  theStack:
    re-ACK e7a34ba

Tree-SHA512: eb047f0eab822322402024e883c154b7e4985cc6fe018ef347db39afdd3edf64f4885f28cffd0f2e7f975c646f662e82ffa2ac74f28bde90020cece8435abb6f
ePirat pushed a commit to videolan/vlc that referenced this pull request Nov 17, 2026
Previously, opencv built with a bunch of warnings treated as errors.

This caused the build to fail with the latest nightly Clang
since llvm/llvm-project#180955, which
caused the bundled old openexr half.cpp to produce warnings
treated as errors like this:

    contrib/build-i686/opencv4/3rdparty/openexr/Half/half.cpp:73:7: error: unsequenced accesses to volatile qualified 'f' [-Werror,-Wunsequenced]
       73 |         f *= f;                         // this will overflow before
          |           ~~ ^
    1 error generated.

There is little point in reporting this issue further upstream;
openexr itself has changed this code already in 2021 so this code
no longer uses volatile, so those warnings/errors wouldn't appear
any longer.

OpenCV 5.x has dropped the bundled openexr code as well.

Just apply this OpenCV patch (from upstream OpenCV commit
30ff9c6775f3449dcf015eb9c7da26be3e51191d, from OpenCV 3.4.18 and
4.4.6) to stop treating these warnings as errors.
dschuff added a commit to emscripten-core/emscripten that referenced this pull request Nov 18, 2026
Recent Clang (llvm/llvm-project#180955) extended -Wunsequenced to
diagnose multiple unsequenced accesses to volatile-qualified variables.

Backport the log1p fix from upstream llvm-project commit 5f47feeedda0
(preserving the 0x1p-24f constant for tn from this llvm-libc snapshot)
by computing tp and tn into non-volatile temporaries before comparing.
@aeubanks

Copy link
Copy Markdown
Contributor

FYI I'm putting this under a -Wunsequenced-volatile subgroup in #244073 so downstream users can clean up their codebases async

aeubanks added a commit that referenced this pull request Nov 19, 2026
…latile (#244073)

So it can be disabled separately while people clean up violations.

Initially implemented in #180955.

Assisted with Gemini
motokultivator added a commit to ROCm/ROCgdb that referenced this pull request Nov 24, 2026
Recent Clang versions warn with -Wunsequenced ("unsequenced accesses
to volatile qualified ...") when the same volatile variable is read
more than once in a single expression.  The warning comes from the new
check added in llvm/llvm-project#180955 ("[clang] Add check in
SemaChecking for multiple unsequenced volatile accesses").  The
testsuite treats the warning as a failure to prepare the test, so
gdb.rocm/alu-exceptions.exp ends up UNTESTED.

raise_denorm, raise_underflow and raise_inexact multiplied a volatile
variable by itself (x * x).  Use two separate volatile operands
initialized to the same value, as raise_float_div0 already does.  The
operation performed on the device is unchanged.

Co-Authored-By: Claude <[email protected]>
motokultivator added a commit to ROCm/ROCgdb that referenced this pull request Nov 24, 2026
Recent Clang versions warn with -Wunsequenced ("unsequenced accesses
to volatile qualified ...") when the same volatile variable is read
more than once in a single expression.  The warning comes from the new
check added in llvm/llvm-project#180955 ("[clang] Add check in
SemaChecking for multiple unsequenced volatile accesses").  Rewrite
the affected code so each volatile is read only once per expression,
without changing what is being tested.

target-float.c: the infinity check "dtop + dtop == dtop && dtop != 0.0"
read the volatile dtop several times in one expression.  Those
unsequenced accesses are undefined behavior, so this is a build fix
for compilers that diagnose them.  Read dtop once into a local variable
and use that in the check.  The value is still rounded to double by the
store to the volatile, so behavior is otherwise unchanged.

The testsuite treats the warning as a failure to prepare the test, so
the tests below end up UNTESTED without the following changes.

gdb.base/constvars.c (also used by gdb.base/volatile.exp): the
initializers of the volatile arrays were of the form {vox, vox}.  Read
the second element through the existing pointer to the variable
(e.g. {vox, *vapidity}).  Variable names, types and values are
unchanged.

gdb.opt/inline-break.c: "x = func7a (x) + func7b (x);" read the
volatile x twice in one expression.  Store the results of the two
calls in temporaries and add them afterwards (same for func8).  The
calls are still inlined into main.

Co-Authored-By: Claude <[email protected]>
motokultivator added a commit to ROCm/ROCgdb that referenced this pull request Nov 24, 2026
Recent Clang versions warn with -Wunsequenced ("unsequenced accesses
to volatile qualified ...") when the same volatile variable is read
more than once in a single expression.  The warning comes from the new
check added in llvm/llvm-project#180955 ("[clang] Add check in
SemaChecking for multiple unsequenced volatile accesses").  The
testsuite treats the warning as a failure to prepare the test, so
gdb.rocm/alu-exceptions.exp ends up UNTESTED.

raise_denorm, raise_underflow and raise_inexact multiplied a volatile
variable by itself (x * x).  Use two separate volatile operands
initialized to the same value, as raise_float_div0 already does.  The
operation performed on the device is unchanged.

Co-Authored-By: Claude <[email protected]>
motokultivator added a commit to ROCm/ROCgdb that referenced this pull request Nov 24, 2026
Recent Clang versions warn with -Wunsequenced ("unsequenced accesses
to volatile qualified ...") when the same volatile variable is read
more than once in a single expression.  The warning comes from the new
check added in llvm/llvm-project#180955 ("[clang] Add check in
SemaChecking for multiple unsequenced volatile accesses").  Rewrite
the affected code so each volatile is read only once per expression,
without changing what is being tested.

target-float.c: the infinity check "dtop + dtop == dtop && dtop != 0.0"
read the volatile dtop several times in one expression.  Those
unsequenced accesses are undefined behavior, so this is a build fix
for compilers that diagnose them.  Read dtop once into a local variable
and use that in the check.  The value is still rounded to double by the
store to the volatile, so behavior is otherwise unchanged.

The testsuite treats the warning as a failure to prepare the test, so
the tests below end up UNTESTED without the following changes.

gdb.base/constvars.c (also used by gdb.base/volatile.exp): the
initializers of the volatile arrays were of the form {vox, vox}.  Read
the second element through the existing pointer to the variable
(e.g. {vox, *vapidity}).  Variable names, types and values are
unchanged.

gdb.opt/inline-break.c: "x = func7a (x) + func7b (x);" read the
volatile x twice in one expression.  Store the results of the two
calls in temporaries and add them afterwards (same for func8).  The
calls are still inlined into main.

Co-Authored-By: Claude <[email protected]>
lumachad pushed a commit to ROCm/ROCgdb that referenced this pull request Nov 28, 2026
Recent Clang versions warn with -Wunsequenced ("unsequenced accesses
to volatile qualified ...") when the same volatile variable is read
more than once in a single expression.  The warning comes from the new
check added in llvm/llvm-project#180955 ("[clang] Add check in
SemaChecking for multiple unsequenced volatile accesses").  The
testsuite treats the warning as a failure to prepare the test, so
gdb.rocm/alu-exceptions.exp ends up UNTESTED.

raise_denorm, raise_underflow and raise_inexact multiplied a volatile
variable by itself (x * x).  Use two separate volatile operands
initialized to the same value, as raise_float_div0 already does.  The
operation performed on the device is unchanged.

Co-Authored-By: Claude <[email protected]>
(cherry picked from commit 4472d71)
lumachad pushed a commit to ROCm/ROCgdb that referenced this pull request Nov 28, 2026
Recent Clang versions warn with -Wunsequenced ("unsequenced accesses
to volatile qualified ...") when the same volatile variable is read
more than once in a single expression.  The warning comes from the new
check added in llvm/llvm-project#180955 ("[clang] Add check in
SemaChecking for multiple unsequenced volatile accesses").  Rewrite
the affected code so each volatile is read only once per expression,
without changing what is being tested.

target-float.c: the infinity check "dtop + dtop == dtop && dtop != 0.0"
read the volatile dtop several times in one expression.  Those
unsequenced accesses are undefined behavior, so this is a build fix
for compilers that diagnose them.  Read dtop once into a local variable
and use that in the check.  The value is still rounded to double by the
store to the volatile, so behavior is otherwise unchanged.

The testsuite treats the warning as a failure to prepare the test, so
the tests below end up UNTESTED without the following changes.

gdb.base/constvars.c (also used by gdb.base/volatile.exp): the
initializers of the volatile arrays were of the form {vox, vox}.  Read
the second element through the existing pointer to the variable
(e.g. {vox, *vapidity}).  Variable names, types and values are
unchanged.

gdb.opt/inline-break.c: "x = func7a (x) + func7b (x);" read the
volatile x twice in one expression.  Store the results of the two
calls in temporaries and add them afterwards (same for func8).  The
calls are still inlined into main.

Co-Authored-By: Claude <[email protected]>
(cherry picked from commit 61fee7a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend:PowerPC backend:SystemZ clang:frontend Language frontend issues, e.g. anything involving "Sema" clang Clang issues not falling into any other category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants