Skip to content

Commit ff8aadf

Browse files
committed
[clang][diagnostics] Don't warn about unreachable code in constexpr if
The point of a constexpr if statement is to determine which branch to take at compile time, so warning on unreachable code is meaningless in these situations. Fixes #57123. Reviewed By: thakis Differential Revision: https://reviews.llvm.org/D131818
1 parent 3a8d7fe commit ff8aadf

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

clang/lib/Analysis/ReachableCode.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,12 @@ static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B,
299299
if (isa<BinaryOperator>(Term)) {
300300
return isConfigurationValue(Term, PP);
301301
}
302+
// Do not treat constexpr if statement successors as unreachable in warnings
303+
// since the point of these statements is to determine branches at compile
304+
// time.
305+
if (const auto *IS = dyn_cast<IfStmt>(Term);
306+
IS != nullptr && IS->isConstexpr())
307+
return true;
302308
}
303309

304310
const Stmt *Cond = B->getTerminatorCondition(/* stripParens */ false);

clang/test/SemaCXX/unreachable-code.cpp

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -fsyntax-only -Wunreachable-code-aggressive -fblocks -verify %s
1+
// RUN: %clang_cc1 -std=c++17 -fcxx-exceptions -fexceptions -fsyntax-only -Wunreachable-code-aggressive -fblocks -verify %s
22

33
int j;
44
int bar();
@@ -99,3 +99,34 @@ void f(int a) {
9999
}
100100

101101
}
102+
103+
namespace gh57123 {
104+
bool foo() {
105+
if constexpr (true) {
106+
if (true)
107+
return true;
108+
else
109+
return false; // expected-warning {{will never be executed}}
110+
}
111+
else
112+
return false; // no-warning
113+
}
114+
115+
bool bar() {
116+
if (true)
117+
return true;
118+
else
119+
return false; // expected-warning {{will never be executed}}
120+
}
121+
122+
bool baz() {
123+
if constexpr (true)
124+
return true;
125+
else {
126+
if (true)
127+
return true;
128+
else
129+
return false; // expected-warning {{will never be executed}}
130+
}
131+
}
132+
}

0 commit comments

Comments
 (0)