Skip to content

Commit 2f2b61b

Browse files
committed
[INSTR COMBINE] implementing instr combine of select into cast (fixes #107034)
1 parent c1df376 commit 2f2b61b

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3645,12 +3645,47 @@ static bool hasAffectedValue(Value *V, SmallPtrSetImpl<Value *> &Affected,
36453645
return false;
36463646
}
36473647

3648+
// Checks for following pattern:
3649+
// ```
3650+
// %any1 = select i1 %any0, float 1.000000e+00, float 0.000000e+00
3651+
// ```
3652+
// which then gets folded into:
3653+
// ```
3654+
// %any1 = uitofp i1 %any0 to float
3655+
// ```
3656+
// (also works with double)
3657+
static std::optional<Instruction*> mabyeFoldIntoCast(Value* CondVal, ConstantFP *TrueVal, ConstantFP *FalseVal, Type *SelType, llvm::StringRef out) {
3658+
if (TrueVal->getValueAPF().convertToDouble() != 1.0) {
3659+
return std::optional<Instruction*>();
3660+
}
3661+
3662+
if (FalseVal->getValueAPF().convertToDouble() != 0.0) {
3663+
return std::optional<Instruction*>();
3664+
}
3665+
3666+
return CastInst::Create(llvm::Instruction::UIToFP, CondVal, SelType, out);
3667+
}
3668+
3669+
36483670
Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
36493671
Value *CondVal = SI.getCondition();
36503672
Value *TrueVal = SI.getTrueValue();
36513673
Value *FalseVal = SI.getFalseValue();
36523674
Type *SelType = SI.getType();
36533675

3676+
3677+
if (ConstantFP *True = dyn_cast<ConstantFP>(TrueVal)) {
3678+
if (ConstantFP *False = dyn_cast<ConstantFP>(FalseVal)) {
3679+
if (SelType->isFloatTy() || SelType->isDoubleTy()) {
3680+
std::optional<Instruction*> folded = mabyeFoldIntoCast(CondVal, True, False, SelType, SI.getName());
3681+
3682+
if (folded.has_value()) {
3683+
return folded.value();
3684+
}
3685+
}
3686+
}
3687+
}
3688+
36543689
if (Value *V = simplifySelectInst(CondVal, TrueVal, FalseVal,
36553690
SQ.getWithInstruction(&SI)))
36563691
return replaceInstUsesWith(SI, V);
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
; RUN: opt < %s -passes=instcombine -S | FileCheck %s
2+
3+
define noundef float @ifelse(i1 noundef zeroext %x) unnamed_addr {
4+
start:
5+
; CHECK: %.= uitofp i1 %x to float
6+
%. = select i1 %x, float 1.000000e+00, float 0.000000e+00
7+
ret float %.
8+
}

0 commit comments

Comments
 (0)