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