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 
29 namespace llvm {
30 
31 class LoopInfo;
32 class LoopVectorizationLegality;
33 class LoopVectorizationCostModel;
34 class PredicatedScalarEvolution;
35 class LoopVectorizationRequirements;
36 class LoopVectorizeHints;
37 class OptimizationRemarkEmitter;
38 class TargetTransformInfo;
39 class TargetLibraryInfo;
40 class VPRecipeBuilder;
41 
42 /// VPlan-based builder utility analogous to IRBuilder.
43 class VPBuilder {
44   VPBasicBlock *BB = nullptr;
45   VPBasicBlock::iterator InsertPt = VPBasicBlock::iterator();
46 
47   VPInstruction *createInstruction(unsigned Opcode,
48                                    ArrayRef<VPValue *> Operands) {
49     VPInstruction *Instr = new VPInstruction(Opcode, Operands);
50     if (BB)
51       BB->insert(Instr, InsertPt);
52     return Instr;
53   }
54 
55   VPInstruction *createInstruction(unsigned Opcode,
56                                    std::initializer_list<VPValue *> Operands) {
57     return createInstruction(Opcode, ArrayRef<VPValue *>(Operands));
58   }
59 
60 public:
61   VPBuilder() {}
62 
63   /// Clear the insertion point: created instructions will not be inserted into
64   /// a block.
65   void clearInsertionPoint() {
66     BB = nullptr;
67     InsertPt = VPBasicBlock::iterator();
68   }
69 
70   VPBasicBlock *getInsertBlock() const { return BB; }
71   VPBasicBlock::iterator getInsertPoint() const { return InsertPt; }
72 
73   /// InsertPoint - A saved insertion point.
74   class VPInsertPoint {
75     VPBasicBlock *Block = nullptr;
76     VPBasicBlock::iterator Point;
77 
78   public:
79     /// Creates a new insertion point which doesn't point to anything.
80     VPInsertPoint() = default;
81 
82     /// Creates a new insertion point at the given location.
83     VPInsertPoint(VPBasicBlock *InsertBlock, VPBasicBlock::iterator InsertPoint)
84         : Block(InsertBlock), Point(InsertPoint) {}
85 
86     /// Returns true if this insert point is set.
87     bool isSet() const { return Block != nullptr; }
88 
89     VPBasicBlock *getBlock() const { return Block; }
90     VPBasicBlock::iterator getPoint() const { return Point; }
91   };
92 
93   /// Sets the current insert point to a previously-saved location.
94   void restoreIP(VPInsertPoint IP) {
95     if (IP.isSet())
96       setInsertPoint(IP.getBlock(), IP.getPoint());
97     else
98       clearInsertionPoint();
99   }
100 
101   /// This specifies that created VPInstructions should be appended to the end
102   /// of the specified block.
103   void setInsertPoint(VPBasicBlock *TheBB) {
104     assert(TheBB && "Attempting to set a null insert point");
105     BB = TheBB;
106     InsertPt = BB->end();
107   }
108 
109   /// This specifies that created instructions should be inserted at the
110   /// specified point.
111   void setInsertPoint(VPBasicBlock *TheBB, VPBasicBlock::iterator IP) {
112     BB = TheBB;
113     InsertPt = IP;
114   }
115 
116   /// Insert and return the specified instruction.
117   VPInstruction *insert(VPInstruction *I) const {
118     BB->insert(I, InsertPt);
119     return I;
120   }
121 
122   /// Create an N-ary operation with \p Opcode, \p Operands and set \p Inst as
123   /// its underlying Instruction.
124   VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands,
125                         Instruction *Inst = nullptr) {
126     VPInstruction *NewVPInst = createInstruction(Opcode, Operands);
127     NewVPInst->setUnderlyingValue(Inst);
128     return NewVPInst;
129   }
130 
131   VPValue *createNot(VPValue *Operand) {
132     return createInstruction(VPInstruction::Not, {Operand});
133   }
134 
135   VPValue *createAnd(VPValue *LHS, VPValue *RHS) {
136     return createInstruction(Instruction::BinaryOps::And, {LHS, RHS});
137   }
138 
139   VPValue *createOr(VPValue *LHS, VPValue *RHS) {
140     return createInstruction(Instruction::BinaryOps::Or, {LHS, RHS});
141   }
142 
143   VPValue *createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal) {
144     return createNaryOp(Instruction::Select, {Cond, TrueVal, FalseVal});
145   }
146 
147   //===--------------------------------------------------------------------===//
148   // RAII helpers.
149   //===--------------------------------------------------------------------===//
150 
151   /// RAII object that stores the current insertion point and restores it when
152   /// the object is destroyed.
153   class InsertPointGuard {
154     VPBuilder &Builder;
155     VPBasicBlock *Block;
156     VPBasicBlock::iterator Point;
157 
158   public:
159     InsertPointGuard(VPBuilder &B)
160         : Builder(B), Block(B.getInsertBlock()), Point(B.getInsertPoint()) {}
161 
162     InsertPointGuard(const InsertPointGuard &) = delete;
163     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
164 
165     ~InsertPointGuard() { Builder.restoreIP(VPInsertPoint(Block, Point)); }
166   };
167 };
168 
169 /// TODO: The following VectorizationFactor was pulled out of
170 /// LoopVectorizationCostModel class. LV also deals with
171 /// VectorizerParams::VectorizationFactor and VectorizationCostTy.
172 /// We need to streamline them.
173 
174 /// Information about vectorization costs.
175 struct VectorizationFactor {
176   /// Vector width with best cost.
177   ElementCount Width;
178   /// Cost of the loop with that width.
179   InstructionCost Cost;
180 
181   VectorizationFactor(ElementCount Width, InstructionCost Cost)
182       : Width(Width), Cost(Cost) {}
183 
184   /// Width 1 means no vectorization, cost 0 means uncomputed cost.
185   static VectorizationFactor Disabled() {
186     return {ElementCount::getFixed(1), 0};
187   }
188 
189   bool operator==(const VectorizationFactor &rhs) const {
190     return Width == rhs.Width && Cost == rhs.Cost;
191   }
192 
193   bool operator!=(const VectorizationFactor &rhs) const {
194     return !(*this == rhs);
195   }
196 };
197 
198 /// A class that represents two vectorization factors (initialized with 0 by
199 /// default). One for fixed-width vectorization and one for scalable
200 /// vectorization. This can be used by the vectorizer to choose from a range of
201 /// fixed and/or scalable VFs in order to find the most cost-effective VF to
202 /// vectorize with.
203 struct FixedScalableVFPair {
204   ElementCount FixedVF;
205   ElementCount ScalableVF;
206 
207   FixedScalableVFPair()
208       : FixedVF(ElementCount::getFixed(0)),
209         ScalableVF(ElementCount::getScalable(0)) {}
210   FixedScalableVFPair(const ElementCount &Max) : FixedScalableVFPair() {
211     *(Max.isScalable() ? &ScalableVF : &FixedVF) = Max;
212   }
213   FixedScalableVFPair(const ElementCount &FixedVF,
214                       const ElementCount &ScalableVF)
215       : FixedVF(FixedVF), ScalableVF(ScalableVF) {
216     assert(!FixedVF.isScalable() && ScalableVF.isScalable() &&
217            "Invalid scalable properties");
218   }
219 
220   static FixedScalableVFPair getNone() { return FixedScalableVFPair(); }
221 
222   /// \return true if either fixed- or scalable VF is non-zero.
223   explicit operator bool() const { return FixedVF || ScalableVF; }
224 
225   /// \return true if either fixed- or scalable VF is a valid vector VF.
226   bool hasVector() const { return FixedVF.isVector() || ScalableVF.isVector(); }
227 };
228 
229 /// Planner drives the vectorization process after having passed
230 /// Legality checks.
231 class LoopVectorizationPlanner {
232   /// The loop that we evaluate.
233   Loop *OrigLoop;
234 
235   /// Loop Info analysis.
236   LoopInfo *LI;
237 
238   /// Target Library Info.
239   const TargetLibraryInfo *TLI;
240 
241   /// Target Transform Info.
242   const TargetTransformInfo *TTI;
243 
244   /// The legality analysis.
245   LoopVectorizationLegality *Legal;
246 
247   /// The profitability analysis.
248   LoopVectorizationCostModel &CM;
249 
250   /// The interleaved access analysis.
251   InterleavedAccessInfo &IAI;
252 
253   PredicatedScalarEvolution &PSE;
254 
255   const LoopVectorizeHints &Hints;
256 
257   LoopVectorizationRequirements &Requirements;
258 
259   OptimizationRemarkEmitter *ORE;
260 
261   SmallVector<VPlanPtr, 4> VPlans;
262 
263   /// A builder used to construct the current plan.
264   VPBuilder Builder;
265 
266 public:
267   LoopVectorizationPlanner(Loop *L, LoopInfo *LI, const TargetLibraryInfo *TLI,
268                            const TargetTransformInfo *TTI,
269                            LoopVectorizationLegality *Legal,
270                            LoopVectorizationCostModel &CM,
271                            InterleavedAccessInfo &IAI,
272                            PredicatedScalarEvolution &PSE,
273                            const LoopVectorizeHints &Hints,
274                            LoopVectorizationRequirements &Requirements,
275                            OptimizationRemarkEmitter *ORE)
276       : OrigLoop(L), LI(LI), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM), IAI(IAI),
277         PSE(PSE), Hints(Hints), Requirements(Requirements), ORE(ORE) {}
278 
279   /// Plan how to best vectorize, return the best VF and its cost, or None if
280   /// vectorization and interleaving should be avoided up front.
281   Optional<VectorizationFactor> plan(ElementCount UserVF, unsigned UserIC);
282 
283   /// Use the VPlan-native path to plan how to best vectorize, return the best
284   /// VF and its cost.
285   VectorizationFactor planInVPlanNativePath(ElementCount UserVF);
286 
287   /// Return the best VPlan for \p VF.
288   VPlan &getBestPlanFor(ElementCount VF) const;
289 
290   /// Generate the IR code for the body of the vectorized loop according to the
291   /// best selected \p VF, \p UF and VPlan \p BestPlan.
292   void executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan,
293                    InnerLoopVectorizer &LB, DominatorTree *DT);
294 
295 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
296   void printPlans(raw_ostream &O);
297 #endif
298 
299   /// Look through the existing plans and return true if we have one with all
300   /// the vectorization factors in question.
301   bool hasPlanWithVF(ElementCount VF) const {
302     return any_of(VPlans,
303                   [&](const VPlanPtr &Plan) { return Plan->hasVF(VF); });
304   }
305 
306   /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
307   /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
308   /// returned value holds for the entire \p Range.
309   static bool
310   getDecisionAndClampRange(const std::function<bool(ElementCount)> &Predicate,
311                            VFRange &Range);
312 
313 protected:
314   /// Collect the instructions from the original loop that would be trivially
315   /// dead in the vectorized loop if generated.
316   void collectTriviallyDeadInstructions(
317       SmallPtrSetImpl<Instruction *> &DeadInstructions);
318 
319   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
320   /// according to the information gathered by Legal when it checked if it is
321   /// legal to vectorize the loop.
322   void buildVPlans(ElementCount MinVF, ElementCount MaxVF);
323 
324 private:
325   /// Build a VPlan according to the information gathered by Legal. \return a
326   /// VPlan for vectorization factors \p Range.Start and up to \p Range.End
327   /// exclusive, possibly decreasing \p Range.End.
328   VPlanPtr buildVPlan(VFRange &Range);
329 
330   /// Build a VPlan using VPRecipes according to the information gather by
331   /// Legal. This method is only used for the legacy inner loop vectorizer.
332   VPlanPtr buildVPlanWithVPRecipes(
333       VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
334       const MapVector<Instruction *, Instruction *> &SinkAfter);
335 
336   /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
337   /// according to the information gathered by Legal when it checked if it is
338   /// legal to vectorize the loop. This method creates VPlans using VPRecipes.
339   void buildVPlansWithVPRecipes(ElementCount MinVF, ElementCount MaxVF);
340 
341   // Adjust the recipes for reductions. For in-loop reductions the chain of
342   // instructions leading from the loop exit instr to the phi need to be
343   // converted to reductions, with one operand being vector and the other being
344   // the scalar reduction chain. For other reductions, a select is introduced
345   // between the phi and live-out recipes when folding the tail.
346   void adjustRecipesForReductions(VPBasicBlock *LatchVPBB, VPlanPtr &Plan,
347                                   VPRecipeBuilder &RecipeBuilder,
348                                   ElementCount MinVF);
349 };
350 
351 } // namespace llvm
352 
353 #endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
354