1 //===- LoopVectorizationPlanner.h - Planner for LoopVectorization ---------===//
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
7 //===----------------------------------------------------------------------===//
10 /// This file provides a LoopVectorizationPlanner class.
11 /// InnerLoopVectorizer vectorizes loops which contain only one basic
12 /// LoopVectorizationPlanner - drives the vectorization process after having
13 /// passed Legality checks.
14 /// The planner builds and optimizes the Vectorization Plans which record the
15 /// decisions how to vectorize the given loop. In particular, represent the
16 /// control-flow of the vectorized version, the replication of instructions that
17 /// are to be scalarized, and interleave access groups.
19 /// Also provides a VPlan-based builder utility analogous to IRBuilder.
20 /// It provides an instruction-level API for generating VPInstructions while
21 /// abstracting away the Recipe manipulation details.
22 //===----------------------------------------------------------------------===//
24 #ifndef LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
25 #define LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/Support/InstructionCost.h"
35 class LoopVectorizationLegality
;
36 class LoopVectorizationCostModel
;
37 class PredicatedScalarEvolution
;
38 class LoopVectorizeHints
;
39 class OptimizationRemarkEmitter
;
40 class TargetTransformInfo
;
41 class TargetLibraryInfo
;
42 class VPRecipeBuilder
;
44 /// VPlan-based builder utility analogous to IRBuilder.
46 VPBasicBlock
*BB
= nullptr;
47 VPBasicBlock::iterator InsertPt
= VPBasicBlock::iterator();
49 /// Insert \p VPI in BB at InsertPt if BB is set.
50 VPInstruction
*tryInsertInstruction(VPInstruction
*VPI
) {
52 BB
->insert(VPI
, InsertPt
);
56 VPInstruction
*createInstruction(unsigned Opcode
,
57 ArrayRef
<VPValue
*> Operands
, DebugLoc DL
,
58 const Twine
&Name
= "") {
59 return tryInsertInstruction(new VPInstruction(Opcode
, Operands
, DL
, Name
));
62 VPInstruction
*createInstruction(unsigned Opcode
,
63 std::initializer_list
<VPValue
*> Operands
,
64 DebugLoc DL
, const Twine
&Name
= "") {
65 return createInstruction(Opcode
, ArrayRef
<VPValue
*>(Operands
), DL
, Name
);
69 VPBuilder() = default;
70 VPBuilder(VPBasicBlock
*InsertBB
) { setInsertPoint(InsertBB
); }
72 /// Clear the insertion point: created instructions will not be inserted into
74 void clearInsertionPoint() {
76 InsertPt
= VPBasicBlock::iterator();
79 VPBasicBlock
*getInsertBlock() const { return BB
; }
80 VPBasicBlock::iterator
getInsertPoint() const { return InsertPt
; }
82 /// InsertPoint - A saved insertion point.
84 VPBasicBlock
*Block
= nullptr;
85 VPBasicBlock::iterator Point
;
88 /// Creates a new insertion point which doesn't point to anything.
89 VPInsertPoint() = default;
91 /// Creates a new insertion point at the given location.
92 VPInsertPoint(VPBasicBlock
*InsertBlock
, VPBasicBlock::iterator InsertPoint
)
93 : Block(InsertBlock
), Point(InsertPoint
) {}
95 /// Returns true if this insert point is set.
96 bool isSet() const { return Block
!= nullptr; }
98 VPBasicBlock
*getBlock() const { return Block
; }
99 VPBasicBlock::iterator
getPoint() const { return Point
; }
102 /// Sets the current insert point to a previously-saved location.
103 void restoreIP(VPInsertPoint IP
) {
105 setInsertPoint(IP
.getBlock(), IP
.getPoint());
107 clearInsertionPoint();
110 /// This specifies that created VPInstructions should be appended to the end
111 /// of the specified block.
112 void setInsertPoint(VPBasicBlock
*TheBB
) {
113 assert(TheBB
&& "Attempting to set a null insert point");
115 InsertPt
= BB
->end();
118 /// This specifies that created instructions should be inserted at the
120 void setInsertPoint(VPBasicBlock
*TheBB
, VPBasicBlock::iterator IP
) {
125 /// This specifies that created instructions should be inserted at the
127 void setInsertPoint(VPRecipeBase
*IP
) {
128 BB
= IP
->getParent();
129 InsertPt
= IP
->getIterator();
132 /// Create an N-ary operation with \p Opcode, \p Operands and set \p Inst as
133 /// its underlying Instruction.
134 VPValue
*createNaryOp(unsigned Opcode
, ArrayRef
<VPValue
*> Operands
,
135 Instruction
*Inst
= nullptr, const Twine
&Name
= "") {
138 DL
= Inst
->getDebugLoc();
139 VPInstruction
*NewVPInst
= createInstruction(Opcode
, Operands
, DL
, Name
);
140 NewVPInst
->setUnderlyingValue(Inst
);
143 VPValue
*createNaryOp(unsigned Opcode
, ArrayRef
<VPValue
*> Operands
,
144 DebugLoc DL
, const Twine
&Name
= "") {
145 return createInstruction(Opcode
, Operands
, DL
, Name
);
148 VPInstruction
*createOverflowingOp(unsigned Opcode
,
149 std::initializer_list
<VPValue
*> Operands
,
150 VPRecipeWithIRFlags::WrapFlagsTy WrapFlags
,
151 DebugLoc DL
, const Twine
&Name
= "") {
152 return tryInsertInstruction(
153 new VPInstruction(Opcode
, Operands
, WrapFlags
, DL
, Name
));
155 VPValue
*createNot(VPValue
*Operand
, DebugLoc DL
, const Twine
&Name
= "") {
156 return createInstruction(VPInstruction::Not
, {Operand
}, DL
, Name
);
159 VPValue
*createAnd(VPValue
*LHS
, VPValue
*RHS
, DebugLoc DL
,
160 const Twine
&Name
= "") {
161 return createInstruction(Instruction::BinaryOps::And
, {LHS
, RHS
}, DL
, Name
);
164 VPValue
*createOr(VPValue
*LHS
, VPValue
*RHS
, DebugLoc DL
,
165 const Twine
&Name
= "") {
166 return createInstruction(Instruction::BinaryOps::Or
, {LHS
, RHS
}, DL
, Name
);
169 VPValue
*createSelect(VPValue
*Cond
, VPValue
*TrueVal
, VPValue
*FalseVal
,
170 DebugLoc DL
, const Twine
&Name
= "") {
171 return createNaryOp(Instruction::Select
, {Cond
, TrueVal
, FalseVal
}, DL
,
175 /// Create a new ICmp VPInstruction with predicate \p Pred and operands \p A
177 /// TODO: add createFCmp when needed.
178 VPValue
*createICmp(CmpInst::Predicate Pred
, VPValue
*A
, VPValue
*B
,
179 DebugLoc DL
= {}, const Twine
&Name
= "");
181 //===--------------------------------------------------------------------===//
183 //===--------------------------------------------------------------------===//
185 /// RAII object that stores the current insertion point and restores it when
186 /// the object is destroyed.
187 class InsertPointGuard
{
190 VPBasicBlock::iterator Point
;
193 InsertPointGuard(VPBuilder
&B
)
194 : Builder(B
), Block(B
.getInsertBlock()), Point(B
.getInsertPoint()) {}
196 InsertPointGuard(const InsertPointGuard
&) = delete;
197 InsertPointGuard
&operator=(const InsertPointGuard
&) = delete;
199 ~InsertPointGuard() { Builder
.restoreIP(VPInsertPoint(Block
, Point
)); }
203 /// TODO: The following VectorizationFactor was pulled out of
204 /// LoopVectorizationCostModel class. LV also deals with
205 /// VectorizerParams::VectorizationFactor and VectorizationCostTy.
206 /// We need to streamline them.
208 /// Information about vectorization costs.
209 struct VectorizationFactor
{
210 /// Vector width with best cost.
213 /// Cost of the loop with that width.
214 InstructionCost Cost
;
216 /// Cost of the scalar loop.
217 InstructionCost ScalarCost
;
219 /// The minimum trip count required to make vectorization profitable, e.g. due
220 /// to runtime checks.
221 ElementCount MinProfitableTripCount
;
223 VectorizationFactor(ElementCount Width
, InstructionCost Cost
,
224 InstructionCost ScalarCost
)
225 : Width(Width
), Cost(Cost
), ScalarCost(ScalarCost
) {}
227 /// Width 1 means no vectorization, cost 0 means uncomputed cost.
228 static VectorizationFactor
Disabled() {
229 return {ElementCount::getFixed(1), 0, 0};
232 bool operator==(const VectorizationFactor
&rhs
) const {
233 return Width
== rhs
.Width
&& Cost
== rhs
.Cost
;
236 bool operator!=(const VectorizationFactor
&rhs
) const {
237 return !(*this == rhs
);
241 /// ElementCountComparator creates a total ordering for ElementCount
242 /// for the purposes of using it in a set structure.
243 struct ElementCountComparator
{
244 bool operator()(const ElementCount
&LHS
, const ElementCount
&RHS
) const {
245 return std::make_tuple(LHS
.isScalable(), LHS
.getKnownMinValue()) <
246 std::make_tuple(RHS
.isScalable(), RHS
.getKnownMinValue());
249 using ElementCountSet
= SmallSet
<ElementCount
, 16, ElementCountComparator
>;
251 /// A class that represents two vectorization factors (initialized with 0 by
252 /// default). One for fixed-width vectorization and one for scalable
253 /// vectorization. This can be used by the vectorizer to choose from a range of
254 /// fixed and/or scalable VFs in order to find the most cost-effective VF to
256 struct FixedScalableVFPair
{
257 ElementCount FixedVF
;
258 ElementCount ScalableVF
;
260 FixedScalableVFPair()
261 : FixedVF(ElementCount::getFixed(0)),
262 ScalableVF(ElementCount::getScalable(0)) {}
263 FixedScalableVFPair(const ElementCount
&Max
) : FixedScalableVFPair() {
264 *(Max
.isScalable() ? &ScalableVF
: &FixedVF
) = Max
;
266 FixedScalableVFPair(const ElementCount
&FixedVF
,
267 const ElementCount
&ScalableVF
)
268 : FixedVF(FixedVF
), ScalableVF(ScalableVF
) {
269 assert(!FixedVF
.isScalable() && ScalableVF
.isScalable() &&
270 "Invalid scalable properties");
273 static FixedScalableVFPair
getNone() { return FixedScalableVFPair(); }
275 /// \return true if either fixed- or scalable VF is non-zero.
276 explicit operator bool() const { return FixedVF
|| ScalableVF
; }
278 /// \return true if either fixed- or scalable VF is a valid vector VF.
279 bool hasVector() const { return FixedVF
.isVector() || ScalableVF
.isVector(); }
282 /// Planner drives the vectorization process after having passed
284 class LoopVectorizationPlanner
{
285 /// The loop that we evaluate.
288 /// Loop Info analysis.
291 /// The dominator tree.
294 /// Target Library Info.
295 const TargetLibraryInfo
*TLI
;
297 /// Target Transform Info.
298 const TargetTransformInfo
&TTI
;
300 /// The legality analysis.
301 LoopVectorizationLegality
*Legal
;
303 /// The profitability analysis.
304 LoopVectorizationCostModel
&CM
;
306 /// The interleaved access analysis.
307 InterleavedAccessInfo
&IAI
;
309 PredicatedScalarEvolution
&PSE
;
311 const LoopVectorizeHints
&Hints
;
313 OptimizationRemarkEmitter
*ORE
;
315 SmallVector
<VPlanPtr
, 4> VPlans
;
317 /// Profitable vector factors.
318 SmallVector
<VectorizationFactor
, 8> ProfitableVFs
;
320 /// A builder used to construct the current plan.
324 LoopVectorizationPlanner(
325 Loop
*L
, LoopInfo
*LI
, DominatorTree
*DT
, const TargetLibraryInfo
*TLI
,
326 const TargetTransformInfo
&TTI
, LoopVectorizationLegality
*Legal
,
327 LoopVectorizationCostModel
&CM
, InterleavedAccessInfo
&IAI
,
328 PredicatedScalarEvolution
&PSE
, const LoopVectorizeHints
&Hints
,
329 OptimizationRemarkEmitter
*ORE
)
330 : OrigLoop(L
), LI(LI
), DT(DT
), TLI(TLI
), TTI(TTI
), Legal(Legal
), CM(CM
),
331 IAI(IAI
), PSE(PSE
), Hints(Hints
), ORE(ORE
) {}
333 /// Plan how to best vectorize, return the best VF and its cost, or
334 /// std::nullopt if vectorization and interleaving should be avoided up front.
335 std::optional
<VectorizationFactor
> plan(ElementCount UserVF
, unsigned UserIC
);
337 /// Use the VPlan-native path to plan how to best vectorize, return the best
339 VectorizationFactor
planInVPlanNativePath(ElementCount UserVF
);
341 /// Return the best VPlan for \p VF.
342 VPlan
&getBestPlanFor(ElementCount VF
) const;
344 /// Generate the IR code for the body of the vectorized loop according to the
345 /// best selected \p VF, \p UF and VPlan \p BestPlan.
346 /// TODO: \p IsEpilogueVectorization is needed to avoid issues due to epilogue
347 /// vectorization re-using plans for both the main and epilogue vector loops.
348 /// It should be removed once the re-use issue has been fixed.
349 /// \p ExpandedSCEVs is passed during execution of the plan for epilogue loop
350 /// to re-use expansion results generated during main plan execution. Returns
351 /// a mapping of SCEVs to their expanded IR values. Note that this is a
352 /// temporary workaround needed due to the current epilogue handling.
353 DenseMap
<const SCEV
*, Value
*>
354 executePlan(ElementCount VF
, unsigned UF
, VPlan
&BestPlan
,
355 InnerLoopVectorizer
&LB
, DominatorTree
*DT
,
356 bool IsEpilogueVectorization
,
357 const DenseMap
<const SCEV
*, Value
*> *ExpandedSCEVs
= nullptr);
359 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
360 void printPlans(raw_ostream
&O
);
363 /// Look through the existing plans and return true if we have one with
364 /// vectorization factor \p VF.
365 bool hasPlanWithVF(ElementCount VF
) const {
366 return any_of(VPlans
,
367 [&](const VPlanPtr
&Plan
) { return Plan
->hasVF(VF
); });
370 /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
371 /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
372 /// returned value holds for the entire \p Range.
374 getDecisionAndClampRange(const std::function
<bool(ElementCount
)> &Predicate
,
377 /// \return The most profitable vectorization factor and the cost of that VF
378 /// for vectorizing the epilogue. Returns VectorizationFactor::Disabled if
379 /// epilogue vectorization is not supported for the loop.
381 selectEpilogueVectorizationFactor(const ElementCount MaxVF
, unsigned IC
);
384 /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
385 /// according to the information gathered by Legal when it checked if it is
386 /// legal to vectorize the loop.
387 void buildVPlans(ElementCount MinVF
, ElementCount MaxVF
);
390 /// Build a VPlan according to the information gathered by Legal. \return a
391 /// VPlan for vectorization factors \p Range.Start and up to \p Range.End
392 /// exclusive, possibly decreasing \p Range.End.
393 VPlanPtr
buildVPlan(VFRange
&Range
);
395 /// Build a VPlan using VPRecipes according to the information gather by
396 /// Legal. This method is only used for the legacy inner loop vectorizer.
397 /// \p Range's largest included VF is restricted to the maximum VF the
398 /// returned VPlan is valid for. If no VPlan can be built for the input range,
399 /// set the largest included VF to the maximum VF for which no plan could be
401 VPlanPtr
tryToBuildVPlanWithVPRecipes(VFRange
&Range
);
403 /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
404 /// according to the information gathered by Legal when it checked if it is
405 /// legal to vectorize the loop. This method creates VPlans using VPRecipes.
406 void buildVPlansWithVPRecipes(ElementCount MinVF
, ElementCount MaxVF
);
408 // Adjust the recipes for reductions. For in-loop reductions the chain of
409 // instructions leading from the loop exit instr to the phi need to be
410 // converted to reductions, with one operand being vector and the other being
411 // the scalar reduction chain. For other reductions, a select is introduced
412 // between the phi and live-out recipes when folding the tail.
413 void adjustRecipesForReductions(VPBasicBlock
*LatchVPBB
, VPlanPtr
&Plan
,
414 VPRecipeBuilder
&RecipeBuilder
,
417 /// \return The most profitable vectorization factor and the cost of that VF.
418 /// This method checks every VF in \p CandidateVFs.
420 selectVectorizationFactor(const ElementCountSet
&CandidateVFs
);
422 /// Returns true if the per-lane cost of VectorizationFactor A is lower than
424 bool isMoreProfitable(const VectorizationFactor
&A
,
425 const VectorizationFactor
&B
) const;
427 /// Determines if we have the infrastructure to vectorize the loop and its
428 /// epilogue, assuming the main loop is vectorized by \p VF.
429 bool isCandidateForEpilogueVectorization(const ElementCount VF
) const;
434 #endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H