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