Skip to content

Commit 7b40dfc

Browse files
fhahnGeneraluseAI
authored andcommitted
[VPlan] Hoist predicated loads with complementary masks. (llvm#168373)
This patch adds a new VPlan transformation to hoist predicated loads, if we can prove they execute unconditionally, i.e. there are 2 predicated loads to the same address with complementary masks. Then we are guaranteed to execute one of them on each iteration, allowing us to remove the mask. The transform groups masked replicating loads by their address SCEV, then checks if there are 2 loads with complementary mask. If that is the case, we check if there are any writes that may alias the load address in the blocks between the first and last load with the same address. The transforms operates after linearizing the CFG, but before introducing replicate regions, which means this is just checking a chain of consecutive blocks. Currently this only uses noalias metadata to check for no-alias (using the helpers added in llvm#166247). Then we create an unpredicated VPReplicateRecipe at the position of the first load, then replace all users of the grouped loads with it. Small Alive2 proof for hoisting with complementary masks: https://alive2.llvm.org/ce/z/kUx742 PR: llvm#168373
1 parent fed8dc7 commit 7b40dfc

File tree

5 files changed

+272
-374
lines changed

5 files changed

+272
-374
lines changed

llvm/lib/Transforms/Vectorize/LoopVectorize.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8336,6 +8336,7 @@ void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
83368336
if (auto Plan = tryToBuildVPlanWithVPRecipes(
83378337
std::unique_ptr<VPlan>(VPlan0->duplicate()), SubRange, &LVer)) {
83388338
// Now optimize the initial VPlan.
8339+
VPlanTransforms::hoistPredicatedLoads(*Plan, *PSE.getSE(), OrigLoop);
83398340
VPlanTransforms::runPass(VPlanTransforms::truncateToMinimalBitwidths,
83408341
*Plan, CM.getMinimalBitwidths());
83418342
VPlanTransforms::runPass(VPlanTransforms::optimize, *Plan);

llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,41 @@ bool VPlanTransforms::tryToConvertVPInstructionsToVPRecipes(
139139
return true;
140140
}
141141

142+
// Check if a load can be hoisted by verifying it doesn't alias with any stores
143+
// in blocks between FirstBB and LastBB using scoped noalias metadata.
144+
static bool canHoistLoadWithNoAliasCheck(VPReplicateRecipe *Load,
145+
VPBasicBlock *FirstBB,
146+
VPBasicBlock *LastBB) {
147+
// Get the load's memory location and check if it aliases with any stores
148+
// using scoped noalias metadata.
149+
auto LoadLoc = vputils::getMemoryLocation(*Load);
150+
if (!LoadLoc || !LoadLoc->AATags.Scope)
151+
return false;
152+
153+
const AAMDNodes &LoadAA = LoadLoc->AATags;
154+
for (VPBlockBase *Block = FirstBB; Block;
155+
Block = Block->getSingleSuccessor()) {
156+
// This function assumes a simple linear chain of blocks. If there are
157+
// multiple successors, we would need more complex analysis.
158+
assert(Block->getNumSuccessors() <= 1 &&
159+
"Expected at most one successor in block chain");
160+
auto *VPBB = cast<VPBasicBlock>(Block);
161+
for (VPRecipeBase &R : *VPBB) {
162+
if (R.mayWriteToMemory()) {
163+
auto Loc = vputils::getMemoryLocation(R);
164+
// Bail out if we can't get the location or if the scoped noalias
165+
// metadata indicates potential aliasing.
166+
if (!Loc || ScopedNoAliasAAResult::mayAliasInScopes(
167+
LoadAA.Scope, Loc->AATags.NoAlias))
168+
return false;
169+
}
170+
}
171+
if (Block == LastBB)
172+
break;
173+
}
174+
return true;
175+
}
176+
142177
/// Return true if we do not know how to (mechanically) hoist or sink \p R out
143178
/// of a loop region.
144179
static bool cannotHoistOrSinkRecipe(const VPRecipeBase &R) {
@@ -4010,6 +4045,122 @@ void VPlanTransforms::hoistInvariantLoads(VPlan &Plan) {
40104045
}
40114046
}
40124047

4048+
// Returns the intersection of metadata from a group of loads.
4049+
static VPIRMetadata getCommonLoadMetadata(ArrayRef<VPReplicateRecipe *> Loads) {
4050+
VPIRMetadata CommonMetadata = *Loads.front();
4051+
for (VPReplicateRecipe *Load : drop_begin(Loads))
4052+
CommonMetadata.intersect(*Load);
4053+
return CommonMetadata;
4054+
}
4055+
4056+
void VPlanTransforms::hoistPredicatedLoads(VPlan &Plan, ScalarEvolution &SE,
4057+
const Loop *L) {
4058+
VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
4059+
VPTypeAnalysis TypeInfo(Plan);
4060+
VPDominatorTree VPDT(Plan);
4061+
4062+
// Group predicated loads by their address SCEV.
4063+
DenseMap<const SCEV *, SmallVector<VPReplicateRecipe *>> LoadsByAddress;
4064+
for (VPBlockBase *Block : vp_depth_first_shallow(LoopRegion->getEntry())) {
4065+
auto *VPBB = cast<VPBasicBlock>(Block);
4066+
for (VPRecipeBase &R : *VPBB) {
4067+
auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
4068+
if (!RepR || RepR->getOpcode() != Instruction::Load ||
4069+
!RepR->isPredicated())
4070+
continue;
4071+
4072+
VPValue *Addr = RepR->getOperand(0);
4073+
const SCEV *AddrSCEV = vputils::getSCEVExprForVPValue(Addr, SE, L);
4074+
if (!isa<SCEVCouldNotCompute>(AddrSCEV))
4075+
LoadsByAddress[AddrSCEV].push_back(RepR);
4076+
}
4077+
}
4078+
4079+
// For each address, collect loads with complementary masks, sort by
4080+
// dominance, and use the earliest load.
4081+
for (auto &[Addr, Loads] : LoadsByAddress) {
4082+
if (Loads.size() < 2)
4083+
continue;
4084+
4085+
// Collect groups of loads with complementary masks.
4086+
SmallVector<SmallVector<VPReplicateRecipe *, 4>> LoadGroups;
4087+
for (VPReplicateRecipe *&LoadI : Loads) {
4088+
if (!LoadI)
4089+
continue;
4090+
4091+
VPValue *MaskI = LoadI->getMask();
4092+
Type *TypeI = TypeInfo.inferScalarType(LoadI);
4093+
SmallVector<VPReplicateRecipe *, 4> Group;
4094+
Group.push_back(LoadI);
4095+
LoadI = nullptr;
4096+
4097+
// Find all loads with the same type.
4098+
for (VPReplicateRecipe *&LoadJ : Loads) {
4099+
if (!LoadJ)
4100+
continue;
4101+
4102+
Type *TypeJ = TypeInfo.inferScalarType(LoadJ);
4103+
if (TypeI == TypeJ) {
4104+
Group.push_back(LoadJ);
4105+
LoadJ = nullptr;
4106+
}
4107+
}
4108+
4109+
// Check if any load in the group has a complementary mask with another,
4110+
// that is M1 == NOT(M2) or M2 == NOT(M1).
4111+
bool HasComplementaryMask =
4112+
any_of(drop_begin(Group), [MaskI](VPReplicateRecipe *Load) {
4113+
VPValue *MaskJ = Load->getMask();
4114+
return match(MaskI, m_Not(m_Specific(MaskJ))) ||
4115+
match(MaskJ, m_Not(m_Specific(MaskI)));
4116+
});
4117+
4118+
if (HasComplementaryMask)
4119+
LoadGroups.push_back(std::move(Group));
4120+
}
4121+
4122+
// For each group, check memory dependencies and hoist the earliest load.
4123+
for (auto &Group : LoadGroups) {
4124+
// Sort loads by dominance order, with earliest (most dominating) first.
4125+
sort(Group, [&VPDT](VPReplicateRecipe *A, VPReplicateRecipe *B) {
4126+
return VPDT.properlyDominates(A, B);
4127+
});
4128+
4129+
VPReplicateRecipe *EarliestLoad = Group.front();
4130+
VPBasicBlock *FirstBB = EarliestLoad->getParent();
4131+
VPBasicBlock *LastBB = Group.back()->getParent();
4132+
4133+
// Check that the load doesn't alias with stores between first and last.
4134+
if (!canHoistLoadWithNoAliasCheck(EarliestLoad, FirstBB, LastBB))
4135+
continue;
4136+
4137+
// Find the load with minimum alignment to use.
4138+
auto *LoadWithMinAlign =
4139+
*min_element(Group, [](VPReplicateRecipe *A, VPReplicateRecipe *B) {
4140+
return cast<LoadInst>(A->getUnderlyingInstr())->getAlign() <
4141+
cast<LoadInst>(B->getUnderlyingInstr())->getAlign();
4142+
});
4143+
4144+
// Collect common metadata from all loads in the group.
4145+
VPIRMetadata CommonMetadata = getCommonLoadMetadata(Group);
4146+
4147+
// Create an unpredicated load with minimum alignment using the earliest
4148+
// dominating address and common metadata.
4149+
auto *UnpredicatedLoad = new VPReplicateRecipe(
4150+
LoadWithMinAlign->getUnderlyingInstr(), EarliestLoad->getOperand(0),
4151+
/*IsSingleScalar=*/false, /*Mask=*/nullptr, /*Flags=*/{},
4152+
CommonMetadata);
4153+
UnpredicatedLoad->insertBefore(EarliestLoad);
4154+
4155+
// Replace all loads in the group with the unpredicated load.
4156+
for (VPReplicateRecipe *Load : Group) {
4157+
Load->replaceAllUsesWith(UnpredicatedLoad);
4158+
Load->eraseFromParent();
4159+
}
4160+
}
4161+
}
4162+
}
4163+
40134164
void VPlanTransforms::materializeConstantVectorTripCount(
40144165
VPlan &Plan, ElementCount BestVF, unsigned BestUF,
40154166
PredicatedScalarEvolution &PSE) {

llvm/lib/Transforms/Vectorize/VPlanTransforms.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,12 @@ struct VPlanTransforms {
314314
/// plan using noalias metadata.
315315
static void hoistInvariantLoads(VPlan &Plan);
316316

317+
/// Hoist predicated loads from the same address to the loop entry block, if
318+
/// they are guaranteed to execute on both paths (i.e., in replicate regions
319+
/// with complementary masks P and NOT P).
320+
static void hoistPredicatedLoads(VPlan &Plan, ScalarEvolution &SE,
321+
const Loop *L);
322+
317323
// Materialize vector trip counts for constants early if it can simply be
318324
// computed as (Original TC / VF * UF) * VF * UF.
319325
static void

0 commit comments

Comments
 (0)