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 "VPlanValue.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/GraphTraits.h"
32 #include "llvm/ADT/MapVector.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/SmallBitVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/ADT/ilist.h"
39 #include "llvm/ADT/ilist_node.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/IR/FMF.h"
44 #include <algorithm>
45 #include <cassert>
46 #include <cstddef>
47 #include <string>
48 
49 namespace llvm {
50 
51 class BasicBlock;
52 class DominatorTree;
53 class InductionDescriptor;
54 class InnerLoopVectorizer;
55 class IRBuilderBase;
56 class LoopInfo;
57 class raw_ostream;
58 class RecurrenceDescriptor;
59 class Value;
60 class VPBasicBlock;
61 class VPRegionBlock;
62 class VPlan;
63 class VPReplicateRecipe;
64 class VPlanSlp;
65 
66 /// Returns a calculation for the total number of elements for a given \p VF.
67 /// For fixed width vectors this value is a constant, whereas for scalable
68 /// vectors it is an expression determined at runtime.
69 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF);
70 
71 /// Return a value for Step multiplied by VF.
72 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
73                        int64_t Step);
74 
75 /// A range of powers-of-2 vectorization factors with fixed start and
76 /// adjustable end. The range includes start and excludes end, e.g.,:
77 /// [1, 9) = {1, 2, 4, 8}
78 struct VFRange {
79   // A power of 2.
80   const ElementCount Start;
81 
82   // Need not be a power of 2. If End <= Start range is empty.
83   ElementCount End;
84 
85   bool isEmpty() const {
86     return End.getKnownMinValue() <= Start.getKnownMinValue();
87   }
88 
89   VFRange(const ElementCount &Start, const ElementCount &End)
90       : Start(Start), End(End) {
91     assert(Start.isScalable() == End.isScalable() &&
92            "Both Start and End should have the same scalable flag");
93     assert(isPowerOf2_32(Start.getKnownMinValue()) &&
94            "Expected Start to be a power of 2");
95   }
96 };
97 
98 using VPlanPtr = std::unique_ptr<VPlan>;
99 
100 /// In what follows, the term "input IR" refers to code that is fed into the
101 /// vectorizer whereas the term "output IR" refers to code that is generated by
102 /// the vectorizer.
103 
104 /// VPLane provides a way to access lanes in both fixed width and scalable
105 /// vectors, where for the latter the lane index sometimes needs calculating
106 /// as a runtime expression.
107 class VPLane {
108 public:
109   /// Kind describes how to interpret Lane.
110   enum class Kind : uint8_t {
111     /// For First, Lane is the index into the first N elements of a
112     /// fixed-vector <N x <ElTy>> or a scalable vector <vscale x N x <ElTy>>.
113     First,
114     /// For ScalableLast, Lane is the offset from the start of the last
115     /// N-element subvector in a scalable vector <vscale x N x <ElTy>>. For
116     /// example, a Lane of 0 corresponds to lane `(vscale - 1) * N`, a Lane of
117     /// 1 corresponds to `((vscale - 1) * N) + 1`, etc.
118     ScalableLast
119   };
120 
121 private:
122   /// in [0..VF)
123   unsigned Lane;
124 
125   /// Indicates how the Lane should be interpreted, as described above.
126   Kind LaneKind;
127 
128 public:
129   VPLane(unsigned Lane, Kind LaneKind) : Lane(Lane), LaneKind(LaneKind) {}
130 
131   static VPLane getFirstLane() { return VPLane(0, VPLane::Kind::First); }
132 
133   static VPLane getLastLaneForVF(const ElementCount &VF) {
134     unsigned LaneOffset = VF.getKnownMinValue() - 1;
135     Kind LaneKind;
136     if (VF.isScalable())
137       // In this case 'LaneOffset' refers to the offset from the start of the
138       // last subvector with VF.getKnownMinValue() elements.
139       LaneKind = VPLane::Kind::ScalableLast;
140     else
141       LaneKind = VPLane::Kind::First;
142     return VPLane(LaneOffset, LaneKind);
143   }
144 
145   /// Returns a compile-time known value for the lane index and asserts if the
146   /// lane can only be calculated at runtime.
147   unsigned getKnownLane() const {
148     assert(LaneKind == Kind::First);
149     return Lane;
150   }
151 
152   /// Returns an expression describing the lane index that can be used at
153   /// runtime.
154   Value *getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const;
155 
156   /// Returns the Kind of lane offset.
157   Kind getKind() const { return LaneKind; }
158 
159   /// Returns true if this is the first lane of the whole vector.
160   bool isFirstLane() const { return Lane == 0 && LaneKind == Kind::First; }
161 
162   /// Maps the lane to a cache index based on \p VF.
163   unsigned mapToCacheIndex(const ElementCount &VF) const {
164     switch (LaneKind) {
165     case VPLane::Kind::ScalableLast:
166       assert(VF.isScalable() && Lane < VF.getKnownMinValue());
167       return VF.getKnownMinValue() + Lane;
168     default:
169       assert(Lane < VF.getKnownMinValue());
170       return Lane;
171     }
172   }
173 
174   /// Returns the maxmimum number of lanes that we are able to consider
175   /// caching for \p VF.
176   static unsigned getNumCachedLanes(const ElementCount &VF) {
177     return VF.getKnownMinValue() * (VF.isScalable() ? 2 : 1);
178   }
179 };
180 
181 /// VPIteration represents a single point in the iteration space of the output
182 /// (vectorized and/or unrolled) IR loop.
183 struct VPIteration {
184   /// in [0..UF)
185   unsigned Part;
186 
187   VPLane Lane;
188 
189   VPIteration(unsigned Part, unsigned Lane,
190               VPLane::Kind Kind = VPLane::Kind::First)
191       : Part(Part), Lane(Lane, Kind) {}
192 
193   VPIteration(unsigned Part, const VPLane &Lane) : Part(Part), Lane(Lane) {}
194 
195   bool isFirstIteration() const { return Part == 0 && Lane.isFirstLane(); }
196 };
197 
198 /// VPTransformState holds information passed down when "executing" a VPlan,
199 /// needed for generating the output IR.
200 struct VPTransformState {
201   VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,
202                    DominatorTree *DT, IRBuilderBase &Builder,
203                    InnerLoopVectorizer *ILV, VPlan *Plan)
204       : VF(VF), UF(UF), LI(LI), DT(DT), Builder(Builder), ILV(ILV), Plan(Plan) {
205   }
206 
207   /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
208   ElementCount VF;
209   unsigned UF;
210 
211   /// Hold the indices to generate specific scalar instructions. Null indicates
212   /// that all instances are to be generated, using either scalar or vector
213   /// instructions.
214   Optional<VPIteration> Instance;
215 
216   struct DataState {
217     /// A type for vectorized values in the new loop. Each value from the
218     /// original loop, when vectorized, is represented by UF vector values in
219     /// the new unrolled loop, where UF is the unroll factor.
220     typedef SmallVector<Value *, 2> PerPartValuesTy;
221 
222     DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
223 
224     using ScalarsPerPartValuesTy = SmallVector<SmallVector<Value *, 4>, 2>;
225     DenseMap<VPValue *, ScalarsPerPartValuesTy> PerPartScalars;
226   } Data;
227 
228   /// Get the generated Value for a given VPValue and a given Part. Note that
229   /// as some Defs are still created by ILV and managed in its ValueMap, this
230   /// method will delegate the call to ILV in such cases in order to provide
231   /// callers a consistent API.
232   /// \see set.
233   Value *get(VPValue *Def, unsigned Part);
234 
235   /// Get the generated Value for a given VPValue and given Part and Lane.
236   Value *get(VPValue *Def, const VPIteration &Instance);
237 
238   bool hasVectorValue(VPValue *Def, unsigned Part) {
239     auto I = Data.PerPartOutput.find(Def);
240     return I != Data.PerPartOutput.end() && Part < I->second.size() &&
241            I->second[Part];
242   }
243 
244   bool hasAnyVectorValue(VPValue *Def) const {
245     return Data.PerPartOutput.find(Def) != Data.PerPartOutput.end();
246   }
247 
248   bool hasScalarValue(VPValue *Def, VPIteration Instance) {
249     auto I = Data.PerPartScalars.find(Def);
250     if (I == Data.PerPartScalars.end())
251       return false;
252     unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
253     return Instance.Part < I->second.size() &&
254            CacheIdx < I->second[Instance.Part].size() &&
255            I->second[Instance.Part][CacheIdx];
256   }
257 
258   /// Set the generated Value for a given VPValue and a given Part.
259   void set(VPValue *Def, Value *V, unsigned Part) {
260     if (!Data.PerPartOutput.count(Def)) {
261       DataState::PerPartValuesTy Entry(UF);
262       Data.PerPartOutput[Def] = Entry;
263     }
264     Data.PerPartOutput[Def][Part] = V;
265   }
266   /// Reset an existing vector value for \p Def and a given \p Part.
267   void reset(VPValue *Def, Value *V, unsigned Part) {
268     auto Iter = Data.PerPartOutput.find(Def);
269     assert(Iter != Data.PerPartOutput.end() &&
270            "need to overwrite existing value");
271     Iter->second[Part] = V;
272   }
273 
274   /// Set the generated scalar \p V for \p Def and the given \p Instance.
275   void set(VPValue *Def, Value *V, const VPIteration &Instance) {
276     auto Iter = Data.PerPartScalars.insert({Def, {}});
277     auto &PerPartVec = Iter.first->second;
278     while (PerPartVec.size() <= Instance.Part)
279       PerPartVec.emplace_back();
280     auto &Scalars = PerPartVec[Instance.Part];
281     unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
282     while (Scalars.size() <= CacheIdx)
283       Scalars.push_back(nullptr);
284     assert(!Scalars[CacheIdx] && "should overwrite existing value");
285     Scalars[CacheIdx] = V;
286   }
287 
288   /// Reset an existing scalar value for \p Def and a given \p Instance.
289   void reset(VPValue *Def, Value *V, const VPIteration &Instance) {
290     auto Iter = Data.PerPartScalars.find(Def);
291     assert(Iter != Data.PerPartScalars.end() &&
292            "need to overwrite existing value");
293     assert(Instance.Part < Iter->second.size() &&
294            "need to overwrite existing value");
295     unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
296     assert(CacheIdx < Iter->second[Instance.Part].size() &&
297            "need to overwrite existing value");
298     Iter->second[Instance.Part][CacheIdx] = V;
299   }
300 
301   /// Hold state information used when constructing the CFG of the output IR,
302   /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
303   struct CFGState {
304     /// The previous VPBasicBlock visited. Initially set to null.
305     VPBasicBlock *PrevVPBB = nullptr;
306 
307     /// The previous IR BasicBlock created or used. Initially set to the new
308     /// header BasicBlock.
309     BasicBlock *PrevBB = nullptr;
310 
311     /// The last IR BasicBlock in the output IR. Set to the exit block of the
312     /// vector loop.
313     BasicBlock *ExitBB = nullptr;
314 
315     /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
316     /// of replication, maps the BasicBlock of the last replica created.
317     SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
318 
319     CFGState() = default;
320 
321     /// Returns the BasicBlock* mapped to the pre-header of the loop region
322     /// containing \p R.
323     BasicBlock *getPreheaderBBFor(VPRecipeBase *R);
324   } CFG;
325 
326   /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
327   LoopInfo *LI;
328 
329   /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
330   DominatorTree *DT;
331 
332   /// Hold a reference to the IRBuilder used to generate output IR code.
333   IRBuilderBase &Builder;
334 
335   VPValue2ValueTy VPValue2Value;
336 
337   /// Hold the canonical scalar IV of the vector loop (start=0, step=VF*UF).
338   Value *CanonicalIV = nullptr;
339 
340   /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
341   InnerLoopVectorizer *ILV;
342 
343   /// Pointer to the VPlan code is generated for.
344   VPlan *Plan;
345 
346   /// Holds recipes that may generate a poison value that is used after
347   /// vectorization, even when their operands are not poison.
348   SmallPtrSet<VPRecipeBase *, 16> MayGeneratePoisonRecipes;
349 
350   /// The loop object for the current parent region, or nullptr.
351   Loop *CurrentVectorLoop = nullptr;
352 };
353 
354 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
355 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
356 class VPBlockBase {
357   friend class VPBlockUtils;
358 
359   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
360 
361   /// An optional name for the block.
362   std::string Name;
363 
364   /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
365   /// it is a topmost VPBlockBase.
366   VPRegionBlock *Parent = nullptr;
367 
368   /// List of predecessor blocks.
369   SmallVector<VPBlockBase *, 1> Predecessors;
370 
371   /// List of successor blocks.
372   SmallVector<VPBlockBase *, 1> Successors;
373 
374   /// VPlan containing the block. Can only be set on the entry block of the
375   /// plan.
376   VPlan *Plan = nullptr;
377 
378   /// Add \p Successor as the last successor to this block.
379   void appendSuccessor(VPBlockBase *Successor) {
380     assert(Successor && "Cannot add nullptr successor!");
381     Successors.push_back(Successor);
382   }
383 
384   /// Add \p Predecessor as the last predecessor to this block.
385   void appendPredecessor(VPBlockBase *Predecessor) {
386     assert(Predecessor && "Cannot add nullptr predecessor!");
387     Predecessors.push_back(Predecessor);
388   }
389 
390   /// Remove \p Predecessor from the predecessors of this block.
391   void removePredecessor(VPBlockBase *Predecessor) {
392     auto Pos = find(Predecessors, Predecessor);
393     assert(Pos && "Predecessor does not exist");
394     Predecessors.erase(Pos);
395   }
396 
397   /// Remove \p Successor from the successors of this block.
398   void removeSuccessor(VPBlockBase *Successor) {
399     auto Pos = find(Successors, Successor);
400     assert(Pos && "Successor does not exist");
401     Successors.erase(Pos);
402   }
403 
404 protected:
405   VPBlockBase(const unsigned char SC, const std::string &N)
406       : SubclassID(SC), Name(N) {}
407 
408 public:
409   /// An enumeration for keeping track of the concrete subclass of VPBlockBase
410   /// that are actually instantiated. Values of this enumeration are kept in the
411   /// SubclassID field of the VPBlockBase objects. They are used for concrete
412   /// type identification.
413   using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
414 
415   using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
416 
417   virtual ~VPBlockBase() = default;
418 
419   const std::string &getName() const { return Name; }
420 
421   void setName(const Twine &newName) { Name = newName.str(); }
422 
423   /// \return an ID for the concrete type of this object.
424   /// This is used to implement the classof checks. This should not be used
425   /// for any other purpose, as the values may change as LLVM evolves.
426   unsigned getVPBlockID() const { return SubclassID; }
427 
428   VPRegionBlock *getParent() { return Parent; }
429   const VPRegionBlock *getParent() const { return Parent; }
430 
431   /// \return A pointer to the plan containing the current block.
432   VPlan *getPlan();
433   const VPlan *getPlan() const;
434 
435   /// Sets the pointer of the plan containing the block. The block must be the
436   /// entry block into the VPlan.
437   void setPlan(VPlan *ParentPlan);
438 
439   void setParent(VPRegionBlock *P) { Parent = P; }
440 
441   /// \return the VPBasicBlock that is the entry of this VPBlockBase,
442   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
443   /// VPBlockBase is a VPBasicBlock, it is returned.
444   const VPBasicBlock *getEntryBasicBlock() const;
445   VPBasicBlock *getEntryBasicBlock();
446 
447   /// \return the VPBasicBlock that is the exiting this VPBlockBase,
448   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
449   /// VPBlockBase is a VPBasicBlock, it is returned.
450   const VPBasicBlock *getExitingBasicBlock() const;
451   VPBasicBlock *getExitingBasicBlock();
452 
453   const VPBlocksTy &getSuccessors() const { return Successors; }
454   VPBlocksTy &getSuccessors() { return Successors; }
455 
456   iterator_range<VPBlockBase **> successors() { return Successors; }
457 
458   const VPBlocksTy &getPredecessors() const { return Predecessors; }
459   VPBlocksTy &getPredecessors() { return Predecessors; }
460 
461   /// \return the successor of this VPBlockBase if it has a single successor.
462   /// Otherwise return a null pointer.
463   VPBlockBase *getSingleSuccessor() const {
464     return (Successors.size() == 1 ? *Successors.begin() : nullptr);
465   }
466 
467   /// \return the predecessor of this VPBlockBase if it has a single
468   /// predecessor. Otherwise return a null pointer.
469   VPBlockBase *getSinglePredecessor() const {
470     return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
471   }
472 
473   size_t getNumSuccessors() const { return Successors.size(); }
474   size_t getNumPredecessors() const { return Predecessors.size(); }
475 
476   /// An Enclosing Block of a block B is any block containing B, including B
477   /// itself. \return the closest enclosing block starting from "this", which
478   /// has successors. \return the root enclosing block if all enclosing blocks
479   /// have no successors.
480   VPBlockBase *getEnclosingBlockWithSuccessors();
481 
482   /// \return the closest enclosing block starting from "this", which has
483   /// predecessors. \return the root enclosing block if all enclosing blocks
484   /// have no predecessors.
485   VPBlockBase *getEnclosingBlockWithPredecessors();
486 
487   /// \return the successors either attached directly to this VPBlockBase or, if
488   /// this VPBlockBase is the exit block of a VPRegionBlock and has no
489   /// successors of its own, search recursively for the first enclosing
490   /// VPRegionBlock that has successors and return them. If no such
491   /// VPRegionBlock exists, return the (empty) successors of the topmost
492   /// VPBlockBase reached.
493   const VPBlocksTy &getHierarchicalSuccessors() {
494     return getEnclosingBlockWithSuccessors()->getSuccessors();
495   }
496 
497   /// \return the hierarchical successor of this VPBlockBase if it has a single
498   /// hierarchical successor. Otherwise return a null pointer.
499   VPBlockBase *getSingleHierarchicalSuccessor() {
500     return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
501   }
502 
503   /// \return the predecessors either attached directly to this VPBlockBase or,
504   /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
505   /// predecessors of its own, search recursively for the first enclosing
506   /// VPRegionBlock that has predecessors and return them. If no such
507   /// VPRegionBlock exists, return the (empty) predecessors of the topmost
508   /// VPBlockBase reached.
509   const VPBlocksTy &getHierarchicalPredecessors() {
510     return getEnclosingBlockWithPredecessors()->getPredecessors();
511   }
512 
513   /// \return the hierarchical predecessor of this VPBlockBase if it has a
514   /// single hierarchical predecessor. Otherwise return a null pointer.
515   VPBlockBase *getSingleHierarchicalPredecessor() {
516     return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
517   }
518 
519   /// Set a given VPBlockBase \p Successor as the single successor of this
520   /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
521   /// This VPBlockBase must have no successors.
522   void setOneSuccessor(VPBlockBase *Successor) {
523     assert(Successors.empty() && "Setting one successor when others exist.");
524     appendSuccessor(Successor);
525   }
526 
527   /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
528   /// successors of this VPBlockBase. This VPBlockBase is not added as
529   /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
530   /// successors.
531   void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
532     assert(Successors.empty() && "Setting two successors when others exist.");
533     appendSuccessor(IfTrue);
534     appendSuccessor(IfFalse);
535   }
536 
537   /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
538   /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
539   /// as successor of any VPBasicBlock in \p NewPreds.
540   void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
541     assert(Predecessors.empty() && "Block predecessors already set.");
542     for (auto *Pred : NewPreds)
543       appendPredecessor(Pred);
544   }
545 
546   /// Remove all the predecessor of this block.
547   void clearPredecessors() { Predecessors.clear(); }
548 
549   /// Remove all the successors of this block.
550   void clearSuccessors() { Successors.clear(); }
551 
552   /// The method which generates the output IR that correspond to this
553   /// VPBlockBase, thereby "executing" the VPlan.
554   virtual void execute(struct VPTransformState *State) = 0;
555 
556   /// Delete all blocks reachable from a given VPBlockBase, inclusive.
557   static void deleteCFG(VPBlockBase *Entry);
558 
559   /// Return true if it is legal to hoist instructions into this block.
560   bool isLegalToHoistInto() {
561     // There are currently no constraints that prevent an instruction to be
562     // hoisted into a VPBlockBase.
563     return true;
564   }
565 
566   /// Replace all operands of VPUsers in the block with \p NewValue and also
567   /// replaces all uses of VPValues defined in the block with NewValue.
568   virtual void dropAllReferences(VPValue *NewValue) = 0;
569 
570 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
571   void printAsOperand(raw_ostream &OS, bool PrintType) const {
572     OS << getName();
573   }
574 
575   /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines
576   /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using
577   /// consequtive numbers.
578   ///
579   /// Note that the numbering is applied to the whole VPlan, so printing
580   /// individual blocks is consistent with the whole VPlan printing.
581   virtual void print(raw_ostream &O, const Twine &Indent,
582                      VPSlotTracker &SlotTracker) const = 0;
583 
584   /// Print plain-text dump of this VPlan to \p O.
585   void print(raw_ostream &O) const {
586     VPSlotTracker SlotTracker(getPlan());
587     print(O, "", SlotTracker);
588   }
589 
590   /// Print the successors of this block to \p O, prefixing all lines with \p
591   /// Indent.
592   void printSuccessors(raw_ostream &O, const Twine &Indent) const;
593 
594   /// Dump this VPBlockBase to dbgs().
595   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
596 #endif
597 };
598 
599 /// A value that is used outside the VPlan. The operand of the user needs to be
600 /// added to the associated LCSSA phi node.
601 class VPLiveOut : public VPUser {
602   PHINode *Phi;
603 
604 public:
605   VPLiveOut(PHINode *Phi, VPValue *Op)
606       : VPUser({Op}, VPUser::VPUserID::LiveOut), Phi(Phi) {}
607 
608   /// Fixup the wrapped LCSSA phi node in the unique exit block.  This simply
609   /// means we need to add the appropriate incoming value from the middle
610   /// block as exiting edges from the scalar epilogue loop (if present) are
611   /// already in place, and we exit the vector loop exclusively to the middle
612   /// block.
613   void fixPhi(VPlan &Plan, VPTransformState &State);
614 
615   /// Returns true if the VPLiveOut uses scalars of operand \p Op.
616   bool usesScalars(const VPValue *Op) const override {
617     assert(is_contained(operands(), Op) &&
618            "Op must be an operand of the recipe");
619     return true;
620   }
621 
622   PHINode *getPhi() const { return Phi; }
623 };
624 
625 /// VPRecipeBase is a base class modeling a sequence of one or more output IR
626 /// instructions. VPRecipeBase owns the the VPValues it defines through VPDef
627 /// and is responsible for deleting its defined values. Single-value
628 /// VPRecipeBases that also inherit from VPValue must make sure to inherit from
629 /// VPRecipeBase before VPValue.
630 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>,
631                      public VPDef,
632                      public VPUser {
633   friend VPBasicBlock;
634   friend class VPBlockUtils;
635 
636   /// Each VPRecipe belongs to a single VPBasicBlock.
637   VPBasicBlock *Parent = nullptr;
638 
639 public:
640   VPRecipeBase(const unsigned char SC, ArrayRef<VPValue *> Operands)
641       : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {}
642 
643   template <typename IterT>
644   VPRecipeBase(const unsigned char SC, iterator_range<IterT> Operands)
645       : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {}
646   virtual ~VPRecipeBase() = default;
647 
648   /// \return the VPBasicBlock which this VPRecipe belongs to.
649   VPBasicBlock *getParent() { return Parent; }
650   const VPBasicBlock *getParent() const { return Parent; }
651 
652   /// The method which generates the output IR instructions that correspond to
653   /// this VPRecipe, thereby "executing" the VPlan.
654   virtual void execute(struct VPTransformState &State) = 0;
655 
656   /// Insert an unlinked recipe into a basic block immediately before
657   /// the specified recipe.
658   void insertBefore(VPRecipeBase *InsertPos);
659   /// Insert an unlinked recipe into \p BB immediately before the insertion
660   /// point \p IP;
661   void insertBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator IP);
662 
663   /// Insert an unlinked Recipe into a basic block immediately after
664   /// the specified Recipe.
665   void insertAfter(VPRecipeBase *InsertPos);
666 
667   /// Unlink this recipe from its current VPBasicBlock and insert it into
668   /// the VPBasicBlock that MovePos lives in, right after MovePos.
669   void moveAfter(VPRecipeBase *MovePos);
670 
671   /// Unlink this recipe and insert into BB before I.
672   ///
673   /// \pre I is a valid iterator into BB.
674   void moveBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator I);
675 
676   /// This method unlinks 'this' from the containing basic block, but does not
677   /// delete it.
678   void removeFromParent();
679 
680   /// This method unlinks 'this' from the containing basic block and deletes it.
681   ///
682   /// \returns an iterator pointing to the element after the erased one
683   iplist<VPRecipeBase>::iterator eraseFromParent();
684 
685   /// Returns the underlying instruction, if the recipe is a VPValue or nullptr
686   /// otherwise.
687   Instruction *getUnderlyingInstr() {
688     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue());
689   }
690   const Instruction *getUnderlyingInstr() const {
691     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue());
692   }
693 
694   /// Method to support type inquiry through isa, cast, and dyn_cast.
695   static inline bool classof(const VPDef *D) {
696     // All VPDefs are also VPRecipeBases.
697     return true;
698   }
699 
700   static inline bool classof(const VPUser *U) {
701     return U->getVPUserID() == VPUser::VPUserID::Recipe;
702   }
703 
704   /// Returns true if the recipe may have side-effects.
705   bool mayHaveSideEffects() const;
706 
707   /// Returns true for PHI-like recipes.
708   bool isPhi() const {
709     return getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC;
710   }
711 
712   /// Returns true if the recipe may read from memory.
713   bool mayReadFromMemory() const;
714 
715   /// Returns true if the recipe may write to memory.
716   bool mayWriteToMemory() const;
717 
718   /// Returns true if the recipe may read from or write to memory.
719   bool mayReadOrWriteMemory() const {
720     return mayReadFromMemory() || mayWriteToMemory();
721   }
722 };
723 
724 inline bool VPUser::classof(const VPDef *Def) {
725   return Def->getVPDefID() == VPRecipeBase::VPInstructionSC ||
726          Def->getVPDefID() == VPRecipeBase::VPWidenSC ||
727          Def->getVPDefID() == VPRecipeBase::VPWidenCallSC ||
728          Def->getVPDefID() == VPRecipeBase::VPWidenSelectSC ||
729          Def->getVPDefID() == VPRecipeBase::VPWidenGEPSC ||
730          Def->getVPDefID() == VPRecipeBase::VPBlendSC ||
731          Def->getVPDefID() == VPRecipeBase::VPInterleaveSC ||
732          Def->getVPDefID() == VPRecipeBase::VPReplicateSC ||
733          Def->getVPDefID() == VPRecipeBase::VPReductionSC ||
734          Def->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC ||
735          Def->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC;
736 }
737 
738 /// This is a concrete Recipe that models a single VPlan-level instruction.
739 /// While as any Recipe it may generate a sequence of IR instructions when
740 /// executed, these instructions would always form a single-def expression as
741 /// the VPInstruction is also a single def-use vertex.
742 class VPInstruction : public VPRecipeBase, public VPValue {
743   friend class VPlanSlp;
744 
745 public:
746   /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
747   enum {
748     FirstOrderRecurrenceSplice =
749         Instruction::OtherOpsEnd + 1, // Combines the incoming and previous
750                                       // values of a first-order recurrence.
751     Not,
752     ICmpULE,
753     SLPLoad,
754     SLPStore,
755     ActiveLaneMask,
756     CanonicalIVIncrement,
757     CanonicalIVIncrementNUW,
758     BranchOnCount,
759     BranchOnCond
760   };
761 
762 private:
763   typedef unsigned char OpcodeTy;
764   OpcodeTy Opcode;
765   FastMathFlags FMF;
766   DebugLoc DL;
767 
768   /// Utility method serving execute(): generates a single instance of the
769   /// modeled instruction.
770   void generateInstruction(VPTransformState &State, unsigned Part);
771 
772 protected:
773   void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); }
774 
775 public:
776   VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands, DebugLoc DL)
777       : VPRecipeBase(VPRecipeBase::VPInstructionSC, Operands),
778         VPValue(VPValue::VPVInstructionSC, nullptr, this), Opcode(Opcode),
779         DL(DL) {}
780 
781   VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
782                 DebugLoc DL = {})
783       : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands), DL) {}
784 
785   /// Method to support type inquiry through isa, cast, and dyn_cast.
786   static inline bool classof(const VPValue *V) {
787     return V->getVPValueID() == VPValue::VPVInstructionSC;
788   }
789 
790   VPInstruction *clone() const {
791     SmallVector<VPValue *, 2> Operands(operands());
792     return new VPInstruction(Opcode, Operands, DL);
793   }
794 
795   /// Method to support type inquiry through isa, cast, and dyn_cast.
796   static inline bool classof(const VPDef *R) {
797     return R->getVPDefID() == VPRecipeBase::VPInstructionSC;
798   }
799 
800   /// Extra classof implementations to allow directly casting from VPUser ->
801   /// VPInstruction.
802   static inline bool classof(const VPUser *U) {
803     auto *R = dyn_cast<VPRecipeBase>(U);
804     return R && R->getVPDefID() == VPRecipeBase::VPInstructionSC;
805   }
806   static inline bool classof(const VPRecipeBase *R) {
807     return R->getVPDefID() == VPRecipeBase::VPInstructionSC;
808   }
809 
810   unsigned getOpcode() const { return Opcode; }
811 
812   /// Generate the instruction.
813   /// TODO: We currently execute only per-part unless a specific instance is
814   /// provided.
815   void execute(VPTransformState &State) override;
816 
817 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
818   /// Print the VPInstruction to \p O.
819   void print(raw_ostream &O, const Twine &Indent,
820              VPSlotTracker &SlotTracker) const override;
821 
822   /// Print the VPInstruction to dbgs() (for debugging).
823   LLVM_DUMP_METHOD void dump() const;
824 #endif
825 
826   /// Return true if this instruction may modify memory.
827   bool mayWriteToMemory() const {
828     // TODO: we can use attributes of the called function to rule out memory
829     //       modifications.
830     return Opcode == Instruction::Store || Opcode == Instruction::Call ||
831            Opcode == Instruction::Invoke || Opcode == SLPStore;
832   }
833 
834   bool hasResult() const {
835     // CallInst may or may not have a result, depending on the called function.
836     // Conservatively return calls have results for now.
837     switch (getOpcode()) {
838     case Instruction::Ret:
839     case Instruction::Br:
840     case Instruction::Store:
841     case Instruction::Switch:
842     case Instruction::IndirectBr:
843     case Instruction::Resume:
844     case Instruction::CatchRet:
845     case Instruction::Unreachable:
846     case Instruction::Fence:
847     case Instruction::AtomicRMW:
848     case VPInstruction::BranchOnCond:
849     case VPInstruction::BranchOnCount:
850       return false;
851     default:
852       return true;
853     }
854   }
855 
856   /// Set the fast-math flags.
857   void setFastMathFlags(FastMathFlags FMFNew);
858 
859   /// Returns true if the recipe only uses the first lane of operand \p Op.
860   bool onlyFirstLaneUsed(const VPValue *Op) const override {
861     assert(is_contained(operands(), Op) &&
862            "Op must be an operand of the recipe");
863     if (getOperand(0) != Op)
864       return false;
865     switch (getOpcode()) {
866     default:
867       return false;
868     case VPInstruction::ActiveLaneMask:
869     case VPInstruction::CanonicalIVIncrement:
870     case VPInstruction::CanonicalIVIncrementNUW:
871     case VPInstruction::BranchOnCount:
872       return true;
873     };
874     llvm_unreachable("switch should return");
875   }
876 };
877 
878 /// VPWidenRecipe is a recipe for producing a copy of vector type its
879 /// ingredient. This recipe covers most of the traditional vectorization cases
880 /// where each ingredient transforms into a vectorized version of itself.
881 class VPWidenRecipe : public VPRecipeBase, public VPValue {
882 public:
883   template <typename IterT>
884   VPWidenRecipe(Instruction &I, iterator_range<IterT> Operands)
885       : VPRecipeBase(VPRecipeBase::VPWidenSC, Operands),
886         VPValue(VPValue::VPVWidenSC, &I, this) {}
887 
888   ~VPWidenRecipe() override = default;
889 
890   /// Method to support type inquiry through isa, cast, and dyn_cast.
891   static inline bool classof(const VPDef *D) {
892     return D->getVPDefID() == VPRecipeBase::VPWidenSC;
893   }
894   static inline bool classof(const VPValue *V) {
895     return V->getVPValueID() == VPValue::VPVWidenSC;
896   }
897 
898   /// Produce widened copies of all Ingredients.
899   void execute(VPTransformState &State) override;
900 
901 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
902   /// Print the recipe.
903   void print(raw_ostream &O, const Twine &Indent,
904              VPSlotTracker &SlotTracker) const override;
905 #endif
906 };
907 
908 /// A recipe for widening Call instructions.
909 class VPWidenCallRecipe : public VPRecipeBase, public VPValue {
910 
911 public:
912   template <typename IterT>
913   VPWidenCallRecipe(CallInst &I, iterator_range<IterT> CallArguments)
914       : VPRecipeBase(VPRecipeBase::VPWidenCallSC, CallArguments),
915         VPValue(VPValue::VPVWidenCallSC, &I, this) {}
916 
917   ~VPWidenCallRecipe() override = default;
918 
919   /// Method to support type inquiry through isa, cast, and dyn_cast.
920   static inline bool classof(const VPDef *D) {
921     return D->getVPDefID() == VPRecipeBase::VPWidenCallSC;
922   }
923 
924   /// Produce a widened version of the call instruction.
925   void execute(VPTransformState &State) override;
926 
927 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
928   /// Print the recipe.
929   void print(raw_ostream &O, const Twine &Indent,
930              VPSlotTracker &SlotTracker) const override;
931 #endif
932 };
933 
934 /// A recipe for widening select instructions.
935 class VPWidenSelectRecipe : public VPRecipeBase, public VPValue {
936 
937   /// Is the condition of the select loop invariant?
938   bool InvariantCond;
939 
940 public:
941   template <typename IterT>
942   VPWidenSelectRecipe(SelectInst &I, iterator_range<IterT> Operands,
943                       bool InvariantCond)
944       : VPRecipeBase(VPRecipeBase::VPWidenSelectSC, Operands),
945         VPValue(VPValue::VPVWidenSelectSC, &I, this),
946         InvariantCond(InvariantCond) {}
947 
948   ~VPWidenSelectRecipe() override = default;
949 
950   /// Method to support type inquiry through isa, cast, and dyn_cast.
951   static inline bool classof(const VPDef *D) {
952     return D->getVPDefID() == VPRecipeBase::VPWidenSelectSC;
953   }
954 
955   /// Produce a widened version of the select instruction.
956   void execute(VPTransformState &State) override;
957 
958 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
959   /// Print the recipe.
960   void print(raw_ostream &O, const Twine &Indent,
961              VPSlotTracker &SlotTracker) const override;
962 #endif
963 };
964 
965 /// A recipe for handling GEP instructions.
966 class VPWidenGEPRecipe : public VPRecipeBase, public VPValue {
967   bool IsPtrLoopInvariant;
968   SmallBitVector IsIndexLoopInvariant;
969 
970 public:
971   template <typename IterT>
972   VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands)
973       : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands),
974         VPValue(VPWidenGEPSC, GEP, this),
975         IsIndexLoopInvariant(GEP->getNumIndices(), false) {}
976 
977   template <typename IterT>
978   VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands,
979                    Loop *OrigLoop)
980       : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands),
981         VPValue(VPValue::VPVWidenGEPSC, GEP, this),
982         IsIndexLoopInvariant(GEP->getNumIndices(), false) {
983     IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand());
984     for (auto Index : enumerate(GEP->indices()))
985       IsIndexLoopInvariant[Index.index()] =
986           OrigLoop->isLoopInvariant(Index.value().get());
987   }
988   ~VPWidenGEPRecipe() override = default;
989 
990   /// Method to support type inquiry through isa, cast, and dyn_cast.
991   static inline bool classof(const VPDef *D) {
992     return D->getVPDefID() == VPRecipeBase::VPWidenGEPSC;
993   }
994 
995   /// Generate the gep nodes.
996   void execute(VPTransformState &State) override;
997 
998 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
999   /// Print the recipe.
1000   void print(raw_ostream &O, const Twine &Indent,
1001              VPSlotTracker &SlotTracker) const override;
1002 #endif
1003 };
1004 
1005 /// A recipe for handling phi nodes of integer and floating-point inductions,
1006 /// producing their vector values.
1007 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase, public VPValue {
1008   PHINode *IV;
1009   const InductionDescriptor &IndDesc;
1010   bool NeedsScalarIV;
1011   bool NeedsVectorIV;
1012 
1013 public:
1014   VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step,
1015                                 const InductionDescriptor &IndDesc,
1016                                 bool NeedsScalarIV, bool NeedsVectorIV)
1017       : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}),
1018         VPValue(IV, this), IV(IV), IndDesc(IndDesc),
1019         NeedsScalarIV(NeedsScalarIV), NeedsVectorIV(NeedsVectorIV) {}
1020 
1021   VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step,
1022                                 const InductionDescriptor &IndDesc,
1023                                 TruncInst *Trunc, bool NeedsScalarIV,
1024                                 bool NeedsVectorIV)
1025       : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}),
1026         VPValue(Trunc, this), IV(IV), IndDesc(IndDesc),
1027         NeedsScalarIV(NeedsScalarIV), NeedsVectorIV(NeedsVectorIV) {}
1028 
1029   ~VPWidenIntOrFpInductionRecipe() override = default;
1030 
1031   /// Method to support type inquiry through isa, cast, and dyn_cast.
1032   static inline bool classof(const VPDef *D) {
1033     return D->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
1034   }
1035 
1036   /// Generate the vectorized and scalarized versions of the phi node as
1037   /// needed by their users.
1038   void execute(VPTransformState &State) override;
1039 
1040 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1041   /// Print the recipe.
1042   void print(raw_ostream &O, const Twine &Indent,
1043              VPSlotTracker &SlotTracker) const override;
1044 #endif
1045 
1046   /// Returns the start value of the induction.
1047   VPValue *getStartValue() { return getOperand(0); }
1048   const VPValue *getStartValue() const { return getOperand(0); }
1049 
1050   /// Returns the step value of the induction.
1051   VPValue *getStepValue() { return getOperand(1); }
1052   const VPValue *getStepValue() const { return getOperand(1); }
1053 
1054   /// Returns the first defined value as TruncInst, if it is one or nullptr
1055   /// otherwise.
1056   TruncInst *getTruncInst() {
1057     return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue());
1058   }
1059   const TruncInst *getTruncInst() const {
1060     return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue());
1061   }
1062 
1063   PHINode *getPHINode() { return IV; }
1064 
1065   /// Returns the induction descriptor for the recipe.
1066   const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
1067 
1068   /// Returns true if the induction is canonical, i.e. starting at 0 and
1069   /// incremented by UF * VF (= the original IV is incremented by 1).
1070   bool isCanonical() const;
1071 
1072   /// Returns the scalar type of the induction.
1073   const Type *getScalarType() const {
1074     const TruncInst *TruncI = getTruncInst();
1075     return TruncI ? TruncI->getType() : IV->getType();
1076   }
1077 
1078   /// Returns true if a scalar phi needs to be created for the induction.
1079   bool needsScalarIV() const { return NeedsScalarIV; }
1080 
1081   /// Returns true if a vector phi needs to be created for the induction.
1082   bool needsVectorIV() const { return NeedsVectorIV; }
1083 };
1084 
1085 /// A pure virtual base class for all recipes modeling header phis, including
1086 /// phis for first order recurrences, pointer inductions and reductions. The
1087 /// start value is the first operand of the recipe and the incoming value from
1088 /// the backedge is the second operand.
1089 class VPHeaderPHIRecipe : public VPRecipeBase, public VPValue {
1090 protected:
1091   VPHeaderPHIRecipe(unsigned char VPVID, unsigned char VPDefID, PHINode *Phi,
1092                     VPValue *Start = nullptr)
1093       : VPRecipeBase(VPDefID, {}), VPValue(VPVID, Phi, this) {
1094     if (Start)
1095       addOperand(Start);
1096   }
1097 
1098 public:
1099   ~VPHeaderPHIRecipe() override = default;
1100 
1101   /// Method to support type inquiry through isa, cast, and dyn_cast.
1102   static inline bool classof(const VPRecipeBase *B) {
1103     return B->getVPDefID() == VPRecipeBase::VPCanonicalIVPHISC ||
1104            B->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC ||
1105            B->getVPDefID() == VPRecipeBase::VPReductionPHISC ||
1106            B->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC ||
1107            B->getVPDefID() == VPRecipeBase::VPWidenPHISC;
1108   }
1109   static inline bool classof(const VPValue *V) {
1110     return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC ||
1111            V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC ||
1112            V->getVPValueID() == VPValue::VPVReductionPHISC ||
1113            V->getVPValueID() == VPValue::VPVWidenIntOrFpInductionSC ||
1114            V->getVPValueID() == VPValue::VPVWidenPHISC;
1115   }
1116 
1117   /// Generate the phi nodes.
1118   void execute(VPTransformState &State) override = 0;
1119 
1120 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1121   /// Print the recipe.
1122   void print(raw_ostream &O, const Twine &Indent,
1123              VPSlotTracker &SlotTracker) const override = 0;
1124 #endif
1125 
1126   /// Returns the start value of the phi, if one is set.
1127   VPValue *getStartValue() {
1128     return getNumOperands() == 0 ? nullptr : getOperand(0);
1129   }
1130   VPValue *getStartValue() const {
1131     return getNumOperands() == 0 ? nullptr : getOperand(0);
1132   }
1133 
1134   /// Returns the incoming value from the loop backedge.
1135   VPValue *getBackedgeValue() {
1136     return getOperand(1);
1137   }
1138 
1139   /// Returns the backedge value as a recipe. The backedge value is guaranteed
1140   /// to be a recipe.
1141   VPRecipeBase *getBackedgeRecipe() {
1142     return cast<VPRecipeBase>(getBackedgeValue()->getDef());
1143   }
1144 };
1145 
1146 class VPWidenPointerInductionRecipe : public VPHeaderPHIRecipe {
1147   const InductionDescriptor &IndDesc;
1148 
1149   /// SCEV used to expand step.
1150   /// FIXME: move expansion of step to the pre-header, once it is modeled
1151   /// explicitly.
1152   ScalarEvolution &SE;
1153 
1154 public:
1155   /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p
1156   /// Start.
1157   VPWidenPointerInductionRecipe(PHINode *Phi, VPValue *Start,
1158                                 const InductionDescriptor &IndDesc,
1159                                 ScalarEvolution &SE)
1160       : VPHeaderPHIRecipe(VPVWidenPointerInductionSC, VPWidenPointerInductionSC,
1161                           Phi),
1162         IndDesc(IndDesc), SE(SE) {
1163     addOperand(Start);
1164   }
1165 
1166   ~VPWidenPointerInductionRecipe() override = default;
1167 
1168   /// Method to support type inquiry through isa, cast, and dyn_cast.
1169   static inline bool classof(const VPRecipeBase *B) {
1170     return B->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC;
1171   }
1172   static inline bool classof(const VPHeaderPHIRecipe *R) {
1173     return R->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC;
1174   }
1175   static inline bool classof(const VPValue *V) {
1176     return V->getVPValueID() == VPValue::VPVWidenPointerInductionSC;
1177   }
1178 
1179   /// Generate vector values for the pointer induction.
1180   void execute(VPTransformState &State) override;
1181 
1182   /// Returns true if only scalar values will be generated.
1183   bool onlyScalarsGenerated(ElementCount VF);
1184 
1185 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1186   /// Print the recipe.
1187   void print(raw_ostream &O, const Twine &Indent,
1188              VPSlotTracker &SlotTracker) const override;
1189 #endif
1190 };
1191 
1192 /// A recipe for handling header phis that are widened in the vector loop.
1193 /// In the VPlan native path, all incoming VPValues & VPBasicBlock pairs are
1194 /// managed in the recipe directly.
1195 class VPWidenPHIRecipe : public VPHeaderPHIRecipe {
1196   /// List of incoming blocks. Only used in the VPlan native path.
1197   SmallVector<VPBasicBlock *, 2> IncomingBlocks;
1198 
1199 public:
1200   /// Create a new VPWidenPHIRecipe for \p Phi with start value \p Start.
1201   VPWidenPHIRecipe(PHINode *Phi, VPValue *Start = nullptr)
1202       : VPHeaderPHIRecipe(VPVWidenPHISC, VPWidenPHISC, Phi) {
1203     if (Start)
1204       addOperand(Start);
1205   }
1206 
1207   ~VPWidenPHIRecipe() override = default;
1208 
1209   /// Method to support type inquiry through isa, cast, and dyn_cast.
1210   static inline bool classof(const VPRecipeBase *B) {
1211     return B->getVPDefID() == VPRecipeBase::VPWidenPHISC;
1212   }
1213   static inline bool classof(const VPHeaderPHIRecipe *R) {
1214     return R->getVPDefID() == VPRecipeBase::VPWidenPHISC;
1215   }
1216   static inline bool classof(const VPValue *V) {
1217     return V->getVPValueID() == VPValue::VPVWidenPHISC;
1218   }
1219 
1220   /// Generate the phi/select nodes.
1221   void execute(VPTransformState &State) override;
1222 
1223 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1224   /// Print the recipe.
1225   void print(raw_ostream &O, const Twine &Indent,
1226              VPSlotTracker &SlotTracker) const override;
1227 #endif
1228 
1229   /// Adds a pair (\p IncomingV, \p IncomingBlock) to the phi.
1230   void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock) {
1231     addOperand(IncomingV);
1232     IncomingBlocks.push_back(IncomingBlock);
1233   }
1234 
1235   /// Returns the \p I th incoming VPBasicBlock.
1236   VPBasicBlock *getIncomingBlock(unsigned I) { return IncomingBlocks[I]; }
1237 
1238   /// Returns the \p I th incoming VPValue.
1239   VPValue *getIncomingValue(unsigned I) { return getOperand(I); }
1240 };
1241 
1242 /// A recipe for handling first-order recurrence phis. The start value is the
1243 /// first operand of the recipe and the incoming value from the backedge is the
1244 /// second operand.
1245 struct VPFirstOrderRecurrencePHIRecipe : public VPHeaderPHIRecipe {
1246   VPFirstOrderRecurrencePHIRecipe(PHINode *Phi, VPValue &Start)
1247       : VPHeaderPHIRecipe(VPVFirstOrderRecurrencePHISC,
1248                           VPFirstOrderRecurrencePHISC, Phi, &Start) {}
1249 
1250   /// Method to support type inquiry through isa, cast, and dyn_cast.
1251   static inline bool classof(const VPRecipeBase *R) {
1252     return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC;
1253   }
1254   static inline bool classof(const VPHeaderPHIRecipe *R) {
1255     return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC;
1256   }
1257   static inline bool classof(const VPValue *V) {
1258     return V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC;
1259   }
1260 
1261   void execute(VPTransformState &State) override;
1262 
1263 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1264   /// Print the recipe.
1265   void print(raw_ostream &O, const Twine &Indent,
1266              VPSlotTracker &SlotTracker) const override;
1267 #endif
1268 };
1269 
1270 /// A recipe for handling reduction phis. The start value is the first operand
1271 /// of the recipe and the incoming value from the backedge is the second
1272 /// operand.
1273 class VPReductionPHIRecipe : public VPHeaderPHIRecipe {
1274   /// Descriptor for the reduction.
1275   const RecurrenceDescriptor &RdxDesc;
1276 
1277   /// The phi is part of an in-loop reduction.
1278   bool IsInLoop;
1279 
1280   /// The phi is part of an ordered reduction. Requires IsInLoop to be true.
1281   bool IsOrdered;
1282 
1283 public:
1284   /// Create a new VPReductionPHIRecipe for the reduction \p Phi described by \p
1285   /// RdxDesc.
1286   VPReductionPHIRecipe(PHINode *Phi, const RecurrenceDescriptor &RdxDesc,
1287                        VPValue &Start, bool IsInLoop = false,
1288                        bool IsOrdered = false)
1289       : VPHeaderPHIRecipe(VPVReductionPHISC, VPReductionPHISC, Phi, &Start),
1290         RdxDesc(RdxDesc), IsInLoop(IsInLoop), IsOrdered(IsOrdered) {
1291     assert((!IsOrdered || IsInLoop) && "IsOrdered requires IsInLoop");
1292   }
1293 
1294   ~VPReductionPHIRecipe() override = default;
1295 
1296   /// Method to support type inquiry through isa, cast, and dyn_cast.
1297   static inline bool classof(const VPRecipeBase *R) {
1298     return R->getVPDefID() == VPRecipeBase::VPReductionPHISC;
1299   }
1300   static inline bool classof(const VPHeaderPHIRecipe *R) {
1301     return R->getVPDefID() == VPRecipeBase::VPReductionPHISC;
1302   }
1303   static inline bool classof(const VPValue *V) {
1304     return V->getVPValueID() == VPValue::VPVReductionPHISC;
1305   }
1306 
1307   /// Generate the phi/select nodes.
1308   void execute(VPTransformState &State) override;
1309 
1310 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1311   /// Print the recipe.
1312   void print(raw_ostream &O, const Twine &Indent,
1313              VPSlotTracker &SlotTracker) const override;
1314 #endif
1315 
1316   const RecurrenceDescriptor &getRecurrenceDescriptor() const {
1317     return RdxDesc;
1318   }
1319 
1320   /// Returns true, if the phi is part of an ordered reduction.
1321   bool isOrdered() const { return IsOrdered; }
1322 
1323   /// Returns true, if the phi is part of an in-loop reduction.
1324   bool isInLoop() const { return IsInLoop; }
1325 };
1326 
1327 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
1328 /// instructions.
1329 class VPBlendRecipe : public VPRecipeBase, public VPValue {
1330   PHINode *Phi;
1331 
1332 public:
1333   /// The blend operation is a User of the incoming values and of their
1334   /// respective masks, ordered [I0, M0, I1, M1, ...]. Note that a single value
1335   /// might be incoming with a full mask for which there is no VPValue.
1336   VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Operands)
1337       : VPRecipeBase(VPBlendSC, Operands),
1338         VPValue(VPValue::VPVBlendSC, Phi, this), Phi(Phi) {
1339     assert(Operands.size() > 0 &&
1340            ((Operands.size() == 1) || (Operands.size() % 2 == 0)) &&
1341            "Expected either a single incoming value or a positive even number "
1342            "of operands");
1343   }
1344 
1345   /// Method to support type inquiry through isa, cast, and dyn_cast.
1346   static inline bool classof(const VPDef *D) {
1347     return D->getVPDefID() == VPRecipeBase::VPBlendSC;
1348   }
1349 
1350   /// Return the number of incoming values, taking into account that a single
1351   /// incoming value has no mask.
1352   unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; }
1353 
1354   /// Return incoming value number \p Idx.
1355   VPValue *getIncomingValue(unsigned Idx) const { return getOperand(Idx * 2); }
1356 
1357   /// Return mask number \p Idx.
1358   VPValue *getMask(unsigned Idx) const { return getOperand(Idx * 2 + 1); }
1359 
1360   /// Generate the phi/select nodes.
1361   void execute(VPTransformState &State) override;
1362 
1363 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1364   /// Print the recipe.
1365   void print(raw_ostream &O, const Twine &Indent,
1366              VPSlotTracker &SlotTracker) const override;
1367 #endif
1368 
1369   /// Returns true if the recipe only uses the first lane of operand \p Op.
1370   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1371     assert(is_contained(operands(), Op) &&
1372            "Op must be an operand of the recipe");
1373     // Recursing through Blend recipes only, must terminate at header phi's the
1374     // latest.
1375     return all_of(users(),
1376                   [this](VPUser *U) { return U->onlyFirstLaneUsed(this); });
1377   }
1378 };
1379 
1380 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
1381 /// or stores into one wide load/store and shuffles. The first operand of a
1382 /// VPInterleave recipe is the address, followed by the stored values, followed
1383 /// by an optional mask.
1384 class VPInterleaveRecipe : public VPRecipeBase {
1385   const InterleaveGroup<Instruction> *IG;
1386 
1387   bool HasMask = false;
1388 
1389 public:
1390   VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr,
1391                      ArrayRef<VPValue *> StoredValues, VPValue *Mask)
1392       : VPRecipeBase(VPInterleaveSC, {Addr}), IG(IG) {
1393     for (unsigned i = 0; i < IG->getFactor(); ++i)
1394       if (Instruction *I = IG->getMember(i)) {
1395         if (I->getType()->isVoidTy())
1396           continue;
1397         new VPValue(I, this);
1398       }
1399 
1400     for (auto *SV : StoredValues)
1401       addOperand(SV);
1402     if (Mask) {
1403       HasMask = true;
1404       addOperand(Mask);
1405     }
1406   }
1407   ~VPInterleaveRecipe() override = default;
1408 
1409   /// Method to support type inquiry through isa, cast, and dyn_cast.
1410   static inline bool classof(const VPDef *D) {
1411     return D->getVPDefID() == VPRecipeBase::VPInterleaveSC;
1412   }
1413 
1414   /// Return the address accessed by this recipe.
1415   VPValue *getAddr() const {
1416     return getOperand(0); // Address is the 1st, mandatory operand.
1417   }
1418 
1419   /// Return the mask used by this recipe. Note that a full mask is represented
1420   /// by a nullptr.
1421   VPValue *getMask() const {
1422     // Mask is optional and therefore the last, currently 2nd operand.
1423     return HasMask ? getOperand(getNumOperands() - 1) : nullptr;
1424   }
1425 
1426   /// Return the VPValues stored by this interleave group. If it is a load
1427   /// interleave group, return an empty ArrayRef.
1428   ArrayRef<VPValue *> getStoredValues() const {
1429     // The first operand is the address, followed by the stored values, followed
1430     // by an optional mask.
1431     return ArrayRef<VPValue *>(op_begin(), getNumOperands())
1432         .slice(1, getNumStoreOperands());
1433   }
1434 
1435   /// Generate the wide load or store, and shuffles.
1436   void execute(VPTransformState &State) override;
1437 
1438 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1439   /// Print the recipe.
1440   void print(raw_ostream &O, const Twine &Indent,
1441              VPSlotTracker &SlotTracker) const override;
1442 #endif
1443 
1444   const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
1445 
1446   /// Returns the number of stored operands of this interleave group. Returns 0
1447   /// for load interleave groups.
1448   unsigned getNumStoreOperands() const {
1449     return getNumOperands() - (HasMask ? 2 : 1);
1450   }
1451 
1452   /// The recipe only uses the first lane of the address.
1453   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1454     assert(is_contained(operands(), Op) &&
1455            "Op must be an operand of the recipe");
1456     return Op == getAddr() && all_of(getStoredValues(), [Op](VPValue *StoredV) {
1457              return Op != StoredV;
1458            });
1459   }
1460 };
1461 
1462 /// A recipe to represent inloop reduction operations, performing a reduction on
1463 /// a vector operand into a scalar value, and adding the result to a chain.
1464 /// The Operands are {ChainOp, VecOp, [Condition]}.
1465 class VPReductionRecipe : public VPRecipeBase, public VPValue {
1466   /// The recurrence decriptor for the reduction in question.
1467   const RecurrenceDescriptor *RdxDesc;
1468   /// Pointer to the TTI, needed to create the target reduction
1469   const TargetTransformInfo *TTI;
1470 
1471 public:
1472   VPReductionRecipe(const RecurrenceDescriptor *R, Instruction *I,
1473                     VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
1474                     const TargetTransformInfo *TTI)
1475       : VPRecipeBase(VPRecipeBase::VPReductionSC, {ChainOp, VecOp}),
1476         VPValue(VPValue::VPVReductionSC, I, this), RdxDesc(R), TTI(TTI) {
1477     if (CondOp)
1478       addOperand(CondOp);
1479   }
1480 
1481   ~VPReductionRecipe() override = default;
1482 
1483   /// Method to support type inquiry through isa, cast, and dyn_cast.
1484   static inline bool classof(const VPValue *V) {
1485     return V->getVPValueID() == VPValue::VPVReductionSC;
1486   }
1487 
1488   /// Generate the reduction in the loop
1489   void execute(VPTransformState &State) override;
1490 
1491 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1492   /// Print the recipe.
1493   void print(raw_ostream &O, const Twine &Indent,
1494              VPSlotTracker &SlotTracker) const override;
1495 #endif
1496 
1497   /// The VPValue of the scalar Chain being accumulated.
1498   VPValue *getChainOp() const { return getOperand(0); }
1499   /// The VPValue of the vector value to be reduced.
1500   VPValue *getVecOp() const { return getOperand(1); }
1501   /// The VPValue of the condition for the block.
1502   VPValue *getCondOp() const {
1503     return getNumOperands() > 2 ? getOperand(2) : nullptr;
1504   }
1505 };
1506 
1507 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
1508 /// copies of the original scalar type, one per lane, instead of producing a
1509 /// single copy of widened type for all lanes. If the instruction is known to be
1510 /// uniform only one copy, per lane zero, will be generated.
1511 class VPReplicateRecipe : public VPRecipeBase, public VPValue {
1512   /// Indicator if only a single replica per lane is needed.
1513   bool IsUniform;
1514 
1515   /// Indicator if the replicas are also predicated.
1516   bool IsPredicated;
1517 
1518   /// Indicator if the scalar values should also be packed into a vector.
1519   bool AlsoPack;
1520 
1521 public:
1522   template <typename IterT>
1523   VPReplicateRecipe(Instruction *I, iterator_range<IterT> Operands,
1524                     bool IsUniform, bool IsPredicated = false)
1525       : VPRecipeBase(VPReplicateSC, Operands), VPValue(VPVReplicateSC, I, this),
1526         IsUniform(IsUniform), IsPredicated(IsPredicated) {
1527     // Retain the previous behavior of predicateInstructions(), where an
1528     // insert-element of a predicated instruction got hoisted into the
1529     // predicated basic block iff it was its only user. This is achieved by
1530     // having predicated instructions also pack their values into a vector by
1531     // default unless they have a replicated user which uses their scalar value.
1532     AlsoPack = IsPredicated && !I->use_empty();
1533   }
1534 
1535   ~VPReplicateRecipe() override = default;
1536 
1537   /// Method to support type inquiry through isa, cast, and dyn_cast.
1538   static inline bool classof(const VPDef *D) {
1539     return D->getVPDefID() == VPRecipeBase::VPReplicateSC;
1540   }
1541 
1542   static inline bool classof(const VPValue *V) {
1543     return V->getVPValueID() == VPValue::VPVReplicateSC;
1544   }
1545 
1546   /// Generate replicas of the desired Ingredient. Replicas will be generated
1547   /// for all parts and lanes unless a specific part and lane are specified in
1548   /// the \p State.
1549   void execute(VPTransformState &State) override;
1550 
1551   void setAlsoPack(bool Pack) { AlsoPack = Pack; }
1552 
1553 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1554   /// Print the recipe.
1555   void print(raw_ostream &O, const Twine &Indent,
1556              VPSlotTracker &SlotTracker) const override;
1557 #endif
1558 
1559   bool isUniform() const { return IsUniform; }
1560 
1561   bool isPacked() const { return AlsoPack; }
1562 
1563   bool isPredicated() const { return IsPredicated; }
1564 
1565   /// Returns true if the recipe only uses the first lane of operand \p Op.
1566   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1567     assert(is_contained(operands(), Op) &&
1568            "Op must be an operand of the recipe");
1569     return isUniform();
1570   }
1571 
1572   /// Returns true if the recipe uses scalars of operand \p Op.
1573   bool usesScalars(const VPValue *Op) const override {
1574     assert(is_contained(operands(), Op) &&
1575            "Op must be an operand of the recipe");
1576     return true;
1577   }
1578 };
1579 
1580 /// A recipe for generating conditional branches on the bits of a mask.
1581 class VPBranchOnMaskRecipe : public VPRecipeBase {
1582 public:
1583   VPBranchOnMaskRecipe(VPValue *BlockInMask)
1584       : VPRecipeBase(VPBranchOnMaskSC, {}) {
1585     if (BlockInMask) // nullptr means all-one mask.
1586       addOperand(BlockInMask);
1587   }
1588 
1589   /// Method to support type inquiry through isa, cast, and dyn_cast.
1590   static inline bool classof(const VPDef *D) {
1591     return D->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC;
1592   }
1593 
1594   /// Generate the extraction of the appropriate bit from the block mask and the
1595   /// conditional branch.
1596   void execute(VPTransformState &State) override;
1597 
1598 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1599   /// Print the recipe.
1600   void print(raw_ostream &O, const Twine &Indent,
1601              VPSlotTracker &SlotTracker) const override {
1602     O << Indent << "BRANCH-ON-MASK ";
1603     if (VPValue *Mask = getMask())
1604       Mask->printAsOperand(O, SlotTracker);
1605     else
1606       O << " All-One";
1607   }
1608 #endif
1609 
1610   /// Return the mask used by this recipe. Note that a full mask is represented
1611   /// by a nullptr.
1612   VPValue *getMask() const {
1613     assert(getNumOperands() <= 1 && "should have either 0 or 1 operands");
1614     // Mask is optional.
1615     return getNumOperands() == 1 ? getOperand(0) : nullptr;
1616   }
1617 
1618   /// Returns true if the recipe uses scalars of operand \p Op.
1619   bool usesScalars(const VPValue *Op) const override {
1620     assert(is_contained(operands(), Op) &&
1621            "Op must be an operand of the recipe");
1622     return true;
1623   }
1624 };
1625 
1626 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
1627 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
1628 /// order to merge values that are set under such a branch and feed their uses.
1629 /// The phi nodes can be scalar or vector depending on the users of the value.
1630 /// This recipe works in concert with VPBranchOnMaskRecipe.
1631 class VPPredInstPHIRecipe : public VPRecipeBase, public VPValue {
1632 public:
1633   /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
1634   /// nodes after merging back from a Branch-on-Mask.
1635   VPPredInstPHIRecipe(VPValue *PredV)
1636       : VPRecipeBase(VPPredInstPHISC, PredV),
1637         VPValue(VPValue::VPVPredInstPHI, nullptr, this) {}
1638   ~VPPredInstPHIRecipe() override = default;
1639 
1640   /// Method to support type inquiry through isa, cast, and dyn_cast.
1641   static inline bool classof(const VPDef *D) {
1642     return D->getVPDefID() == VPRecipeBase::VPPredInstPHISC;
1643   }
1644 
1645   /// Generates phi nodes for live-outs as needed to retain SSA form.
1646   void execute(VPTransformState &State) override;
1647 
1648 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1649   /// Print the recipe.
1650   void print(raw_ostream &O, const Twine &Indent,
1651              VPSlotTracker &SlotTracker) const override;
1652 #endif
1653 
1654   /// Returns true if the recipe uses scalars of operand \p Op.
1655   bool usesScalars(const VPValue *Op) const override {
1656     assert(is_contained(operands(), Op) &&
1657            "Op must be an operand of the recipe");
1658     return true;
1659   }
1660 };
1661 
1662 /// A Recipe for widening load/store operations.
1663 /// The recipe uses the following VPValues:
1664 /// - For load: Address, optional mask
1665 /// - For store: Address, stored value, optional mask
1666 /// TODO: We currently execute only per-part unless a specific instance is
1667 /// provided.
1668 class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
1669   Instruction &Ingredient;
1670 
1671   // Whether the loaded-from / stored-to addresses are consecutive.
1672   bool Consecutive;
1673 
1674   // Whether the consecutive loaded/stored addresses are in reverse order.
1675   bool Reverse;
1676 
1677   void setMask(VPValue *Mask) {
1678     if (!Mask)
1679       return;
1680     addOperand(Mask);
1681   }
1682 
1683   bool isMasked() const {
1684     return isStore() ? getNumOperands() == 3 : getNumOperands() == 2;
1685   }
1686 
1687 public:
1688   VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask,
1689                                  bool Consecutive, bool Reverse)
1690       : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr}), Ingredient(Load),
1691         Consecutive(Consecutive), Reverse(Reverse) {
1692     assert((Consecutive || !Reverse) && "Reverse implies consecutive");
1693     new VPValue(VPValue::VPVMemoryInstructionSC, &Load, this);
1694     setMask(Mask);
1695   }
1696 
1697   VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr,
1698                                  VPValue *StoredValue, VPValue *Mask,
1699                                  bool Consecutive, bool Reverse)
1700       : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr, StoredValue}),
1701         Ingredient(Store), Consecutive(Consecutive), Reverse(Reverse) {
1702     assert((Consecutive || !Reverse) && "Reverse implies consecutive");
1703     setMask(Mask);
1704   }
1705 
1706   /// Method to support type inquiry through isa, cast, and dyn_cast.
1707   static inline bool classof(const VPDef *D) {
1708     return D->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC;
1709   }
1710 
1711   /// Return the address accessed by this recipe.
1712   VPValue *getAddr() const {
1713     return getOperand(0); // Address is the 1st, mandatory operand.
1714   }
1715 
1716   /// Return the mask used by this recipe. Note that a full mask is represented
1717   /// by a nullptr.
1718   VPValue *getMask() const {
1719     // Mask is optional and therefore the last operand.
1720     return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
1721   }
1722 
1723   /// Returns true if this recipe is a store.
1724   bool isStore() const { return isa<StoreInst>(Ingredient); }
1725 
1726   /// Return the address accessed by this recipe.
1727   VPValue *getStoredValue() const {
1728     assert(isStore() && "Stored value only available for store instructions");
1729     return getOperand(1); // Stored value is the 2nd, mandatory operand.
1730   }
1731 
1732   // Return whether the loaded-from / stored-to addresses are consecutive.
1733   bool isConsecutive() const { return Consecutive; }
1734 
1735   // Return whether the consecutive loaded/stored addresses are in reverse
1736   // order.
1737   bool isReverse() const { return Reverse; }
1738 
1739   /// Generate the wide load/store.
1740   void execute(VPTransformState &State) override;
1741 
1742 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1743   /// Print the recipe.
1744   void print(raw_ostream &O, const Twine &Indent,
1745              VPSlotTracker &SlotTracker) const override;
1746 #endif
1747 
1748   /// Returns true if the recipe only uses the first lane of operand \p Op.
1749   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1750     assert(is_contained(operands(), Op) &&
1751            "Op must be an operand of the recipe");
1752 
1753     // Widened, consecutive memory operations only demand the first lane of
1754     // their address, unless the same operand is also stored. That latter can
1755     // happen with opaque pointers.
1756     return Op == getAddr() && isConsecutive() &&
1757            (!isStore() || Op != getStoredValue());
1758   }
1759 
1760   Instruction &getIngredient() const { return Ingredient; }
1761 };
1762 
1763 /// Recipe to expand a SCEV expression.
1764 class VPExpandSCEVRecipe : public VPRecipeBase, public VPValue {
1765   const SCEV *Expr;
1766   ScalarEvolution &SE;
1767 
1768 public:
1769   VPExpandSCEVRecipe(const SCEV *Expr, ScalarEvolution &SE)
1770       : VPRecipeBase(VPExpandSCEVSC, {}), VPValue(nullptr, this), Expr(Expr),
1771         SE(SE) {}
1772 
1773   ~VPExpandSCEVRecipe() override = default;
1774 
1775   /// Method to support type inquiry through isa, cast, and dyn_cast.
1776   static inline bool classof(const VPDef *D) {
1777     return D->getVPDefID() == VPExpandSCEVSC;
1778   }
1779 
1780   /// Generate a canonical vector induction variable of the vector loop, with
1781   void execute(VPTransformState &State) override;
1782 
1783 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1784   /// Print the recipe.
1785   void print(raw_ostream &O, const Twine &Indent,
1786              VPSlotTracker &SlotTracker) const override;
1787 #endif
1788 
1789   const SCEV *getSCEV() const { return Expr; }
1790 };
1791 
1792 /// Canonical scalar induction phi of the vector loop. Starting at the specified
1793 /// start value (either 0 or the resume value when vectorizing the epilogue
1794 /// loop). VPWidenCanonicalIVRecipe represents the vector version of the
1795 /// canonical induction variable.
1796 class VPCanonicalIVPHIRecipe : public VPHeaderPHIRecipe {
1797   DebugLoc DL;
1798 
1799 public:
1800   VPCanonicalIVPHIRecipe(VPValue *StartV, DebugLoc DL)
1801       : VPHeaderPHIRecipe(VPValue::VPVCanonicalIVPHISC, VPCanonicalIVPHISC,
1802                           nullptr, StartV),
1803         DL(DL) {}
1804 
1805   ~VPCanonicalIVPHIRecipe() override = default;
1806 
1807   /// Method to support type inquiry through isa, cast, and dyn_cast.
1808   static inline bool classof(const VPDef *D) {
1809     return D->getVPDefID() == VPCanonicalIVPHISC;
1810   }
1811   static inline bool classof(const VPHeaderPHIRecipe *D) {
1812     return D->getVPDefID() == VPCanonicalIVPHISC;
1813   }
1814   static inline bool classof(const VPValue *V) {
1815     return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC;
1816   }
1817 
1818   /// Generate the canonical scalar induction phi of the vector loop.
1819   void execute(VPTransformState &State) override;
1820 
1821 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1822   /// Print the recipe.
1823   void print(raw_ostream &O, const Twine &Indent,
1824              VPSlotTracker &SlotTracker) const override;
1825 #endif
1826 
1827   /// Returns the scalar type of the induction.
1828   const Type *getScalarType() const {
1829     return getOperand(0)->getLiveInIRValue()->getType();
1830   }
1831 
1832   /// Returns true if the recipe only uses the first lane of operand \p Op.
1833   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1834     assert(is_contained(operands(), Op) &&
1835            "Op must be an operand of the recipe");
1836     return true;
1837   }
1838 };
1839 
1840 /// A Recipe for widening the canonical induction variable of the vector loop.
1841 class VPWidenCanonicalIVRecipe : public VPRecipeBase, public VPValue {
1842 public:
1843   VPWidenCanonicalIVRecipe(VPCanonicalIVPHIRecipe *CanonicalIV)
1844       : VPRecipeBase(VPWidenCanonicalIVSC, {CanonicalIV}),
1845         VPValue(VPValue::VPVWidenCanonicalIVSC, nullptr, this) {}
1846 
1847   ~VPWidenCanonicalIVRecipe() override = default;
1848 
1849   /// Method to support type inquiry through isa, cast, and dyn_cast.
1850   static inline bool classof(const VPDef *D) {
1851     return D->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1852   }
1853 
1854   /// Extra classof implementations to allow directly casting from VPUser ->
1855   /// VPWidenCanonicalIVRecipe.
1856   static inline bool classof(const VPUser *U) {
1857     auto *R = dyn_cast<VPRecipeBase>(U);
1858     return R && R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1859   }
1860   static inline bool classof(const VPRecipeBase *R) {
1861     return R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1862   }
1863 
1864   /// Generate a canonical vector induction variable of the vector loop, with
1865   /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and
1866   /// step = <VF*UF, VF*UF, ..., VF*UF>.
1867   void execute(VPTransformState &State) override;
1868 
1869 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1870   /// Print the recipe.
1871   void print(raw_ostream &O, const Twine &Indent,
1872              VPSlotTracker &SlotTracker) const override;
1873 #endif
1874 
1875   /// Returns the scalar type of the induction.
1876   const Type *getScalarType() const {
1877     return cast<VPCanonicalIVPHIRecipe>(getOperand(0)->getDef())
1878         ->getScalarType();
1879   }
1880 };
1881 
1882 /// A recipe for handling phi nodes of integer and floating-point inductions,
1883 /// producing their scalar values.
1884 class VPScalarIVStepsRecipe : public VPRecipeBase, public VPValue {
1885   /// Scalar type to use for the generated values.
1886   Type *Ty;
1887   /// If not nullptr, truncate the generated values to TruncToTy.
1888   Type *TruncToTy;
1889   const InductionDescriptor &IndDesc;
1890 
1891 public:
1892   VPScalarIVStepsRecipe(Type *Ty, const InductionDescriptor &IndDesc,
1893                         VPValue *CanonicalIV, VPValue *Start, VPValue *Step,
1894                         Type *TruncToTy)
1895       : VPRecipeBase(VPScalarIVStepsSC, {CanonicalIV, Start, Step}),
1896         VPValue(nullptr, this), Ty(Ty), TruncToTy(TruncToTy), IndDesc(IndDesc) {
1897   }
1898 
1899   ~VPScalarIVStepsRecipe() override = default;
1900 
1901   /// Method to support type inquiry through isa, cast, and dyn_cast.
1902   static inline bool classof(const VPDef *D) {
1903     return D->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC;
1904   }
1905   /// Extra classof implementations to allow directly casting from VPUser ->
1906   /// VPScalarIVStepsRecipe.
1907   static inline bool classof(const VPUser *U) {
1908     auto *R = dyn_cast<VPRecipeBase>(U);
1909     return R && R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC;
1910   }
1911   static inline bool classof(const VPRecipeBase *R) {
1912     return R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC;
1913   }
1914 
1915   /// Generate the scalarized versions of the phi node as needed by their users.
1916   void execute(VPTransformState &State) override;
1917 
1918 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1919   /// Print the recipe.
1920   void print(raw_ostream &O, const Twine &Indent,
1921              VPSlotTracker &SlotTracker) const override;
1922 #endif
1923 
1924   /// Returns true if the induction is canonical, i.e. starting at 0 and
1925   /// incremented by UF * VF (= the original IV is incremented by 1).
1926   bool isCanonical() const;
1927 
1928   VPCanonicalIVPHIRecipe *getCanonicalIV() const;
1929   VPValue *getStartValue() const { return getOperand(1); }
1930   VPValue *getStepValue() const { return getOperand(2); }
1931 
1932   /// Returns true if the recipe only uses the first lane of operand \p Op.
1933   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1934     assert(is_contained(operands(), Op) &&
1935            "Op must be an operand of the recipe");
1936     return true;
1937   }
1938 };
1939 
1940 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1941 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
1942 /// output IR instructions. All PHI-like recipes must come before any non-PHI recipes.
1943 class VPBasicBlock : public VPBlockBase {
1944 public:
1945   using RecipeListTy = iplist<VPRecipeBase>;
1946 
1947 private:
1948   /// The VPRecipes held in the order of output instructions to generate.
1949   RecipeListTy Recipes;
1950 
1951 public:
1952   VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1953       : VPBlockBase(VPBasicBlockSC, Name.str()) {
1954     if (Recipe)
1955       appendRecipe(Recipe);
1956   }
1957 
1958   ~VPBasicBlock() override {
1959     while (!Recipes.empty())
1960       Recipes.pop_back();
1961   }
1962 
1963   /// Instruction iterators...
1964   using iterator = RecipeListTy::iterator;
1965   using const_iterator = RecipeListTy::const_iterator;
1966   using reverse_iterator = RecipeListTy::reverse_iterator;
1967   using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
1968 
1969   //===--------------------------------------------------------------------===//
1970   /// Recipe iterator methods
1971   ///
1972   inline iterator begin() { return Recipes.begin(); }
1973   inline const_iterator begin() const { return Recipes.begin(); }
1974   inline iterator end() { return Recipes.end(); }
1975   inline const_iterator end() const { return Recipes.end(); }
1976 
1977   inline reverse_iterator rbegin() { return Recipes.rbegin(); }
1978   inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
1979   inline reverse_iterator rend() { return Recipes.rend(); }
1980   inline const_reverse_iterator rend() const { return Recipes.rend(); }
1981 
1982   inline size_t size() const { return Recipes.size(); }
1983   inline bool empty() const { return Recipes.empty(); }
1984   inline const VPRecipeBase &front() const { return Recipes.front(); }
1985   inline VPRecipeBase &front() { return Recipes.front(); }
1986   inline const VPRecipeBase &back() const { return Recipes.back(); }
1987   inline VPRecipeBase &back() { return Recipes.back(); }
1988 
1989   /// Returns a reference to the list of recipes.
1990   RecipeListTy &getRecipeList() { return Recipes; }
1991 
1992   /// Returns a pointer to a member of the recipe list.
1993   static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
1994     return &VPBasicBlock::Recipes;
1995   }
1996 
1997   /// Method to support type inquiry through isa, cast, and dyn_cast.
1998   static inline bool classof(const VPBlockBase *V) {
1999     return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
2000   }
2001 
2002   void insert(VPRecipeBase *Recipe, iterator InsertPt) {
2003     assert(Recipe && "No recipe to append.");
2004     assert(!Recipe->Parent && "Recipe already in VPlan");
2005     Recipe->Parent = this;
2006     Recipes.insert(InsertPt, Recipe);
2007   }
2008 
2009   /// Augment the existing recipes of a VPBasicBlock with an additional
2010   /// \p Recipe as the last recipe.
2011   void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
2012 
2013   /// The method which generates the output IR instructions that correspond to
2014   /// this VPBasicBlock, thereby "executing" the VPlan.
2015   void execute(struct VPTransformState *State) override;
2016 
2017   /// Return the position of the first non-phi node recipe in the block.
2018   iterator getFirstNonPhi();
2019 
2020   /// Returns an iterator range over the PHI-like recipes in the block.
2021   iterator_range<iterator> phis() {
2022     return make_range(begin(), getFirstNonPhi());
2023   }
2024 
2025   void dropAllReferences(VPValue *NewValue) override;
2026 
2027   /// Split current block at \p SplitAt by inserting a new block between the
2028   /// current block and its successors and moving all recipes starting at
2029   /// SplitAt to the new block. Returns the new block.
2030   VPBasicBlock *splitAt(iterator SplitAt);
2031 
2032   VPRegionBlock *getEnclosingLoopRegion();
2033 
2034 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2035   /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
2036   /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
2037   ///
2038   /// Note that the numbering is applied to the whole VPlan, so printing
2039   /// individual blocks is consistent with the whole VPlan printing.
2040   void print(raw_ostream &O, const Twine &Indent,
2041              VPSlotTracker &SlotTracker) const override;
2042   using VPBlockBase::print; // Get the print(raw_stream &O) version.
2043 #endif
2044 
2045   /// If the block has multiple successors, return the branch recipe terminating
2046   /// the block. If there are no or only a single successor, return nullptr;
2047   VPRecipeBase *getTerminator();
2048   const VPRecipeBase *getTerminator() const;
2049 
2050   /// Returns true if the block is exiting it's parent region.
2051   bool isExiting() const;
2052 
2053 private:
2054   /// Create an IR BasicBlock to hold the output instructions generated by this
2055   /// VPBasicBlock, and return it. Update the CFGState accordingly.
2056   BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
2057 };
2058 
2059 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
2060 /// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG.
2061 /// A VPRegionBlock may indicate that its contents are to be replicated several
2062 /// times. This is designed to support predicated scalarization, in which a
2063 /// scalar if-then code structure needs to be generated VF * UF times. Having
2064 /// this replication indicator helps to keep a single model for multiple
2065 /// candidate VF's. The actual replication takes place only once the desired VF
2066 /// and UF have been determined.
2067 class VPRegionBlock : public VPBlockBase {
2068   /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
2069   VPBlockBase *Entry;
2070 
2071   /// Hold the Single Exiting block of the SESE region modelled by the
2072   /// VPRegionBlock.
2073   VPBlockBase *Exiting;
2074 
2075   /// An indicator whether this region is to generate multiple replicated
2076   /// instances of output IR corresponding to its VPBlockBases.
2077   bool IsReplicator;
2078 
2079 public:
2080   VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting,
2081                 const std::string &Name = "", bool IsReplicator = false)
2082       : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting),
2083         IsReplicator(IsReplicator) {
2084     assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
2085     assert(Exiting->getSuccessors().empty() && "Exit block has successors.");
2086     Entry->setParent(this);
2087     Exiting->setParent(this);
2088   }
2089   VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
2090       : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exiting(nullptr),
2091         IsReplicator(IsReplicator) {}
2092 
2093   ~VPRegionBlock() override {
2094     if (Entry) {
2095       VPValue DummyValue;
2096       Entry->dropAllReferences(&DummyValue);
2097       deleteCFG(Entry);
2098     }
2099   }
2100 
2101   /// Method to support type inquiry through isa, cast, and dyn_cast.
2102   static inline bool classof(const VPBlockBase *V) {
2103     return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
2104   }
2105 
2106   const VPBlockBase *getEntry() const { return Entry; }
2107   VPBlockBase *getEntry() { return Entry; }
2108 
2109   /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
2110   /// EntryBlock must have no predecessors.
2111   void setEntry(VPBlockBase *EntryBlock) {
2112     assert(EntryBlock->getPredecessors().empty() &&
2113            "Entry block cannot have predecessors.");
2114     Entry = EntryBlock;
2115     EntryBlock->setParent(this);
2116   }
2117 
2118   // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
2119   // specific interface of llvm::Function, instead of using
2120   // GraphTraints::getEntryNode. We should add a new template parameter to
2121   // DominatorTreeBase representing the Graph type.
2122   VPBlockBase &front() const { return *Entry; }
2123 
2124   const VPBlockBase *getExiting() const { return Exiting; }
2125   VPBlockBase *getExiting() { return Exiting; }
2126 
2127   /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p
2128   /// ExitingBlock must have no successors.
2129   void setExiting(VPBlockBase *ExitingBlock) {
2130     assert(ExitingBlock->getSuccessors().empty() &&
2131            "Exit block cannot have successors.");
2132     Exiting = ExitingBlock;
2133     ExitingBlock->setParent(this);
2134   }
2135 
2136   /// Returns the pre-header VPBasicBlock of the loop region.
2137   VPBasicBlock *getPreheaderVPBB() {
2138     assert(!isReplicator() && "should only get pre-header of loop regions");
2139     return getSinglePredecessor()->getExitingBasicBlock();
2140   }
2141 
2142   /// An indicator whether this region is to generate multiple replicated
2143   /// instances of output IR corresponding to its VPBlockBases.
2144   bool isReplicator() const { return IsReplicator; }
2145 
2146   /// The method which generates the output IR instructions that correspond to
2147   /// this VPRegionBlock, thereby "executing" the VPlan.
2148   void execute(struct VPTransformState *State) override;
2149 
2150   void dropAllReferences(VPValue *NewValue) override;
2151 
2152 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2153   /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
2154   /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
2155   /// consequtive numbers.
2156   ///
2157   /// Note that the numbering is applied to the whole VPlan, so printing
2158   /// individual regions is consistent with the whole VPlan printing.
2159   void print(raw_ostream &O, const Twine &Indent,
2160              VPSlotTracker &SlotTracker) const override;
2161   using VPBlockBase::print; // Get the print(raw_stream &O) version.
2162 #endif
2163 };
2164 
2165 //===----------------------------------------------------------------------===//
2166 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs     //
2167 //===----------------------------------------------------------------------===//
2168 
2169 // The following set of template specializations implement GraphTraits to treat
2170 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
2171 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
2172 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
2173 // successors/predecessors but not to the blocks inside the region.
2174 
2175 template <> struct GraphTraits<VPBlockBase *> {
2176   using NodeRef = VPBlockBase *;
2177   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
2178 
2179   static NodeRef getEntryNode(NodeRef N) { return N; }
2180 
2181   static inline ChildIteratorType child_begin(NodeRef N) {
2182     return N->getSuccessors().begin();
2183   }
2184 
2185   static inline ChildIteratorType child_end(NodeRef N) {
2186     return N->getSuccessors().end();
2187   }
2188 };
2189 
2190 template <> struct GraphTraits<const VPBlockBase *> {
2191   using NodeRef = const VPBlockBase *;
2192   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
2193 
2194   static NodeRef getEntryNode(NodeRef N) { return N; }
2195 
2196   static inline ChildIteratorType child_begin(NodeRef N) {
2197     return N->getSuccessors().begin();
2198   }
2199 
2200   static inline ChildIteratorType child_end(NodeRef N) {
2201     return N->getSuccessors().end();
2202   }
2203 };
2204 
2205 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
2206 // of successors for the inverse traversal.
2207 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
2208   using NodeRef = VPBlockBase *;
2209   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
2210 
2211   static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
2212 
2213   static inline ChildIteratorType child_begin(NodeRef N) {
2214     return N->getPredecessors().begin();
2215   }
2216 
2217   static inline ChildIteratorType child_end(NodeRef N) {
2218     return N->getPredecessors().end();
2219   }
2220 };
2221 
2222 // The following set of template specializations implement GraphTraits to
2223 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
2224 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
2225 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
2226 // there won't be automatic recursion into other VPBlockBases that turn to be
2227 // VPRegionBlocks.
2228 
2229 template <>
2230 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
2231   using GraphRef = VPRegionBlock *;
2232   using nodes_iterator = df_iterator<NodeRef>;
2233 
2234   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
2235 
2236   static nodes_iterator nodes_begin(GraphRef N) {
2237     return nodes_iterator::begin(N->getEntry());
2238   }
2239 
2240   static nodes_iterator nodes_end(GraphRef N) {
2241     // df_iterator::end() returns an empty iterator so the node used doesn't
2242     // matter.
2243     return nodes_iterator::end(N);
2244   }
2245 };
2246 
2247 template <>
2248 struct GraphTraits<const VPRegionBlock *>
2249     : public GraphTraits<const VPBlockBase *> {
2250   using GraphRef = const VPRegionBlock *;
2251   using nodes_iterator = df_iterator<NodeRef>;
2252 
2253   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
2254 
2255   static nodes_iterator nodes_begin(GraphRef N) {
2256     return nodes_iterator::begin(N->getEntry());
2257   }
2258 
2259   static nodes_iterator nodes_end(GraphRef N) {
2260     // df_iterator::end() returns an empty iterator so the node used doesn't
2261     // matter.
2262     return nodes_iterator::end(N);
2263   }
2264 };
2265 
2266 template <>
2267 struct GraphTraits<Inverse<VPRegionBlock *>>
2268     : public GraphTraits<Inverse<VPBlockBase *>> {
2269   using GraphRef = VPRegionBlock *;
2270   using nodes_iterator = df_iterator<NodeRef>;
2271 
2272   static NodeRef getEntryNode(Inverse<GraphRef> N) {
2273     return N.Graph->getExiting();
2274   }
2275 
2276   static nodes_iterator nodes_begin(GraphRef N) {
2277     return nodes_iterator::begin(N->getExiting());
2278   }
2279 
2280   static nodes_iterator nodes_end(GraphRef N) {
2281     // df_iterator::end() returns an empty iterator so the node used doesn't
2282     // matter.
2283     return nodes_iterator::end(N);
2284   }
2285 };
2286 
2287 /// Iterator to traverse all successors of a VPBlockBase node. This includes the
2288 /// entry node of VPRegionBlocks. Exit blocks of a region implicitly have their
2289 /// parent region's successors. This ensures all blocks in a region are visited
2290 /// before any blocks in a successor region when doing a reverse post-order
2291 // traversal of the graph.
2292 template <typename BlockPtrTy>
2293 class VPAllSuccessorsIterator
2294     : public iterator_facade_base<VPAllSuccessorsIterator<BlockPtrTy>,
2295                                   std::forward_iterator_tag, VPBlockBase> {
2296   BlockPtrTy Block;
2297   /// Index of the current successor. For VPBasicBlock nodes, this simply is the
2298   /// index for the successor array. For VPRegionBlock, SuccessorIdx == 0 is
2299   /// used for the region's entry block, and SuccessorIdx - 1 are the indices
2300   /// for the successor array.
2301   size_t SuccessorIdx;
2302 
2303   static BlockPtrTy getBlockWithSuccs(BlockPtrTy Current) {
2304     while (Current && Current->getNumSuccessors() == 0)
2305       Current = Current->getParent();
2306     return Current;
2307   }
2308 
2309   /// Templated helper to dereference successor \p SuccIdx of \p Block. Used by
2310   /// both the const and non-const operator* implementations.
2311   template <typename T1> static T1 deref(T1 Block, unsigned SuccIdx) {
2312     if (auto *R = dyn_cast<VPRegionBlock>(Block)) {
2313       if (SuccIdx == 0)
2314         return R->getEntry();
2315       SuccIdx--;
2316     }
2317 
2318     // For exit blocks, use the next parent region with successors.
2319     return getBlockWithSuccs(Block)->getSuccessors()[SuccIdx];
2320   }
2321 
2322 public:
2323   VPAllSuccessorsIterator(BlockPtrTy Block, size_t Idx = 0)
2324       : Block(Block), SuccessorIdx(Idx) {}
2325   VPAllSuccessorsIterator(const VPAllSuccessorsIterator &Other)
2326       : Block(Other.Block), SuccessorIdx(Other.SuccessorIdx) {}
2327 
2328   VPAllSuccessorsIterator &operator=(const VPAllSuccessorsIterator &R) {
2329     Block = R.Block;
2330     SuccessorIdx = R.SuccessorIdx;
2331     return *this;
2332   }
2333 
2334   static VPAllSuccessorsIterator end(BlockPtrTy Block) {
2335     BlockPtrTy ParentWithSuccs = getBlockWithSuccs(Block);
2336     unsigned NumSuccessors = ParentWithSuccs
2337                                  ? ParentWithSuccs->getNumSuccessors()
2338                                  : Block->getNumSuccessors();
2339 
2340     if (auto *R = dyn_cast<VPRegionBlock>(Block))
2341       return {R, NumSuccessors + 1};
2342     return {Block, NumSuccessors};
2343   }
2344 
2345   bool operator==(const VPAllSuccessorsIterator &R) const {
2346     return Block == R.Block && SuccessorIdx == R.SuccessorIdx;
2347   }
2348 
2349   const VPBlockBase *operator*() const { return deref(Block, SuccessorIdx); }
2350 
2351   BlockPtrTy operator*() { return deref(Block, SuccessorIdx); }
2352 
2353   VPAllSuccessorsIterator &operator++() {
2354     SuccessorIdx++;
2355     return *this;
2356   }
2357 
2358   VPAllSuccessorsIterator operator++(int X) {
2359     VPAllSuccessorsIterator Orig = *this;
2360     SuccessorIdx++;
2361     return Orig;
2362   }
2363 };
2364 
2365 /// Helper for GraphTraits specialization that traverses through VPRegionBlocks.
2366 template <typename BlockTy> class VPBlockRecursiveTraversalWrapper {
2367   BlockTy Entry;
2368 
2369 public:
2370   VPBlockRecursiveTraversalWrapper(BlockTy Entry) : Entry(Entry) {}
2371   BlockTy getEntry() { return Entry; }
2372 };
2373 
2374 /// GraphTraits specialization to recursively traverse VPBlockBase nodes,
2375 /// including traversing through VPRegionBlocks.  Exit blocks of a region
2376 /// implicitly have their parent region's successors. This ensures all blocks in
2377 /// a region are visited before any blocks in a successor region when doing a
2378 /// reverse post-order traversal of the graph.
2379 template <>
2380 struct GraphTraits<VPBlockRecursiveTraversalWrapper<VPBlockBase *>> {
2381   using NodeRef = VPBlockBase *;
2382   using ChildIteratorType = VPAllSuccessorsIterator<VPBlockBase *>;
2383 
2384   static NodeRef
2385   getEntryNode(VPBlockRecursiveTraversalWrapper<VPBlockBase *> N) {
2386     return N.getEntry();
2387   }
2388 
2389   static inline ChildIteratorType child_begin(NodeRef N) {
2390     return ChildIteratorType(N);
2391   }
2392 
2393   static inline ChildIteratorType child_end(NodeRef N) {
2394     return ChildIteratorType::end(N);
2395   }
2396 };
2397 
2398 template <>
2399 struct GraphTraits<VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> {
2400   using NodeRef = const VPBlockBase *;
2401   using ChildIteratorType = VPAllSuccessorsIterator<const VPBlockBase *>;
2402 
2403   static NodeRef
2404   getEntryNode(VPBlockRecursiveTraversalWrapper<const VPBlockBase *> N) {
2405     return N.getEntry();
2406   }
2407 
2408   static inline ChildIteratorType child_begin(NodeRef N) {
2409     return ChildIteratorType(N);
2410   }
2411 
2412   static inline ChildIteratorType child_end(NodeRef N) {
2413     return ChildIteratorType::end(N);
2414   }
2415 };
2416 
2417 /// VPlan models a candidate for vectorization, encoding various decisions take
2418 /// to produce efficient output IR, including which branches, basic-blocks and
2419 /// output IR instructions to generate, and their cost. VPlan holds a
2420 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
2421 /// VPBlock.
2422 class VPlan {
2423   friend class VPlanPrinter;
2424   friend class VPSlotTracker;
2425 
2426   /// Hold the single entry to the Hierarchical CFG of the VPlan.
2427   VPBlockBase *Entry;
2428 
2429   /// Holds the VFs applicable to this VPlan.
2430   SmallSetVector<ElementCount, 2> VFs;
2431 
2432   /// Holds the name of the VPlan, for printing.
2433   std::string Name;
2434 
2435   /// Holds all the external definitions created for this VPlan. External
2436   /// definitions must be immutable and hold a pointer to their underlying IR.
2437   DenseMap<Value *, VPValue *> VPExternalDefs;
2438 
2439   /// Represents the trip count of the original loop, for folding
2440   /// the tail.
2441   VPValue *TripCount = nullptr;
2442 
2443   /// Represents the backedge taken count of the original loop, for folding
2444   /// the tail. It equals TripCount - 1.
2445   VPValue *BackedgeTakenCount = nullptr;
2446 
2447   /// Represents the vector trip count.
2448   VPValue VectorTripCount;
2449 
2450   /// Holds a mapping between Values and their corresponding VPValue inside
2451   /// VPlan.
2452   Value2VPValueTy Value2VPValue;
2453 
2454   /// Contains all VPValues that been allocated by addVPValue directly and need
2455   /// to be free when the plan's destructor is called.
2456   SmallVector<VPValue *, 16> VPValuesToFree;
2457 
2458   /// Indicates whether it is safe use the Value2VPValue mapping or if the
2459   /// mapping cannot be used any longer, because it is stale.
2460   bool Value2VPValueEnabled = true;
2461 
2462   /// Values used outside the plan.
2463   MapVector<PHINode *, VPLiveOut *> LiveOuts;
2464 
2465 public:
2466   VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {
2467     if (Entry)
2468       Entry->setPlan(this);
2469   }
2470 
2471   ~VPlan() {
2472     clearLiveOuts();
2473 
2474     if (Entry) {
2475       VPValue DummyValue;
2476       for (VPBlockBase *Block : depth_first(Entry))
2477         Block->dropAllReferences(&DummyValue);
2478 
2479       VPBlockBase::deleteCFG(Entry);
2480     }
2481     for (VPValue *VPV : VPValuesToFree)
2482       delete VPV;
2483     if (TripCount)
2484       delete TripCount;
2485     if (BackedgeTakenCount)
2486       delete BackedgeTakenCount;
2487     for (auto &P : VPExternalDefs)
2488       delete P.second;
2489   }
2490 
2491   /// Prepare the plan for execution, setting up the required live-in values.
2492   void prepareToExecute(Value *TripCount, Value *VectorTripCount,
2493                         Value *CanonicalIVStartValue, VPTransformState &State);
2494 
2495   /// Generate the IR code for this VPlan.
2496   void execute(struct VPTransformState *State);
2497 
2498   VPBlockBase *getEntry() { return Entry; }
2499   const VPBlockBase *getEntry() const { return Entry; }
2500 
2501   VPBlockBase *setEntry(VPBlockBase *Block) {
2502     Entry = Block;
2503     Block->setPlan(this);
2504     return Entry;
2505   }
2506 
2507   /// The trip count of the original loop.
2508   VPValue *getOrCreateTripCount() {
2509     if (!TripCount)
2510       TripCount = new VPValue();
2511     return TripCount;
2512   }
2513 
2514   /// The backedge taken count of the original loop.
2515   VPValue *getOrCreateBackedgeTakenCount() {
2516     if (!BackedgeTakenCount)
2517       BackedgeTakenCount = new VPValue();
2518     return BackedgeTakenCount;
2519   }
2520 
2521   /// The vector trip count.
2522   VPValue &getVectorTripCount() { return VectorTripCount; }
2523 
2524   /// Mark the plan to indicate that using Value2VPValue is not safe any
2525   /// longer, because it may be stale.
2526   void disableValue2VPValue() { Value2VPValueEnabled = false; }
2527 
2528   void addVF(ElementCount VF) { VFs.insert(VF); }
2529 
2530   bool hasVF(ElementCount VF) { return VFs.count(VF); }
2531 
2532   const std::string &getName() const { return Name; }
2533 
2534   void setName(const Twine &newName) { Name = newName.str(); }
2535 
2536   /// Get the existing or add a new external definition for \p V.
2537   VPValue *getOrAddExternalDef(Value *V) {
2538     auto I = VPExternalDefs.insert({V, nullptr});
2539     if (I.second)
2540       I.first->second = new VPValue(V);
2541     return I.first->second;
2542   }
2543 
2544   void addVPValue(Value *V) {
2545     assert(Value2VPValueEnabled &&
2546            "IR value to VPValue mapping may be out of date!");
2547     assert(V && "Trying to add a null Value to VPlan");
2548     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
2549     VPValue *VPV = new VPValue(V);
2550     Value2VPValue[V] = VPV;
2551     VPValuesToFree.push_back(VPV);
2552   }
2553 
2554   void addVPValue(Value *V, VPValue *VPV) {
2555     assert(Value2VPValueEnabled && "Value2VPValue mapping may be out of date!");
2556     assert(V && "Trying to add a null Value to VPlan");
2557     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
2558     Value2VPValue[V] = VPV;
2559   }
2560 
2561   /// Returns the VPValue for \p V. \p OverrideAllowed can be used to disable
2562   /// checking whether it is safe to query VPValues using IR Values.
2563   VPValue *getVPValue(Value *V, bool OverrideAllowed = false) {
2564     assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) &&
2565            "Value2VPValue mapping may be out of date!");
2566     assert(V && "Trying to get the VPValue of a null Value");
2567     assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
2568     return Value2VPValue[V];
2569   }
2570 
2571   /// Gets the VPValue or adds a new one (if none exists yet) for \p V. \p
2572   /// OverrideAllowed can be used to disable checking whether it is safe to
2573   /// query VPValues using IR Values.
2574   VPValue *getOrAddVPValue(Value *V, bool OverrideAllowed = false) {
2575     assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) &&
2576            "Value2VPValue mapping may be out of date!");
2577     assert(V && "Trying to get or add the VPValue of a null Value");
2578     if (!Value2VPValue.count(V))
2579       addVPValue(V);
2580     return getVPValue(V);
2581   }
2582 
2583   void removeVPValueFor(Value *V) {
2584     assert(Value2VPValueEnabled &&
2585            "IR value to VPValue mapping may be out of date!");
2586     Value2VPValue.erase(V);
2587   }
2588 
2589 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2590   /// Print this VPlan to \p O.
2591   void print(raw_ostream &O) const;
2592 
2593   /// Print this VPlan in DOT format to \p O.
2594   void printDOT(raw_ostream &O) const;
2595 
2596   /// Dump the plan to stderr (for debugging).
2597   LLVM_DUMP_METHOD void dump() const;
2598 #endif
2599 
2600   /// Returns a range mapping the values the range \p Operands to their
2601   /// corresponding VPValues.
2602   iterator_range<mapped_iterator<Use *, std::function<VPValue *(Value *)>>>
2603   mapToVPValues(User::op_range Operands) {
2604     std::function<VPValue *(Value *)> Fn = [this](Value *Op) {
2605       return getOrAddVPValue(Op);
2606     };
2607     return map_range(Operands, Fn);
2608   }
2609 
2610   /// Returns true if \p VPV is uniform after vectorization.
2611   bool isUniformAfterVectorization(VPValue *VPV) const {
2612     auto RepR = dyn_cast_or_null<VPReplicateRecipe>(VPV->getDef());
2613     return !VPV->getDef() || (RepR && RepR->isUniform());
2614   }
2615 
2616   /// Returns the VPRegionBlock of the vector loop.
2617   VPRegionBlock *getVectorLoopRegion() {
2618     return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
2619   }
2620   const VPRegionBlock *getVectorLoopRegion() const {
2621     return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
2622   }
2623 
2624   /// Returns the canonical induction recipe of the vector loop.
2625   VPCanonicalIVPHIRecipe *getCanonicalIV() {
2626     VPBasicBlock *EntryVPBB = getVectorLoopRegion()->getEntryBasicBlock();
2627     if (EntryVPBB->empty()) {
2628       // VPlan native path.
2629       EntryVPBB = cast<VPBasicBlock>(EntryVPBB->getSingleSuccessor());
2630     }
2631     return cast<VPCanonicalIVPHIRecipe>(&*EntryVPBB->begin());
2632   }
2633 
2634   void addLiveOut(PHINode *PN, VPValue *V);
2635 
2636   void clearLiveOuts() {
2637     for (auto &KV : LiveOuts)
2638       delete KV.second;
2639     LiveOuts.clear();
2640   }
2641 
2642   void removeLiveOut(PHINode *PN) {
2643     delete LiveOuts[PN];
2644     LiveOuts.erase(PN);
2645   }
2646 
2647   const MapVector<PHINode *, VPLiveOut *> &getLiveOuts() const {
2648     return LiveOuts;
2649   }
2650 
2651 private:
2652   /// Add to the given dominator tree the header block and every new basic block
2653   /// that was created between it and the latch block, inclusive.
2654   static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB,
2655                                   BasicBlock *LoopPreHeaderBB,
2656                                   BasicBlock *LoopExitBB);
2657 };
2658 
2659 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2660 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
2661 /// indented and follows the dot format.
2662 class VPlanPrinter {
2663   raw_ostream &OS;
2664   const VPlan &Plan;
2665   unsigned Depth = 0;
2666   unsigned TabWidth = 2;
2667   std::string Indent;
2668   unsigned BID = 0;
2669   SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
2670 
2671   VPSlotTracker SlotTracker;
2672 
2673   /// Handle indentation.
2674   void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
2675 
2676   /// Print a given \p Block of the Plan.
2677   void dumpBlock(const VPBlockBase *Block);
2678 
2679   /// Print the information related to the CFG edges going out of a given
2680   /// \p Block, followed by printing the successor blocks themselves.
2681   void dumpEdges(const VPBlockBase *Block);
2682 
2683   /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
2684   /// its successor blocks.
2685   void dumpBasicBlock(const VPBasicBlock *BasicBlock);
2686 
2687   /// Print a given \p Region of the Plan.
2688   void dumpRegion(const VPRegionBlock *Region);
2689 
2690   unsigned getOrCreateBID(const VPBlockBase *Block) {
2691     return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
2692   }
2693 
2694   Twine getOrCreateName(const VPBlockBase *Block);
2695 
2696   Twine getUID(const VPBlockBase *Block);
2697 
2698   /// Print the information related to a CFG edge between two VPBlockBases.
2699   void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
2700                 const Twine &Label);
2701 
2702 public:
2703   VPlanPrinter(raw_ostream &O, const VPlan &P)
2704       : OS(O), Plan(P), SlotTracker(&P) {}
2705 
2706   LLVM_DUMP_METHOD void dump();
2707 };
2708 
2709 struct VPlanIngredient {
2710   const Value *V;
2711 
2712   VPlanIngredient(const Value *V) : V(V) {}
2713 
2714   void print(raw_ostream &O) const;
2715 };
2716 
2717 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
2718   I.print(OS);
2719   return OS;
2720 }
2721 
2722 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
2723   Plan.print(OS);
2724   return OS;
2725 }
2726 #endif
2727 
2728 //===----------------------------------------------------------------------===//
2729 // VPlan Utilities
2730 //===----------------------------------------------------------------------===//
2731 
2732 /// Class that provides utilities for VPBlockBases in VPlan.
2733 class VPBlockUtils {
2734 public:
2735   VPBlockUtils() = delete;
2736 
2737   /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
2738   /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
2739   /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's
2740   /// successors are moved from \p BlockPtr to \p NewBlock. \p NewBlock must
2741   /// have neither successors nor predecessors.
2742   static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
2743     assert(NewBlock->getSuccessors().empty() &&
2744            NewBlock->getPredecessors().empty() &&
2745            "Can't insert new block with predecessors or successors.");
2746     NewBlock->setParent(BlockPtr->getParent());
2747     SmallVector<VPBlockBase *> Succs(BlockPtr->successors());
2748     for (VPBlockBase *Succ : Succs) {
2749       disconnectBlocks(BlockPtr, Succ);
2750       connectBlocks(NewBlock, Succ);
2751     }
2752     connectBlocks(BlockPtr, NewBlock);
2753   }
2754 
2755   /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
2756   /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
2757   /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
2758   /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors
2759   /// and \p IfTrue and \p IfFalse must have neither successors nor
2760   /// predecessors.
2761   static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
2762                                    VPBlockBase *BlockPtr) {
2763     assert(IfTrue->getSuccessors().empty() &&
2764            "Can't insert IfTrue with successors.");
2765     assert(IfFalse->getSuccessors().empty() &&
2766            "Can't insert IfFalse with successors.");
2767     BlockPtr->setTwoSuccessors(IfTrue, IfFalse);
2768     IfTrue->setPredecessors({BlockPtr});
2769     IfFalse->setPredecessors({BlockPtr});
2770     IfTrue->setParent(BlockPtr->getParent());
2771     IfFalse->setParent(BlockPtr->getParent());
2772   }
2773 
2774   /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
2775   /// the successors of \p From and \p From to the predecessors of \p To. Both
2776   /// VPBlockBases must have the same parent, which can be null. Both
2777   /// VPBlockBases can be already connected to other VPBlockBases.
2778   static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
2779     assert((From->getParent() == To->getParent()) &&
2780            "Can't connect two block with different parents");
2781     assert(From->getNumSuccessors() < 2 &&
2782            "Blocks can't have more than two successors.");
2783     From->appendSuccessor(To);
2784     To->appendPredecessor(From);
2785   }
2786 
2787   /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
2788   /// from the successors of \p From and \p From from the predecessors of \p To.
2789   static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
2790     assert(To && "Successor to disconnect is null.");
2791     From->removeSuccessor(To);
2792     To->removePredecessor(From);
2793   }
2794 
2795   /// Try to merge \p Block into its single predecessor, if \p Block is a
2796   /// VPBasicBlock and its predecessor has a single successor. Returns a pointer
2797   /// to the predecessor \p Block was merged into or nullptr otherwise.
2798   static VPBasicBlock *tryToMergeBlockIntoPredecessor(VPBlockBase *Block) {
2799     auto *VPBB = dyn_cast<VPBasicBlock>(Block);
2800     auto *PredVPBB =
2801         dyn_cast_or_null<VPBasicBlock>(Block->getSinglePredecessor());
2802     if (!VPBB || !PredVPBB || PredVPBB->getNumSuccessors() != 1)
2803       return nullptr;
2804 
2805     for (VPRecipeBase &R : make_early_inc_range(*VPBB))
2806       R.moveBefore(*PredVPBB, PredVPBB->end());
2807     VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
2808     auto *ParentRegion = cast<VPRegionBlock>(Block->getParent());
2809     if (ParentRegion->getExiting() == Block)
2810       ParentRegion->setExiting(PredVPBB);
2811     SmallVector<VPBlockBase *> Successors(Block->successors());
2812     for (auto *Succ : Successors) {
2813       VPBlockUtils::disconnectBlocks(Block, Succ);
2814       VPBlockUtils::connectBlocks(PredVPBB, Succ);
2815     }
2816     delete Block;
2817     return PredVPBB;
2818   }
2819 
2820   /// Return an iterator range over \p Range which only includes \p BlockTy
2821   /// blocks. The accesses are casted to \p BlockTy.
2822   template <typename BlockTy, typename T>
2823   static auto blocksOnly(const T &Range) {
2824     // Create BaseTy with correct const-ness based on BlockTy.
2825     using BaseTy =
2826         typename std::conditional<std::is_const<BlockTy>::value,
2827                                   const VPBlockBase, VPBlockBase>::type;
2828 
2829     // We need to first create an iterator range over (const) BlocktTy & instead
2830     // of (const) BlockTy * for filter_range to work properly.
2831     auto Mapped =
2832         map_range(Range, [](BaseTy *Block) -> BaseTy & { return *Block; });
2833     auto Filter = make_filter_range(
2834         Mapped, [](BaseTy &Block) { return isa<BlockTy>(&Block); });
2835     return map_range(Filter, [](BaseTy &Block) -> BlockTy * {
2836       return cast<BlockTy>(&Block);
2837     });
2838   }
2839 };
2840 
2841 class VPInterleavedAccessInfo {
2842   DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
2843       InterleaveGroupMap;
2844 
2845   /// Type for mapping of instruction based interleave groups to VPInstruction
2846   /// interleave groups
2847   using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
2848                              InterleaveGroup<VPInstruction> *>;
2849 
2850   /// Recursively \p Region and populate VPlan based interleave groups based on
2851   /// \p IAI.
2852   void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
2853                    InterleavedAccessInfo &IAI);
2854   /// Recursively traverse \p Block and populate VPlan based interleave groups
2855   /// based on \p IAI.
2856   void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
2857                   InterleavedAccessInfo &IAI);
2858 
2859 public:
2860   VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
2861 
2862   ~VPInterleavedAccessInfo() {
2863     SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
2864     // Avoid releasing a pointer twice.
2865     for (auto &I : InterleaveGroupMap)
2866       DelSet.insert(I.second);
2867     for (auto *Ptr : DelSet)
2868       delete Ptr;
2869   }
2870 
2871   /// Get the interleave group that \p Instr belongs to.
2872   ///
2873   /// \returns nullptr if doesn't have such group.
2874   InterleaveGroup<VPInstruction> *
2875   getInterleaveGroup(VPInstruction *Instr) const {
2876     return InterleaveGroupMap.lookup(Instr);
2877   }
2878 };
2879 
2880 /// Class that maps (parts of) an existing VPlan to trees of combined
2881 /// VPInstructions.
2882 class VPlanSlp {
2883   enum class OpMode { Failed, Load, Opcode };
2884 
2885   /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
2886   /// DenseMap keys.
2887   struct BundleDenseMapInfo {
2888     static SmallVector<VPValue *, 4> getEmptyKey() {
2889       return {reinterpret_cast<VPValue *>(-1)};
2890     }
2891 
2892     static SmallVector<VPValue *, 4> getTombstoneKey() {
2893       return {reinterpret_cast<VPValue *>(-2)};
2894     }
2895 
2896     static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
2897       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2898     }
2899 
2900     static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
2901                         const SmallVector<VPValue *, 4> &RHS) {
2902       return LHS == RHS;
2903     }
2904   };
2905 
2906   /// Mapping of values in the original VPlan to a combined VPInstruction.
2907   DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
2908       BundleToCombined;
2909 
2910   VPInterleavedAccessInfo &IAI;
2911 
2912   /// Basic block to operate on. For now, only instructions in a single BB are
2913   /// considered.
2914   const VPBasicBlock &BB;
2915 
2916   /// Indicates whether we managed to combine all visited instructions or not.
2917   bool CompletelySLP = true;
2918 
2919   /// Width of the widest combined bundle in bits.
2920   unsigned WidestBundleBits = 0;
2921 
2922   using MultiNodeOpTy =
2923       typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
2924 
2925   // Input operand bundles for the current multi node. Each multi node operand
2926   // bundle contains values not matching the multi node's opcode. They will
2927   // be reordered in reorderMultiNodeOps, once we completed building a
2928   // multi node.
2929   SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
2930 
2931   /// Indicates whether we are building a multi node currently.
2932   bool MultiNodeActive = false;
2933 
2934   /// Check if we can vectorize Operands together.
2935   bool areVectorizable(ArrayRef<VPValue *> Operands) const;
2936 
2937   /// Add combined instruction \p New for the bundle \p Operands.
2938   void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
2939 
2940   /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
2941   VPInstruction *markFailed();
2942 
2943   /// Reorder operands in the multi node to maximize sequential memory access
2944   /// and commutative operations.
2945   SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
2946 
2947   /// Choose the best candidate to use for the lane after \p Last. The set of
2948   /// candidates to choose from are values with an opcode matching \p Last's
2949   /// or loads consecutive to \p Last.
2950   std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
2951                                        SmallPtrSetImpl<VPValue *> &Candidates,
2952                                        VPInterleavedAccessInfo &IAI);
2953 
2954 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2955   /// Print bundle \p Values to dbgs().
2956   void dumpBundle(ArrayRef<VPValue *> Values);
2957 #endif
2958 
2959 public:
2960   VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
2961 
2962   ~VPlanSlp() = default;
2963 
2964   /// Tries to build an SLP tree rooted at \p Operands and returns a
2965   /// VPInstruction combining \p Operands, if they can be combined.
2966   VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
2967 
2968   /// Return the width of the widest combined bundle in bits.
2969   unsigned getWidestBundleBits() const { return WidestBundleBits; }
2970 
2971   /// Return true if all visited instruction can be combined.
2972   bool isCompletelySLP() const { return CompletelySLP; }
2973 };
2974 
2975 namespace vputils {
2976 
2977 /// Returns true if only the first lane of \p Def is used.
2978 bool onlyFirstLaneUsed(VPValue *Def);
2979 
2980 /// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p
2981 /// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in
2982 /// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's
2983 /// pre-header already contains a recipe expanding \p Expr, return it. If not,
2984 /// create a new one.
2985 VPValue *getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
2986                                        ScalarEvolution &SE);
2987 } // end namespace vputils
2988 
2989 } // end namespace llvm
2990 
2991 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
2992