Skip to content

Commit 1201e54

Browse files
david-armMDevereau
authored andcommitted
[LV] Add support for partial reductions without a binary op
Consider IR such as this: for.body: %iv = phi i64 [ 0, %entry ], [ %iv.next, %for.body ] %accum = phi i32 [ 0, %entry ], [ %add, %for.body ] %gep.a = getelementptr i8, ptr %a, i64 %iv %load.a = load i8, ptr %gep.a, align 1 %ext.a = zext i8 %load.a to i32 %add = add i32 %ext.a, %accum %iv.next = add i64 %iv, 1 %exitcond.not = icmp eq i64 %iv.next, 1025 br i1 %exitcond.not, label %for.exit, label %for.body Conceptually we can vectorise this using partial reductions too, although the current loop vectoriser implementation requires the accumulation of a multiply. For AArch64 this is easily done with a udot or sdot with an identity operand, i.e. a vector of (i16 1). In order to do this I had to teach getScaledReductions that the accumulated value may come from a unary op, hence there is only one extension to consider. Similarly, I updated the vplan and AArch64 TTI cost model to understand the possible unary op.
1 parent 319338a commit 1201e54

File tree

11 files changed

+345
-282
lines changed

11 files changed

+345
-282
lines changed

llvm/include/llvm/Analysis/TargetTransformInfo.h

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1325,9 +1325,21 @@ class TargetTransformInfo {
13251325
/// \return The cost of a partial reduction, which is a reduction from a
13261326
/// vector to another vector with fewer elements of larger size. They are
13271327
/// represented by the llvm.experimental.partial.reduce.add intrinsic, which
1328-
/// takes an accumulator and a binary operation operand that itself is fed by
1329-
/// two extends. An example of an operation that uses a partial reduction is a
1330-
/// dot product, which reduces two vectors to another of 4 times fewer and 4
1328+
/// takes an accumulator of type \p AccumType and a second vector operand to
1329+
/// be accumulated, whose element count is specified by \p VF. The type of
1330+
/// reduction is specified by \p Opcode. The second operand passed to the
1331+
/// intrinsic could be the result of an extend, such as sext or zext. In
1332+
/// this case \p BinOp is nullopt, \p InputTypeA represents the type being
1333+
/// extended and \p OpAExtend the operation, i.e. sign- or zero-extend.
1334+
/// Also, \p InputTypeB should be nullptr and OpBExtend should be None.
1335+
/// Alternatively, the second operand could be the result of a binary
1336+
/// operation performed on two extends, i.e.
1337+
/// mul(zext i8 %a -> i32, zext i8 %b -> i32).
1338+
/// In this case \p BinOp may specify the opcode of the binary operation,
1339+
/// \p InputTypeA and \p InputTypeB the types being extended, and
1340+
/// \p OpAExtend, \p OpBExtend the form of extensions. An example of an
1341+
/// operation that uses a partial reduction is a dot product, which reduces
1342+
/// two vectors in binary mul operation to another of 4 times fewer and 4
13311343
/// times larger elements.
13321344
LLVM_ABI InstructionCost getPartialReductionCost(
13331345
unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType,

llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5402,11 +5402,21 @@ InstructionCost AArch64TTIImpl::getPartialReductionCost(
54025402

54035403
// Sub opcodes currently only occur in chained cases.
54045404
// Independent partial reduction subtractions are still costed as an add
5405-
if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
5405+
if ((Opcode != Instruction::Add && Opcode != Instruction::Sub) ||
5406+
OpAExtend == TTI::PR_None)
54065407
return Invalid;
54075408

5408-
if (InputTypeA != InputTypeB)
5409+
// We only support multiply binary operations for now, and for muls we
5410+
// require the types being extended to be the same.
5411+
// NOTE: For muls AArch64 supports lowering mixed extensions to a usdot but
5412+
// only if the i8mm or sve/streaming features are available.
5413+
if (BinOp && (*BinOp != Instruction::Mul || InputTypeA != InputTypeB ||
5414+
OpBExtend == TTI::PR_None ||
5415+
(OpAExtend != OpBExtend && !ST->hasMatMulInt8() &&
5416+
!ST->isSVEorStreamingSVEAvailable())))
54095417
return Invalid;
5418+
assert((BinOp || (OpBExtend == TTI::PR_None && !InputTypeB)) &&
5419+
"Unexpected values for OpBExtend or InputTypeB");
54105420

54115421
EVT InputEVT = EVT::getEVT(InputTypeA);
54125422
EVT AccumEVT = EVT::getEVT(AccumType);
@@ -5453,15 +5463,6 @@ InstructionCost AArch64TTIImpl::getPartialReductionCost(
54535463
} else
54545464
return Invalid;
54555465

5456-
// AArch64 supports lowering mixed fixed-width extensions to a usdot but only
5457-
// if the i8mm feature is available.
5458-
if (OpAExtend == TTI::PR_None || OpBExtend == TTI::PR_None ||
5459-
(OpAExtend != OpBExtend && !ST->hasMatMulInt8()))
5460-
return Invalid;
5461-
5462-
if (!BinOp || *BinOp != Instruction::Mul)
5463-
return Invalid;
5464-
54655466
return Cost;
54665467
}
54675468

llvm/lib/Transforms/Vectorize/LoopVectorize.cpp

Lines changed: 60 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -8150,15 +8150,15 @@ void VPRecipeBuilder::collectScaledReductions(VFRange &Range) {
81508150
// something that isn't another partial reduction. This is because the
81518151
// extends are intended to be lowered along with the reduction itself.
81528152

8153-
// Build up a set of partial reduction bin ops for efficient use checking.
8154-
SmallSet<User *, 4> PartialReductionBinOps;
8153+
// Build up a set of partial reduction ops for efficient use checking.
8154+
SmallSet<User *, 4> PartialReductionOps;
81558155
for (const auto &[PartialRdx, _] : PartialReductionChains)
8156-
PartialReductionBinOps.insert(PartialRdx.BinOp);
8156+
PartialReductionOps.insert(PartialRdx.ExtendUser);
81578157

81588158
auto ExtendIsOnlyUsedByPartialReductions =
8159-
[&PartialReductionBinOps](Instruction *Extend) {
8159+
[&PartialReductionOps](Instruction *Extend) {
81608160
return all_of(Extend->users(), [&](const User *U) {
8161-
return PartialReductionBinOps.contains(U);
8161+
return PartialReductionOps.contains(U);
81628162
});
81638163
};
81648164

@@ -8167,15 +8167,14 @@ void VPRecipeBuilder::collectScaledReductions(VFRange &Range) {
81678167
for (auto Pair : PartialReductionChains) {
81688168
PartialReductionChain Chain = Pair.first;
81698169
if (ExtendIsOnlyUsedByPartialReductions(Chain.ExtendA) &&
8170-
ExtendIsOnlyUsedByPartialReductions(Chain.ExtendB))
8170+
(!Chain.ExtendB || ExtendIsOnlyUsedByPartialReductions(Chain.ExtendB)))
81718171
ScaledReductionMap.try_emplace(Chain.Reduction, Pair.second);
81728172
}
81738173
}
81748174

81758175
bool VPRecipeBuilder::getScaledReductions(
81768176
Instruction *PHI, Instruction *RdxExitInstr, VFRange &Range,
81778177
SmallVectorImpl<std::pair<PartialReductionChain, unsigned>> &Chains) {
8178-
81798178
if (!CM.TheLoop->contains(RdxExitInstr))
81808179
return false;
81818180

@@ -8204,43 +8203,75 @@ bool VPRecipeBuilder::getScaledReductions(
82048203
if (PhiOp != PHI)
82058204
return false;
82068205

8207-
auto *BinOp = dyn_cast<BinaryOperator>(Op);
8208-
if (!BinOp || !BinOp->hasOneUse())
8209-
return false;
8210-
82118206
using namespace llvm::PatternMatch;
8212-
// Use the side-effect of match to replace BinOp only if the pattern is
8213-
// matched, we don't care at this point whether it actually matched.
8214-
match(BinOp, m_Neg(m_BinOp(BinOp)));
82158207

8216-
Value *A, *B;
8217-
if (!match(BinOp->getOperand(0), m_ZExtOrSExt(m_Value(A))) ||
8218-
!match(BinOp->getOperand(1), m_ZExtOrSExt(m_Value(B))))
8219-
return false;
8208+
// If the update is a binary operator, check both of its operands to see if
8209+
// they are extends. Otherwise, see if the update comes directly from an
8210+
// extend.
8211+
Instruction *Exts[2] = {nullptr};
8212+
BinaryOperator *ExtendUser = dyn_cast<BinaryOperator>(Op);
8213+
std::optional<unsigned> BinOpc;
8214+
Type *ExtOpTypes[2] = {nullptr};
8215+
8216+
auto CollectExtInfo = [&Exts,
8217+
&ExtOpTypes](SmallVectorImpl<Value *> &Ops) -> bool {
8218+
unsigned I = 0;
8219+
for (Value *OpI : Ops) {
8220+
Value *ExtOp;
8221+
if (!match(OpI, m_ZExtOrSExt(m_Value(ExtOp))))
8222+
return false;
8223+
Exts[I] = cast<Instruction>(OpI);
8224+
ExtOpTypes[I] = ExtOp->getType();
8225+
I++;
8226+
}
8227+
return true;
8228+
};
8229+
8230+
if (ExtendUser) {
8231+
if (!ExtendUser->hasOneUse())
8232+
return false;
82208233

8221-
Instruction *ExtA = cast<Instruction>(BinOp->getOperand(0));
8222-
Instruction *ExtB = cast<Instruction>(BinOp->getOperand(1));
8234+
// Use the side-effect of match to replace BinOp only if the pattern is
8235+
// matched, we don't care at this point whether it actually matched.
8236+
match(ExtendUser, m_Neg(m_BinOp(ExtendUser)));
8237+
8238+
SmallVector<Value *> Ops(ExtendUser->operands());
8239+
if (!CollectExtInfo(Ops))
8240+
return false;
8241+
8242+
BinOpc = std::make_optional(ExtendUser->getOpcode());
8243+
} else if (match(Update, m_Add(m_Value(), m_Value()))) {
8244+
// We already know the operands for Update are Op and PhiOp.
8245+
SmallVector<Value *> Ops({Op});
8246+
if (!CollectExtInfo(Ops))
8247+
return false;
8248+
8249+
ExtendUser = Update;
8250+
BinOpc = std::nullopt;
8251+
} else
8252+
return false;
82238253

82248254
TTI::PartialReductionExtendKind OpAExtend =
8225-
TargetTransformInfo::getPartialReductionExtendKind(ExtA);
8255+
TargetTransformInfo::getPartialReductionExtendKind(Exts[0]);
82268256
TTI::PartialReductionExtendKind OpBExtend =
8227-
TargetTransformInfo::getPartialReductionExtendKind(ExtB);
8228-
8229-
PartialReductionChain Chain(RdxExitInstr, ExtA, ExtB, BinOp);
8257+
Exts[1] ? TargetTransformInfo::getPartialReductionExtendKind(Exts[1])
8258+
: TargetTransformInfo::PR_None;
8259+
PartialReductionChain Chain(RdxExitInstr, Exts[0], Exts[1], ExtendUser);
82308260

82318261
TypeSize PHISize = PHI->getType()->getPrimitiveSizeInBits();
8232-
TypeSize ASize = A->getType()->getPrimitiveSizeInBits();
8233-
8262+
TypeSize ASize = ExtOpTypes[0]->getPrimitiveSizeInBits();
82348263
if (!PHISize.hasKnownScalarFactor(ASize))
82358264
return false;
82368265

8237-
unsigned TargetScaleFactor = PHISize.getKnownScalarFactor(ASize);
8266+
unsigned TargetScaleFactor =
8267+
PHI->getType()->getPrimitiveSizeInBits().getKnownScalarFactor(
8268+
ExtOpTypes[0]->getPrimitiveSizeInBits());
82388269

82398270
if (LoopVectorizationPlanner::getDecisionAndClampRange(
82408271
[&](ElementCount VF) {
82418272
InstructionCost Cost = TTI->getPartialReductionCost(
8242-
Update->getOpcode(), A->getType(), B->getType(), PHI->getType(),
8243-
VF, OpAExtend, OpBExtend, BinOp->getOpcode());
8273+
Update->getOpcode(), ExtOpTypes[0], ExtOpTypes[1],
8274+
PHI->getType(), VF, OpAExtend, OpBExtend, BinOpc);
82448275
return Cost.isValid();
82458276
},
82468277
Range)) {

llvm/lib/Transforms/Vectorize/VPRecipeBuilder.h

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,22 +24,23 @@ struct HistogramInfo;
2424
struct VFRange;
2525

2626
/// A chain of instructions that form a partial reduction.
27-
/// Designed to match: reduction_bin_op (bin_op (extend (A), (extend (B))),
28-
/// accumulator).
27+
/// Designed to match either:
28+
/// reduction_bin_op (extend (A), accumulator), or
29+
/// reduction_bin_op (bin_op (extend (A), (extend (B))), accumulator).
2930
struct PartialReductionChain {
3031
PartialReductionChain(Instruction *Reduction, Instruction *ExtendA,
31-
Instruction *ExtendB, Instruction *BinOp)
32-
: Reduction(Reduction), ExtendA(ExtendA), ExtendB(ExtendB), BinOp(BinOp) {
33-
}
32+
Instruction *ExtendB, Instruction *ExtendUser)
33+
: Reduction(Reduction), ExtendA(ExtendA), ExtendB(ExtendB),
34+
ExtendUser(ExtendUser) {}
3435
/// The top-level binary operation that forms the reduction to a scalar
3536
/// after the loop body.
3637
Instruction *Reduction;
3738
/// The extension of each of the inner binary operation's operands.
3839
Instruction *ExtendA;
3940
Instruction *ExtendB;
4041

41-
/// The binary operation using the extends that is then reduced.
42-
Instruction *BinOp;
42+
/// The user of the extend that is then reduced.
43+
Instruction *ExtendUser;
4344
};
4445

4546
/// Helper class to create VPRecipies from IR instructions.

llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp

Lines changed: 46 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -296,34 +296,21 @@ bool VPRecipeBase::isScalarCast() const {
296296
InstructionCost
297297
VPPartialReductionRecipe::computeCost(ElementCount VF,
298298
VPCostContext &Ctx) const {
299-
std::optional<unsigned> Opcode = std::nullopt;
300-
VPValue *BinOp = getOperand(1);
299+
std::optional<unsigned> Opcode;
300+
VPValue *Op = getOperand(0);
301+
VPRecipeBase *OpR = Op->getDefiningRecipe();
301302

302-
// If the partial reduction is predicated, a select will be operand 0 rather
303-
// than the binary op
303+
// If the partial reduction is predicated, a select will be operand 0
304304
using namespace llvm::VPlanPatternMatch;
305-
if (match(getOperand(1), m_Select(m_VPValue(), m_VPValue(), m_VPValue())))
306-
BinOp = BinOp->getDefiningRecipe()->getOperand(1);
307-
308-
// If BinOp is a negation, use the side effect of match to assign the actual
309-
// binary operation to BinOp
310-
match(BinOp, m_Binary<Instruction::Sub>(m_SpecificInt(0), m_VPValue(BinOp)));
311-
VPRecipeBase *BinOpR = BinOp->getDefiningRecipe();
312-
313-
if (auto *WidenR = dyn_cast<VPWidenRecipe>(BinOpR))
314-
Opcode = std::make_optional(WidenR->getOpcode());
315-
316-
VPRecipeBase *ExtAR = BinOpR->getOperand(0)->getDefiningRecipe();
317-
VPRecipeBase *ExtBR = BinOpR->getOperand(1)->getDefiningRecipe();
305+
if (match(getOperand(1), m_Select(m_VPValue(), m_VPValue(Op), m_VPValue()))) {
306+
OpR = Op->getDefiningRecipe();
307+
}
318308

319-
auto *PhiType = Ctx.Types.inferScalarType(getOperand(1));
320-
auto *InputTypeA = Ctx.Types.inferScalarType(ExtAR ? ExtAR->getOperand(0)
321-
: BinOpR->getOperand(0));
322-
auto *InputTypeB = Ctx.Types.inferScalarType(ExtBR ? ExtBR->getOperand(0)
323-
: BinOpR->getOperand(1));
309+
Type *InputTypeA = nullptr, *InputTypeB = nullptr;
310+
TTI::PartialReductionExtendKind ExtAType = TargetTransformInfo::PR_None,
311+
ExtBType = TargetTransformInfo::PR_None;
324312

325313
auto GetExtendKind = [](VPRecipeBase *R) {
326-
// The extend could come from outside the plan.
327314
if (!R)
328315
return TargetTransformInfo::PR_None;
329316
auto *WidenCastR = dyn_cast<VPWidenCastRecipe>(R);
@@ -336,9 +323,43 @@ VPPartialReductionRecipe::computeCost(ElementCount VF,
336323
return TargetTransformInfo::PR_None;
337324
};
338325

326+
// Pick out opcode, type/ext information and use sub side effects from a widen recipe.
327+
auto HandleWiden = [&](VPWidenRecipe* Widen){
328+
if (match(Widen,
329+
m_Binary<Instruction::Sub>(m_SpecificInt(0), m_VPValue(Op)))) {
330+
Widen = dyn_cast<VPWidenRecipe>(Op->getDefiningRecipe());
331+
}
332+
Opcode = Widen->getOpcode();
333+
VPRecipeBase *ExtAR = Widen->getOperand(0)->getDefiningRecipe();
334+
VPRecipeBase *ExtBR = Widen->getOperand(1)->getDefiningRecipe();
335+
InputTypeA = Ctx.Types.inferScalarType(ExtAR ? ExtAR->getOperand(0)
336+
: Widen->getOperand(0));
337+
InputTypeB = Ctx.Types.inferScalarType(ExtBR ? ExtBR->getOperand(0)
338+
: Widen->getOperand(1));
339+
ExtAType = GetExtendKind(ExtAR);
340+
ExtBType = GetExtendKind(ExtBR);
341+
};
342+
343+
if (isa<VPWidenCastRecipe>(OpR)) {
344+
InputTypeA = Ctx.Types.inferScalarType(OpR->getOperand(0));
345+
ExtAType = GetExtendKind(OpR);
346+
} else if (isa<VPReductionPHIRecipe>(OpR)) {
347+
auto RedPhiOp1R = getOperand(1)->getDefiningRecipe();
348+
if (isa<VPWidenCastRecipe>(RedPhiOp1R)) {
349+
InputTypeA = Ctx.Types.inferScalarType(RedPhiOp1R->getOperand(0));
350+
ExtAType = GetExtendKind(RedPhiOp1R);
351+
} else if (auto Widen = dyn_cast<VPWidenRecipe>(RedPhiOp1R))
352+
HandleWiden(Widen);
353+
} else if (auto Widen = dyn_cast<VPWidenRecipe>(OpR)) {
354+
HandleWiden(Widen);
355+
} else if (auto Reduction = dyn_cast<VPPartialReductionRecipe>(OpR)) {
356+
return Reduction->computeCost(VF, Ctx);
357+
}
358+
359+
auto *PhiType = Ctx.Types.inferScalarType(getOperand(1));
339360
return Ctx.TTI.getPartialReductionCost(getOpcode(), InputTypeA, InputTypeB,
340-
PhiType, VF, GetExtendKind(ExtAR),
341-
GetExtendKind(ExtBR), Opcode);
361+
PhiType, VF, ExtAType, ExtBType,
362+
Opcode);
342363
}
343364

344365
void VPPartialReductionRecipe::execute(VPTransformState &State) {

llvm/test/CodeGen/AArch64/neon-partial-reduce-dot-product.ll

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1233,4 +1233,3 @@ entry:
12331233
%partial.reduce = tail call <2 x i64> @llvm.experimental.vector.partial.reduce.add(<2 x i64> %acc, <8 x i64> %input.wide)
12341234
ret <2 x i64> %partial.reduce
12351235
}
1236-

0 commit comments

Comments
 (0)