@@ -1299,6 +1299,8 @@ Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
1299
1299
if (TrueVal == OldOp)
1300
1300
return nullptr ;
1301
1301
1302
+ bool NewOpNeverUndef = false ;
1303
+
1302
1304
if (Value *V = simplifyWithOpReplaced (TrueVal, OldOp, NewOp, SQ,
1303
1305
/* AllowRefinement=*/ true )) {
1304
1306
// Need some guarantees about the new simplified op to ensure we don't inf
@@ -1308,13 +1310,20 @@ Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
1308
1310
isGuaranteedNotToBeUndef (V, SQ.AC , &Sel, &DT))
1309
1311
return replaceOperand (Sel, Swapped ? 2 : 1 , V);
1310
1312
1311
- // If NewOp is a constant and OldOp is not replace iff NewOp doesn't
1312
- // contain and undef elements.
1313
- if (match (NewOp, m_ImmConstant ())) {
1314
- if (isGuaranteedNotToBeUndef (NewOp, SQ.AC , &Sel, &DT))
1315
- return replaceOperand (Sel, Swapped ? 2 : 1 , V);
1313
+ // We can't do any further replacement if NewOp may be undef.
1314
+ if (!isGuaranteedNotToBeUndef (NewOp, SQ.AC , &Sel, &DT))
1316
1315
return nullptr ;
1317
- }
1316
+
1317
+ // If NewOp is a constant, replace.
1318
+ if (match (NewOp, m_ImmConstant ()))
1319
+ return replaceOperand (Sel, Swapped ? 2 : 1 , V);
1320
+
1321
+ // If we simplified the TrueArm -> NewOp then replace.
1322
+ // This handles things like `select`/`min`/`max`/`or`/`and`/etc...
1323
+ if (NewOp == V)
1324
+ return replaceOperand (Sel, Swapped ? 2 : 1 , V);
1325
+
1326
+ NewOpNeverUndef = true ;
1318
1327
}
1319
1328
1320
1329
// Even if TrueVal does not simplify, we can directly replace a use of
@@ -1326,7 +1335,7 @@ Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
1326
1335
// FIXME: Support vectors.
1327
1336
if (OldOp == CmpLHS && match (NewOp, m_ImmConstant ()) &&
1328
1337
!match (OldOp, m_ImmConstant ()) && !Cmp.getType ()->isVectorTy () &&
1329
- isGuaranteedNotToBeUndef (NewOp, SQ.AC , &Sel, &DT))
1338
+ (NewOpNeverUndef || isGuaranteedNotToBeUndef (NewOp, SQ.AC , &Sel, &DT) ))
1330
1339
if (replaceInInstruction (TrueVal, OldOp, NewOp))
1331
1340
return &Sel;
1332
1341
return nullptr ;
0 commit comments