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