Skip to content

[AArch64][LV] Reduce cost of scaled reduction extends #134074

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1693,6 +1693,15 @@ InstructionCost VPWidenRecipe::computeCost(ElementCount VF,
if (RHS->isLiveIn())
RHSInfo = Ctx.TTI.getOperandInfo(RHS->getLiveInIRValue());

// The mul is folded into another target instruction when participating
// in scaled reductions.
if (Opcode == Instruction::Mul && !hasMoreThanOneUniqueUser()) {
if (all_of(users(), [](const VPUser *U) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, if there is only one unique user then we don't actually need to walk over every user, right? Also hasMoreThanOneUniqueUser can return false if there are no users at all. I wonder if it's better to add a new getSingleUniqueUser interface that does something like:

  VPUser *getSingleUniqueUser() const {
    if (getNumUsers() == 0)
      return nullptr;

    // Check if all users match the first user.
    auto Current = user_begin();
    while (Current != user_end()) {
      if (*user_begin() != *Current)
        return nullptr;
      Current++;
    }
    return *Current;
  }

then you could do something like:

  if (Opcode == Instruction::Mul) {
    auto *SingleUser = getSingleUniqueUser();
    if (SingleUser && isa_and_present<VPPartialReductionRecipe>(SingleUser))
      return TTI::TCC_Free;
  }

return isa_and_present<VPPartialReductionRecipe>(U);
}))
return TTI::TCC_Free;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my comment on isScaledReductionExtension - I have concerns this is essentially AArch64-specific code being used for all targets.

}

if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
getOperand(1)->isDefinedOutsideLoopRegions())
RHSInfo.Kind = TargetTransformInfo::OK_UniformValue;
Expand Down Expand Up @@ -1757,6 +1766,43 @@ void VPWidenCastRecipe::execute(VPTransformState &State) {
setFlags(CastOp);
}

// Detects whether the extension should be folded away into a combined
// target instruction, and therefore given a cost of 0.
// Handles patterns similar to the following:
// * partial_reduce(ext, phi)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this supported yet? I do have a patch for this (#133922), but is still in review. I guess the comment doesn't do any harm, but it suggests it's something we already support that's all.

// * partial_reduce(mul(ext, ext), phi)
// * partial_reduce(sub(0, mul(ext, ext)), phi)
static bool isScaledReductionExtension(const VPWidenCastRecipe *Extend) {
unsigned Opcode = Extend->getOpcode();
if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt)
return false;

// Check that all users are either a partial reduction, or a multiply
// (and possibly subtract) used by a partial reduction.
return all_of(Extend->users(), [](const VPUser *U) {
// Look through a (possible) multiply.
if (const VPWidenRecipe *I = dyn_cast_if_present<VPWidenRecipe>(U)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, whilst this may be true for aarch64 I wonder if it's correct in general to assume that a partial reduction by definition folds a mul into a udot? It's my understanding that at the IR level partial reductions are far more abstract than just a udot or sdot. At the IR level we're simply partially reducing a set of values into a smaller set. It's quite conceivable that a target has support for this that doesn't involve muls, i.e. an instruction that sums up each 4 bytes of an input and accumulates in 32-bit result? In which case the mul is not free. At the moment this does like we're taking a AArch64 cost model and using it in a general way for everyone.

if (I->getOpcode() == Instruction::Mul) {
if (I->hasMoreThanOneUniqueUser())
return false;
U = *(I->user_begin());
}
}

// Look through a (possible) sub.
if (const VPWidenRecipe *I = dyn_cast_if_present<VPWidenRecipe>(U)) {
if (I->getOpcode() == Instruction::Sub) {
if (I->hasMoreThanOneUniqueUser())
return false;
U = *(I->user_begin());
}
}

// Final check that we end up contributing to a partial reduction.
return isa_and_present<VPPartialReductionRecipe>(U);
});
}

InstructionCost VPWidenCastRecipe::computeCost(ElementCount VF,
VPCostContext &Ctx) const {
// TODO: In some cases, VPWidenCastRecipes are created but not considered in
Expand Down Expand Up @@ -1796,6 +1842,10 @@ InstructionCost VPWidenCastRecipe::computeCost(ElementCount VF,
// For Z/Sext, get the context from the operand.
else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
Opcode == Instruction::FPExt) {
// If the extend is performed as part of another operation, it can be
// considered 'free'.
if (isScaledReductionExtension(this))
return TargetTransformInfo::TCC_Free;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible for the sext/zext to have multiple uses, i.e. one for the partial reduction and one used for something else? If so, then it won't be free. We might need to check that all uses are for partial reductions.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In fact, can't you just look at uses of this recipe and if all uses are for the VPPartialReductionRecipe then mark as free? I just wonder if this avoids having to keep a pointer set.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already do that, in VPRecipeBuilder::collectScaledReductions

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, then I think it would be good to have an assertion here at least, just in case that changes in future.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For our initial motivating use case (the AArch64 dot product instructions), there would be an extra recipe (a multiply) between the extends and the partial reduction. So we would need to look for uses of uses. I'm not sure if anyone has a case for more than one operation between the extends and the reduction, but I decided to keep it simple for now instead of walking the vplan.

If it's preferable to do the walk, then sure, I can convert it.

(I guess we could also make the multiply free, but so far that hasn't been an issue in using wider VFs)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Walking the plan would be needed for an assert anyway.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only free iff the target has an instruction that implements the partial reduction in a way that it folds in the extend. I think this warrants another CastContextHint enum value for the case where the extend is used in a partial reduction context. Then the TTI.getCastInstrCost can determine whether this is folded into the operation, and is therefore TCC_Free.

This does mean widening the meaning of CastContextHint beyond loads, but I can't see any fundamental reason why that hint should only be limited to loads.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a bit of a conflict there, though – the current code looks up the operand and calculates a CCH based on that, whereas this focuses on users. This would override the existing CCH... I guess we could do that if the current CCH is Normal or None, otherwise leave it as is?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the documentation for CastContextHint says:

/// Represents a hint about the context in which a cast is used.
///
/// For zext/sext, the context of the cast is the operand, which must be a
/// load of some kind. For trunc, the context is of the cast is the single
/// user of the instruction, which must be a store of some kind.

The first sentence suggests adding a new hint would make sense for this case, and the second part suggests that the interpretation is currently specific to loads/stores. For partial reductions, we'd indeed look at the single use.

This would override the existing CCH

If I read the code correctly for the zext/sext case it can only be set to TTI::CastContextHint::None at the point where you want to define it?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Immediately below my change is the code to look up the CCH based on the operand. I was imagining overriding the CCH after that code and letting the existing getCastInstrCost call below make use of the info. I think it'd be more appropriate that way – a normal load of <vscale x 16 x i8> can be used directly by an sdot instruction, whereas the result of a gather for the same type couldn't be.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't sound like a job for CCH, as it cannot handle the mul. In the long run I would expect this to work like #113903, where there is one vplan recipe that gets the entire cost of the extending reduction added to it. And we happily leave the legacy cost model behind us.

The mul should also be free, as in

if (auto RedCost = getReductionPatternCost(I, VF, VectorTy))
. I was hoping that #113903 would be done by now and we could have one solution for the two sets of extending reductions, that should ideally work the same. The mul should also be free though, and the entire cost of the dot should come from getPartialReductionCost.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the extend is free then it should be modeled similar to other special reductions in #113903 as @davemgreen mentioned.

Recipes should encapsulate all information required to compute their costs. Otherwise we may have to spread logic to detect those free extends to multiple places (e.g. register pressure computation).

This should also make it easier to perform a specific TTI query, instead of encoding some target-dependent knowledge directly in ::computeCost

if (Operand->isLiveIn())
CCH = TTI::CastContextHint::Normal;
else if (Operand->getDefiningRecipe())
Expand Down
Loading
Loading