Skip to content

Commit 577199f

Browse files
committed
Reapply "[VPlan] Set branch weight metadata on middle term in VPlan (NFC) (#143035)"
This reverts commit 0604dc1. The recommitted version addresses post-commit comments and adjusts the place the branch weights are added. It now runs before VPlans are optimized for VF and UF, which may remove the vector loop region, causing a crash trying to get the middle block after that. Test case added in 72f99b7. Original message: Manage branch weights for the BranchOnCond in the middle block in VPlan. This requires updating VPInstruction to inherit from VPIRMetadata, which in general makes sense as there are a number of opcodes that could take metadata. There are other branches (part of the skeleton) that also need branch weights adding. PR: #143035
1 parent 72f99b7 commit 577199f

File tree

5 files changed

+66
-45
lines changed

5 files changed

+66
-45
lines changed

llvm/lib/Transforms/Vectorize/LoopVectorize.cpp

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7300,6 +7300,9 @@ DenseMap<const SCEV *, Value *> LoopVectorizationPlanner::executePlan(
73007300
VPlanTransforms::runPass(VPlanTransforms::unrollByUF, BestVPlan, BestUF,
73017301
OrigLoop->getHeader()->getContext());
73027302
VPlanTransforms::runPass(VPlanTransforms::materializeBroadcasts, BestVPlan);
7303+
if (hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator()))
7304+
VPlanTransforms::runPass(VPlanTransforms::addBranchWeightToMiddleTerminator,
7305+
BestVPlan, BestVF);
73037306
VPlanTransforms::optimizeForVFAndUF(BestVPlan, BestVF, BestUF, PSE);
73047307
VPlanTransforms::simplifyRecipes(BestVPlan, *Legal->getWidestInductionType());
73057308
VPlanTransforms::narrowInterleaveGroups(
@@ -7309,11 +7312,8 @@ DenseMap<const SCEV *, Value *> LoopVectorizationPlanner::executePlan(
73097312

73107313
VPlanTransforms::convertToConcreteRecipes(BestVPlan,
73117314
*Legal->getWidestInductionType());
7312-
// Retrieve and store the middle block before dissolving regions. Regions are
7313-
// dissolved after optimizing for VF and UF, which completely removes unneeded
7314-
// loop regions first.
7315-
VPBasicBlock *MiddleVPBB =
7316-
BestVPlan.getVectorLoopRegion() ? BestVPlan.getMiddleBlock() : nullptr;
7315+
// Regions are dissolved after optimizing for VF and UF, which completely
7316+
// removes unneeded loop regions first.
73177317
VPlanTransforms::dissolveLoopRegions(BestVPlan);
73187318
// Perform the actual loop transformation.
73197319
VPTransformState State(&TTI, BestVF, LI, DT, ILV.AC, ILV.Builder, &BestVPlan,
@@ -7456,20 +7456,6 @@ DenseMap<const SCEV *, Value *> LoopVectorizationPlanner::executePlan(
74567456

74577457
ILV.printDebugTracesAtEnd();
74587458

7459-
// 4. Adjust branch weight of the branch in the middle block.
7460-
if (HeaderVPBB) {
7461-
auto *MiddleTerm =
7462-
cast<BranchInst>(State.CFG.VPBB2IRBB[MiddleVPBB]->getTerminator());
7463-
if (MiddleTerm->isConditional() &&
7464-
hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator())) {
7465-
// Assume that `Count % VectorTripCount` is equally distributed.
7466-
unsigned TripCount = BestVPlan.getUF() * State.VF.getKnownMinValue();
7467-
assert(TripCount > 0 && "trip count should not be zero");
7468-
const uint32_t Weights[] = {1, TripCount - 1};
7469-
setBranchWeights(*MiddleTerm, Weights, /*IsExpected=*/false);
7470-
}
7471-
}
7472-
74737459
return ExpandedSCEVs;
74747460
}
74757461

llvm/lib/Transforms/Vectorize/VPlan.h

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -882,11 +882,40 @@ template <unsigned PartOpIdx> class VPUnrollPartAccessor {
882882
unsigned getUnrollPart(VPUser &U) const;
883883
};
884884

885+
/// Helper to manage IR metadata for recipes. It filters out metadata that
886+
/// cannot be propagated.
887+
class VPIRMetadata {
888+
SmallVector<std::pair<unsigned, MDNode *>> Metadata;
889+
890+
public:
891+
VPIRMetadata() {}
892+
893+
/// Adds metatadata that can be preserved from the original instruction
894+
/// \p I.
895+
VPIRMetadata(Instruction &I) { getMetadataToPropagate(&I, Metadata); }
896+
897+
/// Adds metatadata that can be preserved from the original instruction
898+
/// \p I and noalias metadata guaranteed by runtime checks using \p LVer.
899+
VPIRMetadata(Instruction &I, LoopVersioning *LVer);
900+
901+
/// Copy constructor for cloning.
902+
VPIRMetadata(const VPIRMetadata &Other) : Metadata(Other.Metadata) {}
903+
904+
/// Add all metadata to \p I.
905+
void applyMetadata(Instruction &I) const;
906+
907+
/// Add metadata with kind \p Kind and \p Node.
908+
void addMetadata(unsigned Kind, MDNode *Node) {
909+
Metadata.emplace_back(Kind, Node);
910+
}
911+
};
912+
885913
/// This is a concrete Recipe that models a single VPlan-level instruction.
886914
/// While as any Recipe it may generate a sequence of IR instructions when
887915
/// executed, these instructions would always form a single-def expression as
888916
/// the VPInstruction is also a single def-use vertex.
889917
class VPInstruction : public VPRecipeWithIRFlags,
918+
public VPIRMetadata,
890919
public VPUnrollPartAccessor<1> {
891920
friend class VPlanSlp;
892921

@@ -976,7 +1005,7 @@ class VPInstruction : public VPRecipeWithIRFlags,
9761005
VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands, DebugLoc DL = {},
9771006
const Twine &Name = "")
9781007
: VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, DL),
979-
Opcode(Opcode), Name(Name.str()) {}
1008+
VPIRMetadata(), Opcode(Opcode), Name(Name.str()) {}
9801009

9811010
VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands,
9821011
const VPIRFlags &Flags, DebugLoc DL = {},
@@ -1268,29 +1297,6 @@ struct VPIRPhi : public VPIRInstruction, public VPPhiAccessors {
12681297
const VPRecipeBase *getAsRecipe() const override { return this; }
12691298
};
12701299

1271-
/// Helper to manage IR metadata for recipes. It filters out metadata that
1272-
/// cannot be propagated.
1273-
class VPIRMetadata {
1274-
SmallVector<std::pair<unsigned, MDNode *>> Metadata;
1275-
1276-
public:
1277-
VPIRMetadata() {}
1278-
1279-
/// Adds metatadata that can be preserved from the original instruction
1280-
/// \p I.
1281-
VPIRMetadata(Instruction &I) { getMetadataToPropagate(&I, Metadata); }
1282-
1283-
/// Adds metatadata that can be preserved from the original instruction
1284-
/// \p I and noalias metadata guaranteed by runtime checks using \p LVer.
1285-
VPIRMetadata(Instruction &I, LoopVersioning *LVer);
1286-
1287-
/// Copy constructor for cloning.
1288-
VPIRMetadata(const VPIRMetadata &Other) : Metadata(Other.Metadata) {}
1289-
1290-
/// Add all metadata to \p I.
1291-
void applyMetadata(Instruction &I) const;
1292-
};
1293-
12941300
/// VPWidenRecipe is a recipe for producing a widened instruction using the
12951301
/// opcode and operands of the recipe. This recipe covers most of the
12961302
/// traditional vectorization cases where each recipe transforms into a

llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ VPInstruction::VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands,
409409
const VPIRFlags &Flags, DebugLoc DL,
410410
const Twine &Name)
411411
: VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, Flags, DL),
412-
Opcode(Opcode), Name(Name.str()) {
412+
VPIRMetadata(), Opcode(Opcode), Name(Name.str()) {
413413
assert(flagsValidForOpcode(getOpcode()) &&
414414
"Set flags not supported for the provided opcode");
415415
}
@@ -590,7 +590,9 @@ Value *VPInstruction::generate(VPTransformState &State) {
590590
}
591591
case VPInstruction::BranchOnCond: {
592592
Value *Cond = State.get(getOperand(0), VPLane(0));
593-
return createCondBranch(Cond, getParent(), State);
593+
auto *Br = createCondBranch(Cond, getParent(), State);
594+
applyMetadata(*Br);
595+
return Br;
594596
}
595597
case VPInstruction::BranchOnCount: {
596598
// First create the compare.

llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include "llvm/Analysis/LoopInfo.h"
3232
#include "llvm/Analysis/VectorUtils.h"
3333
#include "llvm/IR/Intrinsics.h"
34+
#include "llvm/IR/MDBuilder.h"
3435
#include "llvm/IR/PatternMatch.h"
3536
#include "llvm/Support/Casting.h"
3637
#include "llvm/Support/TypeSize.h"
@@ -3203,3 +3204,25 @@ void VPlanTransforms::narrowInterleaveGroups(VPlan &Plan, ElementCount VF,
32033204
Plan.getOrAddLiveIn(ConstantInt::get(CanIV->getScalarType(), 1)));
32043205
removeDeadRecipes(Plan);
32053206
}
3207+
3208+
/// Add branch weight metadata, if the \p Plan's middle block is terminated by a
3209+
/// BranchOnCond recipe.
3210+
void VPlanTransforms::addBranchWeightToMiddleTerminator(VPlan &Plan,
3211+
ElementCount VF) {
3212+
VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
3213+
auto *MiddleTerm =
3214+
dyn_cast_or_null<VPInstruction>(MiddleVPBB->getTerminator());
3215+
// Only add branch metadata if there is a (conditional) terminator.
3216+
if (!MiddleTerm)
3217+
return;
3218+
3219+
assert(MiddleTerm->getOpcode() == VPInstruction::BranchOnCond &&
3220+
"must have a BranchOnCond");
3221+
// Assume that `TripCount % VectorStep ` is equally distributed.
3222+
unsigned VectorStep = Plan.getUF() * VF.getKnownMinValue();
3223+
assert(VectorStep > 0 && "trip count should not be zero");
3224+
MDBuilder MDB(Plan.getScalarHeader()->getIRBasicBlock()->getContext());
3225+
MDNode *BranchWeights =
3226+
MDB.createBranchWeights({1, VectorStep - 1}, /*IsExpected=*/false);
3227+
MiddleTerm->addMetadata(LLVMContext::MD_prof, BranchWeights);
3228+
}

llvm/lib/Transforms/Vectorize/VPlanTransforms.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,10 @@ struct VPlanTransforms {
234234
/// removed in the future.
235235
static DenseMap<VPBasicBlock *, VPValue *>
236236
introduceMasksAndLinearize(VPlan &Plan, bool FoldTail);
237+
238+
/// Add branch weight metadata, if the \p Plan's middle block is terminated by
239+
/// a BranchOnCond recipe.
240+
static void addBranchWeightToMiddleTerminator(VPlan &Plan, ElementCount VF);
237241
};
238242

239243
} // namespace llvm

0 commit comments

Comments
 (0)