Skip to content

Commit 91f14d3

Browse files
[LoopVectorize][AArch64][SVE] Generate wide active lane masks
This patch makes the LoopVectorize generate lane masks longer than the VF to allow the target to better utilise the instruction set. The vectorizer emit one or more wide `llvm.get.active.lane.mask.*` calls plus several `llvm.vector.extract.*` calls to yield the required number of VF-wide masks. The motivating exammple is a vectorised loop with unroll factor 2 that can use the SVE2.1 `whilelo` instruction with predicate pair result, or a SVE `whilelo` instruction with smaller element size plus `punpklo`/`punpkhi`. How wide is the lane mask that the vectoriser emits is controlled by a TargetTransformInfo hook `getMaxPredicateLength`.The default impementation (return the same length as the VF) keeps the change non-functional for targets that can't or are not prepared to handle wider lane masks.
1 parent 56a6f84 commit 91f14d3

23 files changed

+3097
-1198
lines changed

llvm/include/llvm/Analysis/TargetTransformInfo.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1241,6 +1241,8 @@ class TargetTransformInfo {
12411241
/// and the number of execution units in the CPU.
12421242
unsigned getMaxInterleaveFactor(ElementCount VF) const;
12431243

1244+
ElementCount getMaxPredicateLength(ElementCount VF) const;
1245+
12441246
/// Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
12451247
static OperandValueInfo getOperandInfo(const Value *V);
12461248

@@ -1998,6 +2000,9 @@ class TargetTransformInfo::Concept {
19982000
virtual bool shouldPrefetchAddressSpace(unsigned AS) const = 0;
19992001

20002002
virtual unsigned getMaxInterleaveFactor(ElementCount VF) = 0;
2003+
2004+
virtual ElementCount getMaxPredicateLength(ElementCount VF) const = 0;
2005+
20012006
virtual InstructionCost getArithmeticInstrCost(
20022007
unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
20032008
OperandValueInfo Opd1Info, OperandValueInfo Opd2Info,
@@ -2620,6 +2625,11 @@ class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
26202625
unsigned getMaxInterleaveFactor(ElementCount VF) override {
26212626
return Impl.getMaxInterleaveFactor(VF);
26222627
}
2628+
2629+
ElementCount getMaxPredicateLength(ElementCount VF) const override {
2630+
return Impl.getMaxPredicateLength(VF);
2631+
}
2632+
26232633
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
26242634
unsigned &JTSize,
26252635
ProfileSummaryInfo *PSI,

llvm/include/llvm/Analysis/TargetTransformInfoImpl.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,8 @@ class TargetTransformInfoImplBase {
531531

532532
unsigned getMaxInterleaveFactor(ElementCount VF) const { return 1; }
533533

534+
ElementCount getMaxPredicateLength(ElementCount VF) const { return VF; }
535+
534536
InstructionCost getArithmeticInstrCost(
535537
unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
536538
TTI::OperandValueInfo Opd1Info, TTI::OperandValueInfo Opd2Info,

llvm/include/llvm/CodeGen/BasicTTIImpl.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -888,6 +888,8 @@ class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
888888

889889
unsigned getMaxInterleaveFactor(ElementCount VF) { return 1; }
890890

891+
ElementCount getMaxPredicateLength(ElementCount VF) const { return VF; }
892+
891893
InstructionCost getArithmeticInstrCost(
892894
unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
893895
TTI::OperandValueInfo Opd1Info = {TTI::OK_AnyValue, TTI::OP_None},

llvm/lib/Analysis/TargetTransformInfo.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -816,6 +816,10 @@ unsigned TargetTransformInfo::getMaxInterleaveFactor(ElementCount VF) const {
816816
return TTIImpl->getMaxInterleaveFactor(VF);
817817
}
818818

819+
ElementCount TargetTransformInfo::getMaxPredicateLength(ElementCount VF) const {
820+
return TTIImpl->getMaxPredicateLength(VF);
821+
}
822+
819823
TargetTransformInfo::OperandValueInfo
820824
TargetTransformInfo::getOperandInfo(const Value *V) {
821825
OperandValueKind OpInfo = OK_AnyValue;

llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3383,6 +3383,15 @@ unsigned AArch64TTIImpl::getMaxInterleaveFactor(ElementCount VF) {
33833383
return ST->getMaxInterleaveFactor();
33843384
}
33853385

3386+
ElementCount AArch64TTIImpl::getMaxPredicateLength(ElementCount VF) const {
3387+
// Do not create masks bigger than `<vscale x 16 x i1>`.
3388+
unsigned N = ST->hasSVE() ? 16 : 0;
3389+
// Do not create masks that are more than twice the VF.
3390+
N = std::min(N, 2 * VF.getKnownMinValue());
3391+
return VF.isScalable() ? ElementCount::getScalable(N)
3392+
: ElementCount::getFixed(N);
3393+
}
3394+
33863395
// For Falkor, we want to avoid having too many strided loads in a loop since
33873396
// that can exhaust the HW prefetcher resources. We adjust the unroller
33883397
// MaxCount preference below to attempt to ensure unrolling doesn't create too

llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,8 @@ class AArch64TTIImpl : public BasicTTIImplBase<AArch64TTIImpl> {
157157

158158
unsigned getMaxInterleaveFactor(ElementCount VF);
159159

160+
ElementCount getMaxPredicateLength(ElementCount VF) const;
161+
160162
bool prefersVectorizedAddressing() const;
161163

162164
InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *Src,

llvm/lib/Transforms/Vectorize/LoopVectorizationPlanner.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,14 @@ class VPBuilder {
198198
VPValue *createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B,
199199
DebugLoc DL = {}, const Twine &Name = "");
200200

201+
VPValue *createGetActiveLaneMask(VPValue *IV, VPValue *TC, DebugLoc DL,
202+
const Twine &Name = "") {
203+
auto *ALM = new VPActiveLaneMaskRecipe(IV, TC, DL, Name);
204+
if (BB)
205+
BB->insert(ALM, InsertPt);
206+
return ALM;
207+
}
208+
201209
//===--------------------------------------------------------------------===//
202210
// RAII helpers.
203211
//===--------------------------------------------------------------------===//

llvm/lib/Transforms/Vectorize/LoopVectorize.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,10 @@ class InnerLoopVectorizer {
588588
/// count of the original loop for both main loop and epilogue vectorization.
589589
void setTripCount(Value *TC) { TripCount = TC; }
590590

591+
ElementCount getMaxPredicateLength(ElementCount VF) const {
592+
return TTI->getMaxPredicateLength(VF);
593+
}
594+
591595
protected:
592596
friend class LoopVectorizationPlanner;
593597

@@ -7525,7 +7529,8 @@ LoopVectorizationPlanner::executePlan(
75257529
LLVM_DEBUG(BestVPlan.dump());
75267530

75277531
// Perform the actual loop transformation.
7528-
VPTransformState State(BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan,
7532+
VPTransformState State(BestVF, BestUF, TTI.getMaxPredicateLength(BestVF), LI,
7533+
DT, ILV.Builder, &ILV, &BestVPlan,
75297534
OrigLoop->getHeader()->getContext());
75307535

75317536
// 0. Generate SCEV-dependent code into the preheader, including TripCount,

llvm/lib/Transforms/Vectorize/VPlan.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,12 +214,13 @@ VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
214214
return It;
215215
}
216216

217-
VPTransformState::VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,
217+
VPTransformState::VPTransformState(ElementCount VF, unsigned UF,
218+
ElementCount MaxPred, LoopInfo *LI,
218219
DominatorTree *DT, IRBuilderBase &Builder,
219220
InnerLoopVectorizer *ILV, VPlan *Plan,
220221
LLVMContext &Ctx)
221-
: VF(VF), UF(UF), LI(LI), DT(DT), Builder(Builder), ILV(ILV), Plan(Plan),
222-
LVer(nullptr),
222+
: VF(VF), UF(UF), MaxPred(MaxPred), LI(LI), DT(DT), Builder(Builder),
223+
ILV(ILV), Plan(Plan), LVer(nullptr),
223224
TypeAnalysis(Plan->getCanonicalIV()->getScalarType(), Ctx) {}
224225

225226
Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {

llvm/lib/Transforms/Vectorize/VPlan.h

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -234,13 +234,14 @@ struct VPIteration {
234234
/// VPTransformState holds information passed down when "executing" a VPlan,
235235
/// needed for generating the output IR.
236236
struct VPTransformState {
237-
VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,
238-
DominatorTree *DT, IRBuilderBase &Builder,
237+
VPTransformState(ElementCount VF, unsigned UF, ElementCount MaxPred,
238+
LoopInfo *LI, DominatorTree *DT, IRBuilderBase &Builder,
239239
InnerLoopVectorizer *ILV, VPlan *Plan, LLVMContext &Ctx);
240240

241241
/// The chosen Vectorization and Unroll Factors of the loop being vectorized.
242242
ElementCount VF;
243243
unsigned UF;
244+
ElementCount MaxPred;
244245

245246
/// Hold the indices to generate specific scalar instructions. Null indicates
246247
/// that all instances are to be generated, using either scalar or vector
@@ -1168,7 +1169,6 @@ class VPInstruction : public VPRecipeWithIRFlags {
11681169
Not,
11691170
SLPLoad,
11701171
SLPStore,
1171-
ActiveLaneMask,
11721172
ExplicitVectorLength,
11731173
CalculateTripCountMinusVF,
11741174
// Increment the canonical IV separately for each unrolled part.
@@ -1322,6 +1322,50 @@ class VPInstruction : public VPRecipeWithIRFlags {
13221322
}
13231323
};
13241324

1325+
class VPActiveLaneMaskRecipe : public VPRecipeWithIRFlags {
1326+
const std::string Name;
1327+
1328+
public:
1329+
VPActiveLaneMaskRecipe(VPValue *IV, VPValue *TC, DebugLoc DL = {},
1330+
const Twine &Name = "")
1331+
: VPRecipeWithIRFlags(VPDef::VPActiveLaneMaskSC,
1332+
std::initializer_list<VPValue *>{IV, TC}, DL),
1333+
Name(Name.str()) {}
1334+
1335+
VP_CLASSOF_IMPL(VPDef::VPActiveLaneMaskSC)
1336+
1337+
VPActiveLaneMaskRecipe *clone() override {
1338+
SmallVector<VPValue *, 2> Operands(operands());
1339+
assert(Operands.size() == 2 && "by construction");
1340+
auto *New = new VPActiveLaneMaskRecipe(Operands[0], Operands[1],
1341+
getDebugLoc(), Name);
1342+
New->transferFlags(*this);
1343+
return New;
1344+
}
1345+
1346+
void execute(VPTransformState &State) override;
1347+
1348+
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1349+
/// Print the recipe.
1350+
void print(raw_ostream &O, const Twine &Indent,
1351+
VPSlotTracker &SlotTracker) const override;
1352+
#endif
1353+
1354+
bool onlyFirstLaneUsed(const VPValue *Op) const override {
1355+
assert(is_contained(operands(), Op) &&
1356+
"Op must be an operand of the recipe");
1357+
1358+
return true;
1359+
}
1360+
1361+
bool onlyFirstPartUsed(const VPValue *Op) const override {
1362+
assert(is_contained(operands(), Op) &&
1363+
"Op must be an operand of the recipe");
1364+
1365+
return false;
1366+
}
1367+
};
1368+
13251369
/// VPWidenRecipe is a recipe for producing a copy of vector type its
13261370
/// ingredient. This recipe covers most of the traditional vectorization cases
13271371
/// where each ingredient transforms into a vectorized version of itself.

llvm/lib/Transforms/Vectorize/VPlanPatternMatch.h

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -216,11 +216,6 @@ m_BranchOnCond(const Op0_t &Op0) {
216216
return m_VPInstruction<VPInstruction::BranchOnCond>(Op0);
217217
}
218218

219-
template <typename Op0_t, typename Op1_t>
220-
inline BinaryVPInstruction_match<Op0_t, Op1_t, VPInstruction::ActiveLaneMask>
221-
m_ActiveLaneMask(const Op0_t &Op0, const Op1_t &Op1) {
222-
return m_VPInstruction<VPInstruction::ActiveLaneMask>(Op0, Op1);
223-
}
224219

225220
template <typename Op0_t, typename Op1_t>
226221
inline BinaryVPInstruction_match<Op0_t, Op1_t, VPInstruction::BranchOnCount>
@@ -273,6 +268,35 @@ inline AllBinaryRecipe_match<Op0_t, Op1_t, Instruction::Or>
273268
m_Or(const Op0_t &Op0, const Op1_t &Op1) {
274269
return m_Binary<Instruction::Or, Op0_t, Op1_t>(Op0, Op1);
275270
}
271+
272+
template <typename Op0_t, typename Op1_t>
273+
struct VPActiveLaneMask_match {
274+
Op0_t Op0;
275+
Op1_t Op1;
276+
277+
VPActiveLaneMask_match(Op0_t Op0, Op1_t Op1) : Op0(Op0), Op1(Op1) {}
278+
279+
bool match(const VPValue *V) {
280+
auto *DefR = V->getDefiningRecipe();
281+
return DefR && match(DefR);
282+
}
283+
284+
bool match(const VPRecipeBase *R) {
285+
auto *DefR = dyn_cast<VPActiveLaneMaskRecipe>(R);
286+
if (!DefR)
287+
return false;
288+
assert(DefR->getNumOperands() == 2 &&
289+
"recipe with matched opcode does not have 2 operands");
290+
return Op0.match(DefR->getOperand(0)) && Op1.match(DefR->getOperand(1));
291+
}
292+
};
293+
294+
template <typename Op0_t, typename Op1_t>
295+
inline VPActiveLaneMask_match<Op0_t, Op1_t>
296+
m_ActiveLaneMask(const Op0_t &Op0, const Op1_t &Op1) {
297+
return {Op0, Op1};
298+
}
299+
276300
} // namespace VPlanPatternMatch
277301
} // namespace llvm
278302

llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp

Lines changed: 86 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -343,24 +343,7 @@ Value *VPInstruction::generatePerPart(VPTransformState &State, unsigned Part) {
343343
Value *Op2 = State.get(getOperand(2), Part);
344344
return Builder.CreateSelect(Cond, Op1, Op2, Name);
345345
}
346-
case VPInstruction::ActiveLaneMask: {
347-
// Get first lane of vector induction variable.
348-
Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
349-
// Get the original loop tripcount.
350-
Value *ScalarTC = State.get(getOperand(1), VPIteration(Part, 0));
351346

352-
// If this part of the active lane mask is scalar, generate the CMP directly
353-
// to avoid unnecessary extracts.
354-
if (State.VF.isScalar())
355-
return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
356-
Name);
357-
358-
auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
359-
auto *PredTy = VectorType::get(Int1Ty, State.VF);
360-
return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
361-
{PredTy, ScalarTC->getType()},
362-
{VIVElem0, ScalarTC}, nullptr, Name);
363-
}
364347
case VPInstruction::FirstOrderRecurrenceSplice: {
365348
// Generate code to combine the previous and current values in vector v3.
366349
//
@@ -624,7 +607,6 @@ bool VPInstruction::onlyFirstLaneUsed(const VPValue *Op) const {
624607
case VPInstruction::PtrAdd:
625608
// TODO: Cover additional opcodes.
626609
return vputils::onlyFirstLaneUsed(this);
627-
case VPInstruction::ActiveLaneMask:
628610
case VPInstruction::ExplicitVectorLength:
629611
case VPInstruction::CalculateTripCountMinusVF:
630612
case VPInstruction::CanonicalIVIncrementForPart:
@@ -659,9 +641,6 @@ void VPInstruction::print(raw_ostream &O, const Twine &Indent,
659641
case VPInstruction::SLPStore:
660642
O << "combined store";
661643
break;
662-
case VPInstruction::ActiveLaneMask:
663-
O << "active lane mask";
664-
break;
665644
case VPInstruction::ExplicitVectorLength:
666645
O << "EXPLICIT-VECTOR-LENGTH";
667646
break;
@@ -698,8 +677,94 @@ void VPInstruction::print(raw_ostream &O, const Twine &Indent,
698677
DL.print(O);
699678
}
700679
}
680+
681+
void VPActiveLaneMaskRecipe::print(raw_ostream &O, const Twine &Indent,
682+
VPSlotTracker &SlotTracker) const {
683+
O << Indent << "EMIT ";
684+
685+
printAsOperand(O, SlotTracker);
686+
O << " = active lane mask";
687+
printFlags(O);
688+
printOperands(O, SlotTracker);
689+
690+
if (auto DL = getDebugLoc()) {
691+
O << ", !dbg ";
692+
DL.print(O);
693+
}
694+
}
695+
701696
#endif
702697

698+
void VPActiveLaneMaskRecipe::execute(VPTransformState &State) {
699+
assert(!State.Instance && "VPInstruction executing an Instance");
700+
701+
IRBuilderBase &Builder = State.Builder;
702+
Builder.SetCurrentDebugLocation(getDebugLoc());
703+
704+
// If this the active lane mask is scalar, generate the CMP directly
705+
// to avoid unnecessary extracts.
706+
if (State.VF.isScalar()) {
707+
for (int Part = State.UF - 1; Part >= 0; --Part) {
708+
// Get first lane of vector induction variable.
709+
Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
710+
// Get the original loop tripcount.
711+
Value *ScalarTC = State.get(getOperand(1), VPIteration(0, 0));
712+
713+
Value *V = Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0,
714+
ScalarTC, Name);
715+
State.set(this, V, Part);
716+
}
717+
return;
718+
}
719+
720+
auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
721+
auto *PredTy = VectorType::get(Int1Ty, State.VF);
722+
723+
unsigned MaxPred = std::min(State.MaxPred.getKnownMinValue(),
724+
State.UF * State.VF.getKnownMinValue());
725+
if (State.UF <= 1 || MaxPred <= State.VF.getKnownMinValue() ||
726+
MaxPred % State.VF.getKnownMinValue() != 0) {
727+
for (int Part = State.UF - 1; Part >= 0; --Part) {
728+
// Get first lane of vector induction variable.
729+
Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
730+
// Get the original loop tripcount.
731+
Value *ScalarTC = State.get(getOperand(1), VPIteration(0, 0));
732+
Value *V = Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
733+
{PredTy, ScalarTC->getType()},
734+
{VIVElem0, ScalarTC}, nullptr, Name);
735+
State.set(this, V, Part);
736+
}
737+
return;
738+
}
739+
740+
// Generate long active lane masks covering all the unrolled iterations.
741+
unsigned PartsPerMask = MaxPred / State.VF.getKnownMinValue();
742+
auto *LongPredTy = VectorType::get(Int1Ty, MaxPred, State.VF.isScalable());
743+
SmallVector<Value *> LongMask(State.UF / PartsPerMask, nullptr);
744+
for (int Part = State.UF - PartsPerMask; Part >= 0; Part -= PartsPerMask) {
745+
// Get first lane of vector induction variable.
746+
Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
747+
// Get the original loop tripcount.
748+
Value *ScalarTC = State.get(getOperand(1), VPIteration(0, 0));
749+
Value *V = Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
750+
{LongPredTy, ScalarTC->getType()},
751+
{VIVElem0, ScalarTC}, nullptr, Name);
752+
LongMask[Part / PartsPerMask] = V;
753+
}
754+
755+
for (int Part = State.UF - 1; Part >= 0; --Part) {
756+
Value *ALM = LongMask[Part / PartsPerMask];
757+
const unsigned I = Part % PartsPerMask;
758+
Value *V = Builder.CreateIntrinsic(
759+
Intrinsic::vector_extract, {PredTy, ALM->getType()},
760+
{ALM, ConstantInt::get(Type::getInt64Ty(Builder.getContext()),
761+
I * State.VF.getKnownMinValue())},
762+
nullptr, Name);
763+
764+
State.set(this, V, Part);
765+
}
766+
}
767+
703768
void VPWidenCallRecipe::execute(VPTransformState &State) {
704769
assert(State.VF.isVector() && "not widening");
705770
auto &CI = *cast<CallInst>(getUnderlyingInstr());

0 commit comments

Comments
 (0)