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