Bug type: miscompilation
Component: ValueTracking
Bug location: llvm/include/llvm/Analysis/SimplifyQuery.h: getWithCondContext
llvm/lib/Analysis/ValueTracking.cpp: ComputeNumSignBitsImpl
computeKnownBitsFromOperator
computeKnownFPClass
isKnownNonZeroFromOperator
isKnownToBeAPowerOfTwo
isNonEqualPHIs
Issue title: Miscompilation at O3
Labels: miscompilation
llvm:analysis
Reported by: dtcxzyw

```
#include "csmith.h"
uint32_t a;
int16_t c;
void d() {
  for (a = -15; a >= 6; a = safe_add_func_uint16_t_u_u(a, 9))
    ;
  c = safe_lshift_func_int16_t_s_u(safe_lshift_func_uint16_t_u_s(a,14), 0);
}
int main() {
  d();
  printf("%d\n", c);
  return 0;
}
```

```
dtcxzyw@dtcxzyw:~/WorkSpace/Projects/compilers/LLVM/llvm-build$ gcc -O0 test.c -fsanitize=undefined -I/usr/include/csmith -w
dtcxzyw@dtcxzyw:~/WorkSpace/Projects/compilers/LLVM/llvm-build$ ./a.out 
-16384
dtcxzyw@dtcxzyw:~/WorkSpace/Projects/compilers/LLVM/llvm-build$ bin/clang -O3 test.c -I/usr/include/csmith -w
dtcxzyw@dtcxzyw:~/WorkSpace/Projects/compilers/LLVM/llvm-build$ ./a.out 
0
```

llvm version: 2d6ff0c533aa1b0fe6d91764846f636c4a4e911c

Comments: author: dtcxzyw
body: Reduced testcase: https://alive2.llvm.org/ce/z/9fExrA
```
; bin/opt -passes=instcombine test.ll -S
define i16 @src() {
entry:
  br label %for.inc

for.inc:
  %storemerge6 = phi i32 [ -15, %entry ], [ %conv1, %for.inc ]
  %add.i = add nsw i32 %storemerge6, 9
  %conv1 = and i32 %add.i, 65535
  %cmp = icmp ugt i32 %conv1, 5
  br i1 %cmp, label %for.inc, label %for.end

for.end:
  %conv2 = trunc nuw nsw i32 %conv1 to i16
  %cmp3.i = icmp ugt i32 %conv1, 3
  %0 = shl nuw i16 %conv2, 14
  %cond.in.i = select i1 %cmp3.i, i16 %conv2, i16 %0
  ret i16 %cond.in.i
}
```

Fix patch:
commit a87fbeb3a77a53ded341277c5b326f7696d47594
Author: Yingwei Zheng <dtcxzyw2333@gmail.com>
Date:   Wed Jul 24 20:06:36 2024 +0800

    [ValueTracking] Don't use CondContext in dataflow analysis of phi nodes (#100316)
    
    See the following case:
    ```
    define i16 @pr100298() {
    entry:
      br label %for.inc
    
    for.inc:
      %indvar = phi i32 [ -15, %entry ], [ %mask, %for.inc ]
      %add = add nsw i32 %indvar, 9
      %mask = and i32 %add, 65535
      %cmp1 = icmp ugt i32 %mask, 5
      br i1 %cmp1, label %for.inc, label %for.end
    
    for.end:
      %conv = trunc i32 %add to i16
      %cmp2 = icmp ugt i32 %mask, 3
      %shl = shl nuw i16 %conv, 14
      %res = select i1 %cmp2, i16 %conv, i16 %shl
      ret i16 %res
    }
    ```
    
    When computing knownbits of `%shl` with `%cmp2=false`, we cannot use
    this condition in the analysis of `%mask (%for.inc -> %for.inc)`.
    
    Fixes https://github.com/llvm/llvm-project/issues/100298.
    
    (cherry picked from commit 59eae919c938f890e9b9b4be8a3fa3cb1b11ed89)

diff --git a/llvm/include/llvm/Analysis/SimplifyQuery.h b/llvm/include/llvm/Analysis/SimplifyQuery.h
index a560744f0122..e8f43c8c2e91 100644
--- a/llvm/include/llvm/Analysis/SimplifyQuery.h
+++ b/llvm/include/llvm/Analysis/SimplifyQuery.h
@@ -130,6 +130,12 @@ struct SimplifyQuery {
     Copy.CC = &CC;
     return Copy;
   }
+
+  SimplifyQuery getWithoutCondContext() const {
+    SimplifyQuery Copy(*this);
+    Copy.CC = nullptr;
+    return Copy;
+  }
 };
 
 } // end namespace llvm
diff --git a/llvm/lib/Analysis/ValueTracking.cpp b/llvm/lib/Analysis/ValueTracking.cpp
index 40fe1ffe13f1..4b77c0046cc7 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -1435,7 +1435,7 @@ static void computeKnownBitsFromOperator(const Operator *I,
         // inferred hold at original context instruction.  TODO: It may be
         // correct to use the original context.  IF warranted, explore and
         // add sufficient tests to cover.
-        SimplifyQuery RecQ = Q;
+        SimplifyQuery RecQ = Q.getWithoutCondContext();
         RecQ.CxtI = P;
         computeKnownBits(R, DemandedElts, Known2, Depth + 1, RecQ);
         switch (Opcode) {
@@ -1468,7 +1468,7 @@ static void computeKnownBitsFromOperator(const Operator *I,
         // phi. This is important because that is where the value is actually
         // "evaluated" even though it is used later somewhere else. (see also
         // D69571).
-        SimplifyQuery RecQ = Q;
+        SimplifyQuery RecQ = Q.getWithoutCondContext();
 
         unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
         Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
@@ -1546,7 +1546,7 @@ static void computeKnownBitsFromOperator(const Operator *I,
         // phi. This is important because that is where the value is actually
         // "evaluated" even though it is used later somewhere else. (see also
         // D69571).
-        SimplifyQuery RecQ = Q;
+        SimplifyQuery RecQ = Q.getWithoutCondContext();
         RecQ.CxtI = P->getIncomingBlock(u)->getTerminator();
 
         Known2 = KnownBits(BitWidth);
@@ -2329,7 +2329,7 @@ bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
     // it is an induction variable where in each step its value is a power of
     // two.
     auto *PN = cast<PHINode>(I);
-    SimplifyQuery RecQ = Q;
+    SimplifyQuery RecQ = Q.getWithoutCondContext();
 
     // Check if it is an induction variable and always power of two.
     if (isPowerOfTwoRecurrence(PN, OrZero, Depth, RecQ))
@@ -2943,7 +2943,7 @@ static bool isKnownNonZeroFromOperator(const Operator *I,
       return true;
 
     // Check if all incoming values are non-zero using recursion.
-    SimplifyQuery RecQ = Q;
+    SimplifyQuery RecQ = Q.getWithoutCondContext();
     unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
     return llvm::all_of(PN->operands(), [&](const Use &U) {
       if (U.get() == PN)
@@ -3509,7 +3509,7 @@ static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
     if (UsedFullRecursion)
       return false;
 
-    SimplifyQuery RecQ = Q;
+    SimplifyQuery RecQ = Q.getWithoutCondContext();
     RecQ.CxtI = IncomBB->getTerminator();
     if (!isKnownNonEqual(IV1, IV2, DemandedElts, Depth + 1, RecQ))
       return false;
@@ -4001,7 +4001,7 @@ static unsigned ComputeNumSignBitsImpl(const Value *V,
 
       // Take the minimum of all incoming values.  This can't infinitely loop
       // because of our depth threshold.
-      SimplifyQuery RecQ = Q;
+      SimplifyQuery RecQ = Q.getWithoutCondContext();
       Tmp = TyBits;
       for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
         if (Tmp == 1) return Tmp;
@@ -5909,10 +5909,10 @@ void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
         // Recurse, but cap the recursion to two levels, because we don't want
         // to waste time spinning around in loops. We need at least depth 2 to
         // detect known sign bits.
-        computeKnownFPClass(
-            IncValue, DemandedElts, InterestedClasses, KnownSrc,
-            PhiRecursionLimit,
-            Q.getWithInstruction(P->getIncomingBlock(U)->getTerminator()));
+        computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
+                            PhiRecursionLimit,
+                            Q.getWithoutCondContext().getWithInstruction(
+                                P->getIncomingBlock(U)->getTerminator()));
 
         if (First) {
           Known = KnownSrc;


Regression tests:
file: llvm/test/Transforms/InstCombine/pr100298.ll
commands: opt -S -passes=instcombine < %s
tests: test_name: pr100298
test_body: define i16 @pr100298() {
entry:
  br label %for.inc

for.inc:                                          ; preds = %for.inc, %entry
  %indvar = phi i32 [ -15, %entry ], [ %mask, %for.inc ]
  %add = add nsw i32 %indvar, 9
  %mask = and i32 %add, 65535
  %cmp1 = icmp ugt i32 %mask, 5
  br i1 %cmp1, label %for.inc, label %for.end

for.end:                                          ; preds = %for.inc
  %conv = trunc i32 %add to i16
  %cmp2 = icmp ugt i32 %mask, 3
  %shl = shl nuw i16 %conv, 14
  %res = select i1 %cmp2, i16 %conv, i16 %shl
  ret i16 %res
}