xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlanValue.h (revision a0e1313c23296da1cf592f972ed97e5dea10b8ea)
1 //===- VPlanValue.h - Represent Values in Vectorizer Plan -----------------===//
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 contains the declarations of the entities induced by Vectorization
11 /// Plans, e.g. the instructions the VPlan intends to generate if executed.
12 /// VPlan models the following entities:
13 /// VPValue   VPUser   VPDef
14 ///    |        |
15 ///   VPInstruction
16 /// These are documented in docs/VectorizationPlan.rst.
17 ///
18 //===----------------------------------------------------------------------===//
19 
20 #ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_VALUE_H
21 #define LLVM_TRANSFORMS_VECTORIZE_VPLAN_VALUE_H
22 
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/TinyPtrVector.h"
27 #include "llvm/ADT/iterator_range.h"
28 
29 namespace llvm {
30 
31 // Forward declarations.
32 class raw_ostream;
33 class Value;
34 class VPDef;
35 class VPSlotTracker;
36 class VPUser;
37 class VPRecipeBase;
38 class VPWidenMemoryInstructionRecipe;
39 
40 // This is the base class of the VPlan Def/Use graph, used for modeling the data
41 // flow into, within and out of the VPlan. VPValues can stand for live-ins
42 // coming from the input IR, instructions which VPlan will generate if executed
43 // and live-outs which the VPlan will need to fix accordingly.
44 class VPValue {
45   friend class VPBuilder;
46   friend class VPDef;
47   friend class VPInstruction;
48   friend struct VPlanTransforms;
49   friend class VPBasicBlock;
50   friend class VPInterleavedAccessInfo;
51   friend class VPSlotTracker;
52   friend class VPRecipeBase;
53   friend class VPWidenMemoryInstructionRecipe;
54 
55   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
56 
57   SmallVector<VPUser *, 1> Users;
58 
59 protected:
60   // Hold the underlying Value, if any, attached to this VPValue.
61   Value *UnderlyingVal;
62 
63   /// Pointer to the VPDef that defines this VPValue. If it is nullptr, the
64   /// VPValue is not defined by any recipe modeled in VPlan.
65   VPDef *Def;
66 
67   VPValue(const unsigned char SC, Value *UV = nullptr, VPDef *Def = nullptr);
68 
69   // DESIGN PRINCIPLE: Access to the underlying IR must be strictly limited to
70   // the front-end and back-end of VPlan so that the middle-end is as
71   // independent as possible of the underlying IR. We grant access to the
72   // underlying IR using friendship. In that way, we should be able to use VPlan
73   // for multiple underlying IRs (Polly?) by providing a new VPlan front-end,
74   // back-end and analysis information for the new IR.
75 
76   // Set \p Val as the underlying Value of this VPValue.
77   void setUnderlyingValue(Value *Val) {
78     assert(!UnderlyingVal && "Underlying Value is already set.");
79     UnderlyingVal = Val;
80   }
81 
82 public:
83   /// Return the underlying Value attached to this VPValue.
84   Value *getUnderlyingValue() { return UnderlyingVal; }
85   const Value *getUnderlyingValue() const { return UnderlyingVal; }
86 
87   /// An enumeration for keeping track of the concrete subclass of VPValue that
88   /// are actually instantiated. Values of this enumeration are kept in the
89   /// SubclassID field of the VPValue objects. They are used for concrete
90   /// type identification.
91   enum {
92     VPValueSC,
93     VPVBlendSC,
94     VPVInstructionSC,
95     VPVMemoryInstructionSC,
96     VPVPredInstPHI,
97     VPVReductionSC,
98     VPVReplicateSC,
99     VPVWidenSC,
100     VPVWidenCallSC,
101     VPVWidenGEPSC,
102     VPVWidenIntOrFpIndcutionSC,
103     VPVWidenPHISC,
104     VPVWidenSelectSC,
105   };
106 
107   VPValue(Value *UV = nullptr, VPDef *Def = nullptr)
108       : VPValue(VPValueSC, UV, Def) {}
109   VPValue(const VPValue &) = delete;
110   VPValue &operator=(const VPValue &) = delete;
111 
112   virtual ~VPValue();
113 
114   /// \return an ID for the concrete type of this object.
115   /// This is used to implement the classof checks. This should not be used
116   /// for any other purpose, as the values may change as LLVM evolves.
117   unsigned getVPValueID() const { return SubclassID; }
118 
119 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
120   void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const;
121   void print(raw_ostream &OS, VPSlotTracker &Tracker) const;
122 
123   /// Dump the value to stderr (for debugging).
124   void dump() const;
125 #endif
126 
127   unsigned getNumUsers() const { return Users.size(); }
128   void addUser(VPUser &User) { Users.push_back(&User); }
129 
130   /// Remove a single \p User from the list of users.
131   void removeUser(VPUser &User) {
132     bool Found = false;
133     // The same user can be added multiple times, e.g. because the same VPValue
134     // is used twice by the same VPUser. Remove a single one.
135     erase_if(Users, [&User, &Found](VPUser *Other) {
136       if (Found)
137         return false;
138       if (Other == &User) {
139         Found = true;
140         return true;
141       }
142       return false;
143     });
144   }
145 
146   typedef SmallVectorImpl<VPUser *>::iterator user_iterator;
147   typedef SmallVectorImpl<VPUser *>::const_iterator const_user_iterator;
148   typedef iterator_range<user_iterator> user_range;
149   typedef iterator_range<const_user_iterator> const_user_range;
150 
151   user_iterator user_begin() { return Users.begin(); }
152   const_user_iterator user_begin() const { return Users.begin(); }
153   user_iterator user_end() { return Users.end(); }
154   const_user_iterator user_end() const { return Users.end(); }
155   user_range users() { return user_range(user_begin(), user_end()); }
156   const_user_range users() const {
157     return const_user_range(user_begin(), user_end());
158   }
159 
160   /// Returns true if the value has more than one unique user.
161   bool hasMoreThanOneUniqueUser() {
162     if (getNumUsers() == 0)
163       return false;
164 
165     // Check if all users match the first user.
166     auto Current = std::next(user_begin());
167     while (Current != user_end() && *user_begin() == *Current)
168       Current++;
169     return Current != user_end();
170   }
171 
172   void replaceAllUsesWith(VPValue *New);
173 
174   VPDef *getDef() { return Def; }
175 
176   /// Returns the underlying IR value, if this VPValue is defined outside the
177   /// scope of VPlan. Returns nullptr if the VPValue is defined by a VPDef
178   /// inside a VPlan.
179   Value *getLiveInIRValue() {
180     assert(!getDef() &&
181            "VPValue is not a live-in; it is defined by a VPDef inside a VPlan");
182     return getUnderlyingValue();
183   }
184 };
185 
186 typedef DenseMap<Value *, VPValue *> Value2VPValueTy;
187 typedef DenseMap<VPValue *, Value *> VPValue2ValueTy;
188 
189 raw_ostream &operator<<(raw_ostream &OS, const VPValue &V);
190 
191 /// This class augments VPValue with operands which provide the inverse def-use
192 /// edges from VPValue's users to their defs.
193 class VPUser {
194   SmallVector<VPValue *, 2> Operands;
195 
196 protected:
197 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
198   /// Print the operands to \p O.
199   void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const;
200 #endif
201 
202 public:
203   VPUser() {}
204   VPUser(ArrayRef<VPValue *> Operands) {
205     for (VPValue *Operand : Operands)
206       addOperand(Operand);
207   }
208 
209   VPUser(std::initializer_list<VPValue *> Operands)
210       : VPUser(ArrayRef<VPValue *>(Operands)) {}
211   template <typename IterT> VPUser(iterator_range<IterT> Operands) {
212     for (VPValue *Operand : Operands)
213       addOperand(Operand);
214   }
215 
216   VPUser(const VPUser &) = delete;
217   VPUser &operator=(const VPUser &) = delete;
218   virtual ~VPUser() {
219     for (VPValue *Op : operands())
220       Op->removeUser(*this);
221   }
222 
223   void addOperand(VPValue *Operand) {
224     Operands.push_back(Operand);
225     Operand->addUser(*this);
226   }
227 
228   unsigned getNumOperands() const { return Operands.size(); }
229   inline VPValue *getOperand(unsigned N) const {
230     assert(N < Operands.size() && "Operand index out of bounds");
231     return Operands[N];
232   }
233 
234   void setOperand(unsigned I, VPValue *New) {
235     Operands[I]->removeUser(*this);
236     Operands[I] = New;
237     New->addUser(*this);
238   }
239 
240   void removeLastOperand() {
241     VPValue *Op = Operands.pop_back_val();
242     Op->removeUser(*this);
243   }
244 
245   typedef SmallVectorImpl<VPValue *>::iterator operand_iterator;
246   typedef SmallVectorImpl<VPValue *>::const_iterator const_operand_iterator;
247   typedef iterator_range<operand_iterator> operand_range;
248   typedef iterator_range<const_operand_iterator> const_operand_range;
249 
250   operand_iterator op_begin() { return Operands.begin(); }
251   const_operand_iterator op_begin() const { return Operands.begin(); }
252   operand_iterator op_end() { return Operands.end(); }
253   const_operand_iterator op_end() const { return Operands.end(); }
254   operand_range operands() { return operand_range(op_begin(), op_end()); }
255   const_operand_range operands() const {
256     return const_operand_range(op_begin(), op_end());
257   }
258 
259   /// Method to support type inquiry through isa, cast, and dyn_cast.
260   static inline bool classof(const VPDef *Recipe);
261 };
262 
263 /// This class augments a recipe with a set of VPValues defined by the recipe.
264 /// It allows recipes to define zero, one or multiple VPValues. A VPDef owns
265 /// the VPValues it defines and is responsible for deleting its defined values.
266 /// Single-value VPDefs that also inherit from VPValue must make sure to inherit
267 /// from VPDef before VPValue.
268 class VPDef {
269   friend class VPValue;
270 
271   /// Subclass identifier (for isa/dyn_cast).
272   const unsigned char SubclassID;
273 
274   /// The VPValues defined by this VPDef.
275   TinyPtrVector<VPValue *> DefinedValues;
276 
277   /// Add \p V as a defined value by this VPDef.
278   void addDefinedValue(VPValue *V) {
279     assert(V->getDef() == this &&
280            "can only add VPValue already linked with this VPDef");
281     DefinedValues.push_back(V);
282   }
283 
284   /// Remove \p V from the values defined by this VPDef. \p V must be a defined
285   /// value of this VPDef.
286   void removeDefinedValue(VPValue *V) {
287     assert(V->getDef() == this &&
288            "can only remove VPValue linked with this VPDef");
289     assert(is_contained(DefinedValues, V) &&
290            "VPValue to remove must be in DefinedValues");
291     erase_value(DefinedValues, V);
292     V->Def = nullptr;
293   }
294 
295 public:
296   /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
297   /// that is actually instantiated. Values of this enumeration are kept in the
298   /// SubclassID field of the VPRecipeBase objects. They are used for concrete
299   /// type identification.
300   using VPRecipeTy = enum {
301     VPBlendSC,
302     VPBranchOnMaskSC,
303     VPInstructionSC,
304     VPInterleaveSC,
305     VPPredInstPHISC,
306     VPReductionSC,
307     VPReplicateSC,
308     VPWidenCallSC,
309     VPWidenCanonicalIVSC,
310     VPWidenGEPSC,
311     VPWidenIntOrFpInductionSC,
312     VPWidenMemoryInstructionSC,
313     VPWidenPHISC,
314     VPWidenSC,
315     VPWidenSelectSC
316   };
317 
318   VPDef(const unsigned char SC) : SubclassID(SC) {}
319 
320   virtual ~VPDef() {
321     for (VPValue *D : make_early_inc_range(DefinedValues)) {
322       assert(D->Def == this &&
323              "all defined VPValues should point to the containing VPDef");
324       assert(D->getNumUsers() == 0 &&
325              "all defined VPValues should have no more users");
326       D->Def = nullptr;
327       delete D;
328     }
329   }
330 
331   /// Returns the only VPValue defined by the VPDef. Can only be called for
332   /// VPDefs with a single defined value.
333   VPValue *getVPSingleValue() {
334     assert(DefinedValues.size() == 1 && "must have exactly one defined value");
335     assert(DefinedValues[0] && "defined value must be non-null");
336     return DefinedValues[0];
337   }
338   const VPValue *getVPSingleValue() const {
339     assert(DefinedValues.size() == 1 && "must have exactly one defined value");
340     assert(DefinedValues[0] && "defined value must be non-null");
341     return DefinedValues[0];
342   }
343 
344   /// Returns the VPValue with index \p I defined by the VPDef.
345   VPValue *getVPValue(unsigned I) {
346     assert(DefinedValues[I] && "defined value must be non-null");
347     return DefinedValues[I];
348   }
349   const VPValue *getVPValue(unsigned I = 0) const {
350     assert(DefinedValues[I] && "defined value must be non-null");
351     return DefinedValues[I];
352   }
353 
354   /// Returns an ArrayRef of the values defined by the VPDef.
355   ArrayRef<VPValue *> definedValues() { return DefinedValues; }
356   /// Returns an ArrayRef of the values defined by the VPDef.
357   ArrayRef<VPValue *> definedValues() const { return DefinedValues; }
358 
359   /// Returns the number of values defined by the VPDef.
360   unsigned getNumDefinedValues() const { return DefinedValues.size(); }
361 
362   /// \return an ID for the concrete type of this object.
363   /// This is used to implement the classof checks. This should not be used
364   /// for any other purpose, as the values may change as LLVM evolves.
365   unsigned getVPDefID() const { return SubclassID; }
366 
367 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
368   /// Dump the VPDef to stderr (for debugging).
369   void dump() const;
370 
371   /// Each concrete VPDef prints itself.
372   virtual void print(raw_ostream &O, const Twine &Indent,
373                      VPSlotTracker &SlotTracker) const = 0;
374 #endif
375 };
376 
377 class VPlan;
378 class VPBasicBlock;
379 class VPRegionBlock;
380 
381 /// This class can be used to assign consecutive numbers to all VPValues in a
382 /// VPlan and allows querying the numbering for printing, similar to the
383 /// ModuleSlotTracker for IR values.
384 class VPSlotTracker {
385   DenseMap<const VPValue *, unsigned> Slots;
386   unsigned NextSlot = 0;
387 
388   void assignSlot(const VPValue *V);
389   void assignSlots(const VPlan &Plan);
390 
391 public:
392   VPSlotTracker(const VPlan *Plan = nullptr) {
393     if (Plan)
394       assignSlots(*Plan);
395   }
396 
397   unsigned getSlot(const VPValue *V) const {
398     auto I = Slots.find(V);
399     if (I == Slots.end())
400       return -1;
401     return I->second;
402   }
403 };
404 
405 } // namespace llvm
406 
407 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_VALUE_H
408