[llvm] [IR][JumpThreading] Fix infinite recursion on compare self-reference [updated] (PR #129501)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Sun Apr 6 12:53:36 PDT 2025


================
@@ -1519,12 +1526,24 @@ Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB,
   }
 
   // If we have a CmpInst, try to fold it for each incoming edge into PredBB.
+  // Note that during the execution of the pass, phi nodes may become constant
+  // and may be removed, which can lead to self-referencing instructions in
+  // code that becomes unreachable. Consequently, we need to handle those
+  // instructions in unreachable code and check before going into recursion.
   if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) {
     if (CondCmp->getParent() == BB) {
-      Constant *Op0 =
-          evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0), DL);
-      Constant *Op1 =
-          evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1), DL);
+      Constant *Op0 = nullptr;
+      Constant *Op1 = nullptr;
+      if (Value *V0 = CondCmp->getOperand(0); !Visited.contains(V0)) {
+        Visited.insert(V0);
----------------
nikic wrote:

You can also handle the erase in the same place, e.g. by adding a `auto _ = make_scope_exit([V]() { Visited.erase(V); });`

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


More information about the llvm-commits mailing list