Skip to content

Commit aa19ff3

Browse files
committed
[LV] Vectorize maxnum/minnum w/o fast-math flags.
Update LV to vectorize maxnum/minnum reductions without fast-math flags, by adding an extra check in the loop if any inputs to maxnum/minnum are NaN. If any input is NaN, *exit the vector loop, *compute the reduction result up to the vector iteration that contained NaN inputs and * resume in the scalar loop New recurrence kinds are added for reductions using maxnum/minnum without fast-math flags. The new recurrence kinds are not supported in the code to generate IR to perform the reductions to prevent accidential mis-use. Users need to add the required checks ensuring no NaN inputs, and convert to regular FMin/FMax recurrence kinds.
1 parent 39de14f commit aa19ff3

File tree

14 files changed

+367
-44
lines changed

14 files changed

+367
-44
lines changed

llvm/include/llvm/Analysis/IVDescriptors.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ enum class RecurKind {
4747
FMul, ///< Product of floats.
4848
FMin, ///< FP min implemented in terms of select(cmp()).
4949
FMax, ///< FP max implemented in terms of select(cmp()).
50+
FMinNumNoFMFs, ///< FP min with llvm.minnum semantics and no fast-math flags.
51+
FMaxNumNoFMFs, ///< FP max with llvm.maxnumsemantics and no fast-math flags.
5052
FMinimum, ///< FP min with llvm.minimum semantics
5153
FMaximum, ///< FP max with llvm.maximum semantics
5254
FMinimumNum, ///< FP min with llvm.minimumnum semantics

llvm/lib/Analysis/IVDescriptors.cpp

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -941,10 +941,28 @@ RecurrenceDescriptor::InstDesc RecurrenceDescriptor::isRecurrenceInstr(
941941
m_Intrinsic<Intrinsic::minimumnum>(m_Value(), m_Value())) ||
942942
match(I, m_Intrinsic<Intrinsic::maximumnum>(m_Value(), m_Value()));
943943
};
944-
if (isIntMinMaxRecurrenceKind(Kind) ||
945-
(HasRequiredFMF() && isFPMinMaxRecurrenceKind(Kind)))
944+
if (isIntMinMaxRecurrenceKind(Kind))
946945
return isMinMaxPattern(I, Kind, Prev);
947-
else if (isFMulAddIntrinsic(I))
946+
if (isFPMinMaxRecurrenceKind(Kind)) {
947+
if (HasRequiredFMF())
948+
return isMinMaxPattern(I, Kind, Prev);
949+
// For FMax/FMin reductions using maxnum/minnum intrinsics with non-NaN
950+
// start value, we may be able to vectorize with extra checks ensuring the
951+
// inputs are not NaN.
952+
auto *StartV = dyn_cast<ConstantFP>(
953+
OrigPhi->getIncomingValueForBlock(L->getLoopPredecessor()));
954+
if (StartV && !StartV->getValue().isNaN() &&
955+
isMinMaxPattern(I, Kind, Prev).isRecurrence()) {
956+
if (((Kind == RecurKind::FMax &&
957+
match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) ||
958+
Kind == RecurKind::FMaxNumNoFMFs))
959+
return InstDesc(I, RecurKind::FMaxNumNoFMFs);
960+
if (((Kind == RecurKind::FMin &&
961+
match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) ||
962+
Kind == RecurKind::FMinNumNoFMFs))
963+
return InstDesc(I, RecurKind::FMinNumNoFMFs);
964+
}
965+
} else if (isFMulAddIntrinsic(I))
948966
return InstDesc(Kind == RecurKind::FMulAdd, I,
949967
I->hasAllowReassoc() ? nullptr : I);
950968
return InstDesc(false, I);

llvm/lib/Transforms/Utils/LoopUtils.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -938,8 +938,10 @@ constexpr Intrinsic::ID llvm::getReductionIntrinsicID(RecurKind RK) {
938938
case RecurKind::UMin:
939939
return Intrinsic::vector_reduce_umin;
940940
case RecurKind::FMax:
941+
case RecurKind::FMaxNumNoFMFs:
941942
return Intrinsic::vector_reduce_fmax;
942943
case RecurKind::FMin:
944+
case RecurKind::FMinNumNoFMFs:
943945
return Intrinsic::vector_reduce_fmin;
944946
case RecurKind::FMaximum:
945947
return Intrinsic::vector_reduce_fmaximum;

llvm/lib/Transforms/Vectorize/LoopVectorize.cpp

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4347,8 +4347,15 @@ bool LoopVectorizationPlanner::isCandidateForEpilogueVectorization(
43474347
ElementCount VF) const {
43484348
// Cross iteration phis such as reductions need special handling and are
43494349
// currently unsupported.
4350-
if (any_of(OrigLoop->getHeader()->phis(),
4351-
[&](PHINode &Phi) { return Legal->isFixedOrderRecurrence(&Phi); }))
4350+
if (any_of(OrigLoop->getHeader()->phis(), [&](PHINode &Phi) {
4351+
if (Legal->isReductionVariable(&Phi)) {
4352+
RecurKind RK =
4353+
Legal->getRecurrenceDescriptor(&Phi).getRecurrenceKind();
4354+
return RK == RecurKind::FMinNumNoFMFs ||
4355+
RK == RecurKind::FMaxNumNoFMFs;
4356+
}
4357+
return Legal->isFixedOrderRecurrence(&Phi);
4358+
}))
43524359
return false;
43534360

43544361
// Phis with uses outside of the loop require special handling and are
@@ -8811,6 +8818,9 @@ VPlanPtr LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(
88118818

88128819
// Adjust the recipes for any inloop reductions.
88138820
adjustRecipesForReductions(Plan, RecipeBuilder, Range.Start);
8821+
if (!VPlanTransforms::runPass(
8822+
VPlanTransforms::handleMaxMinNumReductionsWithoutFastMath, *Plan))
8823+
return nullptr;
88148824

88158825
// Transform recipes to abstract recipes if it is legal and beneficial and
88168826
// clamp the range for better cost estimation.

llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23187,6 +23187,8 @@ class HorizontalReduction {
2318723187
case RecurKind::FindFirstIVUMin:
2318823188
case RecurKind::FindLastIVSMax:
2318923189
case RecurKind::FindLastIVUMax:
23190+
case RecurKind::FMaxNumNoFMFs:
23191+
case RecurKind::FMinNumNoFMFs:
2319023192
case RecurKind::FMaximumNum:
2319123193
case RecurKind::FMinimumNum:
2319223194
case RecurKind::None:
@@ -23324,6 +23326,8 @@ class HorizontalReduction {
2332423326
case RecurKind::FindFirstIVUMin:
2332523327
case RecurKind::FindLastIVSMax:
2332623328
case RecurKind::FindLastIVUMax:
23329+
case RecurKind::FMaxNumNoFMFs:
23330+
case RecurKind::FMinNumNoFMFs:
2332723331
case RecurKind::FMaximumNum:
2332823332
case RecurKind::FMinimumNum:
2332923333
case RecurKind::None:
@@ -23426,6 +23430,8 @@ class HorizontalReduction {
2342623430
case RecurKind::FindFirstIVUMin:
2342723431
case RecurKind::FindLastIVSMax:
2342823432
case RecurKind::FindLastIVUMax:
23433+
case RecurKind::FMaxNumNoFMFs:
23434+
case RecurKind::FMinNumNoFMFs:
2342923435
case RecurKind::FMaximumNum:
2343023436
case RecurKind::FMinimumNum:
2343123437
case RecurKind::None:

llvm/lib/Transforms/Vectorize/VPlan.h

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1326,20 +1326,22 @@ class LLVM_ABI_FOR_TEST VPWidenRecipe : public VPRecipeWithIRFlags,
13261326
unsigned Opcode;
13271327

13281328
public:
1329-
VPWidenRecipe(unsigned Opcode, ArrayRef<VPValue *> Operands,
1330-
const VPIRFlags &Flags, DebugLoc DL)
1331-
: VPRecipeWithIRFlags(VPDef::VPWidenSC, Operands, Flags, DL),
1332-
Opcode(Opcode) {}
1333-
13341329
VPWidenRecipe(Instruction &I, ArrayRef<VPValue *> Operands)
13351330
: VPRecipeWithIRFlags(VPDef::VPWidenSC, Operands, I), VPIRMetadata(I),
13361331
Opcode(I.getOpcode()) {}
13371332

1333+
VPWidenRecipe(unsigned Opcode, ArrayRef<VPValue *> Operands,
1334+
const VPIRFlags &Flags, const VPIRMetadata &Metadata,
1335+
DebugLoc DL)
1336+
: VPRecipeWithIRFlags(VPDef::VPWidenSC, Operands, Flags, DL),
1337+
VPIRMetadata(Metadata), Opcode(Opcode) {}
1338+
13381339
~VPWidenRecipe() override = default;
13391340

13401341
VPWidenRecipe *clone() override {
1341-
auto *R = new VPWidenRecipe(*getUnderlyingInstr(), operands());
1342-
R->transferFlags(*this);
1342+
auto *R =
1343+
new VPWidenRecipe(getOpcode(), operands(), *this, *this, getDebugLoc());
1344+
R->setUnderlyingValue(getUnderlyingValue());
13431345
return R;
13441346
}
13451347

llvm/lib/Transforms/Vectorize/VPlanAnalysis.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ Type *VPTypeAnalysis::inferScalarTypeForRecipe(const VPInstruction *R) {
8585
return ResTy;
8686
}
8787
case Instruction::ICmp:
88+
case Instruction::FCmp:
8889
case VPInstruction::ActiveLaneMask:
8990
assert(inferScalarType(R->getOperand(0)) ==
9091
inferScalarType(R->getOperand(1)) &&

llvm/lib/Transforms/Vectorize/VPlanConstruction.cpp

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,3 +628,140 @@ void VPlanTransforms::attachCheckBlock(VPlan &Plan, Value *Cond,
628628
Term->addMetadata(LLVMContext::MD_prof, BranchWeights);
629629
}
630630
}
631+
632+
static VPValue *getMinMaxCompareValue(VPSingleDefRecipe *MinMaxOp,
633+
VPReductionPHIRecipe *RedPhi) {
634+
auto *RepR = dyn_cast<VPReplicateRecipe>(MinMaxOp);
635+
if (!isa<VPWidenIntrinsicRecipe>(MinMaxOp) &&
636+
!(RepR && (isa<IntrinsicInst>(RepR->getUnderlyingInstr()))))
637+
return nullptr;
638+
639+
if (MinMaxOp->getOperand(0) == RedPhi)
640+
return MinMaxOp->getOperand(1);
641+
return MinMaxOp->getOperand(0);
642+
}
643+
644+
/// Returns true if there VPlan is read-only and execution can be resumed at the
645+
/// beginning of the last vector iteration in the scalar loop
646+
static bool canResumeInScalarLoopFromVectorLoop(VPlan &Plan) {
647+
for (VPBlockBase *VPB : vp_depth_first_shallow(
648+
Plan.getVectorLoopRegion()->getEntryBasicBlock())) {
649+
auto *VPBB = dyn_cast<VPBasicBlock>(VPB);
650+
if (!VPBB)
651+
return false;
652+
for (auto &R : *VPBB) {
653+
if (match(&R, m_BranchOnCount(m_VPValue(), m_VPValue())))
654+
continue;
655+
if (R.mayWriteToMemory())
656+
return false;
657+
}
658+
}
659+
return true;
660+
}
661+
662+
bool VPlanTransforms::handleMaxMinNumReductionsWithoutFastMath(VPlan &Plan) {
663+
VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
664+
VPValue *AnyNaN = nullptr;
665+
VPReductionPHIRecipe *RedPhiR = nullptr;
666+
VPRecipeWithIRFlags *MinMaxOp = nullptr;
667+
bool HasUnsupportedPhi = false;
668+
for (auto &R : LoopRegion->getEntryBasicBlock()->phis()) {
669+
HasUnsupportedPhi |=
670+
!isa<VPCanonicalIVPHIRecipe, VPWidenIntOrFpInductionRecipe,
671+
VPReductionPHIRecipe>(&R);
672+
auto *Cur = dyn_cast<VPReductionPHIRecipe>(&R);
673+
if (!Cur)
674+
continue;
675+
if (RedPhiR)
676+
return false;
677+
if (Cur->getRecurrenceKind() != RecurKind::FMaxNumNoFMFs &&
678+
Cur->getRecurrenceKind() != RecurKind::FMinNumNoFMFs)
679+
continue;
680+
681+
RedPhiR = Cur;
682+
MinMaxOp = dyn_cast<VPRecipeWithIRFlags>(
683+
RedPhiR->getBackedgeValue()->getDefiningRecipe());
684+
if (!MinMaxOp)
685+
return false;
686+
VPValue *In = getMinMaxCompareValue(MinMaxOp, RedPhiR);
687+
if (!In)
688+
return false;
689+
690+
auto *IsNaN =
691+
new VPInstruction(Instruction::FCmp, {In, In}, {CmpInst::FCMP_UNO}, {});
692+
IsNaN->insertBefore(MinMaxOp);
693+
AnyNaN = new VPInstruction(VPInstruction::AnyOf, {IsNaN});
694+
AnyNaN->getDefiningRecipe()->insertAfter(IsNaN);
695+
}
696+
697+
if (!AnyNaN)
698+
return true;
699+
700+
if (HasUnsupportedPhi || !canResumeInScalarLoopFromVectorLoop(Plan))
701+
return false;
702+
703+
auto *MiddleVPBB = Plan.getMiddleBlock();
704+
auto *RdxResult = dyn_cast<VPInstruction>(&MiddleVPBB->front());
705+
if (!RdxResult ||
706+
RdxResult->getOpcode() != VPInstruction::ComputeReductionResult ||
707+
RdxResult->getOperand(0) != RedPhiR)
708+
return false;
709+
710+
auto *ScalarPH = Plan.getScalarPreheader();
711+
// Update the resume phis in the scalar preheader. They all must either resume
712+
// from the reduction result or the canonical induction. Bail out if there are
713+
// other resume phis.
714+
for (auto &R : ScalarPH->phis()) {
715+
auto *ResumeR = cast<VPPhi>(&R);
716+
VPValue *VecV = ResumeR->getOperand(0);
717+
VPValue *BypassV = ResumeR->getOperand(ResumeR->getNumOperands() - 1);
718+
if (VecV != RdxResult && VecV != &Plan.getVectorTripCount())
719+
return false;
720+
ResumeR->setOperand(
721+
1, VecV == &Plan.getVectorTripCount() ? Plan.getCanonicalIV() : VecV);
722+
ResumeR->addOperand(BypassV);
723+
}
724+
725+
// Create a new reduction phi recipe with either FMin/FMax, replacing
726+
// FMinNumNoFMFs/FMaxNumNoFMFs.
727+
RecurKind NewRK = RedPhiR->getRecurrenceKind() != RecurKind::FMinNumNoFMFs
728+
? RecurKind::FMin
729+
: RecurKind::FMax;
730+
auto *NewRedPhiR = new VPReductionPHIRecipe(
731+
cast<PHINode>(RedPhiR->getUnderlyingValue()), NewRK,
732+
*RedPhiR->getStartValue(), RedPhiR->isInLoop(), RedPhiR->isOrdered());
733+
NewRedPhiR->addOperand(RedPhiR->getOperand(1));
734+
NewRedPhiR->insertBefore(RedPhiR);
735+
RedPhiR->replaceAllUsesWith(NewRedPhiR);
736+
RedPhiR->eraseFromParent();
737+
738+
// Update the loop exit condition to exit if either any of the inputs is NaN
739+
// or the vector trip count is reached.
740+
VPBasicBlock *LatchVPBB = LoopRegion->getExitingBasicBlock();
741+
VPBuilder Builder(LatchVPBB->getTerminator());
742+
auto *LatchExitingBranch = cast<VPInstruction>(LatchVPBB->getTerminator());
743+
assert(LatchExitingBranch->getOpcode() == VPInstruction::BranchOnCount &&
744+
"Unexpected terminator");
745+
auto *IsLatchExitTaken =
746+
Builder.createICmp(CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),
747+
LatchExitingBranch->getOperand(1));
748+
auto *AnyExitTaken =
749+
Builder.createNaryOp(Instruction::Or, {AnyNaN, IsLatchExitTaken});
750+
Builder.createNaryOp(VPInstruction::BranchOnCond, AnyExitTaken);
751+
LatchExitingBranch->eraseFromParent();
752+
753+
// Split the middle block and introduce a new block, branching to the scalar
754+
// preheader to resume iteration in the scalar loop if any NaNs have been
755+
// encountered.
756+
MiddleVPBB->splitAt(std::prev(MiddleVPBB->end()));
757+
Builder.setInsertPoint(MiddleVPBB, MiddleVPBB->begin());
758+
auto *NewSel =
759+
Builder.createSelect(AnyNaN, NewRedPhiR, RdxResult->getOperand(1));
760+
RdxResult->setOperand(1, NewSel);
761+
Builder.setInsertPoint(MiddleVPBB);
762+
Builder.createNaryOp(VPInstruction::BranchOnCond, AnyNaN);
763+
VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
764+
MiddleVPBB->swapSuccessors();
765+
std::swap(ScalarPH->getPredecessors()[1], ScalarPH->getPredecessors().back());
766+
return true;
767+
}

llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,7 @@ Value *VPInstruction::generate(VPTransformState &State) {
587587
Value *Op = State.get(getOperand(0), vputils::onlyFirstLaneUsed(this));
588588
return Builder.CreateFreeze(Op, Name);
589589
}
590+
case Instruction::FCmp:
590591
case Instruction::ICmp: {
591592
bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
592593
Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
@@ -863,7 +864,7 @@ Value *VPInstruction::generate(VPTransformState &State) {
863864
Value *Res = State.get(getOperand(0));
864865
for (VPValue *Op : drop_begin(operands()))
865866
Res = Builder.CreateOr(Res, State.get(Op));
866-
return Builder.CreateOrReduce(Res);
867+
return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
867868
}
868869
case VPInstruction::FirstActiveLane: {
869870
if (getNumOperands() == 1) {
@@ -1036,6 +1037,7 @@ bool VPInstruction::opcodeMayReadOrWriteFromMemory() const {
10361037
switch (getOpcode()) {
10371038
case Instruction::ExtractElement:
10381039
case Instruction::Freeze:
1040+
case Instruction::FCmp:
10391041
case Instruction::ICmp:
10401042
case Instruction::Select:
10411043
case VPInstruction::AnyOf:
@@ -1071,6 +1073,7 @@ bool VPInstruction::onlyFirstLaneUsed(const VPValue *Op) const {
10711073
return Op == getOperand(1);
10721074
case Instruction::PHI:
10731075
return true;
1076+
case Instruction::FCmp:
10741077
case Instruction::ICmp:
10751078
case Instruction::Select:
10761079
case Instruction::Or:
@@ -1103,6 +1106,7 @@ bool VPInstruction::onlyFirstPartUsed(const VPValue *Op) const {
11031106
switch (getOpcode()) {
11041107
default:
11051108
return false;
1109+
case Instruction::FCmp:
11061110
case Instruction::ICmp:
11071111
case Instruction::Select:
11081112
return vputils::onlyFirstPartUsed(this);
@@ -1787,7 +1791,7 @@ bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
17871791
return Opcode == Instruction::ZExt;
17881792
break;
17891793
case OperationType::Cmp:
1790-
return Opcode == Instruction::ICmp;
1794+
return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
17911795
case OperationType::Other:
17921796
return true;
17931797
}

llvm/lib/Transforms/Vectorize/VPlanTransforms.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,11 @@ struct VPlanTransforms {
9999
/// not valid.
100100
static bool adjustFixedOrderRecurrences(VPlan &Plan, VPBuilder &Builder);
101101

102+
/// Check if \p Plan contains any FMaxNumNoFMFs or FMinNumNoFMFs reductions.
103+
/// If they do, try to update the vector loop to exit early if any input is
104+
/// NaN and resume executing in the scalar loop to handle the NaNs there.
105+
static bool handleMaxMinNumReductionsWithoutFastMath(VPlan &Plan);
106+
102107
/// Clear NSW/NUW flags from reduction instructions if necessary.
103108
static void clearReductionWrapFlags(VPlan &Plan);
104109

0 commit comments

Comments
 (0)