Do not check if we are in a discared context in non-immediate contexts

This fixes in a regression introduced by 6eeda06c1.

When deducing the return type of nested function calls, only the
return type of the outermost expression should be ignored.

Instead of assuming all contextes nested in a discared statements
are themselves discarded, only assume that in immediate contexts.

Similarly, only consider contextes immediately in an immediate or
discarded statement as being themselves immediate.

GitOrigin-RevId: 2334314550724812bb94e36c6b5df7d665bdbd9d
diff --git a/include/clang/Sema/Sema.h b/include/clang/Sema/Sema.h
index 40c0b54..8182d25 100644
--- a/include/clang/Sema/Sema.h
+++ b/include/clang/Sema/Sema.h
@@ -1324,12 +1324,15 @@
 
     bool isImmediateFunctionContext() const {
       return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
-             InImmediateFunctionContext;
+             (Context == ExpressionEvaluationContext::DiscardedStatement &&
+              InImmediateFunctionContext);
     }
 
     bool isDiscardedStatementContext() const {
       return Context == ExpressionEvaluationContext::DiscardedStatement ||
-             InDiscardedStatement;
+             (Context ==
+                  ExpressionEvaluationContext::ImmediateFunctionContext &&
+              InDiscardedStatement);
     }
   };
 
diff --git a/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp b/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
index ed61119..72a6187 100644
--- a/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
+++ b/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
@@ -159,4 +159,19 @@
       surprise: {}
   }
 }
+
+namespace deduced_return_type_in_discareded_statement {
+
+template <typename T>
+auto a(const T &t) {
+  return t;
+}
+
+void f() {
+  if constexpr (false) {
+    a(a(0));
+  }
+}
+} // namespace deduced_return_type_in_discareded_statement
+
 #endif