1 //===- VPlan.h - Represent A Vectorizer Plan --------------------*- C++ -*-===//
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 Vectorization Plan base classes:
11 /// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
12 ///    VPBlockBase, together implementing a Hierarchical CFG;
13 /// 2. Specializations of GraphTraits that allow VPBlockBase graphs to be
14 ///    treated as proper graphs for generic algorithms;
15 /// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained
16 ///    within VPBasicBlocks;
17 /// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
18 ///    instruction;
19 /// 5. The VPlan class holding a candidate for vectorization;
20 /// 6. The VPlanPrinter class providing a way to print a plan in dot format;
21 /// These are documented in docs/VectorizationPlan.rst.
22 //
23 //===----------------------------------------------------------------------===//
24 
25 #ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26 #define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27 
28 #include "VPlanLoopInfo.h"
29 #include "VPlanValue.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/DepthFirstIterator.h"
32 #include "llvm/ADT/GraphTraits.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/SmallBitVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/Twine.h"
39 #include "llvm/ADT/ilist.h"
40 #include "llvm/ADT/ilist_node.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include <algorithm>
44 #include <cassert>
45 #include <cstddef>
46 #include <map>
47 #include <string>
48 
49 namespace llvm {
50 
51 class BasicBlock;
52 class DominatorTree;
53 class InnerLoopVectorizer;
54 class LoopInfo;
55 class raw_ostream;
56 class RecurrenceDescriptor;
57 class Value;
58 class VPBasicBlock;
59 class VPRegionBlock;
60 class VPlan;
61 class VPlanSlp;
62 
63 /// A range of powers-of-2 vectorization factors with fixed start and
64 /// adjustable end. The range includes start and excludes end, e.g.,:
65 /// [1, 9) = {1, 2, 4, 8}
66 struct VFRange {
67   // A power of 2.
68   const ElementCount Start;
69 
70   // Need not be a power of 2. If End <= Start range is empty.
71   ElementCount End;
72 
73   bool isEmpty() const {
74     return End.getKnownMinValue() <= Start.getKnownMinValue();
75   }
76 
77   VFRange(const ElementCount &Start, const ElementCount &End)
78       : Start(Start), End(End) {
79     assert(Start.isScalable() == End.isScalable() &&
80            "Both Start and End should have the same scalable flag");
81     assert(isPowerOf2_32(Start.getKnownMinValue()) &&
82            "Expected Start to be a power of 2");
83   }
84 };
85 
86 using VPlanPtr = std::unique_ptr<VPlan>;
87 
88 /// In what follows, the term "input IR" refers to code that is fed into the
89 /// vectorizer whereas the term "output IR" refers to code that is generated by
90 /// the vectorizer.
91 
92 /// VPIteration represents a single point in the iteration space of the output
93 /// (vectorized and/or unrolled) IR loop.
94 struct VPIteration {
95   /// in [0..UF)
96   unsigned Part;
97 
98   /// in [0..VF)
99   unsigned Lane;
100 };
101 
102 /// This is a helper struct for maintaining vectorization state. It's used for
103 /// mapping values from the original loop to their corresponding values in
104 /// the new loop. Two mappings are maintained: one for vectorized values and
105 /// one for scalarized values. Vectorized values are represented with UF
106 /// vector values in the new loop, and scalarized values are represented with
107 /// UF x VF scalar values in the new loop. UF and VF are the unroll and
108 /// vectorization factors, respectively.
109 ///
110 /// Entries can be added to either map with setVectorValue and setScalarValue,
111 /// which assert that an entry was not already added before. If an entry is to
112 /// replace an existing one, call resetVectorValue and resetScalarValue. This is
113 /// currently needed to modify the mapped values during "fix-up" operations that
114 /// occur once the first phase of widening is complete. These operations include
115 /// type truncation and the second phase of recurrence widening.
116 ///
117 /// Entries from either map can be retrieved using the getVectorValue and
118 /// getScalarValue functions, which assert that the desired value exists.
119 struct VectorizerValueMap {
120   friend struct VPTransformState;
121 
122 private:
123   /// The unroll factor. Each entry in the vector map contains UF vector values.
124   unsigned UF;
125 
126   /// The vectorization factor. Each entry in the scalar map contains UF x VF
127   /// scalar values.
128   ElementCount VF;
129 
130   /// The vector and scalar map storage. We use std::map and not DenseMap
131   /// because insertions to DenseMap invalidate its iterators.
132   using VectorParts = SmallVector<Value *, 2>;
133   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
134   std::map<Value *, VectorParts> VectorMapStorage;
135   std::map<Value *, ScalarParts> ScalarMapStorage;
136 
137 public:
138   /// Construct an empty map with the given unroll and vectorization factors.
139   VectorizerValueMap(unsigned UF, ElementCount VF) : UF(UF), VF(VF) {}
140 
141   /// \return True if the map has any vector entry for \p Key.
142   bool hasAnyVectorValue(Value *Key) const {
143     return VectorMapStorage.count(Key);
144   }
145 
146   /// \return True if the map has a vector entry for \p Key and \p Part.
147   bool hasVectorValue(Value *Key, unsigned Part) const {
148     assert(Part < UF && "Queried Vector Part is too large.");
149     if (!hasAnyVectorValue(Key))
150       return false;
151     const VectorParts &Entry = VectorMapStorage.find(Key)->second;
152     assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
153     return Entry[Part] != nullptr;
154   }
155 
156   /// \return True if the map has any scalar entry for \p Key.
157   bool hasAnyScalarValue(Value *Key) const {
158     return ScalarMapStorage.count(Key);
159   }
160 
161   /// \return True if the map has a scalar entry for \p Key and \p Instance.
162   bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
163     assert(Instance.Part < UF && "Queried Scalar Part is too large.");
164     assert(Instance.Lane < VF.getKnownMinValue() &&
165            "Queried Scalar Lane is too large.");
166     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
167 
168     if (!hasAnyScalarValue(Key))
169       return false;
170     const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
171     assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
172     assert(Entry[Instance.Part].size() == VF.getKnownMinValue() &&
173            "ScalarParts has wrong dimensions.");
174     return Entry[Instance.Part][Instance.Lane] != nullptr;
175   }
176 
177   /// Retrieve the existing vector value that corresponds to \p Key and
178   /// \p Part.
179   Value *getVectorValue(Value *Key, unsigned Part) {
180     assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
181     return VectorMapStorage[Key][Part];
182   }
183 
184   /// Retrieve the existing scalar value that corresponds to \p Key and
185   /// \p Instance.
186   Value *getScalarValue(Value *Key, const VPIteration &Instance) {
187     assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
188     return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
189   }
190 
191   /// Set a vector value associated with \p Key and \p Part. Assumes such a
192   /// value is not already set. If it is, use resetVectorValue() instead.
193   void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
194     assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
195     if (!VectorMapStorage.count(Key)) {
196       VectorParts Entry(UF);
197       VectorMapStorage[Key] = Entry;
198     }
199     VectorMapStorage[Key][Part] = Vector;
200   }
201 
202   /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
203   /// value is not already set.
204   void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
205     assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
206     if (!ScalarMapStorage.count(Key)) {
207       ScalarParts Entry(UF);
208       // TODO: Consider storing uniform values only per-part, as they occupy
209       //       lane 0 only, keeping the other VF-1 redundant entries null.
210       for (unsigned Part = 0; Part < UF; ++Part)
211         Entry[Part].resize(VF.getKnownMinValue(), nullptr);
212       ScalarMapStorage[Key] = Entry;
213     }
214     ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
215   }
216 
217   /// Reset the vector value associated with \p Key for the given \p Part.
218   /// This function can be used to update values that have already been
219   /// vectorized. This is the case for "fix-up" operations including type
220   /// truncation and the second phase of recurrence vectorization.
221   void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
222     assert(hasVectorValue(Key, Part) && "Vector value not set for part");
223     VectorMapStorage[Key][Part] = Vector;
224   }
225 
226   /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
227   /// This function can be used to update values that have already been
228   /// scalarized. This is the case for "fix-up" operations including scalar phi
229   /// nodes for scalarized and predicated instructions.
230   void resetScalarValue(Value *Key, const VPIteration &Instance,
231                         Value *Scalar) {
232     assert(hasScalarValue(Key, Instance) &&
233            "Scalar value not set for part and lane");
234     ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
235   }
236 };
237 
238 /// This class is used to enable the VPlan to invoke a method of ILV. This is
239 /// needed until the method is refactored out of ILV and becomes reusable.
240 struct VPCallback {
241   virtual ~VPCallback() {}
242   virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
243   virtual Value *getOrCreateScalarValue(Value *V,
244                                         const VPIteration &Instance) = 0;
245 };
246 
247 /// VPTransformState holds information passed down when "executing" a VPlan,
248 /// needed for generating the output IR.
249 struct VPTransformState {
250   VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,
251                    DominatorTree *DT, IRBuilder<> &Builder,
252                    VectorizerValueMap &ValueMap, InnerLoopVectorizer *ILV,
253                    VPCallback &Callback)
254       : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
255         ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
256 
257   /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
258   ElementCount VF;
259   unsigned UF;
260 
261   /// Hold the indices to generate specific scalar instructions. Null indicates
262   /// that all instances are to be generated, using either scalar or vector
263   /// instructions.
264   Optional<VPIteration> Instance;
265 
266   struct DataState {
267     /// A type for vectorized values in the new loop. Each value from the
268     /// original loop, when vectorized, is represented by UF vector values in
269     /// the new unrolled loop, where UF is the unroll factor.
270     typedef SmallVector<Value *, 2> PerPartValuesTy;
271 
272     DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
273   } Data;
274 
275   /// Get the generated Value for a given VPValue and a given Part. Note that
276   /// as some Defs are still created by ILV and managed in its ValueMap, this
277   /// method will delegate the call to ILV in such cases in order to provide
278   /// callers a consistent API.
279   /// \see set.
280   Value *get(VPValue *Def, unsigned Part) {
281     // If Values have been set for this Def return the one relevant for \p Part.
282     if (Data.PerPartOutput.count(Def))
283       return Data.PerPartOutput[Def][Part];
284     // Def is managed by ILV: bring the Values from ValueMap.
285     return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
286   }
287 
288   /// Get the generated Value for a given VPValue and given Part and Lane.
289   Value *get(VPValue *Def, const VPIteration &Instance) {
290     // If the Def is managed directly by VPTransformState, extract the lane from
291     // the relevant part. Note that currently only VPInstructions and external
292     // defs are managed by VPTransformState. Other Defs are still created by ILV
293     // and managed in its ValueMap. For those this method currently just
294     // delegates the call to ILV below.
295     if (Data.PerPartOutput.count(Def)) {
296       auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
297       if (!VecPart->getType()->isVectorTy()) {
298         assert(Instance.Lane == 0 && "cannot get lane > 0 for scalar");
299         return VecPart;
300       }
301       // TODO: Cache created scalar values.
302       return Builder.CreateExtractElement(VecPart,
303                                           Builder.getInt32(Instance.Lane));
304     }
305 
306     return Callback.getOrCreateScalarValue(VPValue2Value[Def], Instance);
307   }
308 
309   /// Set the generated Value for a given VPValue and a given Part.
310   void set(VPValue *Def, Value *V, unsigned Part) {
311     if (!Data.PerPartOutput.count(Def)) {
312       DataState::PerPartValuesTy Entry(UF);
313       Data.PerPartOutput[Def] = Entry;
314     }
315     Data.PerPartOutput[Def][Part] = V;
316   }
317   void set(VPValue *Def, Value *IRDef, Value *V, unsigned Part);
318 
319   /// Hold state information used when constructing the CFG of the output IR,
320   /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
321   struct CFGState {
322     /// The previous VPBasicBlock visited. Initially set to null.
323     VPBasicBlock *PrevVPBB = nullptr;
324 
325     /// The previous IR BasicBlock created or used. Initially set to the new
326     /// header BasicBlock.
327     BasicBlock *PrevBB = nullptr;
328 
329     /// The last IR BasicBlock in the output IR. Set to the new latch
330     /// BasicBlock, used for placing the newly created BasicBlocks.
331     BasicBlock *LastBB = nullptr;
332 
333     /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
334     /// of replication, maps the BasicBlock of the last replica created.
335     SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
336 
337     /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed
338     /// up at the end of vector code generation.
339     SmallVector<VPBasicBlock *, 8> VPBBsToFix;
340 
341     CFGState() = default;
342   } CFG;
343 
344   /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
345   LoopInfo *LI;
346 
347   /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
348   DominatorTree *DT;
349 
350   /// Hold a reference to the IRBuilder used to generate output IR code.
351   IRBuilder<> &Builder;
352 
353   /// Hold a reference to the Value state information used when generating the
354   /// Values of the output IR.
355   VectorizerValueMap &ValueMap;
356 
357   /// Hold a reference to a mapping between VPValues in VPlan and original
358   /// Values they correspond to.
359   VPValue2ValueTy VPValue2Value;
360 
361   /// Hold the canonical scalar IV of the vector loop (start=0, step=VF*UF).
362   Value *CanonicalIV = nullptr;
363 
364   /// Hold the trip count of the scalar loop.
365   Value *TripCount = nullptr;
366 
367   /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
368   InnerLoopVectorizer *ILV;
369 
370   VPCallback &Callback;
371 };
372 
373 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
374 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
375 class VPBlockBase {
376   friend class VPBlockUtils;
377 
378   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
379 
380   /// An optional name for the block.
381   std::string Name;
382 
383   /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
384   /// it is a topmost VPBlockBase.
385   VPRegionBlock *Parent = nullptr;
386 
387   /// List of predecessor blocks.
388   SmallVector<VPBlockBase *, 1> Predecessors;
389 
390   /// List of successor blocks.
391   SmallVector<VPBlockBase *, 1> Successors;
392 
393   /// Successor selector, null for zero or single successor blocks.
394   VPValue *CondBit = nullptr;
395 
396   /// Current block predicate - null if the block does not need a predicate.
397   VPValue *Predicate = nullptr;
398 
399   /// VPlan containing the block. Can only be set on the entry block of the
400   /// plan.
401   VPlan *Plan = nullptr;
402 
403   /// Add \p Successor as the last successor to this block.
404   void appendSuccessor(VPBlockBase *Successor) {
405     assert(Successor && "Cannot add nullptr successor!");
406     Successors.push_back(Successor);
407   }
408 
409   /// Add \p Predecessor as the last predecessor to this block.
410   void appendPredecessor(VPBlockBase *Predecessor) {
411     assert(Predecessor && "Cannot add nullptr predecessor!");
412     Predecessors.push_back(Predecessor);
413   }
414 
415   /// Remove \p Predecessor from the predecessors of this block.
416   void removePredecessor(VPBlockBase *Predecessor) {
417     auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
418     assert(Pos && "Predecessor does not exist");
419     Predecessors.erase(Pos);
420   }
421 
422   /// Remove \p Successor from the successors of this block.
423   void removeSuccessor(VPBlockBase *Successor) {
424     auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
425     assert(Pos && "Successor does not exist");
426     Successors.erase(Pos);
427   }
428 
429 protected:
430   VPBlockBase(const unsigned char SC, const std::string &N)
431       : SubclassID(SC), Name(N) {}
432 
433 public:
434   /// An enumeration for keeping track of the concrete subclass of VPBlockBase
435   /// that are actually instantiated. Values of this enumeration are kept in the
436   /// SubclassID field of the VPBlockBase objects. They are used for concrete
437   /// type identification.
438   using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
439 
440   using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
441 
442   virtual ~VPBlockBase() = default;
443 
444   const std::string &getName() const { return Name; }
445 
446   void setName(const Twine &newName) { Name = newName.str(); }
447 
448   /// \return an ID for the concrete type of this object.
449   /// This is used to implement the classof checks. This should not be used
450   /// for any other purpose, as the values may change as LLVM evolves.
451   unsigned getVPBlockID() const { return SubclassID; }
452 
453   VPRegionBlock *getParent() { return Parent; }
454   const VPRegionBlock *getParent() const { return Parent; }
455 
456   /// \return A pointer to the plan containing the current block.
457   VPlan *getPlan();
458   const VPlan *getPlan() const;
459 
460   /// Sets the pointer of the plan containing the block. The block must be the
461   /// entry block into the VPlan.
462   void setPlan(VPlan *ParentPlan);
463 
464   void setParent(VPRegionBlock *P) { Parent = P; }
465 
466   /// \return the VPBasicBlock that is the entry of this VPBlockBase,
467   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
468   /// VPBlockBase is a VPBasicBlock, it is returned.
469   const VPBasicBlock *getEntryBasicBlock() const;
470   VPBasicBlock *getEntryBasicBlock();
471 
472   /// \return the VPBasicBlock that is the exit of this VPBlockBase,
473   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
474   /// VPBlockBase is a VPBasicBlock, it is returned.
475   const VPBasicBlock *getExitBasicBlock() const;
476   VPBasicBlock *getExitBasicBlock();
477 
478   const VPBlocksTy &getSuccessors() const { return Successors; }
479   VPBlocksTy &getSuccessors() { return Successors; }
480 
481   const VPBlocksTy &getPredecessors() const { return Predecessors; }
482   VPBlocksTy &getPredecessors() { return Predecessors; }
483 
484   /// \return the successor of this VPBlockBase if it has a single successor.
485   /// Otherwise return a null pointer.
486   VPBlockBase *getSingleSuccessor() const {
487     return (Successors.size() == 1 ? *Successors.begin() : nullptr);
488   }
489 
490   /// \return the predecessor of this VPBlockBase if it has a single
491   /// predecessor. Otherwise return a null pointer.
492   VPBlockBase *getSinglePredecessor() const {
493     return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
494   }
495 
496   size_t getNumSuccessors() const { return Successors.size(); }
497   size_t getNumPredecessors() const { return Predecessors.size(); }
498 
499   /// An Enclosing Block of a block B is any block containing B, including B
500   /// itself. \return the closest enclosing block starting from "this", which
501   /// has successors. \return the root enclosing block if all enclosing blocks
502   /// have no successors.
503   VPBlockBase *getEnclosingBlockWithSuccessors();
504 
505   /// \return the closest enclosing block starting from "this", which has
506   /// predecessors. \return the root enclosing block if all enclosing blocks
507   /// have no predecessors.
508   VPBlockBase *getEnclosingBlockWithPredecessors();
509 
510   /// \return the successors either attached directly to this VPBlockBase or, if
511   /// this VPBlockBase is the exit block of a VPRegionBlock and has no
512   /// successors of its own, search recursively for the first enclosing
513   /// VPRegionBlock that has successors and return them. If no such
514   /// VPRegionBlock exists, return the (empty) successors of the topmost
515   /// VPBlockBase reached.
516   const VPBlocksTy &getHierarchicalSuccessors() {
517     return getEnclosingBlockWithSuccessors()->getSuccessors();
518   }
519 
520   /// \return the hierarchical successor of this VPBlockBase if it has a single
521   /// hierarchical successor. Otherwise return a null pointer.
522   VPBlockBase *getSingleHierarchicalSuccessor() {
523     return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
524   }
525 
526   /// \return the predecessors either attached directly to this VPBlockBase or,
527   /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
528   /// predecessors of its own, search recursively for the first enclosing
529   /// VPRegionBlock that has predecessors and return them. If no such
530   /// VPRegionBlock exists, return the (empty) predecessors of the topmost
531   /// VPBlockBase reached.
532   const VPBlocksTy &getHierarchicalPredecessors() {
533     return getEnclosingBlockWithPredecessors()->getPredecessors();
534   }
535 
536   /// \return the hierarchical predecessor of this VPBlockBase if it has a
537   /// single hierarchical predecessor. Otherwise return a null pointer.
538   VPBlockBase *getSingleHierarchicalPredecessor() {
539     return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
540   }
541 
542   /// \return the condition bit selecting the successor.
543   VPValue *getCondBit() { return CondBit; }
544 
545   const VPValue *getCondBit() const { return CondBit; }
546 
547   void setCondBit(VPValue *CV) { CondBit = CV; }
548 
549   VPValue *getPredicate() { return Predicate; }
550 
551   const VPValue *getPredicate() const { return Predicate; }
552 
553   void setPredicate(VPValue *Pred) { Predicate = Pred; }
554 
555   /// Set a given VPBlockBase \p Successor as the single successor of this
556   /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
557   /// This VPBlockBase must have no successors.
558   void setOneSuccessor(VPBlockBase *Successor) {
559     assert(Successors.empty() && "Setting one successor when others exist.");
560     appendSuccessor(Successor);
561   }
562 
563   /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
564   /// successors of this VPBlockBase. \p Condition is set as the successor
565   /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
566   /// IfFalse. This VPBlockBase must have no successors.
567   void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
568                         VPValue *Condition) {
569     assert(Successors.empty() && "Setting two successors when others exist.");
570     assert(Condition && "Setting two successors without condition!");
571     CondBit = Condition;
572     appendSuccessor(IfTrue);
573     appendSuccessor(IfFalse);
574   }
575 
576   /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
577   /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
578   /// as successor of any VPBasicBlock in \p NewPreds.
579   void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
580     assert(Predecessors.empty() && "Block predecessors already set.");
581     for (auto *Pred : NewPreds)
582       appendPredecessor(Pred);
583   }
584 
585   /// Remove all the predecessor of this block.
586   void clearPredecessors() { Predecessors.clear(); }
587 
588   /// Remove all the successors of this block and set to null its condition bit
589   void clearSuccessors() {
590     Successors.clear();
591     CondBit = nullptr;
592   }
593 
594   /// The method which generates the output IR that correspond to this
595   /// VPBlockBase, thereby "executing" the VPlan.
596   virtual void execute(struct VPTransformState *State) = 0;
597 
598   /// Delete all blocks reachable from a given VPBlockBase, inclusive.
599   static void deleteCFG(VPBlockBase *Entry);
600 
601   void printAsOperand(raw_ostream &OS, bool PrintType) const {
602     OS << getName();
603   }
604 
605   void print(raw_ostream &OS) const {
606     // TODO: Only printing VPBB name for now since we only have dot printing
607     // support for VPInstructions/Recipes.
608     printAsOperand(OS, false);
609   }
610 
611   /// Return true if it is legal to hoist instructions into this block.
612   bool isLegalToHoistInto() {
613     // There are currently no constraints that prevent an instruction to be
614     // hoisted into a VPBlockBase.
615     return true;
616   }
617 };
618 
619 /// VPRecipeBase is a base class modeling a sequence of one or more output IR
620 /// instructions.
621 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
622   friend VPBasicBlock;
623   friend class VPBlockUtils;
624 
625   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
626 
627   /// Each VPRecipe belongs to a single VPBasicBlock.
628   VPBasicBlock *Parent = nullptr;
629 
630 public:
631   /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
632   /// that is actually instantiated. Values of this enumeration are kept in the
633   /// SubclassID field of the VPRecipeBase objects. They are used for concrete
634   /// type identification.
635   using VPRecipeTy = enum {
636     VPBlendSC,
637     VPBranchOnMaskSC,
638     VPInstructionSC,
639     VPInterleaveSC,
640     VPPredInstPHISC,
641     VPReductionSC,
642     VPReplicateSC,
643     VPWidenCallSC,
644     VPWidenCanonicalIVSC,
645     VPWidenGEPSC,
646     VPWidenIntOrFpInductionSC,
647     VPWidenMemoryInstructionSC,
648     VPWidenPHISC,
649     VPWidenSC,
650     VPWidenSelectSC
651   };
652 
653   VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
654   virtual ~VPRecipeBase() = default;
655 
656   /// \return an ID for the concrete type of this object.
657   /// This is used to implement the classof checks. This should not be used
658   /// for any other purpose, as the values may change as LLVM evolves.
659   unsigned getVPRecipeID() const { return SubclassID; }
660 
661   /// \return the VPBasicBlock which this VPRecipe belongs to.
662   VPBasicBlock *getParent() { return Parent; }
663   const VPBasicBlock *getParent() const { return Parent; }
664 
665   /// The method which generates the output IR instructions that correspond to
666   /// this VPRecipe, thereby "executing" the VPlan.
667   virtual void execute(struct VPTransformState &State) = 0;
668 
669   /// Each recipe prints itself.
670   virtual void print(raw_ostream &O, const Twine &Indent,
671                      VPSlotTracker &SlotTracker) const = 0;
672 
673   /// Dump the recipe to stderr (for debugging).
674   void dump() const;
675 
676   /// Insert an unlinked recipe into a basic block immediately before
677   /// the specified recipe.
678   void insertBefore(VPRecipeBase *InsertPos);
679 
680   /// Insert an unlinked Recipe into a basic block immediately after
681   /// the specified Recipe.
682   void insertAfter(VPRecipeBase *InsertPos);
683 
684   /// Unlink this recipe from its current VPBasicBlock and insert it into
685   /// the VPBasicBlock that MovePos lives in, right after MovePos.
686   void moveAfter(VPRecipeBase *MovePos);
687 
688   /// This method unlinks 'this' from the containing basic block, but does not
689   /// delete it.
690   void removeFromParent();
691 
692   /// This method unlinks 'this' from the containing basic block and deletes it.
693   ///
694   /// \returns an iterator pointing to the element after the erased one
695   iplist<VPRecipeBase>::iterator eraseFromParent();
696 
697   /// Returns a pointer to a VPUser, if the recipe inherits from VPUser or
698   /// nullptr otherwise.
699   VPUser *toVPUser();
700 
701   /// Returns a pointer to a VPValue, if the recipe inherits from VPValue or
702   /// nullptr otherwise.
703   VPValue *toVPValue();
704   const VPValue *toVPValue() const;
705 
706   /// Returns the underlying instruction, if the recipe is a VPValue or nullptr
707   /// otherwise.
708   Instruction *getUnderlyingInstr() {
709     if (auto *VPV = toVPValue())
710       return cast_or_null<Instruction>(VPV->getUnderlyingValue());
711     return nullptr;
712   }
713   const Instruction *getUnderlyingInstr() const {
714     if (auto *VPV = toVPValue())
715       return cast_or_null<Instruction>(VPV->getUnderlyingValue());
716     return nullptr;
717   }
718 };
719 
720 inline bool VPUser::classof(const VPRecipeBase *Recipe) {
721   return Recipe->getVPRecipeID() == VPRecipeBase::VPInstructionSC ||
722          Recipe->getVPRecipeID() == VPRecipeBase::VPWidenSC ||
723          Recipe->getVPRecipeID() == VPRecipeBase::VPWidenCallSC ||
724          Recipe->getVPRecipeID() == VPRecipeBase::VPWidenSelectSC ||
725          Recipe->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC ||
726          Recipe->getVPRecipeID() == VPRecipeBase::VPBlendSC ||
727          Recipe->getVPRecipeID() == VPRecipeBase::VPInterleaveSC ||
728          Recipe->getVPRecipeID() == VPRecipeBase::VPReplicateSC ||
729          Recipe->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC ||
730          Recipe->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
731 }
732 
733 /// This is a concrete Recipe that models a single VPlan-level instruction.
734 /// While as any Recipe it may generate a sequence of IR instructions when
735 /// executed, these instructions would always form a single-def expression as
736 /// the VPInstruction is also a single def-use vertex.
737 class VPInstruction : public VPUser, public VPValue, public VPRecipeBase {
738   friend class VPlanSlp;
739 
740 public:
741   /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
742   enum {
743     Not = Instruction::OtherOpsEnd + 1,
744     ICmpULE,
745     SLPLoad,
746     SLPStore,
747     ActiveLaneMask,
748   };
749 
750 private:
751   typedef unsigned char OpcodeTy;
752   OpcodeTy Opcode;
753 
754   /// Utility method serving execute(): generates a single instance of the
755   /// modeled instruction.
756   void generateInstruction(VPTransformState &State, unsigned Part);
757 
758 protected:
759   void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); }
760 
761 public:
762   VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
763       : VPUser(Operands), VPValue(VPValue::VPInstructionSC),
764         VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
765 
766   VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
767       : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
768 
769   /// Method to support type inquiry through isa, cast, and dyn_cast.
770   static inline bool classof(const VPValue *V) {
771     return V->getVPValueID() == VPValue::VPInstructionSC;
772   }
773 
774   VPInstruction *clone() const {
775     SmallVector<VPValue *, 2> Operands(operands());
776     return new VPInstruction(Opcode, Operands);
777   }
778 
779   /// Method to support type inquiry through isa, cast, and dyn_cast.
780   static inline bool classof(const VPRecipeBase *R) {
781     return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
782   }
783 
784   unsigned getOpcode() const { return Opcode; }
785 
786   /// Generate the instruction.
787   /// TODO: We currently execute only per-part unless a specific instance is
788   /// provided.
789   void execute(VPTransformState &State) override;
790 
791   /// Print the Recipe.
792   void print(raw_ostream &O, const Twine &Indent,
793              VPSlotTracker &SlotTracker) const override;
794 
795   /// Print the VPInstruction.
796   void print(raw_ostream &O) const;
797   void print(raw_ostream &O, VPSlotTracker &SlotTracker) const;
798 
799   /// Return true if this instruction may modify memory.
800   bool mayWriteToMemory() const {
801     // TODO: we can use attributes of the called function to rule out memory
802     //       modifications.
803     return Opcode == Instruction::Store || Opcode == Instruction::Call ||
804            Opcode == Instruction::Invoke || Opcode == SLPStore;
805   }
806 
807   bool hasResult() const {
808     // CallInst may or may not have a result, depending on the called function.
809     // Conservatively return calls have results for now.
810     switch (getOpcode()) {
811     case Instruction::Ret:
812     case Instruction::Br:
813     case Instruction::Store:
814     case Instruction::Switch:
815     case Instruction::IndirectBr:
816     case Instruction::Resume:
817     case Instruction::CatchRet:
818     case Instruction::Unreachable:
819     case Instruction::Fence:
820     case Instruction::AtomicRMW:
821       return false;
822     default:
823       return true;
824     }
825   }
826 };
827 
828 /// VPWidenRecipe is a recipe for producing a copy of vector type its
829 /// ingredient. This recipe covers most of the traditional vectorization cases
830 /// where each ingredient transforms into a vectorized version of itself.
831 class VPWidenRecipe : public VPRecipeBase, public VPUser {
832   /// Hold the instruction to be widened.
833   Instruction &Ingredient;
834 
835 public:
836   template <typename IterT>
837   VPWidenRecipe(Instruction &I, iterator_range<IterT> Operands)
838       : VPRecipeBase(VPWidenSC), VPUser(Operands), Ingredient(I) {}
839 
840   ~VPWidenRecipe() override = default;
841 
842   /// Method to support type inquiry through isa, cast, and dyn_cast.
843   static inline bool classof(const VPRecipeBase *V) {
844     return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
845   }
846 
847   /// Produce widened copies of all Ingredients.
848   void execute(VPTransformState &State) override;
849 
850   /// Print the recipe.
851   void print(raw_ostream &O, const Twine &Indent,
852              VPSlotTracker &SlotTracker) const override;
853 };
854 
855 /// A recipe for widening Call instructions.
856 class VPWidenCallRecipe : public VPRecipeBase, public VPUser {
857   /// Hold the call to be widened.
858   CallInst &Ingredient;
859 
860 public:
861   template <typename IterT>
862   VPWidenCallRecipe(CallInst &I, iterator_range<IterT> CallArguments)
863       : VPRecipeBase(VPWidenCallSC), VPUser(CallArguments), Ingredient(I) {}
864 
865   ~VPWidenCallRecipe() override = default;
866 
867   /// Method to support type inquiry through isa, cast, and dyn_cast.
868   static inline bool classof(const VPRecipeBase *V) {
869     return V->getVPRecipeID() == VPRecipeBase::VPWidenCallSC;
870   }
871 
872   /// Produce a widened version of the call instruction.
873   void execute(VPTransformState &State) override;
874 
875   /// Print the recipe.
876   void print(raw_ostream &O, const Twine &Indent,
877              VPSlotTracker &SlotTracker) const override;
878 };
879 
880 /// A recipe for widening select instructions.
881 class VPWidenSelectRecipe : public VPRecipeBase, public VPUser {
882 private:
883   /// Hold the select to be widened.
884   SelectInst &Ingredient;
885 
886   /// Is the condition of the select loop invariant?
887   bool InvariantCond;
888 
889 public:
890   template <typename IterT>
891   VPWidenSelectRecipe(SelectInst &I, iterator_range<IterT> Operands,
892                       bool InvariantCond)
893       : VPRecipeBase(VPWidenSelectSC), VPUser(Operands), Ingredient(I),
894         InvariantCond(InvariantCond) {}
895 
896   ~VPWidenSelectRecipe() override = default;
897 
898   /// Method to support type inquiry through isa, cast, and dyn_cast.
899   static inline bool classof(const VPRecipeBase *V) {
900     return V->getVPRecipeID() == VPRecipeBase::VPWidenSelectSC;
901   }
902 
903   /// Produce a widened version of the select instruction.
904   void execute(VPTransformState &State) override;
905 
906   /// Print the recipe.
907   void print(raw_ostream &O, const Twine &Indent,
908              VPSlotTracker &SlotTracker) const override;
909 };
910 
911 /// A recipe for handling GEP instructions.
912 class VPWidenGEPRecipe : public VPRecipeBase, public VPUser {
913   GetElementPtrInst *GEP;
914 
915   bool IsPtrLoopInvariant;
916   SmallBitVector IsIndexLoopInvariant;
917 
918 public:
919   template <typename IterT>
920   VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands)
921       : VPRecipeBase(VPWidenGEPSC), VPUser(Operands), GEP(GEP),
922         IsIndexLoopInvariant(GEP->getNumIndices(), false) {}
923 
924   template <typename IterT>
925   VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands,
926                    Loop *OrigLoop)
927       : VPRecipeBase(VPWidenGEPSC), VPUser(Operands), GEP(GEP),
928         IsIndexLoopInvariant(GEP->getNumIndices(), false) {
929     IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand());
930     for (auto Index : enumerate(GEP->indices()))
931       IsIndexLoopInvariant[Index.index()] =
932           OrigLoop->isLoopInvariant(Index.value().get());
933   }
934   ~VPWidenGEPRecipe() override = default;
935 
936   /// Method to support type inquiry through isa, cast, and dyn_cast.
937   static inline bool classof(const VPRecipeBase *V) {
938     return V->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC;
939   }
940 
941   /// Generate the gep nodes.
942   void execute(VPTransformState &State) override;
943 
944   /// Print the recipe.
945   void print(raw_ostream &O, const Twine &Indent,
946              VPSlotTracker &SlotTracker) const override;
947 };
948 
949 /// A recipe for handling phi nodes of integer and floating-point inductions,
950 /// producing their vector and scalar values.
951 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
952   PHINode *IV;
953   TruncInst *Trunc;
954 
955 public:
956   VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
957       : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
958   ~VPWidenIntOrFpInductionRecipe() override = default;
959 
960   /// Method to support type inquiry through isa, cast, and dyn_cast.
961   static inline bool classof(const VPRecipeBase *V) {
962     return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
963   }
964 
965   /// Generate the vectorized and scalarized versions of the phi node as
966   /// needed by their users.
967   void execute(VPTransformState &State) override;
968 
969   /// Print the recipe.
970   void print(raw_ostream &O, const Twine &Indent,
971              VPSlotTracker &SlotTracker) const override;
972 };
973 
974 /// A recipe for handling all phi nodes except for integer and FP inductions.
975 class VPWidenPHIRecipe : public VPRecipeBase {
976   PHINode *Phi;
977 
978 public:
979   VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
980   ~VPWidenPHIRecipe() override = default;
981 
982   /// Method to support type inquiry through isa, cast, and dyn_cast.
983   static inline bool classof(const VPRecipeBase *V) {
984     return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
985   }
986 
987   /// Generate the phi/select nodes.
988   void execute(VPTransformState &State) override;
989 
990   /// Print the recipe.
991   void print(raw_ostream &O, const Twine &Indent,
992              VPSlotTracker &SlotTracker) const override;
993 };
994 
995 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
996 /// instructions.
997 class VPBlendRecipe : public VPRecipeBase, public VPUser {
998   PHINode *Phi;
999 
1000 public:
1001   /// The blend operation is a User of the incoming values and of their
1002   /// respective masks, ordered [I0, M0, I1, M1, ...]. Note that a single value
1003   /// might be incoming with a full mask for which there is no VPValue.
1004   VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Operands)
1005       : VPRecipeBase(VPBlendSC), VPUser(Operands), Phi(Phi) {
1006     assert(Operands.size() > 0 &&
1007            ((Operands.size() == 1) || (Operands.size() % 2 == 0)) &&
1008            "Expected either a single incoming value or a positive even number "
1009            "of operands");
1010   }
1011 
1012   /// Method to support type inquiry through isa, cast, and dyn_cast.
1013   static inline bool classof(const VPRecipeBase *V) {
1014     return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
1015   }
1016 
1017   /// Return the number of incoming values, taking into account that a single
1018   /// incoming value has no mask.
1019   unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; }
1020 
1021   /// Return incoming value number \p Idx.
1022   VPValue *getIncomingValue(unsigned Idx) const { return getOperand(Idx * 2); }
1023 
1024   /// Return mask number \p Idx.
1025   VPValue *getMask(unsigned Idx) const { return getOperand(Idx * 2 + 1); }
1026 
1027   /// Generate the phi/select nodes.
1028   void execute(VPTransformState &State) override;
1029 
1030   /// Print the recipe.
1031   void print(raw_ostream &O, const Twine &Indent,
1032              VPSlotTracker &SlotTracker) const override;
1033 };
1034 
1035 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
1036 /// or stores into one wide load/store and shuffles.
1037 class VPInterleaveRecipe : public VPRecipeBase, public VPUser {
1038   const InterleaveGroup<Instruction> *IG;
1039 
1040 public:
1041   VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr,
1042                      VPValue *Mask)
1043       : VPRecipeBase(VPInterleaveSC), VPUser({Addr}), IG(IG) {
1044     if (Mask)
1045       addOperand(Mask);
1046   }
1047   ~VPInterleaveRecipe() override = default;
1048 
1049   /// Method to support type inquiry through isa, cast, and dyn_cast.
1050   static inline bool classof(const VPRecipeBase *V) {
1051     return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
1052   }
1053 
1054   /// Return the address accessed by this recipe.
1055   VPValue *getAddr() const {
1056     return getOperand(0); // Address is the 1st, mandatory operand.
1057   }
1058 
1059   /// Return the mask used by this recipe. Note that a full mask is represented
1060   /// by a nullptr.
1061   VPValue *getMask() const {
1062     // Mask is optional and therefore the last, currently 2nd operand.
1063     return getNumOperands() == 2 ? getOperand(1) : nullptr;
1064   }
1065 
1066   /// Generate the wide load or store, and shuffles.
1067   void execute(VPTransformState &State) override;
1068 
1069   /// Print the recipe.
1070   void print(raw_ostream &O, const Twine &Indent,
1071              VPSlotTracker &SlotTracker) const override;
1072 
1073   const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
1074 };
1075 
1076 /// A recipe to represent inloop reduction operations, performing a reduction on
1077 /// a vector operand into a scalar value, and adding the result to a chain.
1078 class VPReductionRecipe : public VPRecipeBase {
1079   /// The recurrence decriptor for the reduction in question.
1080   RecurrenceDescriptor *RdxDesc;
1081   /// The original instruction being converted to a reduction.
1082   Instruction *I;
1083   /// The VPValue of the vector value to be reduced.
1084   VPValue *VecOp;
1085   /// The VPValue of the scalar Chain being accumulated.
1086   VPValue *ChainOp;
1087   /// The VPValue of the condition for the block.
1088   VPValue *CondOp;
1089   /// Fast math flags to use for the resulting reduction operation.
1090   bool NoNaN;
1091   /// Pointer to the TTI, needed to create the target reduction
1092   const TargetTransformInfo *TTI;
1093 
1094 public:
1095   VPReductionRecipe(RecurrenceDescriptor *R, Instruction *I, VPValue *ChainOp,
1096                     VPValue *VecOp, VPValue *CondOp, bool NoNaN,
1097                     const TargetTransformInfo *TTI)
1098       : VPRecipeBase(VPReductionSC), RdxDesc(R), I(I), VecOp(VecOp),
1099         ChainOp(ChainOp), CondOp(CondOp), NoNaN(NoNaN), TTI(TTI) {}
1100 
1101   ~VPReductionRecipe() override = default;
1102 
1103   /// Method to support type inquiry through isa, cast, and dyn_cast.
1104   static inline bool classof(const VPRecipeBase *V) {
1105     return V->getVPRecipeID() == VPRecipeBase::VPReductionSC;
1106   }
1107 
1108   /// Generate the reduction in the loop
1109   void execute(VPTransformState &State) override;
1110 
1111   /// Print the recipe.
1112   void print(raw_ostream &O, const Twine &Indent,
1113              VPSlotTracker &SlotTracker) const override;
1114 };
1115 
1116 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
1117 /// copies of the original scalar type, one per lane, instead of producing a
1118 /// single copy of widened type for all lanes. If the instruction is known to be
1119 /// uniform only one copy, per lane zero, will be generated.
1120 class VPReplicateRecipe : public VPRecipeBase, public VPUser {
1121   /// The instruction being replicated.
1122   Instruction *Ingredient;
1123 
1124   /// Indicator if only a single replica per lane is needed.
1125   bool IsUniform;
1126 
1127   /// Indicator if the replicas are also predicated.
1128   bool IsPredicated;
1129 
1130   /// Indicator if the scalar values should also be packed into a vector.
1131   bool AlsoPack;
1132 
1133 public:
1134   template <typename IterT>
1135   VPReplicateRecipe(Instruction *I, iterator_range<IterT> Operands,
1136                     bool IsUniform, bool IsPredicated = false)
1137       : VPRecipeBase(VPReplicateSC), VPUser(Operands), Ingredient(I),
1138         IsUniform(IsUniform), IsPredicated(IsPredicated) {
1139     // Retain the previous behavior of predicateInstructions(), where an
1140     // insert-element of a predicated instruction got hoisted into the
1141     // predicated basic block iff it was its only user. This is achieved by
1142     // having predicated instructions also pack their values into a vector by
1143     // default unless they have a replicated user which uses their scalar value.
1144     AlsoPack = IsPredicated && !I->use_empty();
1145   }
1146 
1147   ~VPReplicateRecipe() override = default;
1148 
1149   /// Method to support type inquiry through isa, cast, and dyn_cast.
1150   static inline bool classof(const VPRecipeBase *V) {
1151     return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
1152   }
1153 
1154   /// Generate replicas of the desired Ingredient. Replicas will be generated
1155   /// for all parts and lanes unless a specific part and lane are specified in
1156   /// the \p State.
1157   void execute(VPTransformState &State) override;
1158 
1159   void setAlsoPack(bool Pack) { AlsoPack = Pack; }
1160 
1161   /// Print the recipe.
1162   void print(raw_ostream &O, const Twine &Indent,
1163              VPSlotTracker &SlotTracker) const override;
1164 };
1165 
1166 /// A recipe for generating conditional branches on the bits of a mask.
1167 class VPBranchOnMaskRecipe : public VPRecipeBase, public VPUser {
1168 public:
1169   VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
1170     if (BlockInMask) // nullptr means all-one mask.
1171       addOperand(BlockInMask);
1172   }
1173 
1174   /// Method to support type inquiry through isa, cast, and dyn_cast.
1175   static inline bool classof(const VPRecipeBase *V) {
1176     return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
1177   }
1178 
1179   /// Generate the extraction of the appropriate bit from the block mask and the
1180   /// conditional branch.
1181   void execute(VPTransformState &State) override;
1182 
1183   /// Print the recipe.
1184   void print(raw_ostream &O, const Twine &Indent,
1185              VPSlotTracker &SlotTracker) const override {
1186     O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
1187     if (VPValue *Mask = getMask())
1188       Mask->print(O, SlotTracker);
1189     else
1190       O << " All-One";
1191     O << "\\l\"";
1192   }
1193 
1194   /// Return the mask used by this recipe. Note that a full mask is represented
1195   /// by a nullptr.
1196   VPValue *getMask() const {
1197     assert(getNumOperands() <= 1 && "should have either 0 or 1 operands");
1198     // Mask is optional.
1199     return getNumOperands() == 1 ? getOperand(0) : nullptr;
1200   }
1201 };
1202 
1203 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
1204 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
1205 /// order to merge values that are set under such a branch and feed their uses.
1206 /// The phi nodes can be scalar or vector depending on the users of the value.
1207 /// This recipe works in concert with VPBranchOnMaskRecipe.
1208 class VPPredInstPHIRecipe : public VPRecipeBase {
1209   Instruction *PredInst;
1210 
1211 public:
1212   /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
1213   /// nodes after merging back from a Branch-on-Mask.
1214   VPPredInstPHIRecipe(Instruction *PredInst)
1215       : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
1216   ~VPPredInstPHIRecipe() override = default;
1217 
1218   /// Method to support type inquiry through isa, cast, and dyn_cast.
1219   static inline bool classof(const VPRecipeBase *V) {
1220     return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
1221   }
1222 
1223   /// Generates phi nodes for live-outs as needed to retain SSA form.
1224   void execute(VPTransformState &State) override;
1225 
1226   /// Print the recipe.
1227   void print(raw_ostream &O, const Twine &Indent,
1228              VPSlotTracker &SlotTracker) const override;
1229 };
1230 
1231 /// A Recipe for widening load/store operations.
1232 /// The recipe uses the following VPValues:
1233 /// - For load: Address, optional mask
1234 /// - For store: Address, stored value, optional mask
1235 /// TODO: We currently execute only per-part unless a specific instance is
1236 /// provided.
1237 class VPWidenMemoryInstructionRecipe : public VPRecipeBase,
1238                                        public VPValue,
1239                                        public VPUser {
1240 
1241   void setMask(VPValue *Mask) {
1242     if (!Mask)
1243       return;
1244     addOperand(Mask);
1245   }
1246 
1247   bool isMasked() const {
1248     return (isa<LoadInst>(getUnderlyingInstr()) && getNumOperands() == 2) ||
1249            (isa<StoreInst>(getUnderlyingInstr()) && getNumOperands() == 3);
1250   }
1251 
1252 public:
1253   VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask)
1254       : VPRecipeBase(VPWidenMemoryInstructionSC),
1255         VPValue(VPValue::VPMemoryInstructionSC, &Load), VPUser({Addr}) {
1256     setMask(Mask);
1257   }
1258 
1259   VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr,
1260                                  VPValue *StoredValue, VPValue *Mask)
1261       : VPRecipeBase(VPWidenMemoryInstructionSC),
1262         VPValue(VPValue::VPMemoryInstructionSC, &Store),
1263         VPUser({Addr, StoredValue}) {
1264     setMask(Mask);
1265   }
1266 
1267   /// Method to support type inquiry through isa, cast, and dyn_cast.
1268   static inline bool classof(const VPRecipeBase *V) {
1269     return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
1270   }
1271 
1272   /// Return the address accessed by this recipe.
1273   VPValue *getAddr() const {
1274     return getOperand(0); // Address is the 1st, mandatory operand.
1275   }
1276 
1277   /// Return the mask used by this recipe. Note that a full mask is represented
1278   /// by a nullptr.
1279   VPValue *getMask() const {
1280     // Mask is optional and therefore the last operand.
1281     return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
1282   }
1283 
1284   /// Return the address accessed by this recipe.
1285   VPValue *getStoredValue() const {
1286     assert(isa<StoreInst>(getUnderlyingInstr()) &&
1287            "Stored value only available for store instructions");
1288     return getOperand(1); // Stored value is the 2nd, mandatory operand.
1289   }
1290 
1291   /// Generate the wide load/store.
1292   void execute(VPTransformState &State) override;
1293 
1294   /// Print the recipe.
1295   void print(raw_ostream &O, const Twine &Indent,
1296              VPSlotTracker &SlotTracker) const override;
1297 };
1298 
1299 /// A Recipe for widening the canonical induction variable of the vector loop.
1300 class VPWidenCanonicalIVRecipe : public VPRecipeBase {
1301   /// A VPValue representing the canonical vector IV.
1302   VPValue Val;
1303 
1304 public:
1305   VPWidenCanonicalIVRecipe() : VPRecipeBase(VPWidenCanonicalIVSC) {}
1306   ~VPWidenCanonicalIVRecipe() override = default;
1307 
1308   /// Return the VPValue representing the canonical vector induction variable of
1309   /// the vector loop.
1310   const VPValue *getVPValue() const { return &Val; }
1311   VPValue *getVPValue() { return &Val; }
1312 
1313   /// Method to support type inquiry through isa, cast, and dyn_cast.
1314   static inline bool classof(const VPRecipeBase *V) {
1315     return V->getVPRecipeID() == VPRecipeBase::VPWidenCanonicalIVSC;
1316   }
1317 
1318   /// Generate a canonical vector induction variable of the vector loop, with
1319   /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and
1320   /// step = <VF*UF, VF*UF, ..., VF*UF>.
1321   void execute(VPTransformState &State) override;
1322 
1323   /// Print the recipe.
1324   void print(raw_ostream &O, const Twine &Indent,
1325              VPSlotTracker &SlotTracker) const override;
1326 };
1327 
1328 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1329 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
1330 /// output IR instructions.
1331 class VPBasicBlock : public VPBlockBase {
1332 public:
1333   using RecipeListTy = iplist<VPRecipeBase>;
1334 
1335 private:
1336   /// The VPRecipes held in the order of output instructions to generate.
1337   RecipeListTy Recipes;
1338 
1339 public:
1340   VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1341       : VPBlockBase(VPBasicBlockSC, Name.str()) {
1342     if (Recipe)
1343       appendRecipe(Recipe);
1344   }
1345 
1346   ~VPBasicBlock() override { Recipes.clear(); }
1347 
1348   /// Instruction iterators...
1349   using iterator = RecipeListTy::iterator;
1350   using const_iterator = RecipeListTy::const_iterator;
1351   using reverse_iterator = RecipeListTy::reverse_iterator;
1352   using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
1353 
1354   //===--------------------------------------------------------------------===//
1355   /// Recipe iterator methods
1356   ///
1357   inline iterator begin() { return Recipes.begin(); }
1358   inline const_iterator begin() const { return Recipes.begin(); }
1359   inline iterator end() { return Recipes.end(); }
1360   inline const_iterator end() const { return Recipes.end(); }
1361 
1362   inline reverse_iterator rbegin() { return Recipes.rbegin(); }
1363   inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
1364   inline reverse_iterator rend() { return Recipes.rend(); }
1365   inline const_reverse_iterator rend() const { return Recipes.rend(); }
1366 
1367   inline size_t size() const { return Recipes.size(); }
1368   inline bool empty() const { return Recipes.empty(); }
1369   inline const VPRecipeBase &front() const { return Recipes.front(); }
1370   inline VPRecipeBase &front() { return Recipes.front(); }
1371   inline const VPRecipeBase &back() const { return Recipes.back(); }
1372   inline VPRecipeBase &back() { return Recipes.back(); }
1373 
1374   /// Returns a reference to the list of recipes.
1375   RecipeListTy &getRecipeList() { return Recipes; }
1376 
1377   /// Returns a pointer to a member of the recipe list.
1378   static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
1379     return &VPBasicBlock::Recipes;
1380   }
1381 
1382   /// Method to support type inquiry through isa, cast, and dyn_cast.
1383   static inline bool classof(const VPBlockBase *V) {
1384     return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
1385   }
1386 
1387   void insert(VPRecipeBase *Recipe, iterator InsertPt) {
1388     assert(Recipe && "No recipe to append.");
1389     assert(!Recipe->Parent && "Recipe already in VPlan");
1390     Recipe->Parent = this;
1391     Recipes.insert(InsertPt, Recipe);
1392   }
1393 
1394   /// Augment the existing recipes of a VPBasicBlock with an additional
1395   /// \p Recipe as the last recipe.
1396   void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
1397 
1398   /// The method which generates the output IR instructions that correspond to
1399   /// this VPBasicBlock, thereby "executing" the VPlan.
1400   void execute(struct VPTransformState *State) override;
1401 
1402   /// Replace all operands of VPUsers in the block with \p NewValue and also
1403   /// replaces all uses of VPValues defined in the block with NewValue.
1404   void dropAllReferences(VPValue *NewValue);
1405 
1406   /// Return the position of the first non-phi node recipe in the block.
1407   iterator getFirstNonPhi();
1408 
1409 private:
1410   /// Create an IR BasicBlock to hold the output instructions generated by this
1411   /// VPBasicBlock, and return it. Update the CFGState accordingly.
1412   BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
1413 };
1414 
1415 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1416 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1417 /// A VPRegionBlock may indicate that its contents are to be replicated several
1418 /// times. This is designed to support predicated scalarization, in which a
1419 /// scalar if-then code structure needs to be generated VF * UF times. Having
1420 /// this replication indicator helps to keep a single model for multiple
1421 /// candidate VF's. The actual replication takes place only once the desired VF
1422 /// and UF have been determined.
1423 class VPRegionBlock : public VPBlockBase {
1424   /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1425   VPBlockBase *Entry;
1426 
1427   /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1428   VPBlockBase *Exit;
1429 
1430   /// An indicator whether this region is to generate multiple replicated
1431   /// instances of output IR corresponding to its VPBlockBases.
1432   bool IsReplicator;
1433 
1434 public:
1435   VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1436                 const std::string &Name = "", bool IsReplicator = false)
1437       : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1438         IsReplicator(IsReplicator) {
1439     assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1440     assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1441     Entry->setParent(this);
1442     Exit->setParent(this);
1443   }
1444   VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1445       : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1446         IsReplicator(IsReplicator) {}
1447 
1448   ~VPRegionBlock() override {
1449     if (Entry)
1450       deleteCFG(Entry);
1451   }
1452 
1453   /// Method to support type inquiry through isa, cast, and dyn_cast.
1454   static inline bool classof(const VPBlockBase *V) {
1455     return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1456   }
1457 
1458   const VPBlockBase *getEntry() const { return Entry; }
1459   VPBlockBase *getEntry() { return Entry; }
1460 
1461   /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1462   /// EntryBlock must have no predecessors.
1463   void setEntry(VPBlockBase *EntryBlock) {
1464     assert(EntryBlock->getPredecessors().empty() &&
1465            "Entry block cannot have predecessors.");
1466     Entry = EntryBlock;
1467     EntryBlock->setParent(this);
1468   }
1469 
1470   // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1471   // specific interface of llvm::Function, instead of using
1472   // GraphTraints::getEntryNode. We should add a new template parameter to
1473   // DominatorTreeBase representing the Graph type.
1474   VPBlockBase &front() const { return *Entry; }
1475 
1476   const VPBlockBase *getExit() const { return Exit; }
1477   VPBlockBase *getExit() { return Exit; }
1478 
1479   /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1480   /// ExitBlock must have no successors.
1481   void setExit(VPBlockBase *ExitBlock) {
1482     assert(ExitBlock->getSuccessors().empty() &&
1483            "Exit block cannot have successors.");
1484     Exit = ExitBlock;
1485     ExitBlock->setParent(this);
1486   }
1487 
1488   /// An indicator whether this region is to generate multiple replicated
1489   /// instances of output IR corresponding to its VPBlockBases.
1490   bool isReplicator() const { return IsReplicator; }
1491 
1492   /// The method which generates the output IR instructions that correspond to
1493   /// this VPRegionBlock, thereby "executing" the VPlan.
1494   void execute(struct VPTransformState *State) override;
1495 };
1496 
1497 //===----------------------------------------------------------------------===//
1498 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs     //
1499 //===----------------------------------------------------------------------===//
1500 
1501 // The following set of template specializations implement GraphTraits to treat
1502 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1503 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1504 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
1505 // successors/predecessors but not to the blocks inside the region.
1506 
1507 template <> struct GraphTraits<VPBlockBase *> {
1508   using NodeRef = VPBlockBase *;
1509   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1510 
1511   static NodeRef getEntryNode(NodeRef N) { return N; }
1512 
1513   static inline ChildIteratorType child_begin(NodeRef N) {
1514     return N->getSuccessors().begin();
1515   }
1516 
1517   static inline ChildIteratorType child_end(NodeRef N) {
1518     return N->getSuccessors().end();
1519   }
1520 };
1521 
1522 template <> struct GraphTraits<const VPBlockBase *> {
1523   using NodeRef = const VPBlockBase *;
1524   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
1525 
1526   static NodeRef getEntryNode(NodeRef N) { return N; }
1527 
1528   static inline ChildIteratorType child_begin(NodeRef N) {
1529     return N->getSuccessors().begin();
1530   }
1531 
1532   static inline ChildIteratorType child_end(NodeRef N) {
1533     return N->getSuccessors().end();
1534   }
1535 };
1536 
1537 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1538 // of successors for the inverse traversal.
1539 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
1540   using NodeRef = VPBlockBase *;
1541   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1542 
1543   static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
1544 
1545   static inline ChildIteratorType child_begin(NodeRef N) {
1546     return N->getPredecessors().begin();
1547   }
1548 
1549   static inline ChildIteratorType child_end(NodeRef N) {
1550     return N->getPredecessors().end();
1551   }
1552 };
1553 
1554 // The following set of template specializations implement GraphTraits to
1555 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1556 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1557 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1558 // there won't be automatic recursion into other VPBlockBases that turn to be
1559 // VPRegionBlocks.
1560 
1561 template <>
1562 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1563   using GraphRef = VPRegionBlock *;
1564   using nodes_iterator = df_iterator<NodeRef>;
1565 
1566   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1567 
1568   static nodes_iterator nodes_begin(GraphRef N) {
1569     return nodes_iterator::begin(N->getEntry());
1570   }
1571 
1572   static nodes_iterator nodes_end(GraphRef N) {
1573     // df_iterator::end() returns an empty iterator so the node used doesn't
1574     // matter.
1575     return nodes_iterator::end(N);
1576   }
1577 };
1578 
1579 template <>
1580 struct GraphTraits<const VPRegionBlock *>
1581     : public GraphTraits<const VPBlockBase *> {
1582   using GraphRef = const VPRegionBlock *;
1583   using nodes_iterator = df_iterator<NodeRef>;
1584 
1585   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1586 
1587   static nodes_iterator nodes_begin(GraphRef N) {
1588     return nodes_iterator::begin(N->getEntry());
1589   }
1590 
1591   static nodes_iterator nodes_end(GraphRef N) {
1592     // df_iterator::end() returns an empty iterator so the node used doesn't
1593     // matter.
1594     return nodes_iterator::end(N);
1595   }
1596 };
1597 
1598 template <>
1599 struct GraphTraits<Inverse<VPRegionBlock *>>
1600     : public GraphTraits<Inverse<VPBlockBase *>> {
1601   using GraphRef = VPRegionBlock *;
1602   using nodes_iterator = df_iterator<NodeRef>;
1603 
1604   static NodeRef getEntryNode(Inverse<GraphRef> N) {
1605     return N.Graph->getExit();
1606   }
1607 
1608   static nodes_iterator nodes_begin(GraphRef N) {
1609     return nodes_iterator::begin(N->getExit());
1610   }
1611 
1612   static nodes_iterator nodes_end(GraphRef N) {
1613     // df_iterator::end() returns an empty iterator so the node used doesn't
1614     // matter.
1615     return nodes_iterator::end(N);
1616   }
1617 };
1618 
1619 /// VPlan models a candidate for vectorization, encoding various decisions take
1620 /// to produce efficient output IR, including which branches, basic-blocks and
1621 /// output IR instructions to generate, and their cost. VPlan holds a
1622 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1623 /// VPBlock.
1624 class VPlan {
1625   friend class VPlanPrinter;
1626   friend class VPSlotTracker;
1627 
1628   /// Hold the single entry to the Hierarchical CFG of the VPlan.
1629   VPBlockBase *Entry;
1630 
1631   /// Holds the VFs applicable to this VPlan.
1632   SmallSetVector<ElementCount, 2> VFs;
1633 
1634   /// Holds the name of the VPlan, for printing.
1635   std::string Name;
1636 
1637   /// Holds all the external definitions created for this VPlan.
1638   // TODO: Introduce a specific representation for external definitions in
1639   // VPlan. External definitions must be immutable and hold a pointer to its
1640   // underlying IR that will be used to implement its structural comparison
1641   // (operators '==' and '<').
1642   SmallPtrSet<VPValue *, 16> VPExternalDefs;
1643 
1644   /// Represents the backedge taken count of the original loop, for folding
1645   /// the tail.
1646   VPValue *BackedgeTakenCount = nullptr;
1647 
1648   /// Holds a mapping between Values and their corresponding VPValue inside
1649   /// VPlan.
1650   Value2VPValueTy Value2VPValue;
1651 
1652   /// Contains all VPValues that been allocated by addVPValue directly and need
1653   /// to be free when the plan's destructor is called.
1654   SmallVector<VPValue *, 16> VPValuesToFree;
1655 
1656   /// Holds the VPLoopInfo analysis for this VPlan.
1657   VPLoopInfo VPLInfo;
1658 
1659   /// Holds the condition bit values built during VPInstruction to VPRecipe transformation.
1660   SmallVector<VPValue *, 4> VPCBVs;
1661 
1662 public:
1663   VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {
1664     if (Entry)
1665       Entry->setPlan(this);
1666   }
1667 
1668   ~VPlan() {
1669     if (Entry)
1670       VPBlockBase::deleteCFG(Entry);
1671     for (VPValue *VPV : VPValuesToFree)
1672       delete VPV;
1673     if (BackedgeTakenCount)
1674       delete BackedgeTakenCount;
1675     for (VPValue *Def : VPExternalDefs)
1676       delete Def;
1677     for (VPValue *CBV : VPCBVs)
1678       delete CBV;
1679   }
1680 
1681   /// Generate the IR code for this VPlan.
1682   void execute(struct VPTransformState *State);
1683 
1684   VPBlockBase *getEntry() { return Entry; }
1685   const VPBlockBase *getEntry() const { return Entry; }
1686 
1687   VPBlockBase *setEntry(VPBlockBase *Block) {
1688     Entry = Block;
1689     Block->setPlan(this);
1690     return Entry;
1691   }
1692 
1693   /// The backedge taken count of the original loop.
1694   VPValue *getOrCreateBackedgeTakenCount() {
1695     if (!BackedgeTakenCount)
1696       BackedgeTakenCount = new VPValue();
1697     return BackedgeTakenCount;
1698   }
1699 
1700   void addVF(ElementCount VF) { VFs.insert(VF); }
1701 
1702   bool hasVF(ElementCount VF) { return VFs.count(VF); }
1703 
1704   const std::string &getName() const { return Name; }
1705 
1706   void setName(const Twine &newName) { Name = newName.str(); }
1707 
1708   /// Add \p VPVal to the pool of external definitions if it's not already
1709   /// in the pool.
1710   void addExternalDef(VPValue *VPVal) {
1711     VPExternalDefs.insert(VPVal);
1712   }
1713 
1714   /// Add \p CBV to the vector of condition bit values.
1715   void addCBV(VPValue *CBV) {
1716     VPCBVs.push_back(CBV);
1717   }
1718 
1719   void addVPValue(Value *V) {
1720     assert(V && "Trying to add a null Value to VPlan");
1721     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1722     VPValue *VPV = new VPValue(V);
1723     Value2VPValue[V] = VPV;
1724     VPValuesToFree.push_back(VPV);
1725   }
1726 
1727   void addVPValue(Value *V, VPValue *VPV) {
1728     assert(V && "Trying to add a null Value to VPlan");
1729     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1730     Value2VPValue[V] = VPV;
1731   }
1732 
1733   void addOrReplaceVPValue(Value *V, VPValue *VPV) {
1734     assert(V && "Trying to add a null Value to VPlan");
1735     auto I = Value2VPValue.find(V);
1736     if (I == Value2VPValue.end())
1737       Value2VPValue[V] = VPV;
1738     else
1739       I->second = VPV;
1740   }
1741 
1742   VPValue *getVPValue(Value *V) {
1743     assert(V && "Trying to get the VPValue of a null Value");
1744     assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1745     return Value2VPValue[V];
1746   }
1747 
1748   VPValue *getOrAddVPValue(Value *V) {
1749     assert(V && "Trying to get or add the VPValue of a null Value");
1750     if (!Value2VPValue.count(V))
1751       addVPValue(V);
1752     return getVPValue(V);
1753   }
1754 
1755   void removeVPValueFor(Value *V) { Value2VPValue.erase(V); }
1756 
1757   /// Return the VPLoopInfo analysis for this VPlan.
1758   VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
1759   const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
1760 
1761   /// Dump the plan to stderr (for debugging).
1762   void dump() const;
1763 
1764   /// Returns a range mapping the values the range \p Operands to their
1765   /// corresponding VPValues.
1766   iterator_range<mapped_iterator<Use *, std::function<VPValue *(Value *)>>>
1767   mapToVPValues(User::op_range Operands) {
1768     std::function<VPValue *(Value *)> Fn = [this](Value *Op) {
1769       return getOrAddVPValue(Op);
1770     };
1771     return map_range(Operands, Fn);
1772   }
1773 
1774 private:
1775   /// Add to the given dominator tree the header block and every new basic block
1776   /// that was created between it and the latch block, inclusive.
1777   static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB,
1778                                   BasicBlock *LoopPreHeaderBB,
1779                                   BasicBlock *LoopExitBB);
1780 };
1781 
1782 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1783 /// indented and follows the dot format.
1784 class VPlanPrinter {
1785   friend inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan);
1786   friend inline raw_ostream &operator<<(raw_ostream &OS,
1787                                         const struct VPlanIngredient &I);
1788 
1789 private:
1790   raw_ostream &OS;
1791   const VPlan &Plan;
1792   unsigned Depth = 0;
1793   unsigned TabWidth = 2;
1794   std::string Indent;
1795   unsigned BID = 0;
1796   SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1797 
1798   VPSlotTracker SlotTracker;
1799 
1800   VPlanPrinter(raw_ostream &O, const VPlan &P)
1801       : OS(O), Plan(P), SlotTracker(&P) {}
1802 
1803   /// Handle indentation.
1804   void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1805 
1806   /// Print a given \p Block of the Plan.
1807   void dumpBlock(const VPBlockBase *Block);
1808 
1809   /// Print the information related to the CFG edges going out of a given
1810   /// \p Block, followed by printing the successor blocks themselves.
1811   void dumpEdges(const VPBlockBase *Block);
1812 
1813   /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1814   /// its successor blocks.
1815   void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1816 
1817   /// Print a given \p Region of the Plan.
1818   void dumpRegion(const VPRegionBlock *Region);
1819 
1820   unsigned getOrCreateBID(const VPBlockBase *Block) {
1821     return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1822   }
1823 
1824   const Twine getOrCreateName(const VPBlockBase *Block);
1825 
1826   const Twine getUID(const VPBlockBase *Block);
1827 
1828   /// Print the information related to a CFG edge between two VPBlockBases.
1829   void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1830                 const Twine &Label);
1831 
1832   void dump();
1833 
1834   static void printAsIngredient(raw_ostream &O, const Value *V);
1835 };
1836 
1837 struct VPlanIngredient {
1838   const Value *V;
1839 
1840   VPlanIngredient(const Value *V) : V(V) {}
1841 };
1842 
1843 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1844   VPlanPrinter::printAsIngredient(OS, I.V);
1845   return OS;
1846 }
1847 
1848 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
1849   VPlanPrinter Printer(OS, Plan);
1850   Printer.dump();
1851   return OS;
1852 }
1853 
1854 //===----------------------------------------------------------------------===//
1855 // VPlan Utilities
1856 //===----------------------------------------------------------------------===//
1857 
1858 /// Class that provides utilities for VPBlockBases in VPlan.
1859 class VPBlockUtils {
1860 public:
1861   VPBlockUtils() = delete;
1862 
1863   /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1864   /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1865   /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1866   /// has more than one successor, its conditional bit is propagated to \p
1867   /// NewBlock. \p NewBlock must have neither successors nor predecessors.
1868   static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1869     assert(NewBlock->getSuccessors().empty() &&
1870            "Can't insert new block with successors.");
1871     // TODO: move successors from BlockPtr to NewBlock when this functionality
1872     // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1873     // already has successors.
1874     BlockPtr->setOneSuccessor(NewBlock);
1875     NewBlock->setPredecessors({BlockPtr});
1876     NewBlock->setParent(BlockPtr->getParent());
1877   }
1878 
1879   /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1880   /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1881   /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
1882   /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1883   /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1884   /// must have neither successors nor predecessors.
1885   static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
1886                                    VPValue *Condition, VPBlockBase *BlockPtr) {
1887     assert(IfTrue->getSuccessors().empty() &&
1888            "Can't insert IfTrue with successors.");
1889     assert(IfFalse->getSuccessors().empty() &&
1890            "Can't insert IfFalse with successors.");
1891     BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
1892     IfTrue->setPredecessors({BlockPtr});
1893     IfFalse->setPredecessors({BlockPtr});
1894     IfTrue->setParent(BlockPtr->getParent());
1895     IfFalse->setParent(BlockPtr->getParent());
1896   }
1897 
1898   /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1899   /// the successors of \p From and \p From to the predecessors of \p To. Both
1900   /// VPBlockBases must have the same parent, which can be null. Both
1901   /// VPBlockBases can be already connected to other VPBlockBases.
1902   static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1903     assert((From->getParent() == To->getParent()) &&
1904            "Can't connect two block with different parents");
1905     assert(From->getNumSuccessors() < 2 &&
1906            "Blocks can't have more than two successors.");
1907     From->appendSuccessor(To);
1908     To->appendPredecessor(From);
1909   }
1910 
1911   /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1912   /// from the successors of \p From and \p From from the predecessors of \p To.
1913   static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1914     assert(To && "Successor to disconnect is null.");
1915     From->removeSuccessor(To);
1916     To->removePredecessor(From);
1917   }
1918 
1919   /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge.
1920   static bool isBackEdge(const VPBlockBase *FromBlock,
1921                          const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) {
1922     assert(FromBlock->getParent() == ToBlock->getParent() &&
1923            FromBlock->getParent() && "Must be in same region");
1924     const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock);
1925     const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock);
1926     if (!FromLoop || !ToLoop || FromLoop != ToLoop)
1927       return false;
1928 
1929     // A back-edge is a branch from the loop latch to its header.
1930     return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader();
1931   }
1932 
1933   /// Returns true if \p Block is a loop latch
1934   static bool blockIsLoopLatch(const VPBlockBase *Block,
1935                                const VPLoopInfo *VPLInfo) {
1936     if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block))
1937       return ParentVPL->isLoopLatch(Block);
1938 
1939     return false;
1940   }
1941 
1942   /// Count and return the number of succesors of \p PredBlock excluding any
1943   /// backedges.
1944   static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock,
1945                                       VPLoopInfo *VPLI) {
1946     unsigned Count = 0;
1947     for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) {
1948       if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI))
1949         Count++;
1950     }
1951     return Count;
1952   }
1953 };
1954 
1955 class VPInterleavedAccessInfo {
1956   DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
1957       InterleaveGroupMap;
1958 
1959   /// Type for mapping of instruction based interleave groups to VPInstruction
1960   /// interleave groups
1961   using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
1962                              InterleaveGroup<VPInstruction> *>;
1963 
1964   /// Recursively \p Region and populate VPlan based interleave groups based on
1965   /// \p IAI.
1966   void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
1967                    InterleavedAccessInfo &IAI);
1968   /// Recursively traverse \p Block and populate VPlan based interleave groups
1969   /// based on \p IAI.
1970   void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1971                   InterleavedAccessInfo &IAI);
1972 
1973 public:
1974   VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
1975 
1976   ~VPInterleavedAccessInfo() {
1977     SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
1978     // Avoid releasing a pointer twice.
1979     for (auto &I : InterleaveGroupMap)
1980       DelSet.insert(I.second);
1981     for (auto *Ptr : DelSet)
1982       delete Ptr;
1983   }
1984 
1985   /// Get the interleave group that \p Instr belongs to.
1986   ///
1987   /// \returns nullptr if doesn't have such group.
1988   InterleaveGroup<VPInstruction> *
1989   getInterleaveGroup(VPInstruction *Instr) const {
1990     if (InterleaveGroupMap.count(Instr))
1991       return InterleaveGroupMap.find(Instr)->second;
1992     return nullptr;
1993   }
1994 };
1995 
1996 /// Class that maps (parts of) an existing VPlan to trees of combined
1997 /// VPInstructions.
1998 class VPlanSlp {
1999   enum class OpMode { Failed, Load, Opcode };
2000 
2001   /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
2002   /// DenseMap keys.
2003   struct BundleDenseMapInfo {
2004     static SmallVector<VPValue *, 4> getEmptyKey() {
2005       return {reinterpret_cast<VPValue *>(-1)};
2006     }
2007 
2008     static SmallVector<VPValue *, 4> getTombstoneKey() {
2009       return {reinterpret_cast<VPValue *>(-2)};
2010     }
2011 
2012     static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
2013       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2014     }
2015 
2016     static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
2017                         const SmallVector<VPValue *, 4> &RHS) {
2018       return LHS == RHS;
2019     }
2020   };
2021 
2022   /// Mapping of values in the original VPlan to a combined VPInstruction.
2023   DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
2024       BundleToCombined;
2025 
2026   VPInterleavedAccessInfo &IAI;
2027 
2028   /// Basic block to operate on. For now, only instructions in a single BB are
2029   /// considered.
2030   const VPBasicBlock &BB;
2031 
2032   /// Indicates whether we managed to combine all visited instructions or not.
2033   bool CompletelySLP = true;
2034 
2035   /// Width of the widest combined bundle in bits.
2036   unsigned WidestBundleBits = 0;
2037 
2038   using MultiNodeOpTy =
2039       typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
2040 
2041   // Input operand bundles for the current multi node. Each multi node operand
2042   // bundle contains values not matching the multi node's opcode. They will
2043   // be reordered in reorderMultiNodeOps, once we completed building a
2044   // multi node.
2045   SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
2046 
2047   /// Indicates whether we are building a multi node currently.
2048   bool MultiNodeActive = false;
2049 
2050   /// Check if we can vectorize Operands together.
2051   bool areVectorizable(ArrayRef<VPValue *> Operands) const;
2052 
2053   /// Add combined instruction \p New for the bundle \p Operands.
2054   void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
2055 
2056   /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
2057   VPInstruction *markFailed();
2058 
2059   /// Reorder operands in the multi node to maximize sequential memory access
2060   /// and commutative operations.
2061   SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
2062 
2063   /// Choose the best candidate to use for the lane after \p Last. The set of
2064   /// candidates to choose from are values with an opcode matching \p Last's
2065   /// or loads consecutive to \p Last.
2066   std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
2067                                        SmallPtrSetImpl<VPValue *> &Candidates,
2068                                        VPInterleavedAccessInfo &IAI);
2069 
2070   /// Print bundle \p Values to dbgs().
2071   void dumpBundle(ArrayRef<VPValue *> Values);
2072 
2073 public:
2074   VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
2075 
2076   ~VPlanSlp() = default;
2077 
2078   /// Tries to build an SLP tree rooted at \p Operands and returns a
2079   /// VPInstruction combining \p Operands, if they can be combined.
2080   VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
2081 
2082   /// Return the width of the widest combined bundle in bits.
2083   unsigned getWidestBundleBits() const { return WidestBundleBits; }
2084 
2085   /// Return true if all visited instruction can be combined.
2086   bool isCompletelySLP() const { return CompletelySLP; }
2087 };
2088 } // end namespace llvm
2089 
2090 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
2091