Skip to content

[clang-tidy] fix bugprone-narrowing-conversions false positive for conditional expression #139474

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 3, 2025

Conversation

AndreyG
Copy link
Contributor

@AndreyG AndreyG commented May 11, 2025

Let's consider the following code from the issue #139467:

void test(int cond, char c) {
    char ret = cond > 0 ? ':' : c;
}

Initializer of ret looks the following:

-ImplicitCastExpr 'char' <IntegralCast>
 `-ConditionalOperator 'int'
   |-BinaryOperator 'int' '>'
   | |-ImplicitCastExpr 'int' <LValueToRValue>
   | | `-DeclRefExpr 'int' lvalue ParmVar 'cond' 'int'
   | `-IntegerLiteral 'int' 0
   |-CharacterLiteral 'int' 58
   `-ImplicitCastExpr 'int' <IntegralCast>
     `-ImplicitCastExpr 'char' <LValueToRValue>
       `-DeclRefExpr 'char' lvalue ParmVar 'c' 'char'

So it could be seen that RHS of the conditional operator is DeclRefExpr 'c' which is casted to int and then the whole conditional expression is casted to 'char'. But this last conversion is not narrowing, because RHS was char initially. We should just remove the cast from char to int before the narrowing conversion check.

Fixes #139467

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented May 11, 2025

@llvm/pr-subscribers-clang-tidy

@llvm/pr-subscribers-clang-tools-extra

Author: Andrey (AndreyG)

Changes

Let's consider the following code from the issue #139467:

void test(int cond, char c) {
    char ret = cond &gt; 0 ? ':' : c;
}

Initializer of ret looks the following:

-ImplicitCastExpr 'char' &lt;IntegralCast&gt;
 `-ConditionalOperator 'int'
   |-BinaryOperator 'int' '&gt;'
   | |-ImplicitCastExpr 'int' &lt;LValueToRValue&gt;
   | | `-DeclRefExpr 'int' lvalue ParmVar 'cond' 'int'
   | `-IntegerLiteral 'int' 0
   |-CharacterLiteral 'int' 58
   `-ImplicitCastExpr 'int' &lt;IntegralCast&gt;
     `-ImplicitCastExpr 'char' &lt;LValueToRValue&gt;
       `-DeclRefExpr 'char' lvalue ParmVar 'c' 'char'

So it could be seen that RHS of the conditional operator is DeclRefExpr 'c' which is casted to int and then the whole conditional expression is casted to 'char'. But this last conversion is not narrowing, because RHS was char initially. We should just remove the cast from char to int before the narrowing conversion check.


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

3 Files Affected:

  • (modified) clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp (+12-4)
  • (modified) clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.h (+2)
  • (added) clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c (+6)
diff --git a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp
index bafcd402ca851..9e53bfe83e03e 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp
@@ -554,15 +554,23 @@ bool NarrowingConversionsCheck::handleConditionalOperator(
     // We have an expression like so: `output = cond ? lhs : rhs`
     // From the point of view of narrowing conversion we treat it as two
     // expressions `output = lhs` and `output = rhs`.
-    handleBinaryOperator(Context, CO->getLHS()->getExprLoc(), Lhs,
-                         *CO->getLHS());
-    handleBinaryOperator(Context, CO->getRHS()->getExprLoc(), Lhs,
-                         *CO->getRHS());
+    handleConditionalOperatorArgument(Context, Lhs, CO->getLHS());
+    handleConditionalOperatorArgument(Context, Lhs, CO->getRHS());
     return true;
   }
   return false;
 }
 
+void NarrowingConversionsCheck::handleConditionalOperatorArgument(
+    const ASTContext &Context, const Expr &Lhs, const Expr *Arg) {
+  if (const auto *ICE = llvm::dyn_cast<ImplicitCastExpr>(Arg)) {
+    if (!Arg->getIntegerConstantExpr(Context)) {
+      Arg = ICE->getSubExpr();
+    }
+  }
+  handleBinaryOperator(Context, Arg->getExprLoc(), Lhs, *Arg);
+}
+
 void NarrowingConversionsCheck::handleImplicitCast(
     const ASTContext &Context, const ImplicitCastExpr &Cast) {
   if (Cast.getExprLoc().isMacroID())
diff --git a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.h b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.h
index 20403f920b925..ebddbc2869675 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.h
@@ -85,6 +85,8 @@ class NarrowingConversionsCheck : public ClangTidyCheck {
   bool handleConditionalOperator(const ASTContext &Context, const Expr &Lhs,
                                  const Expr &Rhs);
 
+  void handleConditionalOperatorArgument(const ASTContext &Context, const Expr &Lhs,
+                                         const Expr *Arg);
   void handleImplicitCast(const ASTContext &Context,
                           const ImplicitCastExpr &Cast);
 
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c b/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c
new file mode 100644
index 0000000000000..754d6425b07cd
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy %s bugprone-narrowing-conversions %t -- --
+
+char test(int cond, char c) {
+	char ret = cond > 0 ? ':' : c;
+	return ret;
+}

@EugeneZelenko
Copy link
Contributor

Please mention changes in Release Notes.

Comment on lines 566 to 569
if (const auto *ICE = llvm::dyn_cast<ImplicitCastExpr>(Arg)) {
if (!Arg->getIntegerConstantExpr(Context)) {
Arg = ICE->getSubExpr();
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

As per LLVM coding-style, there shouldn't be any braces for single-stmt ifs.

if (const auto *ICE = llvm::dyn_cast<ImplicitCastExpr>(Arg))
    if (!Arg->getIntegerConstantExpr(Context))
      Arg = ICE->getSubExpr();

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Copy link
Contributor

Choose a reason for hiding this comment

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

this was not fixed

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sorry, I've lost the change during rebase. Fixed this again (f350b58).

@AndreyG
Copy link
Contributor Author

AndreyG commented May 13, 2025

@5chmidti 5chmidti self-requested a review June 21, 2025 11:46
@5chmidti 5chmidti changed the title Fix the issue #139467 ([clang-tidy] false positive narrowing conversion) [clang-tidy] fix bugprone-narrowing-conversions false positive for conditional expression Jul 12, 2025
Copy link

github-actions bot commented Jul 14, 2025

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

Copy link
Contributor

@5chmidti 5chmidti left a comment

Choose a reason for hiding this comment

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

Except for these minor open issues, this looks good, thanks.

Comment on lines 566 to 569
if (const auto *ICE = llvm::dyn_cast<ImplicitCastExpr>(Arg)) {
if (!Arg->getIntegerConstantExpr(Context)) {
Arg = ICE->getSubExpr();
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

this was not fixed

Copy link
Contributor

@vbvictor vbvictor left a comment

Choose a reason for hiding this comment

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

LGTM, please rebase on latest main, ReleaseNotes were cleared after 21th release. After that, could be merged.

Let's consider the following code from the issue llvm#139467:

void test(int cond, char c) {
    char ret = cond > 0 ? ':' : c;
}

Initializer of 'ret' looks the following:

-ImplicitCastExpr 'char' <IntegralCast>
 `-ConditionalOperator 'int'
   |-BinaryOperator 'int' '>'
   | |-ImplicitCastExpr 'int' <LValueToRValue>
   | | `-DeclRefExpr 'int' lvalue ParmVar 'cond' 'int'
   | `-IntegerLiteral 'int' 0
   |-CharacterLiteral 'int' 58
   `-ImplicitCastExpr 'int' <IntegralCast>
     `-ImplicitCastExpr 'char' <LValueToRValue>
       `-DeclRefExpr 'char' lvalue ParmVar 'c' 'char'

So it could be seen that 'RHS' of the conditional operator is
DeclRefExpr 'c' which is casted to 'int' and then the whole conditional expression is casted to 'char'.
But this last conversion is not narrowing, because 'RHS' was 'char' _initially_.
We should just remove the cast from 'char' to 'int' before the narrowing conversion check.
@vbvictor vbvictor merged commit c3902e4 into llvm:main Aug 3, 2025
10 checks passed
Copy link

github-actions bot commented Aug 3, 2025

@AndreyG Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@llvm-ci
Copy link
Collaborator

llvm-ci commented Aug 3, 2025

LLVM Buildbot has detected a new failure on builder clang-aarch64-quick running on linaro-clang-aarch64-quick while building clang-tools-extra at step 5 "ninja check 1".

Full details are available at: https://lab.llvm.org/buildbot/#/builders/65/builds/20669

Here is the relevant piece of the build log for the reference
Step 5 (ninja check 1) failure: stage 1 checked (failure)
******************** TEST 'Clang Tools :: clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.cpp' FAILED ********************
Exit Code: 1

Command Output (stdout):
--
Running ['clang-tidy', '/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.cpp.tmp.cpp', '-fix', '--checks=-*,bugprone-narrowing-conversions', '--config={}', '--', '-std=c++11', '-nostdinc++']...
------------------------ clang-tidy output -----------------------

------------------------------------------------------------------
------------------------------ Fixes -----------------------------

------------------------------------------------------------------
FileCheck -input-file=/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.cpp.tmp.cpp.msg /home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.cpp -check-prefixes=CHECK-MESSAGES -implicit-check-not={{warning|error}}: failed:
FileCheck error: '/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.cpp.tmp.cpp.msg' is empty.
FileCheck command line:  FileCheck -input-file=/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.cpp.tmp.cpp.msg /home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.cpp -check-prefixes=CHECK-MESSAGES -implicit-check-not={{warning|error}}:


--
Command Output (stderr):
--
/usr/bin/python3.10 /home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py /home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.cpp bugprone-narrowing-conversions /home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.cpp.tmp -- -- # RUN: at line 1
+ /usr/bin/python3.10 /home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py /home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.cpp bugprone-narrowing-conversions /home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.cpp.tmp -- --
Traceback (most recent call last):
  File "/home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 399, in <module>
    main()
  File "/home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 395, in main
    CheckRunner(args, extra_args).run()
  File "/home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 306, in run
    self.check_messages(clang_tidy_output)
  File "/home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 267, in check_messages
    try_run(
  File "/home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 62, in try_run
    process_output = subprocess.check_output(args, stderr=subprocess.STDOUT).decode(
  File "/usr/lib/python3.10/subprocess.py", line 421, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.10/subprocess.py", line 526, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['FileCheck', '-input-file=/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.cpp.tmp.cpp.msg', '/home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.cpp', '-check-prefixes=CHECK-MESSAGES', '-implicit-check-not={{warning|error}}:']' returned non-zero exit status 2.

--

********************


@llvm-ci
Copy link
Collaborator

llvm-ci commented Aug 3, 2025

LLVM Buildbot has detected a new failure on builder clang-armv8-quick running on linaro-clang-armv8-quick while building clang-tools-extra at step 5 "ninja check 1".

Full details are available at: https://lab.llvm.org/buildbot/#/builders/154/builds/19723

Here is the relevant piece of the build log for the reference
Step 5 (ninja check 1) failure: stage 1 checked (failure)
******************** TEST 'Clang Tools :: clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c' FAILED ********************
Exit Code: 1

Command Output (stdout):
--
Running ['clang-tidy', '/home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.c.tmp.c', '-fix', '--checks=-*,bugprone-narrowing-conversions', '--config={}', '--', '-nostdinc++']...
------------------------ clang-tidy output -----------------------

------------------------------------------------------------------
------------------------------ Fixes -----------------------------

------------------------------------------------------------------
FileCheck -input-file=/home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.c.tmp.c.msg /home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c -check-prefixes=CHECK-MESSAGES -implicit-check-not={{warning|error}}: failed:
FileCheck error: '/home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.c.tmp.c.msg' is empty.
FileCheck command line:  FileCheck -input-file=/home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.c.tmp.c.msg /home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c -check-prefixes=CHECK-MESSAGES -implicit-check-not={{warning|error}}:


--
Command Output (stderr):
--
/usr/bin/python3.10 /home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py /home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c bugprone-narrowing-conversions /home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.c.tmp -- -- # RUN: at line 1
+ /usr/bin/python3.10 /home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py /home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c bugprone-narrowing-conversions /home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.c.tmp -- --
Traceback (most recent call last):
  File "/home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 399, in <module>
    main()
  File "/home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 395, in main
    CheckRunner(args, extra_args).run()
  File "/home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 306, in run
    self.check_messages(clang_tidy_output)
  File "/home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 267, in check_messages
    try_run(
  File "/home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/../test/clang-tidy/check_clang_tidy.py", line 62, in try_run
    process_output = subprocess.check_output(args, stderr=subprocess.STDOUT).decode(
  File "/usr/lib/python3.10/subprocess.py", line 421, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.10/subprocess.py", line 526, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['FileCheck', '-input-file=/home/tcwg-buildbot/worker/clang-armv8-quick/stage1/tools/clang/tools/extra/test/clang-tidy/checkers/bugprone/Output/narrowing-conversions-conditional-expressions.c.tmp.c.msg', '/home/tcwg-buildbot/worker/clang-armv8-quick/llvm/clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions-conditional-expressions.c', '-check-prefixes=CHECK-MESSAGES', '-implicit-check-not={{warning|error}}:']' returned non-zero exit status 2.

--

********************


@vbvictor
Copy link
Contributor

vbvictor commented Aug 3, 2025

It seems we are having issues on arm platforms, I will revert this patch.

vbvictor added a commit that referenced this pull request Aug 3, 2025
…ive for conditional expression" (#151859)

Reverts #139474 due to lit test failures on `arm`
platforms.
@vbvictor
Copy link
Contributor

vbvictor commented Aug 3, 2025

Please, investigate this issue and when re-applying the reverted patch, commit message should be updated to indicate the problem that was addressed and how it was addressed.

https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy

llvm-sync bot pushed a commit to arm/arm-toolchain that referenced this pull request Aug 3, 2025
…false positive for conditional expression" (#151859)

Reverts llvm/llvm-project#139474 due to lit test failures on `arm`
platforms.
AndreyG added a commit to AndreyG/llvm-project that referenced this pull request Aug 3, 2025
…conditional expression (llvm#139474)

Let's consider the following code from the issue llvm#139467:
```c
void test(int cond, char c) {
    char ret = cond > 0 ? ':' : c;
}
```
Initializer of `ret` looks the following:
```
-ImplicitCastExpr 'char' <IntegralCast>
 `-ConditionalOperator 'int'
   |-BinaryOperator 'int' '>'
   | |-ImplicitCastExpr 'int' <LValueToRValue>
   | | `-DeclRefExpr 'int' lvalue ParmVar 'cond' 'int'
   | `-IntegerLiteral 'int' 0
   |-CharacterLiteral 'int' 58
   `-ImplicitCastExpr 'int' <IntegralCast>
     `-ImplicitCastExpr 'char' <LValueToRValue>
       `-DeclRefExpr 'char' lvalue ParmVar 'c' 'char'
```
So it could be seen that `RHS` of the conditional operator is
`DeclRefExpr 'c'` which is casted to `int` and then the whole
conditional expression is casted to 'char'. But this last conversion is
not narrowing, because `RHS` was `char` _initially_. We should just
remove the cast from `char` to `int` before the narrowing conversion
check.

Fixes llvm#139467

The added tests contains the implementation-defined warning about
'int' to 'char' conversion, which is not applicable to all platforms.
And so the target is explictly set to 'x86_64' (the line 'RUN: -- -target x86_64-unknown-linux').
@AndreyG
Copy link
Contributor Author

AndreyG commented Aug 3, 2025

@vbvictor I've found out that unlike other narrowing-conversion tests, I didn't set explicitly target for the test run.
I've fixed it and created another PR #151874. Please, take a look and sorry for the inconvenience.

AndreyG added a commit to AndreyG/llvm-project that referenced this pull request Aug 3, 2025
…conditional expression (llvm#139474)

Let's consider the following code from the issue llvm#139467:
```c
void test(int cond, char c) {
    char ret = cond > 0 ? ':' : c;
}
```
Initializer of `ret` looks the following:
```
-ImplicitCastExpr 'char' <IntegralCast>
 `-ConditionalOperator 'int'
   |-BinaryOperator 'int' '>'
   | |-ImplicitCastExpr 'int' <LValueToRValue>
   | | `-DeclRefExpr 'int' lvalue ParmVar 'cond' 'int'
   | `-IntegerLiteral 'int' 0
   |-CharacterLiteral 'int' 58
   `-ImplicitCastExpr 'int' <IntegralCast>
     `-ImplicitCastExpr 'char' <LValueToRValue>
       `-DeclRefExpr 'char' lvalue ParmVar 'c' 'char'
```
So it could be seen that `RHS` of the conditional operator is
`DeclRefExpr 'c'` which is casted to `int` and then the whole
conditional expression is casted to 'char'. But this last conversion is
not narrowing, because `RHS` was `char` _initially_. We should just
remove the cast from `char` to `int` before the narrowing conversion
check.

Fixes llvm#139467

The added tests contains the implementation-defined warning about
'int' to 'char' conversion, which is not applicable to all platforms.
And so the target is explictly set to 'x86_64' (the line 'RUN: -- -target x86_64-unknown-linux').
AndreyG added a commit to AndreyG/llvm-project that referenced this pull request Aug 3, 2025
…conditional expression (llvm#139474)

Let's consider the following code from the issue llvm#139467:
```c
void test(int cond, char c) {
    char ret = cond > 0 ? ':' : c;
}
```
Initializer of `ret` looks the following:
```
-ImplicitCastExpr 'char' <IntegralCast>
 `-ConditionalOperator 'int'
   |-BinaryOperator 'int' '>'
   | |-ImplicitCastExpr 'int' <LValueToRValue>
   | | `-DeclRefExpr 'int' lvalue ParmVar 'cond' 'int'
   | `-IntegerLiteral 'int' 0
   |-CharacterLiteral 'int' 58
   `-ImplicitCastExpr 'int' <IntegralCast>
     `-ImplicitCastExpr 'char' <LValueToRValue>
       `-DeclRefExpr 'char' lvalue ParmVar 'c' 'char'
```
So it could be seen that `RHS` of the conditional operator is
`DeclRefExpr 'c'` which is casted to `int` and then the whole
conditional expression is casted to 'char'. But this last conversion is
not narrowing, because `RHS` was `char` _initially_. We should just
remove the cast from `char` to `int` before the narrowing conversion
check.

Fixes llvm#139467

The added tests contains the implementation-defined warning about
'int' to 'char' conversion, which is not applicable to all platforms.
And so the target is explictly set to 'x86_64' (the line 'RUN: -- -target x86_64-unknown-linux').
vbvictor pushed a commit that referenced this pull request Aug 8, 2025
…ve for conditional expression" (#151874)

This is another attempt to merge previously
[reverted](#139474 (comment))
PR #139474. The added tests
`narrowing-conversions-conditional-expressions.c[pp]` failed on
[different (non x86_64)
platforms](#139474 (comment))
because the expected warning is implementation-defined. That's why the
test must explicitly specify target (the line `// RUN: -- -target
x86_64-unknown-linux`).
llvm-sync bot pushed a commit to arm/arm-toolchain that referenced this pull request Aug 8, 2025
…lse positive for conditional expression" (#151874)

This is another attempt to merge previously
[reverted](llvm/llvm-project#139474 (comment))
PR #139474. The added tests
`narrowing-conversions-conditional-expressions.c[pp]` failed on
[different (non x86_64)
platforms](llvm/llvm-project#139474 (comment))
because the expected warning is implementation-defined. That's why the
test must explicitly specify target (the line `// RUN: -- -target
x86_64-unknown-linux`).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

bugprone-narrowing-conversions false positive for contional expression (in C)
6 participants