1 //===- LoopVectorizationPlanner.h - Planner for LoopVectorization ---------===//
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 /// \file
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.
18 ///
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 //===----------------------------------------------------------------------===//
23 
24 #ifndef LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
25 #define LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
26 
27 #include "VPlan.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/Support/InstructionCost.h"
30 
31 namespace llvm {
32 
33 class LoopInfo;
34 class DominatorTree;
35 class LoopVectorizationLegality;
36 class LoopVectorizationCostModel;
37 class PredicatedScalarEvolution;
38 class LoopVectorizeHints;
39 class OptimizationRemarkEmitter;
40 class TargetTransformInfo;
41 class TargetLibraryInfo;
42 class VPRecipeBuilder;
43 
44 /// VPlan-based builder utility analogous to IRBuilder.
45 class VPBuilder {
46   VPBasicBlock *BB = nullptr;
47   VPBasicBlock::iterator InsertPt = VPBasicBlock::iterator();
48 
49   /// Insert \p VPI in BB at InsertPt if BB is set.
50   VPInstruction *tryInsertInstruction(VPInstruction *VPI) {
51     if (BB)
52       BB->insert(VPI, InsertPt);
53     return VPI;
54   }
55 
56   VPInstruction *createInstruction(unsigned Opcode,
57                                    ArrayRef<VPValue *> Operands, DebugLoc DL,
58                                    const Twine &Name = "") {
59     return tryInsertInstruction(new VPInstruction(Opcode, Operands, DL, Name));
60   }
61 
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);
66   }
67 
68 public:
69   VPBuilder() = default;
70   VPBuilder(VPBasicBlock *InsertBB) { setInsertPoint(InsertBB); }
71 
72   /// Clear the insertion point: created instructions will not be inserted into
73   /// a block.
74   void clearInsertionPoint() {
75     BB = nullptr;
76     InsertPt = VPBasicBlock::iterator();
77   }
78 
79   VPBasicBlock *getInsertBlock() const { return BB; }
80   VPBasicBlock::iterator getInsertPoint() const { return InsertPt; }
81 
82   /// InsertPoint - A saved insertion point.
83   class VPInsertPoint {
84     VPBasicBlock *Block = nullptr;
85     VPBasicBlock::iterator Point;
86 
87   public:
88     /// Creates a new insertion point which doesn't point to anything.
89     VPInsertPoint() = default;
90 
91     /// Creates a new insertion point at the given location.
92     VPInsertPoint(VPBasicBlock *InsertBlock, VPBasicBlock::iterator InsertPoint)
93         : Block(InsertBlock), Point(InsertPoint) {}
94 
95     /// Returns true if this insert point is set.
96     bool isSet() const { return Block != nullptr; }
97 
98     VPBasicBlock *getBlock() const { return Block; }
99     VPBasicBlock::iterator getPoint() const { return Point; }
100   };
101 
102   /// Sets the current insert point to a previously-saved location.
103   void restoreIP(VPInsertPoint IP) {
104     if (IP.isSet())
105       setInsertPoint(IP.getBlock(), IP.getPoint());
106     else
107       clearInsertionPoint();
108   }
109 
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");
114     BB = TheBB;
115     InsertPt = BB->end();
116   }
117 
118   /// This specifies that created instructions should be inserted at the
119   /// specified point.
120   void setInsertPoint(VPBasicBlock *TheBB, VPBasicBlock::iterator IP) {
121     BB = TheBB;
122     InsertPt = IP;
123   }
124 
125   /// This specifies that created instructions should be inserted at the
126   /// specified point.
127   void setInsertPoint(VPRecipeBase *IP) {
128     BB = IP->getParent();
129     InsertPt = IP->getIterator();
130   }
131 
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 = "") {
136     DebugLoc DL;
137     if (Inst)
138       DL = Inst->getDebugLoc();
139     VPInstruction *NewVPInst = createInstruction(Opcode, Operands, DL, Name);
140     NewVPInst->setUnderlyingValue(Inst);
141     return NewVPInst;
142   }
143   VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands,
144                         DebugLoc DL, const Twine &Name = "") {
145     return createInstruction(Opcode, Operands, DL, Name);
146   }
147 
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));
154   }
155   VPValue *createNot(VPValue *Operand, DebugLoc DL, const Twine &Name = "") {
156     return createInstruction(VPInstruction::Not, {Operand}, DL, Name);
157   }
158 
159   VPValue *createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL,
160                      const Twine &Name = "") {
161     return createInstruction(Instruction::BinaryOps::And, {LHS, RHS}, DL, Name);
162   }
163 
164   VPValue *createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL,
165                     const Twine &Name = "") {
166     return createInstruction(Instruction::BinaryOps::Or, {LHS, RHS}, DL, Name);
167   }
168 
169   VPValue *createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal,
170                         DebugLoc DL, const Twine &Name = "",
171                         std::optional<FastMathFlags> FMFs = std::nullopt) {
172     auto *Select =
173         FMFs ? new VPInstruction(Instruction::Select, {Cond, TrueVal, FalseVal},
174                                  *FMFs, DL, Name)
175              : new VPInstruction(Instruction::Select, {Cond, TrueVal, FalseVal},
176                                  DL, Name);
177     return tryInsertInstruction(Select);
178   }
179 
180   /// Create a new ICmp VPInstruction with predicate \p Pred and operands \p A
181   /// and \p B.
182   /// TODO: add createFCmp when needed.
183   VPValue *createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B,
184                       DebugLoc DL = {}, const Twine &Name = "");
185 
186   //===--------------------------------------------------------------------===//
187   // RAII helpers.
188   //===--------------------------------------------------------------------===//
189 
190   /// RAII object that stores the current insertion point and restores it when
191   /// the object is destroyed.
192   class InsertPointGuard {
193     VPBuilder &Builder;
194     VPBasicBlock *Block;
195     VPBasicBlock::iterator Point;
196 
197   public:
198     InsertPointGuard(VPBuilder &B)
199         : Builder(B), Block(B.getInsertBlock()), Point(B.getInsertPoint()) {}
200 
201     InsertPointGuard(const InsertPointGuard &) = delete;
202     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
203 
204     ~InsertPointGuard() { Builder.restoreIP(VPInsertPoint(Block, Point)); }
205   };
206 };
207 
208 /// TODO: The following VectorizationFactor was pulled out of
209 /// LoopVectorizationCostModel class. LV also deals with
210 /// VectorizerParams::VectorizationFactor and VectorizationCostTy.
211 /// We need to streamline them.
212 
213 /// Information about vectorization costs.
214 struct VectorizationFactor {
215   /// Vector width with best cost.
216   ElementCount Width;
217 
218   /// Cost of the loop with that width.
219   InstructionCost Cost;
220 
221   /// Cost of the scalar loop.
222   InstructionCost ScalarCost;
223 
224   /// The minimum trip count required to make vectorization profitable, e.g. due
225   /// to runtime checks.
226   ElementCount MinProfitableTripCount;
227 
228   VectorizationFactor(ElementCount Width, InstructionCost Cost,
229                       InstructionCost ScalarCost)
230       : Width(Width), Cost(Cost), ScalarCost(ScalarCost) {}
231 
232   /// Width 1 means no vectorization, cost 0 means uncomputed cost.
233   static VectorizationFactor Disabled() {
234     return {ElementCount::getFixed(1), 0, 0};
235   }
236 
237   bool operator==(const VectorizationFactor &rhs) const {
238     return Width == rhs.Width && Cost == rhs.Cost;
239   }
240 
241   bool operator!=(const VectorizationFactor &rhs) const {
242     return !(*this == rhs);
243   }
244 };
245 
246 /// ElementCountComparator creates a total ordering for ElementCount
247 /// for the purposes of using it in a set structure.
248 struct ElementCountComparator {
249   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
250     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
251            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
252   }
253 };
254 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
255 
256 /// A class that represents two vectorization factors (initialized with 0 by
257 /// default). One for fixed-width vectorization and one for scalable
258 /// vectorization. This can be used by the vectorizer to choose from a range of
259 /// fixed and/or scalable VFs in order to find the most cost-effective VF to
260 /// vectorize with.
261 struct FixedScalableVFPair {
262   ElementCount FixedVF;
263   ElementCount ScalableVF;
264 
265   FixedScalableVFPair()
266       : FixedVF(ElementCount::getFixed(0)),
267         ScalableVF(ElementCount::getScalable(0)) {}
268   FixedScalableVFPair(const ElementCount &Max) : FixedScalableVFPair() {
269     *(Max.isScalable() ? &ScalableVF : &FixedVF) = Max;
270   }
271   FixedScalableVFPair(const ElementCount &FixedVF,
272                       const ElementCount &ScalableVF)
273       : FixedVF(FixedVF), ScalableVF(ScalableVF) {
274     assert(!FixedVF.isScalable() && ScalableVF.isScalable() &&
275            "Invalid scalable properties");
276   }
277 
278   static FixedScalableVFPair getNone() { return FixedScalableVFPair(); }
279 
280   /// \return true if either fixed- or scalable VF is non-zero.
281   explicit operator bool() const { return FixedVF || ScalableVF; }
282 
283   /// \return true if either fixed- or scalable VF is a valid vector VF.
284   bool hasVector() const { return FixedVF.isVector() || ScalableVF.isVector(); }
285 };
286 
287 /// Planner drives the vectorization process after having passed
288 /// Legality checks.
289 class LoopVectorizationPlanner {
290   /// The loop that we evaluate.
291   Loop *OrigLoop;
292 
293   /// Loop Info analysis.
294   LoopInfo *LI;
295 
296   /// The dominator tree.
297   DominatorTree *DT;
298 
299   /// Target Library Info.
300   const TargetLibraryInfo *TLI;
301 
302   /// Target Transform Info.
303   const TargetTransformInfo &TTI;
304 
305   /// The legality analysis.
306   LoopVectorizationLegality *Legal;
307 
308   /// The profitability analysis.
309   LoopVectorizationCostModel &CM;
310 
311   /// The interleaved access analysis.
312   InterleavedAccessInfo &IAI;
313 
314   PredicatedScalarEvolution &PSE;
315 
316   const LoopVectorizeHints &Hints;
317 
318   OptimizationRemarkEmitter *ORE;
319 
320   SmallVector<VPlanPtr, 4> VPlans;
321 
322   /// Profitable vector factors.
323   SmallVector<VectorizationFactor, 8> ProfitableVFs;
324 
325   /// A builder used to construct the current plan.
326   VPBuilder Builder;
327 
328 public:
329   LoopVectorizationPlanner(
330       Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
331       const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal,
332       LoopVectorizationCostModel &CM, InterleavedAccessInfo &IAI,
333       PredicatedScalarEvolution &PSE, const LoopVectorizeHints &Hints,
334       OptimizationRemarkEmitter *ORE)
335       : OrigLoop(L), LI(LI), DT(DT), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM),
336         IAI(IAI), PSE(PSE), Hints(Hints), ORE(ORE) {}
337 
338   /// Plan how to best vectorize, return the best VF and its cost, or
339   /// std::nullopt if vectorization and interleaving should be avoided up front.
340   std::optional<VectorizationFactor> plan(ElementCount UserVF, unsigned UserIC);
341 
342   /// Use the VPlan-native path to plan how to best vectorize, return the best
343   /// VF and its cost.
344   VectorizationFactor planInVPlanNativePath(ElementCount UserVF);
345 
346   /// Return the best VPlan for \p VF.
347   VPlan &getBestPlanFor(ElementCount VF) const;
348 
349   /// Generate the IR code for the vectorized loop captured in VPlan \p BestPlan
350   /// according to the best selected \p VF and  \p UF.
351   ///
352   /// TODO: \p IsEpilogueVectorization is needed to avoid issues due to epilogue
353   /// vectorization re-using plans for both the main and epilogue vector loops.
354   /// It should be removed once the re-use issue has been fixed.
355   /// \p ExpandedSCEVs is passed during execution of the plan for epilogue loop
356   /// to re-use expansion results generated during main plan execution.
357   ///
358   /// Returns a mapping of SCEVs to their expanded IR values and a mapping for
359   /// the reduction resume values. Note that this is a temporary workaround
360   /// needed due to the current epilogue handling.
361   std::pair<DenseMap<const SCEV *, Value *>,
362             DenseMap<const RecurrenceDescriptor *, Value *>>
363   executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan,
364               InnerLoopVectorizer &LB, DominatorTree *DT,
365               bool IsEpilogueVectorization,
366               const DenseMap<const SCEV *, Value *> *ExpandedSCEVs = nullptr);
367 
368 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
369   void printPlans(raw_ostream &O);
370 #endif
371 
372   /// Look through the existing plans and return true if we have one with
373   /// vectorization factor \p VF.
374   bool hasPlanWithVF(ElementCount VF) const {
375     return any_of(VPlans,
376                   [&](const VPlanPtr &Plan) { return Plan->hasVF(VF); });
377   }
378 
379   /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
380   /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
381   /// returned value holds for the entire \p Range.
382   static bool
383   getDecisionAndClampRange(const std::function<bool(ElementCount)> &Predicate,
384                            VFRange &Range);
385 
386   /// \return The most profitable vectorization factor and the cost of that VF
387   /// for vectorizing the epilogue. Returns VectorizationFactor::Disabled if
388   /// epilogue vectorization is not supported for the loop.
389   VectorizationFactor
390   selectEpilogueVectorizationFactor(const ElementCount MaxVF, unsigned IC);
391 
392 protected:
393   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
394   /// according to the information gathered by Legal when it checked if it is
395   /// legal to vectorize the loop.
396   void buildVPlans(ElementCount MinVF, ElementCount MaxVF);
397 
398 private:
399   /// Build a VPlan according to the information gathered by Legal. \return a
400   /// VPlan for vectorization factors \p Range.Start and up to \p Range.End
401   /// exclusive, possibly decreasing \p Range.End.
402   VPlanPtr buildVPlan(VFRange &Range);
403 
404   /// Build a VPlan using VPRecipes according to the information gather by
405   /// Legal. This method is only used for the legacy inner loop vectorizer.
406   /// \p Range's largest included VF is restricted to the maximum VF the
407   /// returned VPlan is valid for. If no VPlan can be built for the input range,
408   /// set the largest included VF to the maximum VF for which no plan could be
409   /// built.
410   VPlanPtr tryToBuildVPlanWithVPRecipes(VFRange &Range);
411 
412   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
413   /// according to the information gathered by Legal when it checked if it is
414   /// legal to vectorize the loop. This method creates VPlans using VPRecipes.
415   void buildVPlansWithVPRecipes(ElementCount MinVF, ElementCount MaxVF);
416 
417   // Adjust the recipes for reductions. For in-loop reductions the chain of
418   // instructions leading from the loop exit instr to the phi need to be
419   // converted to reductions, with one operand being vector and the other being
420   // the scalar reduction chain. For other reductions, a select is introduced
421   // between the phi and live-out recipes when folding the tail.
422   void adjustRecipesForReductions(VPBasicBlock *LatchVPBB, VPlanPtr &Plan,
423                                   VPRecipeBuilder &RecipeBuilder,
424                                   ElementCount MinVF);
425 
426   /// \return The most profitable vectorization factor and the cost of that VF.
427   /// This method checks every VF in \p CandidateVFs.
428   VectorizationFactor
429   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
430 
431   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
432   /// that of B.
433   bool isMoreProfitable(const VectorizationFactor &A,
434                         const VectorizationFactor &B) const;
435 
436   /// Determines if we have the infrastructure to vectorize the loop and its
437   /// epilogue, assuming the main loop is vectorized by \p VF.
438   bool isCandidateForEpilogueVectorization(const ElementCount VF) const;
439 };
440 
441 } // namespace llvm
442 
443 #endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
444