[clang-tools-extra] [clang-tidy] fix and add support for disjunction and conjuction chain in bugprone-redundant-branch-condition-check (PR #242598)

via cfe-commits cfe-commits at lists.llvm.org
Fri Nov 13 22:39:00 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-tidy

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

Author: Abhay Singh (Abhay13332)

<details>
<summary>Changes</summary>

Resolve the existing  `FIXME: Handle longer conjunctive and disjunctive clauses` in `bugprone-redundant-branch-condition` by extending the check to detect and fix redundant condition variables inside multi-operand logical conjunction (`&&`) and disjunction (`||`) chains.

Previously, the check only handled single variables or two-operand logical expressions (`a && b` or `a || b`) and left longer chains unhandled. This change updates the check so that chains of three or more operands (such as `a && b && c` or `a || b || c`) are properly analyzed and fixed in both outer and inner `if` statements.



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


4 Files Affected:

- (modified) clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp (+50-23) 
- (modified) clang-tools-extra/docs/ReleaseNotes.md (+2) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/bugprone/redundant-branch-condition.md (+10) 
- (modified) clang-tools-extra/test/clang-tidy/checkers/bugprone/redundant-branch-condition.cpp (+167) 


``````````diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
index 7934da1f2fbddd..969ba7ea74e5fd 100644
--- a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
@@ -24,10 +24,8 @@ namespace clang::tidy::bugprone {
 static const char CondVarStr[] = "cond_var";
 static const char OuterIfStr[] = "outer_if";
 static const char InnerIfStr[] = "inner_if";
-static const char OuterIfVar1Str[] = "outer_if_var1";
-static const char OuterIfVar2Str[] = "outer_if_var2";
-static const char InnerIfVar1Str[] = "inner_if_var1";
-static const char InnerIfVar2Str[] = "inner_if_var2";
+static const char OuterIfVarStr[] = "outer_if_var";
+static const char InnerIfVarStr[] = "inner_if_var";
 static const char FuncStr[] = "func";
 
 /// Returns whether `Var` is changed in range (`PrevS`..`NextS`).
@@ -67,6 +65,44 @@ static const Stmt *getOutermostLoopBetween(const Stmt *S, const Stmt *Outer,
   return Loop;
 }
 
+namespace {
+// ast matcher to get all declaration whose  all ancestor operator are matched
+// in AncestorOperatorMatcher.
+AST_MATCHER_P2(Expr, getAllDeclWithAncestor,
+               ast_matchers::internal::Matcher<clang::BinaryOperator>,
+               AncestorOperatorMatcher, ast_matchers::internal::Matcher<Expr>,
+               InnerMatcher) {
+  const auto *RootExpr = Node.IgnoreParenImpCasts();
+  if (!RootExpr)
+    return false;
+  llvm::SmallVector<const Expr *, 16> ExprStack;
+  ExprStack.push_back(RootExpr);
+  bool Matched = false;
+  while (!ExprStack.empty()) {
+    const auto *TopExpr = ExprStack.back();
+    ExprStack.pop_back();
+    if (!TopExpr)
+      continue;
+    if (const auto *BO =
+            dyn_cast<BinaryOperator>(TopExpr->IgnoreParenImpCasts())) {
+      ast_matchers::internal::BoundNodesTreeBuilder Useless;
+      if (!AncestorOperatorMatcher.matches(*BO, Finder, &Useless))
+        continue;
+      ExprStack.push_back(BO->getLHS());
+      ExprStack.push_back(BO->getRHS());
+
+    } else {
+      ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
+      if (!InnerMatcher.matches(*TopExpr->IgnoreParenImpCasts(), Finder,
+                                &Result))
+        continue;
+      Builder->addMatch(Result);
+      Matched = true;
+    }
+  }
+  return Matched;
+}
+} // namespace
 void RedundantBranchConditionCheck::registerMatchers(MatchFinder *Finder) {
   const auto ImmutableVar =
       varDecl(anyOf(parmVarDecl(), hasLocalStorage()), hasType(isInteger()),
@@ -74,27 +110,19 @@ void RedundantBranchConditionCheck::registerMatchers(MatchFinder *Finder) {
           .bind(CondVarStr);
   Finder->addMatcher(
       ifStmt(
-          hasCondition(anyOf(
-              declRefExpr(hasDeclaration(ImmutableVar)).bind(OuterIfVar1Str),
-              binaryOperator(hasOperatorName("&&"),
-                             forEach(declRefExpr(hasDeclaration(ImmutableVar))
-                                         .bind(OuterIfVar2Str))))),
+          hasCondition(getAllDeclWithAncestor(
+              hasOperatorName("&&"),
+              declRefExpr(hasDeclaration(ImmutableVar)).bind(OuterIfVarStr))),
           hasThen(hasDescendant(
-              ifStmt(hasCondition(anyOf(
+              ifStmt(hasCondition(getAllDeclWithAncestor(
+                         hasAnyOperatorName("&&", "||"),
                          declRefExpr(hasDeclaration(
                                          varDecl(equalsBoundNode(CondVarStr))))
-                             .bind(InnerIfVar1Str),
-                         binaryOperator(
-                             hasAnyOperatorName("&&", "||"),
-                             hasEitherOperand(
-                                 declRefExpr(hasDeclaration(varDecl(
-                                                 equalsBoundNode(CondVarStr))))
-                                     .bind(InnerIfVar2Str))))))
+                             .bind(InnerIfVarStr))))
                   .bind(InnerIfStr))),
           forFunction(functionDecl().bind(FuncStr)))
           .bind(OuterIfStr),
       this);
-  // FIXME: Handle longer conjunctive and disjunctive clauses.
 }
 
 void RedundantBranchConditionCheck::check(
@@ -103,16 +131,15 @@ void RedundantBranchConditionCheck::check(
   const auto *InnerIf = Result.Nodes.getNodeAs<IfStmt>(InnerIfStr);
   const auto *CondVar = Result.Nodes.getNodeAs<VarDecl>(CondVarStr);
   const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>(FuncStr);
-
   const DeclRefExpr *OuterIfVar = nullptr, *InnerIfVar = nullptr;
-  if (const auto *Inner = Result.Nodes.getNodeAs<DeclRefExpr>(InnerIfVar1Str))
+  if (const auto *Inner = Result.Nodes.getNodeAs<DeclRefExpr>(InnerIfVarStr))
     InnerIfVar = Inner;
   else
-    InnerIfVar = Result.Nodes.getNodeAs<DeclRefExpr>(InnerIfVar2Str);
-  if (const auto *Outer = Result.Nodes.getNodeAs<DeclRefExpr>(OuterIfVar1Str))
+    return;
+  if (const auto *Outer = Result.Nodes.getNodeAs<DeclRefExpr>(OuterIfVarStr))
     OuterIfVar = Outer;
   else
-    OuterIfVar = Result.Nodes.getNodeAs<DeclRefExpr>(OuterIfVar2Str);
+    return;
 
   if (OuterIfVar && InnerIfVar) {
     if (isChangedBefore(OuterIf->getThen(), InnerIfVar, OuterIfVar, CondVar,
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index b6774370511feb..299db2c88770ac 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -238,6 +238,8 @@ infrastructure are described first, followed by tool-specific sections.
     - Fixed false negatives when a nested `if` checks the second operand
       of an outer `&&` condition, as in `if (x && y) { if (y) ... }`.
 
+    - Fixed and added support for long conjuction and disjunction chain.
+
 - Fixed a crash in {doc}`bugprone-std-namespace-modification
   <clang-tidy/checks/bugprone/std-namespace-modification>` when checking
   lambda closure types used as template arguments.
diff --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/redundant-branch-condition.md b/clang-tools-extra/docs/clang-tidy/checks/bugprone/redundant-branch-condition.md
index d6284355e40c58..b86de56dbaed7d 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/bugprone/redundant-branch-condition.md
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/redundant-branch-condition.md
@@ -74,6 +74,16 @@ if (onFire) {
     scream();
 }
 ```
+The check also detects redundant condition variables inside longer chains of
+logical "and" (`&&`) and logical "or" (`||`) expressions:
+
+```c
+bool onFire = isBurning();
+if (onFire && fireFighters < 10 && alarmActive) {
+  if (peopleInTheBuilding > 0 && onFire && doorLocked)
+    scream();
+}
+```
 
 Every possible change is considered, thus if the condition variable is not
 a local variable of the function, it is a volatile or it has an alias (pointer
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/redundant-branch-condition.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/redundant-branch-condition.cpp
index 2f71fc8e2920e7..7e7823c8932ee8 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/redundant-branch-condition.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/redundant-branch-condition.cpp
@@ -14,6 +14,8 @@ bool callTheFD();
 void scream();
 bool isFireFighterComing();
 bool someOtherCondition();
+bool hasEmergencyExits();
+bool powerCutOff();
 
 //===--- Basic Positives --------------------------------------------------===//
 
@@ -405,6 +407,157 @@ void positive_indirect_outer_and_rhs_inner_or_rhs() {
   }
 }
 
+// ===--- Long Conjuction-disjunction Chain Positives --- ===//
+void positive_direct_first_in_four_conj_chain(){
+  bool onFire=isBurning();
+  bool hasEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(onFire && fireFighters<10 && !hasEmergencyExit && isPowerSupplyOn){
+    if(onFire){
+      // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant condition 'onFire' [bugprone-redundant-branch-condition]
+      // CHECK-FIXES: {{^\ *$}}
+    scream();
+    }
+    // CHECK-FIXES: {{^\ *$}}
+  }
+}
+
+void positive_direct_second_in_four_conj_chain(){
+  bool onFire=isBurning();
+  bool hasEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(fireFighters<10 && onFire &&!hasEmergencyExit && isPowerSupplyOn){
+    if(onFire){
+      // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant condition 'onFire' [bugprone-redundant-branch-condition]
+      // CHECK-FIXES: {{^\ *$}}
+    scream();
+    }
+    // CHECK-FIXES: {{^\ *$}}
+  }
+}
+
+void positive_direct_third_in_four_conj_chain(){
+  bool onFire=isBurning();
+  bool hasntEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(onFire && fireFighters<10 && hasntEmergencyExit && isPowerSupplyOn){
+    if(hasntEmergencyExit){
+      // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant condition 'hasntEmergencyExit' [bugprone-redundant-branch-condition]
+      // CHECK-FIXES: {{^\ *$}}
+    scream();
+    }
+    // CHECK-FIXES: {{^\ *$}}
+  }
+}
+
+void positive_direct_fourth_in_four_conj_chain(){
+  bool onFire=isBurning();
+  bool hasEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(onFire && fireFighters<10 && !hasEmergencyExit && isPowerSupplyOn){
+    if(isPowerSupplyOn){
+      // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant condition 'isPowerSupplyOn' [bugprone-redundant-branch-condition]
+      // CHECK-FIXES: {{^\ *$}}
+    scream();
+    }
+          // CHECK-FIXES: {{^\ *$}}
+  }
+}
+
+void positive_indirect_first_in_four_conj_chain(){
+  bool onFire=isBurning();
+  bool hasEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(onFire && fireFighters<10 && !hasEmergencyExit && isPowerSupplyOn){
+    if (someOtherCondition()) {
+      if(onFire){
+        // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant condition 'onFire' [bugprone-redundant-branch-condition]
+        // CHECK-FIXES: {{^\ *$}}
+      scream();
+      }
+      // CHECK-FIXES: {{^\ *$}}
+    }
+  }
+}
+
+void positive_indirect_second_in_four_conj_chain(){
+  bool onFire=isBurning();
+  bool hasEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(fireFighters<10 && onFire &&!hasEmergencyExit && isPowerSupplyOn){
+    if (someOtherCondition()) {
+      if(onFire){
+        // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant condition 'onFire' [bugprone-redundant-branch-condition]
+        // CHECK-FIXES: {{^\ *$}}
+      scream();
+      }
+      // CHECK-FIXES: {{^\ *$}}
+    }  
+  }
+}
+
+void positive_indirect_third_in_four_conj_chain(){
+  bool onFire=isBurning();
+  bool hasntEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(onFire && fireFighters<10 && hasntEmergencyExit && isPowerSupplyOn){
+    if (someOtherCondition()) {
+      if(hasntEmergencyExit){
+        // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant condition 'hasntEmergencyExit' [bugprone-redundant-branch-condition]
+        // CHECK-FIXES: {{^\ *$}}
+      scream();
+      }
+      // CHECK-FIXES: {{^\ *$}}
+    }  
+  }
+}
+
+void positive_indirect_fourth_in_four_conj_chain(){
+  bool onFire=isBurning();
+  bool hasEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(onFire && fireFighters<10 && !hasEmergencyExit && isPowerSupplyOn){
+    if (someOtherCondition()) {
+      if(isPowerSupplyOn){
+        // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant condition 'isPowerSupplyOn' [bugprone-redundant-branch-condition]
+        // CHECK-FIXES: {{^\ *$}}
+      scream();
+      }
+      // CHECK-FIXES: {{^\ *$}}
+    }
+  }
+}
+
+void positive_direct_inner_disj_outer_conj_chain(){
+  bool onFire=isBurning();
+  bool hasntEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(onFire && fireFighters<10 && hasntEmergencyExit && isPowerSupplyOn){
+    if(isCollapsing() ||hasntEmergencyExit){
+      // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant condition 'hasntEmergencyExit' [bugprone-redundant-branch-condition]
+      // CHECK-FIXES: {{^\ *$}}
+    scream();
+    }
+    // CHECK-FIXES: {{^\ *$}}
+    
+  }
+}
+void positive_direct_inner_conj_chain_outer_conj_chain(){
+  bool onFire=isBurning();
+  bool hasntEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(onFire && fireFighters<10 && hasntEmergencyExit && isPowerSupplyOn){
+    if(onFire && hasntEmergencyExit && isPowerSupplyOn){
+      // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant condition 'hasntEmergencyExit' [bugprone-redundant-branch-condition]
+      // CHECK-MESSAGES: :[[@LINE-2]]:5: warning: redundant condition 'isPowerSupplyOn' [bugprone-redundant-branch-condition]
+      // CHECK-MESSAGES: :[[@LINE-3]]:5: warning: redundant condition 'onFire' [bugprone-redundant-branch-condition]
+      // CHECK-FIXES: if(onFire && hasntEmergencyExit && isPowerSupplyOn){
+    scream();
+    }
+  }
+}
+
+
 //===--- Basic Negatives --------------------------------------------------===//
 
 void negative_direct() {
@@ -997,6 +1150,20 @@ void negative_reassigned() {
   }
 }
 
+// ===--- Long Conjuction-disjunction Chain Negatives --- ===//
+
+void negative_direct__outer_disj_inner_conj_chain(){
+  bool onFire=isBurning();
+  bool hasntEmergencyExit=hasEmergencyExits();
+  bool isPowerSupplyOn=!powerCutOff();
+  if(onFire && fireFighters<10 || hasntEmergencyExit && isPowerSupplyOn){
+    if(onFire && hasntEmergencyExit && isPowerSupplyOn){
+      // NO-MESSAGE:Fire may have been extinguished
+    scream();
+    }
+  }
+}
+
 //===--- Special Positives ------------------------------------------------===//
 
 // Condition variable mutated in or after the inner loop

``````````

</details>


https://github.com/llvm/llvm-project/pull/242598


More information about the cfe-commits mailing list