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     VPVInstructionSC,
94     VPVMemoryInstructionSC,
95     VPVReductionSC,
96     VPVReplicateSC,
97     VPVWidenSC,
98     VPVWidenCallSC,
99     VPVWidenCanonicalIVSC,
100     VPVWidenGEPSC,
101     VPVWidenSelectSC,
102 
103     // Phi-like VPValues. Need to be kept together.
104     VPVBlendSC,
105     VPVCanonicalIVPHISC,
106     VPVFirstOrderRecurrencePHISC,
107     VPVWidenPHISC,
108     VPVWidenIntOrFpInductionSC,
109     VPVPredInstPHI,
110     VPVReductionPHISC,
111   };
112 
113   VPValue(Value *UV = nullptr, VPDef *Def = nullptr)
114       : VPValue(VPValueSC, UV, Def) {}
115   VPValue(const VPValue &) = delete;
116   VPValue &operator=(const VPValue &) = delete;
117 
118   virtual ~VPValue();
119 
120   /// \return an ID for the concrete type of this object.
121   /// This is used to implement the classof checks. This should not be used
122   /// for any other purpose, as the values may change as LLVM evolves.
123   unsigned getVPValueID() const { return SubclassID; }
124 
125 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
126   void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const;
127   void print(raw_ostream &OS, VPSlotTracker &Tracker) const;
128 
129   /// Dump the value to stderr (for debugging).
130   void dump() const;
131 #endif
132 
133   unsigned getNumUsers() const { return Users.size(); }
134   void addUser(VPUser &User) { Users.push_back(&User); }
135 
136   /// Remove a single \p User from the list of users.
137   void removeUser(VPUser &User) {
138     bool Found = false;
139     // The same user can be added multiple times, e.g. because the same VPValue
140     // is used twice by the same VPUser. Remove a single one.
141     erase_if(Users, [&User, &Found](VPUser *Other) {
142       if (Found)
143         return false;
144       if (Other == &User) {
145         Found = true;
146         return true;
147       }
148       return false;
149     });
150   }
151 
152   typedef SmallVectorImpl<VPUser *>::iterator user_iterator;
153   typedef SmallVectorImpl<VPUser *>::const_iterator const_user_iterator;
154   typedef iterator_range<user_iterator> user_range;
155   typedef iterator_range<const_user_iterator> const_user_range;
156 
157   user_iterator user_begin() { return Users.begin(); }
158   const_user_iterator user_begin() const { return Users.begin(); }
159   user_iterator user_end() { return Users.end(); }
160   const_user_iterator user_end() const { return Users.end(); }
161   user_range users() { return user_range(user_begin(), user_end()); }
162   const_user_range users() const {
163     return const_user_range(user_begin(), user_end());
164   }
165 
166   /// Returns true if the value has more than one unique user.
167   bool hasMoreThanOneUniqueUser() {
168     if (getNumUsers() == 0)
169       return false;
170 
171     // Check if all users match the first user.
172     auto Current = std::next(user_begin());
173     while (Current != user_end() && *user_begin() == *Current)
174       Current++;
175     return Current != user_end();
176   }
177 
178   void replaceAllUsesWith(VPValue *New);
179 
180   VPDef *getDef() { return Def; }
181 
182   /// Returns the underlying IR value, if this VPValue is defined outside the
183   /// scope of VPlan. Returns nullptr if the VPValue is defined by a VPDef
184   /// inside a VPlan.
185   Value *getLiveInIRValue() {
186     assert(!getDef() &&
187            "VPValue is not a live-in; it is defined by a VPDef inside a VPlan");
188     return getUnderlyingValue();
189   }
190 };
191 
192 typedef DenseMap<Value *, VPValue *> Value2VPValueTy;
193 typedef DenseMap<VPValue *, Value *> VPValue2ValueTy;
194 
195 raw_ostream &operator<<(raw_ostream &OS, const VPValue &V);
196 
197 /// This class augments VPValue with operands which provide the inverse def-use
198 /// edges from VPValue's users to their defs.
199 class VPUser {
200 public:
201   /// Subclass identifier (for isa/dyn_cast).
202   enum class VPUserID {
203     Recipe,
204     // TODO: Currently VPUsers are used in VPBlockBase, but in the future the
205     // only VPUsers should either be recipes or live-outs.
206     Block
207   };
208 
209 private:
210   SmallVector<VPValue *, 2> Operands;
211 
212   VPUserID ID;
213 
214 protected:
215 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
216   /// Print the operands to \p O.
217   void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const;
218 #endif
219 
220   VPUser(ArrayRef<VPValue *> Operands, VPUserID ID) : ID(ID) {
221     for (VPValue *Operand : Operands)
222       addOperand(Operand);
223   }
224 
225   VPUser(std::initializer_list<VPValue *> Operands, VPUserID ID)
226       : VPUser(ArrayRef<VPValue *>(Operands), ID) {}
227 
228   template <typename IterT>
229   VPUser(iterator_range<IterT> Operands, VPUserID ID) : ID(ID) {
230     for (VPValue *Operand : Operands)
231       addOperand(Operand);
232   }
233 
234 public:
235   VPUser() = delete;
236   VPUser(const VPUser &) = delete;
237   VPUser &operator=(const VPUser &) = delete;
238   virtual ~VPUser() {
239     for (VPValue *Op : operands())
240       Op->removeUser(*this);
241   }
242 
243   VPUserID getVPUserID() const { return ID; }
244 
245   void addOperand(VPValue *Operand) {
246     Operands.push_back(Operand);
247     Operand->addUser(*this);
248   }
249 
250   unsigned getNumOperands() const { return Operands.size(); }
251   inline VPValue *getOperand(unsigned N) const {
252     assert(N < Operands.size() && "Operand index out of bounds");
253     return Operands[N];
254   }
255 
256   void setOperand(unsigned I, VPValue *New) {
257     Operands[I]->removeUser(*this);
258     Operands[I] = New;
259     New->addUser(*this);
260   }
261 
262   void removeLastOperand() {
263     VPValue *Op = Operands.pop_back_val();
264     Op->removeUser(*this);
265   }
266 
267   typedef SmallVectorImpl<VPValue *>::iterator operand_iterator;
268   typedef SmallVectorImpl<VPValue *>::const_iterator const_operand_iterator;
269   typedef iterator_range<operand_iterator> operand_range;
270   typedef iterator_range<const_operand_iterator> const_operand_range;
271 
272   operand_iterator op_begin() { return Operands.begin(); }
273   const_operand_iterator op_begin() const { return Operands.begin(); }
274   operand_iterator op_end() { return Operands.end(); }
275   const_operand_iterator op_end() const { return Operands.end(); }
276   operand_range operands() { return operand_range(op_begin(), op_end()); }
277   const_operand_range operands() const {
278     return const_operand_range(op_begin(), op_end());
279   }
280 
281   /// Method to support type inquiry through isa, cast, and dyn_cast.
282   static inline bool classof(const VPDef *Recipe);
283 };
284 
285 /// This class augments a recipe with a set of VPValues defined by the recipe.
286 /// It allows recipes to define zero, one or multiple VPValues. A VPDef owns
287 /// the VPValues it defines and is responsible for deleting its defined values.
288 /// Single-value VPDefs that also inherit from VPValue must make sure to inherit
289 /// from VPDef before VPValue.
290 class VPDef {
291   friend class VPValue;
292 
293   /// Subclass identifier (for isa/dyn_cast).
294   const unsigned char SubclassID;
295 
296   /// The VPValues defined by this VPDef.
297   TinyPtrVector<VPValue *> DefinedValues;
298 
299   /// Add \p V as a defined value by this VPDef.
300   void addDefinedValue(VPValue *V) {
301     assert(V->getDef() == this &&
302            "can only add VPValue already linked with this VPDef");
303     DefinedValues.push_back(V);
304   }
305 
306   /// Remove \p V from the values defined by this VPDef. \p V must be a defined
307   /// value of this VPDef.
308   void removeDefinedValue(VPValue *V) {
309     assert(V->getDef() == this &&
310            "can only remove VPValue linked with this VPDef");
311     assert(is_contained(DefinedValues, V) &&
312            "VPValue to remove must be in DefinedValues");
313     erase_value(DefinedValues, V);
314     V->Def = nullptr;
315   }
316 
317 public:
318   /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
319   /// that is actually instantiated. Values of this enumeration are kept in the
320   /// SubclassID field of the VPRecipeBase objects. They are used for concrete
321   /// type identification.
322   using VPRecipeTy = enum {
323     VPBranchOnMaskSC,
324     VPInstructionSC,
325     VPInterleaveSC,
326     VPReductionSC,
327     VPReplicateSC,
328     VPWidenCallSC,
329     VPWidenCanonicalIVSC,
330     VPWidenGEPSC,
331     VPWidenMemoryInstructionSC,
332     VPWidenSC,
333     VPWidenSelectSC,
334 
335     // Phi-like recipes. Need to be kept together.
336     VPBlendSC,
337     VPCanonicalIVPHISC,
338     VPFirstOrderRecurrencePHISC,
339     VPWidenPHISC,
340     VPWidenIntOrFpInductionSC,
341     VPPredInstPHISC,
342     VPReductionPHISC,
343     VPFirstPHISC = VPBlendSC,
344     VPLastPHISC = VPReductionPHISC,
345   };
346 
347   VPDef(const unsigned char SC) : SubclassID(SC) {}
348 
349   virtual ~VPDef() {
350     for (VPValue *D : make_early_inc_range(DefinedValues)) {
351       assert(D->Def == this &&
352              "all defined VPValues should point to the containing VPDef");
353       assert(D->getNumUsers() == 0 &&
354              "all defined VPValues should have no more users");
355       D->Def = nullptr;
356       delete D;
357     }
358   }
359 
360   /// Returns the only VPValue defined by the VPDef. Can only be called for
361   /// VPDefs with a single defined value.
362   VPValue *getVPSingleValue() {
363     assert(DefinedValues.size() == 1 && "must have exactly one defined value");
364     assert(DefinedValues[0] && "defined value must be non-null");
365     return DefinedValues[0];
366   }
367   const VPValue *getVPSingleValue() const {
368     assert(DefinedValues.size() == 1 && "must have exactly one defined value");
369     assert(DefinedValues[0] && "defined value must be non-null");
370     return DefinedValues[0];
371   }
372 
373   /// Returns the VPValue with index \p I defined by the VPDef.
374   VPValue *getVPValue(unsigned I) {
375     assert(DefinedValues[I] && "defined value must be non-null");
376     return DefinedValues[I];
377   }
378   const VPValue *getVPValue(unsigned I) const {
379     assert(DefinedValues[I] && "defined value must be non-null");
380     return DefinedValues[I];
381   }
382 
383   /// Returns an ArrayRef of the values defined by the VPDef.
384   ArrayRef<VPValue *> definedValues() { return DefinedValues; }
385   /// Returns an ArrayRef of the values defined by the VPDef.
386   ArrayRef<VPValue *> definedValues() const { return DefinedValues; }
387 
388   /// Returns the number of values defined by the VPDef.
389   unsigned getNumDefinedValues() const { return DefinedValues.size(); }
390 
391   /// \return an ID for the concrete type of this object.
392   /// This is used to implement the classof checks. This should not be used
393   /// for any other purpose, as the values may change as LLVM evolves.
394   unsigned getVPDefID() const { return SubclassID; }
395 
396 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
397   /// Dump the VPDef to stderr (for debugging).
398   void dump() const;
399 
400   /// Each concrete VPDef prints itself.
401   virtual void print(raw_ostream &O, const Twine &Indent,
402                      VPSlotTracker &SlotTracker) const = 0;
403 #endif
404 };
405 
406 class VPlan;
407 class VPBasicBlock;
408 
409 /// This class can be used to assign consecutive numbers to all VPValues in a
410 /// VPlan and allows querying the numbering for printing, similar to the
411 /// ModuleSlotTracker for IR values.
412 class VPSlotTracker {
413   DenseMap<const VPValue *, unsigned> Slots;
414   unsigned NextSlot = 0;
415 
416   void assignSlot(const VPValue *V);
417   void assignSlots(const VPlan &Plan);
418 
419 public:
420   VPSlotTracker(const VPlan *Plan = nullptr) {
421     if (Plan)
422       assignSlots(*Plan);
423   }
424 
425   unsigned getSlot(const VPValue *V) const {
426     auto I = Slots.find(V);
427     if (I == Slots.end())
428       return -1;
429     return I->second;
430   }
431 };
432 
433 } // namespace llvm
434 
435 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_VALUE_H
436