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