LLVM 23.0.0git
VPlanAnalysis.cpp
Go to the documentation of this file.
1//===- VPlanAnalysis.cpp - Various Analyses working on VPlan ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "VPlanAnalysis.h"
10#include "VPlan.h"
11#include "VPlanCFG.h"
12#include "VPlanDominatorTree.h"
13#include "VPlanHelpers.h"
14#include "VPlanPatternMatch.h"
17
18using namespace llvm;
19using namespace VPlanPatternMatch;
20
21#define DEBUG_TYPE "vplan"
22
24 VPlan &Plan, DenseSet<VPRecipeBase *> &EphRecipes) {
25 // First, collect seed recipes which are operands of assumes.
29 for (VPRecipeBase &R : *VPBB) {
30 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
31 if (!RepR || !match(RepR, m_Intrinsic<Intrinsic::assume>()))
32 continue;
33 Worklist.push_back(RepR);
34 EphRecipes.insert(RepR);
35 }
36 }
37
38 // Process operands of candidates in worklist and add them to the set of
39 // ephemeral recipes, if they don't have side-effects and are only used by
40 // other ephemeral recipes.
41 while (!Worklist.empty()) {
42 VPRecipeBase *Cur = Worklist.pop_back_val();
43 for (VPValue *Op : Cur->operands()) {
44 auto *OpR = Op->getDefiningRecipe();
45 if (!OpR || OpR->mayHaveSideEffects() || EphRecipes.contains(OpR))
46 continue;
47 if (any_of(Op->users(), [EphRecipes](VPUser *U) {
48 auto *UR = dyn_cast<VPRecipeBase>(U);
49 return !UR || !EphRecipes.contains(UR);
50 }))
51 continue;
52 EphRecipes.insert(OpR);
53 Worklist.push_back(OpR);
54 }
55 }
56}
57
60
62 const VPRecipeBase *B) {
63 if (A == B)
64 return false;
65
66 auto LocalComesBefore = [](const VPRecipeBase *A, const VPRecipeBase *B) {
67 for (auto &R : *A->getParent()) {
68 if (&R == A)
69 return true;
70 if (&R == B)
71 return false;
72 }
73 llvm_unreachable("recipe not found");
74 };
75 const VPBlockBase *ParentA = A->getParent();
76 const VPBlockBase *ParentB = B->getParent();
77 if (ParentA == ParentB)
78 return LocalComesBefore(A, B);
79
80 return Base::properlyDominates(ParentA, ParentB);
81}
82
86 unsigned OverrideMaxNumRegs) const {
88 for (const auto &[RegClass, MaxUsers] : MaxLocalUsers) {
89 unsigned AvailableRegs = OverrideMaxNumRegs > 0
90 ? OverrideMaxNumRegs
91 : TTI.getNumberOfRegisters(RegClass);
92 if (MaxUsers > AvailableRegs) {
93 // Assume that for each register used past what's available we get one
94 // spill and reload.
95 unsigned Spills = MaxUsers - AvailableRegs;
96 InstructionCost SpillCost =
97 TTI.getRegisterClassSpillCost(RegClass, CostKind) +
98 TTI.getRegisterClassReloadCost(RegClass, CostKind);
99 InstructionCost TotalCost = Spills * SpillCost;
100 LLVM_DEBUG(dbgs() << "LV(REG): Cost of " << TotalCost << " from "
101 << Spills << " spills of "
102 << TTI.getRegisterClassName(RegClass) << "\n");
103 Cost += TotalCost;
104 }
105 }
106 return Cost;
107}
108
111 const SmallPtrSetImpl<const Value *> &ValuesToIgnore) {
112 // Each 'key' in the map opens a new interval. The values
113 // of the map are the index of the 'last seen' usage of the
114 // VPValue that is the key.
116
117 // Maps indices to recipes.
119 // Marks the end of each interval.
120 IntervalMap EndPoint;
121 // Saves the list of VPValues that are used in the loop.
123 // Saves the list of values that are used in the loop but are defined outside
124 // the loop (not including non-recipe values such as arguments and
125 // constants).
126 SmallSetVector<VPValue *, 8> LoopInvariants;
127 if (Plan.getVectorTripCount().getNumUsers() > 0)
128 LoopInvariants.insert(&Plan.getVectorTripCount());
129
130 // We scan the loop in a topological order in order and assign a number to
131 // each recipe. We use RPO to ensure that defs are met before their users. We
132 // assume that each recipe that has in-loop users starts an interval. We
133 // record every time that an in-loop value is used, so we have a list of the
134 // first occurences of each recipe and last occurrence of each VPValue.
135 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
137 LoopRegion);
139 if (!VPBB->getParent())
140 break;
141 for (VPRecipeBase &R : *VPBB) {
142 Idx2Recipe.push_back(&R);
143
144 // Save the end location of each USE.
145 for (VPValue *U : R.operands()) {
146 if (isa<VPRecipeValue>(U)) {
147 // Overwrite previous end points.
148 EndPoint[U] = Idx2Recipe.size();
149 Ends.insert(U);
150 } else if (auto *IRV = dyn_cast<VPIRValue>(U)) {
151 // Ignore non-recipe values such as arguments, constants, etc.
152 // FIXME: Might need some motivation why these values are ignored. If
153 // for example an argument is used inside the loop it will increase
154 // the register pressure (so shouldn't we add it to LoopInvariants).
155 if (!isa<Instruction>(IRV->getValue()))
156 continue;
157 // This recipe is outside the loop, record it and continue.
158 LoopInvariants.insert(U);
159 }
160 // Other types of VPValue are currently not tracked.
161 }
162 }
163 if (VPBB == LoopRegion->getExiting()) {
164 // VPWidenIntOrFpInductionRecipes are used implicitly at the end of the
165 // exiting block, where their increment will get materialized eventually.
166 for (auto &R : LoopRegion->getEntryBasicBlock()->phis()) {
167 if (auto *WideIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) {
168 EndPoint[WideIV] = Idx2Recipe.size();
169 Ends.insert(WideIV);
170 }
171 }
172 }
173 }
174
175 // Saves the list of intervals that end with the index in 'key'.
176 using VPValueList = SmallVector<VPValue *, 2>;
178
179 // Next, we transpose the EndPoints into a multi map that holds the list of
180 // intervals that *end* at a specific location.
181 for (auto &Interval : EndPoint)
182 TransposeEnds[Interval.second].push_back(Interval.first);
183
184 SmallPtrSet<VPValue *, 8> OpenIntervals;
187
188 LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
189
190 const auto &TTICapture = TTI;
191 auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
192 if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty) ||
193 (VF.isScalable() &&
194 !TTICapture.isElementTypeLegalForScalableVector(Ty)))
195 return 0;
196 return TTICapture.getRegUsageForType(VectorType::get(Ty, VF));
197 };
198
199 VPValue *CanIV = LoopRegion->getCanonicalIV();
200 // Note: canonical IVs are retained even if they have no users.
201 if (CanIV->getNumUsers() != 0)
202 OpenIntervals.insert(CanIV);
203
204 // We scan the instructions linearly and record each time that a new interval
205 // starts, by placing it in a set. If we find this value in TransposEnds then
206 // we remove it from the set. The max register usage is the maximum register
207 // usage of the recipes of the set.
208 for (unsigned int Idx = 0, Sz = Idx2Recipe.size(); Idx < Sz; ++Idx) {
209 VPRecipeBase *R = Idx2Recipe[Idx];
210
211 // Remove all of the VPValues that end at this location.
212 VPValueList &List = TransposeEnds[Idx];
213 for (VPValue *ToRemove : List)
214 OpenIntervals.erase(ToRemove);
215
216 // Ignore recipes that are never used within the loop and do not have side
217 // effects.
218 if (none_of(R->definedValues(),
219 [&Ends](VPValue *Def) { return Ends.count(Def); }) &&
220 !R->mayHaveSideEffects())
221 continue;
222
223 // Skip recipes for ignored values.
224 // TODO: Should mark recipes for ephemeral values that cannot be removed
225 // explictly in VPlan.
226 if (isa<VPSingleDefRecipe>(R) &&
227 ValuesToIgnore.contains(
228 cast<VPSingleDefRecipe>(R)->getUnderlyingValue()))
229 continue;
230
231 // For each VF find the maximum usage of registers.
232 for (unsigned J = 0, E = VFs.size(); J < E; ++J) {
233 // Count the number of registers used, per register class, given all open
234 // intervals.
235 // Note that elements in this SmallMapVector will be default constructed
236 // as 0. So we can use "RegUsage[ClassID] += n" in the code below even if
237 // there is no previous entry for ClassID.
239
240 for (auto *VPV : OpenIntervals) {
241 // Skip artificial values or values that weren't present in the original
242 // loop.
243 // TODO: Remove skipping values that weren't present in the original
244 // loop after removing the legacy
245 // LoopVectorizationCostModel::calculateRegisterUsage
247 VPBranchOnMaskRecipe>(VPV) ||
249 continue;
250
251 if (VFs[J].isScalar() ||
256 (cast<VPReductionPHIRecipe>(VPV))->isInLoop())) {
257 unsigned ClassID =
258 TTI.getRegisterClassForType(false, VPV->getScalarType());
259 // FIXME: The target might use more than one register for the type
260 // even in the scalar case.
261 RegUsage[ClassID] += 1;
262 } else {
263 // The output from scaled phis and scaled reductions actually has
264 // fewer lanes than the VF.
265 unsigned ScaleFactor =
266 vputils::getVFScaleFactor(VPV->getDefiningRecipe());
267 ElementCount VF = VFs[J];
268 if (ScaleFactor > 1) {
269 VF = VFs[J].divideCoefficientBy(ScaleFactor);
270 LLVM_DEBUG(dbgs() << "LV(REG): Scaled down VF from " << VFs[J]
271 << " to " << VF << " for " << *R << "\n";);
272 }
273
274 Type *ScalarTy = VPV->getScalarType();
275 unsigned ClassID = TTI.getRegisterClassForType(true, ScalarTy);
276 RegUsage[ClassID] += GetRegUsage(ScalarTy, VF);
277 }
278 }
279
280 for (const auto &Pair : RegUsage) {
281 auto &Entry = MaxUsages[J][Pair.first];
282 Entry = std::max(Entry, Pair.second);
283 }
284 }
285
286 LLVM_DEBUG(dbgs() << "LV(REG): At #" << Idx << " Interval # "
287 << OpenIntervals.size() << '\n');
288
289 // Add used VPValues defined by the current recipe to the list of open
290 // intervals.
291 for (VPValue *DefV : R->definedValues())
292 if (Ends.contains(DefV))
293 OpenIntervals.insert(DefV);
294 }
295
296 // We also search for instructions that are defined outside the loop, but are
297 // used inside the loop. We need this number separately from the max-interval
298 // usage number because when we unroll, loop-invariant values do not take
299 // more register.
301 for (unsigned Idx = 0, End = VFs.size(); Idx < End; ++Idx) {
302 // Note that elements in this SmallMapVector will be default constructed
303 // as 0. So we can use "Invariant[ClassID] += n" in the code below even if
304 // there is no previous entry for ClassID.
306
307 for (auto *In : LoopInvariants) {
308 // FIXME: The target might use more than one register for the type
309 // even in the scalar case.
310 bool IsScalar = vputils::onlyScalarValuesUsed(In);
311
312 ElementCount VF = IsScalar ? ElementCount::getFixed(1) : VFs[Idx];
313 unsigned ClassID =
314 TTI.getRegisterClassForType(VF.isVector(), In->getScalarType());
315 Invariant[ClassID] += GetRegUsage(In->getScalarType(), VF);
316 }
317
318 LLVM_DEBUG({
319 dbgs() << "LV(REG): VF = " << VFs[Idx] << '\n';
320 dbgs() << "LV(REG): Found max usage: " << MaxUsages[Idx].size()
321 << " item\n";
322 for (const auto &pair : MaxUsages[Idx]) {
323 dbgs() << "LV(REG): RegisterClass: "
324 << TTI.getRegisterClassName(pair.first) << ", " << pair.second
325 << " registers\n";
326 }
327 dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
328 << " item\n";
329 for (const auto &pair : Invariant) {
330 dbgs() << "LV(REG): RegisterClass: "
331 << TTI.getRegisterClassName(pair.first) << ", " << pair.second
332 << " registers\n";
333 }
334 });
335
336 RU.LoopInvariantRegs = Invariant;
337 RU.MaxLocalUsers = MaxUsages[Idx];
338 RUs[Idx] = RU;
339 }
340
341 return RUs;
342}
ReachingDefInfo InstSet & ToRemove
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
std::pair< uint64_t, uint64_t > Interval
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
This file contains the declarations of the Vectorization Plan base classes:
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
Core dominator tree base class.
bool properlyDominates(const DomTreeNodeBase< VPBlockBase > *A, const DomTreeNodeBase< VPBlockBase > *B) const
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:324
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
size_type size() const
Definition MapVector.h:58
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4399
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4487
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:94
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:323
A recipe for generating conditional branches on the bits of a mask.
Definition VPlan.h:3495
A recipe for generating the phi node tracking the current scalar iteration index.
Definition VPlan.h:4076
A recipe for converting the input value IV value to the corresponding value of an IV with different s...
Definition VPlan.h:4177
bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B)
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:402
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4609
const VPBlockBase * getEntry() const
Definition VPlan.h:4653
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4721
const VPBlockBase * getExiting() const
Definition VPlan.h:4665
VPValues defined by a VPRegionBlock, like the canonical IV.
Definition VPlanValue.h:215
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3404
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4244
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:384
operand_range operands()
Definition VPlanValue.h:457
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
unsigned getNumUsers() const
Definition VPlanValue.h:115
A recipe to compute a pointer to the last element of each part of a widened memory access for widened...
Definition VPlan.h:2267
A recipe to compute the pointers for widened memory accesses of SourceElementTy, with the Stride expr...
Definition VPlan.h:2349
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4757
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4946
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1068
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:185
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool match(Val *V, const Pattern &P)
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExtractLastPart, Op0_t > m_ExtractLastPart(const Op0_t &Op0)
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
unsigned getVFScaleFactor(VPRecipeBase *R)
Get the VF scaling factor applied to the recipe's output, if the recipe has one.
This is an optimization pass for GlobalISel generic memory operations.
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition VPlanCFG.h:288
SmallVector< VPRegisterUsage, 8 > calculateRegisterUsageForPlan(VPlan &Plan, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value * > &ValuesToIgnore)
Estimate the register usage for Plan and vectorization factors in VFs by calculating the highest numb...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1745
void collectEphemeralRecipesForVPlan(VPlan &Plan, DenseSet< VPRecipeBase * > &EphRecipes)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1752
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
TargetTransformInfo TTI
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:334
A struct that represents some properties of the register usage of a loop.
SmallMapVector< unsigned, unsigned, 4 > MaxLocalUsers
Holds the maximum number of concurrent live intervals in the loop.
InstructionCost spillCost(const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, unsigned OverrideMaxNumRegs=0) const
Calculate the estimated cost of any spills due to using more registers than the number available for ...
SmallMapVector< unsigned, unsigned, 4 > LoopInvariantRegs
Holds the number of loop invariant values that are used in the loop.