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