[clang] [Clang][Sema] Refactor checks on for/while loops (NFC) (PR #226101)

2026-10-02 Thread via cfe-commits

https://github.com/Expertcoderz updated 
https://github.com/llvm/llvm-project/pull/226101

>From 0f54aada731474f4ca06dad02a379ad255e9bbae Mon Sep 17 00:00:00 2001
From: Expertcoderz 
Date: Thu, 24 Sep 2026 03:44:08 +
Subject: [PATCH 1/2] [Clang][Sema] Refactor checks on for/while loops (NFC)

CommaVisitor and empty loop handling have been moved into
a new `CheckConditionalLoop()` function to reduce duplication.

Also added clarifying comments to explain the need for
`setHasEmptyLoopBodies()` usage in the specific cases
of `for`/`while` loops.
---
 clang/lib/Sema/SemaStmt.cpp | 51 +
 1 file changed, 35 insertions(+), 16 deletions(-)

diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 74fe253efa1374..ddaa8e11e80b4d 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -462,7 +462,12 @@ StmtResult Sema::ActOnCompoundStmt(SourceLocation L, 
SourceLocation R,
   }
 
   // Check for suspicious empty body (null statement) in `for' and `while'
-  // statements.  Don't do anything for template instantiations, this just adds
+  // statements, for example:
+  //
+  //   for (;;); <- warning: for loop has empty body
+  // foo();
+  //
+  // Don't do anything for template instantiations, this just adds
   // noise.
   if (NumElts != 0 && !CurrentInstantiationScope &&
   getCurCompoundScope().HasEmptyLoopBodies) {
@@ -1814,18 +1819,36 @@ Sema::DiagnoseAssignmentEnum(QualType DstType, QualType 
SrcType,
   << DstType.getUnqualifiedType();
 }
 
+// Checks for issues that are common to `for`/`while` statements.
+static void CheckConditionalLoop(Sema &S, Expr *CondExpr, Stmt *Body) {
+  // Check for comma operator misuse.
+  if (CondExpr &&
+  !S.Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
+CommaVisitor(S).Visit(CondExpr);
+
+  if (isa(Body)) {
+// Tell Sema::ActOnCompoundStmt to perform a check on
+// this suspicious empty `for`/`while` loop when
+// processing the compound statement that contains this loop.
+//
+// The actual check cannot be done here directly as it may
+// depend on other statements following the `for`/`while`
+// loop, in the outer enclosing CompoundStmt; see the
+// comment in Sema::ActOnCompoundStmt for an example
+// of when this happens.
+//
+// This does not apply for `if` statements and range-`for`
+// loops which call DiagnoseEmptyStmtBody() directly.
+S.getCurCompoundScope().setHasEmptyLoopBodies();
+  }
+}
+
 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
 SourceLocation LParenLoc, ConditionResult Cond,
 SourceLocation RParenLoc, Stmt *Body) {
   if (Cond.isInvalid())
 return StmtError();
 
-  auto CondVal = Cond.get();
-
-  if (CondVal.second &&
-  !Diags.isIgnored(diag::warn_comma_operator, 
CondVal.second->getExprLoc()))
-CommaVisitor(*this).Visit(CondVal.second);
-
   // OpenACC3.3 2.14.4:
   // The update directive is executable.  It must not appear in place of the
   // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
@@ -1835,8 +1858,9 @@ StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
 Body = new (Context) NullStmt(Body->getBeginLoc());
   }
 
-  if (isa(Body))
-getCurCompoundScope().setHasEmptyLoopBodies();
+  auto CondVal = Cond.get();
+
+  CheckConditionalLoop(*this, CondVal.second, Body);
 
   return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
WhileLoc, LParenLoc, RParenLoc);
@@ -2320,14 +2344,9 @@ StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, 
SourceLocation LParenLoc,
  Body);
   CheckForRedundantIteration(*this, third.get(), Body);
 
-  if (Second.get().second &&
-  !Diags.isIgnored(diag::warn_comma_operator,
-   Second.get().second->getExprLoc()))
-CommaVisitor(*this).Visit(Second.get().second);
+  CheckConditionalLoop(*this, Second.get().second, Body);
 
-  Expr *Third  = third.release().getAs();
-  if (isa(Body))
-getCurCompoundScope().setHasEmptyLoopBodies();
+  Expr *Third = third.release().getAs();
 
   return new (Context)
   ForStmt(Context, First, Second.get().second, Second.get().first, Third,

>From 6edbeb7474079059ec69bbdebd8ba939a16fce84 Mon Sep 17 00:00:00 2001
From: Expertcoderz 
Date: Sat, 3 Oct 2026 02:24:29 +
Subject: [PATCH 2/2] Rename CheckConditonalLoop() to CheckLoopBody()

---
 clang/lib/Sema/SemaStmt.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index ddaa8e11e80b4d..72737d9d3aab46 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -1820,7 +1820,7 @@ Sema::DiagnoseAssignmentEnum(QualType DstType, QualType 
SrcType,
 }
 
 // Checks for issues that are common to `for`/`while` statements.
-static void 

[clang] [Clang][Sema] Refactor checks on for/while loops (NFC) (PR #226101)

2026-10-02 Thread Ambrose Leeb via cfe-commits

Sirraide wrote:

So to clarify, rename the function to `CheckLoopBody()` if possible and then 
this lgtm

https://github.com/llvm/llvm-project/pull/226101
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Refactor checks on for/while loops (NFC) (PR #226101)

2026-09-24 Thread via cfe-commits

https://github.com/Expertcoderz created 
https://github.com/llvm/llvm-project/pull/226101

This is an NFC refactor of `clang/lib/Sema/SemaStmt.cpp` based on @Sirraide's 
suggestion in 
https://github.com/llvm/llvm-project/pull/225748#discussion_r4083103871.

- For both `Sema::ActOnForStmt` and `Sema::ActOnWhileStmt`, `CommaVisitor` 
visiting and empty loop handling have been factored out into a new 
`CheckConditionalLoop()` function to reduce duplication.

- Also added clarifying comments to explain the need for 
`setHasEmptyLoopBodies()` usage in the specific cases of `for`/`while` loops.

This PR is intended to be merged prior to #225748, which will benefit from this 
refactor by having the redundant-defer checks for both `for`/`while` loops in 
the same `CheckConditionalLoop()` function instead of duplicating them.

>From 0f54aada731474f4ca06dad02a379ad255e9bbae Mon Sep 17 00:00:00 2001
From: Expertcoderz 
Date: Thu, 24 Sep 2026 03:44:08 +
Subject: [PATCH] [Clang][Sema] Refactor checks on for/while loops (NFC)

CommaVisitor and empty loop handling have been moved into
a new `CheckConditionalLoop()` function to reduce duplication.

Also added clarifying comments to explain the need for
`setHasEmptyLoopBodies()` usage in the specific cases
of `for`/`while` loops.
---
 clang/lib/Sema/SemaStmt.cpp | 51 +
 1 file changed, 35 insertions(+), 16 deletions(-)

diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 74fe253efa137..ddaa8e11e80b4 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -462,7 +462,12 @@ StmtResult Sema::ActOnCompoundStmt(SourceLocation L, 
SourceLocation R,
   }
 
   // Check for suspicious empty body (null statement) in `for' and `while'
-  // statements.  Don't do anything for template instantiations, this just adds
+  // statements, for example:
+  //
+  //   for (;;); <- warning: for loop has empty body
+  // foo();
+  //
+  // Don't do anything for template instantiations, this just adds
   // noise.
   if (NumElts != 0 && !CurrentInstantiationScope &&
   getCurCompoundScope().HasEmptyLoopBodies) {
@@ -1814,18 +1819,36 @@ Sema::DiagnoseAssignmentEnum(QualType DstType, QualType 
SrcType,
   << DstType.getUnqualifiedType();
 }
 
+// Checks for issues that are common to `for`/`while` statements.
+static void CheckConditionalLoop(Sema &S, Expr *CondExpr, Stmt *Body) {
+  // Check for comma operator misuse.
+  if (CondExpr &&
+  !S.Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
+CommaVisitor(S).Visit(CondExpr);
+
+  if (isa(Body)) {
+// Tell Sema::ActOnCompoundStmt to perform a check on
+// this suspicious empty `for`/`while` loop when
+// processing the compound statement that contains this loop.
+//
+// The actual check cannot be done here directly as it may
+// depend on other statements following the `for`/`while`
+// loop, in the outer enclosing CompoundStmt; see the
+// comment in Sema::ActOnCompoundStmt for an example
+// of when this happens.
+//
+// This does not apply for `if` statements and range-`for`
+// loops which call DiagnoseEmptyStmtBody() directly.
+S.getCurCompoundScope().setHasEmptyLoopBodies();
+  }
+}
+
 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
 SourceLocation LParenLoc, ConditionResult Cond,
 SourceLocation RParenLoc, Stmt *Body) {
   if (Cond.isInvalid())
 return StmtError();
 
-  auto CondVal = Cond.get();
-
-  if (CondVal.second &&
-  !Diags.isIgnored(diag::warn_comma_operator, 
CondVal.second->getExprLoc()))
-CommaVisitor(*this).Visit(CondVal.second);
-
   // OpenACC3.3 2.14.4:
   // The update directive is executable.  It must not appear in place of the
   // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
@@ -1835,8 +1858,9 @@ StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
 Body = new (Context) NullStmt(Body->getBeginLoc());
   }
 
-  if (isa(Body))
-getCurCompoundScope().setHasEmptyLoopBodies();
+  auto CondVal = Cond.get();
+
+  CheckConditionalLoop(*this, CondVal.second, Body);
 
   return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
WhileLoc, LParenLoc, RParenLoc);
@@ -2320,14 +2344,9 @@ StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, 
SourceLocation LParenLoc,
  Body);
   CheckForRedundantIteration(*this, third.get(), Body);
 
-  if (Second.get().second &&
-  !Diags.isIgnored(diag::warn_comma_operator,
-   Second.get().second->getExprLoc()))
-CommaVisitor(*this).Visit(Second.get().second);
+  CheckConditionalLoop(*this, Second.get().second, Body);
 
-  Expr *Third  = third.release().getAs();
-  if (isa(Body))
-getCurCompoundScope().setHasEmptyLoopBodies();
+  Expr *Third = third.release().getAs();
 
   return new (Context)
 

[clang] [Clang][Sema] Refactor checks on for/while loops (NFC) (PR #226101)

2026-09-24 Thread via cfe-commits

Expertcoderz wrote:

@Sirraide Greetings, I'd like to address some of the specific concerns you've 
raised in 
https://github.com/llvm/llvm-project/pull/225748#discussion_r4083103871 to make 
sure we have everything sorted out.

> The `CommaVisitor` check is repeated in `ActOnForStmt()` and 
> `ActOnWhileStmt()` and I wouldn’t be surprised if it was also in the 
> for-range code.

Fortunately, the definition of `Sema::ActOnCXXForRangeStmt` doesn't seem to 
reference `CommaVisitor` so there should be no duplication in that regard.

As for `ActOnForStmt()` and `ActOnWhileStmt()`, those have been fixed in this 
PR by moving the checks into a shared `CheckConditionalLoop()` routine.

---

> This new check you’re adding is likewise repeated in those places.

That's right; it is an issue that's solved by this refactor as defer checks 
will no longer need to be repeated across the `ActOnForStmt()` and 
`ActOnWhileStmt()`, at the very least.

---

> `DiagnoseEmptyStmtBody()` is done here directly, but _for some reason_, we 
> don’t do that for loops and instead set `HasEmptyLoopBody` and then diagnose 
> loops in `ActOnCompoundStatement()`

I just had a deeper look at the code to find out the reason. It turns out 
(assuming my understanding is correct), that `for`/`while` loops require 
special handling for empty body diagnostics:

```c
for (;;); // OK; no diagnostic
foo();

for (;;); // warning: for loop has empty body
  foo(); // <- note the indentation
```

Whereas the same does not apply for conditionals:

```c
if (true); // warning: if statement has empty body
foo();

if (true); // same warning
  foo();
```

In other words, the diagnostic depends on statements adjacent to the 
`for`/`while` statement, in the enclosing `CompoundStmt` block, hence the way 
it is handled. I've added some comments in this PR to clarify this situation 
upfront.

Thanks for giving me an opportunity to refactor.

https://github.com/llvm/llvm-project/pull/226101
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Refactor checks on for/while loops (NFC) (PR #226101)

2026-09-24 Thread via cfe-commits

llvmorg-github-actions[bot] wrote:




@llvm/pr-subscribers-clang

Author: Expertcoderz (Expertcoderz)


Changes

This is an NFC refactor of `clang/lib/Sema/SemaStmt.cpp` based on @Sirraide's suggestion in 
https://github.com/llvm/llvm-project/pull/225748#discussion_r4083103871.

- For both `Sema::ActOnForStmt` and `Sema::ActOnWhileStmt`, `CommaVisitor` 
visiting and empty loop handling have been factored out into a new 
`CheckConditionalLoop()` function to reduce duplication.

- Also added clarifying comments to explain the need for 
`setHasEmptyLoopBodies()` usage in the specific cases of `for`/`while` loops.

This PR is intended to be merged prior to #225748, which will benefit 
from this refactor by having the redundant-defer checks for both `for`/`while` 
loops in the same `CheckConditionalLoop()` function instead of duplicating them.

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaStmt.cpp (+35-16) 


``diff
The server is unavailable at this time. Please wait a few minutes before you 
try again.
``




https://github.com/llvm/llvm-project/pull/226101
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Refactor checks on for/while loops (NFC) (PR #226101)

2026-09-24 Thread via cfe-commits

github-actions[bot] wrote:



Hello @Expertcoderz :wave:

Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is 
your first PR, here are a few useful links covering our main contribution 
policies and review practices.

* All contributions to LLVM must follow our [LLVM AI Tool Use 
Policy](https://llvm.org/docs/AIToolPolicy.html). In particular, if you used AI 
while working on this PR, remember to add a note to the PR description.
* The [LLVM Code-Review Policy and 
Practices](https://llvm.org/docs/CodeReview.html) document contains practical 
information about the PR process, including how patches are reviewed and 
accepted, and who can review a PR.
* Our [LLVM Developer Policy](https://llvm.org/docs/DeveloperPolicy.html) 
describes our expectations for code quality, commit summaries and contains 
notes on our CI system.

Please reply to this message to confirm that you have read these policies, 
especially the LLVM AI Tool Use Policy, and that any AI tool usage has been 
noted in the PR description.

---

### Frequently asked questions

**How do I add reviewers?**

This PR will be automatically labeled, and the relevant teams will be notified. 
For some parts of the project, reviewers may also be added automatically.

You can also add reviewers manually using the **Reviewers** section on this 
page. If you cannot use that section, it is probably because you do not have 
write permissions for the repository. In that case, you can request a review by 
tagging reviewers in a comment using `@` followed by their GitHub username.

**What if there are no comments?**

If you have not received any comments on your PR after a week, you can request 
a review by pinging the PR with a comment such as “Ping”. The common courtesy 
ping rate is once a week. Please remember that you are asking for volunteer 
time from other developers.

**Are any special GitHub settings required to contribute to LLVM?**

We only require contributors to have a public email address associated with 
their GitHub commits, see this 
[section](https://llvm.org/docs/DeveloperPolicy.html#email-addresses) of LLVM 
Developer Policy for details.

---

If you have questions, feel free to leave a comment on this PR, or ask on [LLVM 
Discord](https://discord.com/invite/xS7Z362) or [LLVM 
Discourse](https://discourse.llvm.org/).

Thank you,
The LLVM Community

https://github.com/llvm/llvm-project/pull/226101
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits