Skip to content

Commit 39f1b89

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 af024dd commit 39f1b89

20 files changed

+3244
-1386
lines changed

llvm/include/llvm/Analysis/TargetTransformInfo.h

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

1231+
ElementCount getMaxPredicateLength(ElementCount VF) const;
1232+
12311233
/// Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
12321234
static OperandValueInfo getOperandInfo(const Value *V);
12331235

@@ -1981,6 +1983,9 @@ class TargetTransformInfo::Concept {
19811983
virtual bool shouldPrefetchAddressSpace(unsigned AS) const = 0;
19821984

19831985
virtual unsigned getMaxInterleaveFactor(ElementCount VF) = 0;
1986+
1987+
virtual ElementCount getMaxPredicateLength(ElementCount VF) const = 0;
1988+
19841989
virtual InstructionCost getArithmeticInstrCost(
19851990
unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
19861991
OperandValueInfo Opd1Info, OperandValueInfo Opd2Info,
@@ -2601,6 +2606,11 @@ class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
26012606
unsigned getMaxInterleaveFactor(ElementCount VF) override {
26022607
return Impl.getMaxInterleaveFactor(VF);
26032608
}
2609+
2610+
ElementCount getMaxPredicateLength(ElementCount VF) const override {
2611+
return Impl.getMaxPredicateLength(VF);
2612+
}
2613+
26042614
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
26052615
unsigned &JTSize,
26062616
ProfileSummaryInfo *PSI,

llvm/include/llvm/Analysis/TargetTransformInfoImpl.h

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

529529
unsigned getMaxInterleaveFactor(ElementCount VF) const { return 1; }
530530

531+
ElementCount getMaxPredicateLength(ElementCount VF) const { return VF; }
532+
531533
InstructionCost getArithmeticInstrCost(
532534
unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
533535
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
@@ -881,6 +881,8 @@ class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
881881

882882
unsigned getMaxInterleaveFactor(ElementCount VF) { return 1; }
883883

884+
ElementCount getMaxPredicateLength(ElementCount VF) const { return VF; }
885+
884886
InstructionCost getArithmeticInstrCost(
885887
unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
886888
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
@@ -808,6 +808,10 @@ unsigned TargetTransformInfo::getMaxInterleaveFactor(ElementCount VF) const {
808808
return TTIImpl->getMaxInterleaveFactor(VF);
809809
}
810810

811+
ElementCount TargetTransformInfo::getMaxPredicateLength(ElementCount VF) const {
812+
return TTIImpl->getMaxPredicateLength(VF);
813+
}
814+
811815
TargetTransformInfo::OperandValueInfo
812816
TargetTransformInfo::getOperandInfo(const Value *V) {
813817
OperandValueKind OpInfo = OK_AnyValue;

llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp

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

3288+
ElementCount AArch64TTIImpl::getMaxPredicateLength(ElementCount VF) const {
3289+
// Do not create masks bigger than `<vscale x 16 x i1>`.
3290+
unsigned N = ST->hasSVE() ? 16 : 0;
3291+
// Do not create masks that are more than twice the VF.
3292+
N = std::min(N, 2 * VF.getKnownMinValue());
3293+
return VF.isScalable() ? ElementCount::getScalable(N)
3294+
: ElementCount::getFixed(N);
3295+
}
3296+
32883297
// For Falkor, we want to avoid having too many strided loads in a loop since
32893298
// that can exhaust the HW prefetcher resources. We adjust the unroller
32903299
// 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
@@ -184,6 +184,14 @@ class VPBuilder {
184184
VPValue *createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B,
185185
DebugLoc DL = {}, const Twine &Name = "");
186186

187+
VPValue *createGetActiveLaneMask(VPValue *IV, VPValue *TC, DebugLoc DL,
188+
const Twine &Name = "") {
189+
auto *ALM = new VPActiveLaneMaskRecipe(IV, TC, DL, Name);
190+
if (BB)
191+
BB->insert(ALM, InsertPt);
192+
return ALM;
193+
}
194+
187195
//===--------------------------------------------------------------------===//
188196
// RAII helpers.
189197
//===--------------------------------------------------------------------===//

llvm/lib/Transforms/Vectorize/LoopVectorize.cpp

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

602+
ElementCount getMaxPredicateLength(ElementCount VF) const {
603+
return TTI->getMaxPredicateLength(VF);
604+
}
605+
602606
protected:
603607
friend class LoopVectorizationPlanner;
604608

@@ -7550,7 +7554,8 @@ LoopVectorizationPlanner::executePlan(
75507554
VPlanTransforms::optimizeForVFAndUF(BestVPlan, BestVF, BestUF, PSE);
75517555

75527556
// Perform the actual loop transformation.
7553-
VPTransformState State(BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan,
7557+
VPTransformState State(BestVF, BestUF, TTI.getMaxPredicateLength(BestVF), LI,
7558+
DT, ILV.Builder, &ILV, &BestVPlan,
75547559
OrigLoop->getHeader()->getContext());
75557560

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

llvm/lib/Transforms/Vectorize/VPlan.h

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -234,15 +234,16 @@ 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)
240-
: VF(VF), UF(UF), LI(LI), DT(DT), Builder(Builder), ILV(ILV), Plan(Plan),
241-
LVer(nullptr), TypeAnalysis(Ctx) {}
240+
: VF(VF), UF(UF), MaxPred(MaxPred), LI(LI), DT(DT), Builder(Builder),
241+
ILV(ILV), Plan(Plan), LVer(nullptr), TypeAnalysis(Ctx) {}
242242

243243
/// The chosen Vectorization and Unroll Factors of the loop being vectorized.
244244
ElementCount VF;
245245
unsigned UF;
246+
ElementCount MaxPred;
246247

247248
/// Hold the indices to generate specific scalar instructions. Null indicates
248249
/// that all instances are to be generated, using either scalar or vector
@@ -1275,6 +1276,43 @@ class VPInstruction : public VPRecipeWithIRFlags {
12751276
}
12761277
};
12771278

1279+
class VPActiveLaneMaskRecipe : public VPRecipeWithIRFlags {
1280+
const std::string Name;
1281+
1282+
public:
1283+
VPActiveLaneMaskRecipe(VPValue *IV, VPValue *TC, DebugLoc DL = {},
1284+
const Twine &Name = "")
1285+
: VPRecipeWithIRFlags(VPDef::VPActiveLaneMaskSC,
1286+
std::initializer_list<VPValue *>{IV, TC}, DL),
1287+
Name(Name.str()) {}
1288+
1289+
VP_CLASSOF_IMPL(VPDef::VPActiveLaneMaskSC)
1290+
1291+
VPRecipeBase *clone() override {
1292+
SmallVector<VPValue *, 2> Operands(operands());
1293+
assert(Operands.size() == 2 && "by construction");
1294+
auto *New = new VPActiveLaneMaskRecipe(Operands[0], Operands[1],
1295+
getDebugLoc(), Name);
1296+
New->transferFlags(*this);
1297+
return New;
1298+
}
1299+
1300+
void execute(VPTransformState &State) override;
1301+
1302+
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1303+
/// Print the recipe.
1304+
void print(raw_ostream &O, const Twine &Indent,
1305+
VPSlotTracker &SlotTracker) const override;
1306+
#endif
1307+
1308+
bool onlyFirstLaneUsed(const VPValue *Op) const override {
1309+
assert(is_contained(operands(), Op) &&
1310+
"Op must be an operand of the recipe");
1311+
1312+
return getOperand(0) == Op;
1313+
}
1314+
};
1315+
12781316
/// VPWidenRecipe is a recipe for producing a copy of vector type its
12791317
/// ingredient. This recipe covers most of the traditional vectorization cases
12801318
/// where each ingredient transforms into a vectorized version of itself.

llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp

Lines changed: 70 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -307,18 +307,7 @@ Value *VPInstruction::generateInstruction(VPTransformState &State,
307307
Value *Op2 = State.get(getOperand(2), Part);
308308
return Builder.CreateSelect(Cond, Op1, Op2, Name);
309309
}
310-
case VPInstruction::ActiveLaneMask: {
311-
// Get first lane of vector induction variable.
312-
Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
313-
// Get the original loop tripcount.
314-
Value *ScalarTC = State.get(getOperand(1), VPIteration(Part, 0));
315310

316-
auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
317-
auto *PredTy = VectorType::get(Int1Ty, State.VF);
318-
return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
319-
{PredTy, ScalarTC->getType()},
320-
{VIVElem0, ScalarTC}, nullptr, Name);
321-
}
322311
case VPInstruction::FirstOrderRecurrenceSplice: {
323312
// Generate code to combine the previous and current values in vector v3.
324313
//
@@ -526,7 +515,6 @@ bool VPInstruction::onlyFirstLaneUsed(const VPValue *Op) const {
526515
case Instruction::ICmp:
527516
// TODO: Cover additional opcodes.
528517
return vputils::onlyFirstLaneUsed(this);
529-
case VPInstruction::ActiveLaneMask:
530518
case VPInstruction::CalculateTripCountMinusVF:
531519
case VPInstruction::CanonicalIVIncrementForPart:
532520
case VPInstruction::BranchOnCount:
@@ -561,9 +549,6 @@ void VPInstruction::print(raw_ostream &O, const Twine &Indent,
561549
case VPInstruction::SLPStore:
562550
O << "combined store";
563551
break;
564-
case VPInstruction::ActiveLaneMask:
565-
O << "active lane mask";
566-
break;
567552
case VPInstruction::FirstOrderRecurrenceSplice:
568553
O << "first-order splice";
569554
break;
@@ -594,8 +579,78 @@ void VPInstruction::print(raw_ostream &O, const Twine &Indent,
594579
DL.print(O);
595580
}
596581
}
582+
583+
void VPActiveLaneMaskRecipe::print(raw_ostream &O, const Twine &Indent,
584+
VPSlotTracker &SlotTracker) const {
585+
O << Indent << "EMIT ";
586+
587+
printAsOperand(O, SlotTracker);
588+
O << " = active lane mask";
589+
printFlags(O);
590+
printOperands(O, SlotTracker);
591+
592+
if (auto DL = getDebugLoc()) {
593+
O << ", !dbg ";
594+
DL.print(O);
595+
}
596+
}
597+
597598
#endif
598599

600+
void VPActiveLaneMaskRecipe::execute(VPTransformState &State) {
601+
assert(!State.Instance && "VPInstruction executing an Instance");
602+
603+
IRBuilderBase &Builder = State.Builder;
604+
Builder.SetCurrentDebugLocation(getDebugLoc());
605+
606+
auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
607+
auto *PredTy = VectorType::get(Int1Ty, State.VF);
608+
609+
unsigned MaxPred = std::min(State.MaxPred.getKnownMinValue(),
610+
State.UF * State.VF.getKnownMinValue());
611+
if (State.UF <= 1 || MaxPred <= State.VF.getKnownMinValue() ||
612+
MaxPred % State.VF.getKnownMinValue() != 0) {
613+
for (int Part = State.UF - 1; Part >= 0; --Part) {
614+
// Get first lane of vector induction variable.
615+
Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
616+
// Get the original loop tripcount.
617+
Value *ScalarTC = State.get(getOperand(1), VPIteration(0, 0));
618+
Value *V = Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
619+
{PredTy, ScalarTC->getType()},
620+
{VIVElem0, ScalarTC}, nullptr, Name);
621+
State.set(this, V, Part);
622+
}
623+
return;
624+
}
625+
626+
// Generate long active lane masks covering all the unrolled iterations.
627+
unsigned PartsPerMask = MaxPred / State.VF.getKnownMinValue();
628+
auto *LongPredTy = VectorType::get(Int1Ty, MaxPred, State.VF.isScalable());
629+
SmallVector<Value *> LongMask(State.UF / PartsPerMask, nullptr);
630+
for (int Part = State.UF - PartsPerMask; Part >= 0; Part -= PartsPerMask) {
631+
// Get first lane of vector induction variable.
632+
Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
633+
// Get the original loop tripcount.
634+
Value *ScalarTC = State.get(getOperand(1), VPIteration(0, 0));
635+
Value *V = Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
636+
{LongPredTy, ScalarTC->getType()},
637+
{VIVElem0, ScalarTC}, nullptr, Name);
638+
LongMask[Part / PartsPerMask] = V;
639+
}
640+
641+
for (int Part = State.UF - 1; Part >= 0; --Part) {
642+
Value *ALM = LongMask[Part / PartsPerMask];
643+
const unsigned I = Part % PartsPerMask;
644+
Value *V = Builder.CreateIntrinsic(
645+
Intrinsic::vector_extract, {PredTy, ALM->getType()},
646+
{ALM, ConstantInt::get(Type::getInt64Ty(Builder.getContext()),
647+
I * State.VF.getKnownMinValue())},
648+
nullptr, Name);
649+
650+
State.set(this, V, Part);
651+
}
652+
}
653+
599654
void VPWidenCallRecipe::execute(VPTransformState &State) {
600655
assert(State.VF.isVector() && "not widening");
601656
auto &CI = *cast<CallInst>(getUnderlyingInstr());

llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -582,8 +582,7 @@ static bool canSimplifyBranchOnCond(VPInstruction *Term) {
582582
if (!Not || Not->getOpcode() != VPInstruction::Not)
583583
return false;
584584

585-
VPInstruction *ALM = dyn_cast<VPInstruction>(Not->getOperand(0));
586-
return ALM && ALM->getOpcode() == VPInstruction::ActiveLaneMask;
585+
return dyn_cast<VPActiveLaneMaskRecipe>(Not->getOperand(0));
587586
}
588587

589588
void VPlanTransforms::optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF,
@@ -1128,9 +1127,8 @@ static VPActiveLaneMaskPHIRecipe *addVPLaneMaskPhiAndUpdateExitBranch(
11281127
"index.part.next");
11291128

11301129
// Create the active lane mask instruction in the VPlan preheader.
1131-
auto *EntryALM =
1132-
Builder.createNaryOp(VPInstruction::ActiveLaneMask, {EntryIncrement, TC},
1133-
DL, "active.lane.mask.entry");
1130+
auto *EntryALM = Builder.createGetActiveLaneMask(EntryIncrement, TC, DL,
1131+
"active.lane.mask.entry");
11341132

11351133
// Now create the ActiveLaneMaskPhi recipe in the main loop using the
11361134
// preheader ActiveLaneMask instruction.
@@ -1144,9 +1142,8 @@ static VPActiveLaneMaskPHIRecipe *addVPLaneMaskPhiAndUpdateExitBranch(
11441142
auto *InLoopIncrement =
11451143
Builder.createOverflowingOp(VPInstruction::CanonicalIVIncrementForPart,
11461144
{IncrementValue}, {false, false}, DL);
1147-
auto *ALM = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
1148-
{InLoopIncrement, TripCount}, DL,
1149-
"active.lane.mask.next");
1145+
auto *ALM = Builder.createGetActiveLaneMask(InLoopIncrement, TripCount, DL,
1146+
"active.lane.mask.next");
11501147
LaneMaskPhi->addOperand(ALM);
11511148

11521149
// Replace the original terminator with BranchOnCond. We have to invert the
@@ -1177,9 +1174,8 @@ void VPlanTransforms::addActiveLaneMask(
11771174
LaneMask = addVPLaneMaskPhiAndUpdateExitBranch(
11781175
Plan, DataAndControlFlowWithoutRuntimeCheck);
11791176
} else {
1180-
LaneMask = new VPInstruction(VPInstruction::ActiveLaneMask,
1181-
{WideCanonicalIV, Plan.getTripCount()},
1182-
nullptr, "active.lane.mask");
1177+
LaneMask = new VPActiveLaneMaskRecipe(WideCanonicalIV, Plan.getTripCount(),
1178+
nullptr, "active.lane.mask");
11831179
LaneMask->insertAfter(WideCanonicalIV);
11841180
}
11851181

llvm/lib/Transforms/Vectorize/VPlanValue.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,7 @@ class VPDef {
360360
VPWidenMemoryInstructionSC,
361361
VPWidenSC,
362362
VPWidenSelectSC,
363+
VPActiveLaneMaskSC,
363364
// START: Phi-like recipes. Need to be kept together.
364365
VPBlendSC,
365366
VPPredInstPHISC,

0 commit comments

Comments
 (0)